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/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
-
-
+
+
-
-
+
+
@@ -23,11 +23,11 @@
**Documentation**: https://fastapi.tiangolo.com
-**Source Code**: https://github.com/tiangolo/fastapi
+**Source Code**: https://github.com/fastapi/fastapi
---
-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:
@@ -50,17 +50,20 @@ The key features are:
-
-
+
-
+
+
+
+
-
+
+
@@ -70,7 +73,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._"
-
uvicorn main:app --reload...fastapi dev main.py...email_validator - for email validation.
-* pydantic-settings - for settings management.
-* pydantic-extra-types - for extra types to be used with Pydantic.
+* email-validator - for email validation.
Used by Starlette:
* httpx - Required if you want to use the `TestClient`.
* jinja2 - Required if you want to use the default template configuration.
* python-multipart - Required if you want to support form "parsing", with `request.form()`.
-* itsdangerous - Required for `SessionMiddleware` support.
-* pyyaml - Required for Starlette's `SchemaGenerator` support (you probably don't need it with FastAPI).
-* ujson - Required if you want to use `UJSONResponse`.
Used by FastAPI / Starlette:
-* uvicorn - for the server that loads and serves your application.
-* orjson - Required if you want to use `ORJSONResponse`.
+* uvicorn - 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.
-You can install all of these with `pip install "fastapi[all]"`.
+### Without `standard` Dependencies
+
+If you don't want to include the `standard` optional dependencies, you can install with `pip install fastapi` instead of `pip install "fastapi[standard]"`.
+
+### Additional Optional Dependencies
+
+There are some additional dependencies you might want to install.
+
+Additional optional Pydantic dependencies:
+
+* pydantic-settings - for settings management.
+* pydantic-extra-types - for extra types to be used with Pydantic.
+
+Additional optional FastAPI dependencies:
+
+* orjson - Required if you want to use `ORJSONResponse`.
+* ujson - Required if you want to use `UJSONResponse`.
## License
diff --git a/docs/az/docs/fastapi-people.md b/docs/az/docs/fastapi-people.md
deleted file mode 100644
index 2ca8e109e..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 %}
-
-
-
+
+
-
-
+
+
@@ -23,11 +23,11 @@
**Sənədlər**: https://fastapi.tiangolo.com
-**Qaynaq Kodu**: https://github.com/tiangolo/fastapi
+**Qaynaq Kodu**: https://github.com/fastapi/fastapi
---
-FastAPI Python 3.8+ ilə API yaratmaq üçün standart Python tip məsləhətlərinə əsaslanan, müasir, sürətli (yüksək performanslı) framework-dür.
+FastAPI Python ilə API yaratmaq üçün standart Python tip məsləhətlərinə əsaslanan, müasir, sürətli (yüksək performanslı) framework-dür.
Əsas xüsusiyyətləri bunlardır:
@@ -63,7 +63,7 @@ FastAPI Python 3.8+ ilə API yaratmaq üçün standart Python Kabir Khan - Microsoft (ref)
+
email_validator - e-poçtun yoxlanılması üçün.
+* email-validator - e-poçtun yoxlanılması üçün.
* pydantic-settings - parametrlərin idarə edilməsi üçün.
* pydantic-extra-types - 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 688f3f95a..c882506ff 100644
--- a/docs/bn/docs/index.md
+++ b/docs/bn/docs/index.md
@@ -5,11 +5,11 @@
FastAPI উচ্চক্ষমতা সম্পন্ন, সহজে শেখার এবং দ্রুত কোড করে প্রোডাকশনের জন্য ফ্রামওয়ার্ক।
-
-
+
+
-
-
+
+
@@ -20,7 +20,7 @@
**নির্দেশিকা নথি**: https://fastapi.tiangolo.com
-**সোর্স কোড**: https://github.com/tiangolo/fastapi
+**সোর্স কোড**: https://github.com/fastapi/fastapi
---
@@ -61,7 +61,7 @@ FastAPI একটি আধুনিক, দ্রুত ( বেশি ক্
"_আমি আজকাল **FastAPI** ব্যবহার করছি। [...] আমরা ভাবছি মাইক্রোসফ্টে **ML সার্ভিস** এ সকল দলের জন্য এটি ব্যবহার করব। যার মধ্যে কিছু পণ্য **Windows** এ সংযোযন হয় এবং কিছু **Office** এর সাথে সংযোযন হচ্ছে।_"
-
ujson - দ্রুত JSON এর জন্য "parsing".
-- email_validator - ইমেল যাচাইকরণের জন্য।
+- email-validator - ইমেল যাচাইকরণের জন্য।
স্টারলেট দ্বারা ব্যবহৃত:
@@ -450,12 +449,12 @@ Pydantic দ্বারা ব্যবহৃত:
- itsdangerous - `SessionMiddleware` সহায়তার জন্য প্রয়োজন।
- pyyaml - স্টারলেটের SchemaGenerator সাপোর্ট এর জন্য প্রয়োজন (আপনার সম্ভাবত FastAPI প্রয়োজন নেই)।
- graphene - `GraphQLApp` সহায়তার জন্য প্রয়োজন।
-- ujson - আপনি `UJSONResponse` ব্যবহার করতে চাইলে প্রয়োজন।
FastAPI / Starlette দ্বারা ব্যবহৃত:
- uvicorn - সার্ভারের জন্য যা আপনার অ্যাপ্লিকেশন লোড করে এবং পরিবেশন করে।
- orjson - আপনি `ORJSONResponse` ব্যবহার করতে চাইলে প্রয়োজন।
+- ujson - আপনি `UJSONResponse` ব্যবহার করতে চাইলে প্রয়োজন।
আপনি এই সব ইনস্টল করতে পারেন `pip install fastapi[all]` দিয়ে.
diff --git a/docs/bn/docs/python-types.md b/docs/bn/docs/python-types.md
new file mode 100644
index 000000000..d5304a65e
--- /dev/null
+++ b/docs/bn/docs/python-types.md
@@ -0,0 +1,596 @@
+# পাইথন এর টাইপ্স পরিচিতি
+
+Python-এ ঐচ্ছিক "টাইপ হিন্ট" (যা "টাইপ অ্যানোটেশন" নামেও পরিচিত) এর জন্য সাপোর্ট রয়েছে।
+
+এই **"টাইপ হিন্ট"** বা অ্যানোটেশনগুলি এক ধরণের বিশেষ সিনট্যাক্স যা একটি ভেরিয়েবলের টাইপ ঘোষণা করতে দেয়।
+
+ভেরিয়েবলগুলির জন্য টাইপ ঘোষণা করলে, এডিটর এবং টুলগুলি আপনাকে আরও ভালো সাপোর্ট দিতে পারে।
+
+এটি পাইথন টাইপ হিন্ট সম্পর্কে একটি দ্রুত **টিউটোরিয়াল / রিফ্রেশার** মাত্র। এটি **FastAPI** এর সাথে ব্যবহার করার জন্য শুধুমাত্র ন্যূনতম প্রয়োজনীয়তা কভার করে... যা আসলে খুব একটা বেশি না।
+
+**FastAPI** এই টাইপ হিন্টগুলির উপর ভিত্তি করে নির্মিত, যা এটিকে অনেক সুবিধা এবং লাভ প্রদান করে।
+
+তবে, আপনি যদি কখনো **FastAPI** ব্যবহার নাও করেন, তবুও এগুলি সম্পর্কে একটু শেখা আপনার উপকারে আসবে।
+
+/// note
+
+যদি আপনি একজন Python বিশেষজ্ঞ হন, এবং টাইপ হিন্ট সম্পর্কে সবকিছু জানেন, তাহলে পরবর্তী অধ্যায়ে চলে যান।
+
+///
+
+## প্রেরণা
+
+চলুন একটি সাধারণ উদাহরণ দিয়ে শুরু করি:
+
+```Python
+{!../../../docs_src/python_types/tutorial001.py!}
+```
+
+এই প্রোগ্রামটি কল করলে আউটপুট হয়:
+
+```
+John Doe
+```
+
+ফাংশনটি নিম্নলিখিত কাজ করে:
+
+* `first_name` এবং `last_name` নেয়।
+* প্রতিটির প্রথম অক্ষরকে `title()` ব্যবহার করে বড় হাতের অক্ষরে রূপান্তর করে।
+* তাদেরকে মাঝখানে একটি স্পেস দিয়ে concatenate করে।
+
+```Python hl_lines="2"
+{!../../../docs_src/python_types/tutorial001.py!}
+```
+
+### এটি সম্পাদনা করুন
+
+এটি একটি খুব সাধারণ প্রোগ্রাম।
+
+কিন্তু এখন কল্পনা করুন যে আপনি এটি শুরু থেকে লিখছিলেন।
+
+এক পর্যায়ে আপনি ফাংশনের সংজ্ঞা শুরু করেছিলেন, আপনার প্যারামিটারগুলি প্রস্তুত ছিল...
+
+কিন্তু তারপর আপনাকে "সেই method কল করতে হবে যা প্রথম অক্ষরকে বড় হাতের অক্ষরে রূপান্তর করে"।
+
+এটা কি `upper` ছিল? নাকি `uppercase`? `first_uppercase`? `capitalize`?
+
+তারপর, আপনি পুরোনো প্রোগ্রামারের বন্ধু, এডিটর অটোকমপ্লিশনের সাহায্যে নেওয়ার চেষ্টা করেন।
+
+আপনি ফাংশনের প্রথম প্যারামিটার `first_name` টাইপ করেন, তারপর একটি ডট (`.`) টাইপ করেন এবং `Ctrl+Space` চাপেন অটোকমপ্লিশন ট্রিগার করার জন্য।
+
+কিন্তু, দুর্ভাগ্যবশত, আপনি কিছুই উপযোগী পান না:
+
+
+
+### টাইপ যোগ করুন
+
+আসুন আগের সংস্করণ থেকে একটি লাইন পরিবর্তন করি।
+
+আমরা ঠিক এই অংশটি পরিবর্তন করব অর্থাৎ ফাংশনের প্যারামিটারগুলি, এইগুলি:
+
+```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` চাপেন এবং আপনি দেখতে পান:
+
+
+
+এর সাথে, আপনি অপশনগুলি দেখে, স্ক্রল করতে পারেন, যতক্ষণ না আপনি এমন একটি অপশন খুঁজে পান যা কিছু মনে পরিয়ে দেয়:
+
+
+
+## আরও প্রেরণা
+
+এই ফাংশনটি দেখুন, এটিতে ইতিমধ্যে টাইপ হিন্ট রয়েছে:
+
+```Python hl_lines="1"
+{!../../../docs_src/python_types/tutorial003.py!}
+```
+
+এডিটর ভেরিয়েবলগুলির টাইপ জানার কারণে, আপনি শুধুমাত্র অটোকমপ্লিশনই পান না, আপনি এরর চেকও পান:
+
+
+
+এখন আপনি জানেন যে আপনাকে এটি ঠিক করতে হবে, `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` হিসেবে সংজ্ঞায়িত করা যাক।
+
+//// tab | Python 3.9+
+
+ভেরিয়েবলটি ঘোষণা করুন, একই কোলন (`:`) সিনট্যাক্স ব্যবহার করে।
+
+টাইপ হিসেবে, `list` ব্যবহার করুন।
+
+যেহেতু লিস্ট এমন একটি টাইপ যা অভ্যন্তরীণ টাইপগুলি ধারণ করে, আপনি তাদের স্কোয়ার ব্রাকেটের ভিতরে ব্যবহার করুন:
+
+```Python hl_lines="1"
+{!> ../../../docs_src/python_types/tutorial006_py39.py!}
+```
+
+////
+
+//// tab | 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` ওই টাইপের পরিবর্তে ব্যবহার করতে পারেন।
+
+///
+
+এর মাধ্যমে, আপনার এডিটর লিস্ট থেকে আইটেম প্রসেস করার সময় সাপোর্ট প্রদান করতে পারবে:
+
+
+
+টাইপগুলি ছাড়া, এটি করা প্রায় অসম্ভব।
+
+লক্ষ্য করুন যে ভেরিয়েবল `item` হল `items` লিস্টের একটি এলিমেন্ট।
+
+তবুও, এডিটর জানে যে এটি একটি `str`, এবং তার জন্য সাপোর্ট প্রদান করে।
+
+#### টাপল এবং সেট
+
+আপনি `tuple` এবং `set` ঘোষণা করার জন্য একই প্রক্রিয়া অনুসরণ করবেন:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="1"
+{!> ../../../docs_src/python_types/tutorial007_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="1 4"
+{!> ../../../docs_src/python_types/tutorial007.py!}
+```
+
+////
+
+এর মানে হল:
+
+* ভেরিয়েবল `items_t` হল একটি `tuple` যা ৩টি আইটেম ধারণ করে, একটি `int`, অন্য একটি `int`, এবং একটি `str`।
+* ভেরিয়েবল `items_s` হল একটি `set`, এবং এর প্রতিটি আইটেম হল `bytes` টাইপের।
+
+#### ডিক্ট
+
+একটি `dict` সংজ্ঞায়িত করতে, আপনি ২টি টাইপ প্যারামিটার কমা দ্বারা পৃথক করে দেবেন।
+
+প্রথম টাইপ প্যারামিটারটি হল `dict`-এর কীগুলির জন্য।
+
+দ্বিতীয় টাইপ প্যারামিটারটি হল `dict`-এর মানগুলির জন্য:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="1"
+{!> ../../../docs_src/python_types/tutorial008_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="1 4"
+{!> ../../../docs_src/python_types/tutorial008.py!}
+```
+
+////
+
+এর মানে হল:
+
+* ভেরিয়েবল `prices` হল একটি `dict`:
+ * এই `dict`-এর কীগুলি হল `str` টাইপের (ধরা যাক, প্রতিটি আইটেমের নাম)।
+ * এই `dict`-এর মানগুলি হল `float` টাইপের (ধরা যাক, প্রতিটি আইটেমের দাম)।
+
+#### ইউনিয়ন
+
+আপনি একটি ভেরিয়েবলকে এমনভাবে ঘোষণা করতে পারেন যেন তা **একাধিক টাইপের** হয়, উদাহরণস্বরূপ, একটি `int` অথবা `str`।
+
+Python 3.6 এবং তার উপরের সংস্করণগুলিতে (Python 3.10 অন্তর্ভুক্ত) আপনি `typing` থেকে `Union` টাইপ ব্যবহার করতে পারেন এবং স্কোয়ার ব্র্যাকেটের মধ্যে গ্রহণযোগ্য টাইপগুলি রাখতে পারেন।
+
+Python 3.10-এ একটি **নতুন সিনট্যাক্স** আছে যেখানে আপনি সম্ভাব্য টাইপগুলিকে একটি ভার্টিকাল বার (`|`) দ্বারা পৃথক করতে পারেন।
+
+//// tab | Python 3.10+
+
+```Python hl_lines="1"
+{!> ../../../docs_src/python_types/tutorial008b_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="1 4"
+{!> ../../../docs_src/python_types/tutorial008b.py!}
+```
+
+////
+
+উভয় ক্ষেত্রেই এর মানে হল যে `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` ব্যবহার করতে পারেন:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="1"
+{!> ../../../docs_src/python_types/tutorial009_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="1 4"
+{!> ../../../docs_src/python_types/tutorial009.py!}
+```
+
+////
+
+//// tab | Python 3.8+ বিকল্প
+
+```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` নিয়ে আর চিন্তা করতে হবে না। 😎
+
+#### জেনেরিক টাইপস
+
+স্কোয়ার ব্র্যাকেটে টাইপ প্যারামিটার নেওয়া এই টাইপগুলিকে **জেনেরিক টাইপ** বা **জেনেরিকস** বলা হয়, যেমন:
+
+//// tab | Python 3.10+
+
+আপনি সেই একই বিল্টইন টাইপ জেনেরিক্স হিসেবে ব্যবহার করতে পারবেন(ভিতরে টাইপ সহ স্কয়ারে ব্রাকেট দিয়ে):
+
+* `list`
+* `tuple`
+* `set`
+* `dict`
+
+এবং Python 3.8 এর মতোই, `typing` মডিউল থেকে:
+
+* `Union`
+* `Optional` (Python 3.8 এর মতোই)
+* ...এবং অন্যান্য।
+
+Python 3.10-এ, `Union` এবং `Optional` জেনেরিকস ব্যবহার করার বিকল্প হিসেবে, আপনি টাইপগুলির ইউনিয়ন ঘোষণা করতে ভার্টিকাল বার (`|`) ব্যবহার করতে পারেন, যা ওদের থেকে অনেক ভালো এবং সহজ।
+
+////
+
+//// tab | Python 3.9+
+
+আপনি সেই একই বিল্টইন টাইপ জেনেরিক্স হিসেবে ব্যবহার করতে পারবেন(ভিতরে টাইপ সহ স্কয়ারে ব্রাকেট দিয়ে):
+
+* `list`
+* `tuple`
+* `set`
+* `dict`
+
+এবং Python 3.8 এর মতোই, `typing` মডিউল থেকে:
+
+* `Union`
+* `Optional`
+* ...এবং অন্যান্য।
+
+////
+
+//// tab | 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!}
+```
+
+এবং তারপর, আবার, আপনি এডিটর সাপোর্ট পেয়ে যাবেন:
+
+
+
+লক্ষ্য করুন যে এর মানে হল "`one_person` হল ক্লাস `Person`-এর একটি **ইন্সট্যান্স**।"
+
+এর মানে এটি নয় যে "`one_person` হল **ক্লাস** যাকে বলা হয় `Person`।"
+
+## Pydantic মডেল
+
+[Pydantic](https://docs.pydantic.dev/) হল একটি Python লাইব্রেরি যা ডাটা ভ্যালিডেশন সম্পাদন করে।
+
+আপনি ডাটার "আকার" এট্রিবিউট সহ ক্লাস হিসেবে ঘোষণা করেন।
+
+এবং প্রতিটি এট্রিবিউট এর একটি টাইপ থাকে।
+
+তারপর আপনি যদি কিছু মান দিয়ে সেই ক্লাসের একটি ইন্সট্যান্স তৈরি করেন-- এটি মানগুলিকে ভ্যালিডেট করবে, প্রয়োজন অনুযায়ী তাদেরকে উপযুক্ত টাইপে রূপান্তর করবে এবং আপনাকে সমস্ত ডাটা সহ একটি অবজেক্ট প্রদান করবে।
+
+এবং আপনি সেই ফলাফল অবজেক্টের সাথে এডিটর সাপোর্ট পাবেন।
+
+অফিসিয়াল Pydantic ডক্স থেকে একটি উদাহরণ:
+
+//// tab | Python 3.10+
+
+```Python
+{!> ../../../docs_src/python_types/tutorial011_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python
+{!> ../../../docs_src/python_types/tutorial011_py39.py!}
+```
+
+////
+
+//// tab | 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` ব্যবহার করে এই টাইপ হিন্টগুলিতে **অতিরিক্ত মেটাডাটা** রাখতে দেয়।
+
+//// tab | Python 3.9+
+
+Python 3.9-এ, `Annotated` স্ট্যান্ডার্ড লাইব্রেরিতে অন্তর্ভুক্ত, তাই আপনি এটি `typing` থেকে ইমপোর্ট করতে পারেন।
+
+```Python hl_lines="1 4"
+{!> ../../../docs_src/python_types/tutorial013_py39.py!}
+```
+
+////
+
+//// tab | 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 টাইপ হিন্ট সম্পর্কে বেসিক থেকে উন্নত লেভেলের ধারণা পেতে পারেন, যা আপনার কোডে টাইপ সেফটি এবং স্পষ্টতা বাড়াতে সাহায্য করবে।
+
+///
diff --git a/docs/de/docs/advanced/additional-responses.md b/docs/de/docs/advanced/additional-responses.md
new file mode 100644
index 000000000..6f2c4b2dd
--- /dev/null
+++ b/docs/de/docs/advanced/additional-responses.md
@@ -0,0 +1,255 @@
+# 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:
+
+
+
+## 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:
+
+* OpenAPI Responses Object, enthält das `Response Object`.
+* OpenAPI Response Object, 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`.
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
new file mode 100644
index 000000000..f29970872
--- /dev/null
+++ b/docs/de/docs/advanced/advanced-dependencies.md
@@ -0,0 +1,177 @@
+# 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__`:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="12"
+{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="11"
+{!> ../../../docs_src/dependencies/tutorial011_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="10"
+{!> ../../../docs_src/dependencies/tutorial011.py!}
+```
+
+////
+
+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:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="8"
+{!> ../../../docs_src/dependencies/tutorial011_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/dependencies/tutorial011.py!}
+```
+
+////
+
+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:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="18"
+{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="17"
+{!> ../../../docs_src/dependencies/tutorial011_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="16"
+{!> ../../../docs_src/dependencies/tutorial011.py!}
+```
+
+////
+
+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`:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="22"
+{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="21"
+{!> ../../../docs_src/dependencies/tutorial011_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="20"
+{!> ../../../docs_src/dependencies/tutorial011.py!}
+```
+
+////
+
+/// 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.
+
+///
diff --git a/docs/de/docs/advanced/async-tests.md b/docs/de/docs/advanced/async-tests.md
new file mode 100644
index 000000000..9f0bd4aa2
--- /dev/null
+++ b/docs/de/docs/advanced/async-tests.md
@@ -0,0 +1,107 @@
+# 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 HTTPX 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:
+
+
+
+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 http://127.0.0.1:9999/api/v1/docs testen:
+
+
+
+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 http://127.0.0.1:9999/api/v1/docs würde es so aussehen:
+
+
+
+/// 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. ✨
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
- In diesem Fall wird der HTTP-Header `Content-Type` auf `application/json` 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 `application/json` gesetzt.
-!!! tip "Tipp"
- Die `ORJSONResponse` ist derzeit nur in FastAPI verfügbar, nicht in Starlette.
+Und er wird als solcher in OpenAPI dokumentiert.
+
+///
+
+/// 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"
-!!! info
- Natürlich stammen der eigentliche `Content-Type`-Header, der Statuscode, usw., aus dem `Response`-Objekt, das Sie zurückgegeben haben.
+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
+
+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"
- **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 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.
+
+///
### `Response`
@@ -153,15 +174,21 @@ Eine schnelle alternative JSON-Response mit `ujson`.
-!!! 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
new file mode 100644
index 000000000..d5a663485
--- /dev/null
+++ b/docs/de/docs/advanced/dataclasses.md
@@ -0,0 +1,101 @@
+# 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 `dataclasses`:
+
+```Python hl_lines="1 7-12 19-20"
+{!../../../docs_src/dataclasses/tutorial001.py!}
+```
+
+Das ist dank **Pydantic** ebenfalls möglich, da es `dataclasses` intern unterstützt.
+
+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:
+
+
+
+## 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 serialisieren.
+
+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 Pydantic-Dokumentation zu Datenklassen.
+
+## Version
+
+Dies ist verfügbar seit FastAPI-Version `0.67.0`. 🔖
diff --git a/docs/de/docs/advanced/events.md b/docs/de/docs/advanced/events.md
new file mode 100644
index 000000000..e898db49b
--- /dev/null
+++ b/docs/de/docs/advanced/events.md
@@ -0,0 +1,177 @@
+# 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 Eventhandler (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 Lifespan Protokolls und definiert Events namens `startup` und `shutdown`.
+
+/// info
+
+Weitere Informationen zu Starlettes `lifespan`-Handlern finden Sie in Starlettes Lifespan-Dokumentation.
+
+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}.
diff --git a/docs/de/docs/advanced/generate-clients.md b/docs/de/docs/advanced/generate-clients.md
index 2fcba5956..b8d66fdd7 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 OpenAPI Generator.
-Wenn Sie ein **Frontend** erstellen, ist openapi-typescript-codegen eine sehr interessante Alternative.
+Wenn Sie ein **Frontend** erstellen, ist openapi-ts eine sehr interessante Alternative.
## Client- und SDK-Generatoren – Sponsor
@@ -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 Speakeasy ausprobieren.
+Beispielsweise könnten Sie Speakeasy ausprobieren.
Es gibt auch mehrere andere Unternehmen, welche ähnliche Dienste anbieten und die Sie online suchen und finden können. 🤓
@@ -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+"
+////
- ```Python hl_lines="9-11 14-15 18 19 23"
- {!> ../../../docs_src/generate_clients/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```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-Payload verwenden, indem sie die Modelle `Item` und `ResponseMessage` verwenden.
@@ -58,14 +62,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:
-!!! 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!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="23 28 36"
- {!> ../../../docs_src/generate_clients/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+
+```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+"
+////
- ```Python hl_lines="8-9 12"
- {!> ../../../docs_src/generate_clients/tutorial003.py!}
- ```
+//// tab | Python 3.8+
+
+```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"
+////
- ```Javascript
- {!> ../../../docs_src/generate_clients/tutorial004.js!}
- ```
+//// tab | Node.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.
@@ -254,12 +273,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/de/docs/advanced/index.md b/docs/de/docs/advanced/index.md
new file mode 100644
index 000000000..953ad317d
--- /dev/null
+++ b/docs/de/docs/advanced/index.md
@@ -0,0 +1,36 @@
+# 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:
+
+* Talk Python Training
+* Test-Driven Development
diff --git a/docs/de/docs/advanced/middleware.md b/docs/de/docs/advanced/middleware.md
new file mode 100644
index 000000000..8912225fb
--- /dev/null
+++ b/docs/de/docs/advanced/middleware.md
@@ -0,0 +1,101 @@
+# 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 ASGI-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:
+
+* Uvicorns `ProxyHeadersMiddleware`
+* MessagePack
+
+Um mehr über weitere verfügbare Middlewares herauszufinden, besuchen Sie Starlettes Middleware-Dokumentation und die ASGI Awesome List.
diff --git a/docs/de/docs/advanced/openapi-callbacks.md b/docs/de/docs/advanced/openapi-callbacks.md
new file mode 100644
index 000000000..d7b5bc885
--- /dev/null
+++ b/docs/de/docs/advanced/openapi-callbacks.md
@@ -0,0 +1,194 @@
+# 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-Url-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 HTTPX oder Requests 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 OpenAPI-3-Ausdruck 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 OpenAPI-3-Ausdruck 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 http://127.0.0.1:8000/docs gehen.
+
+Sie sehen Ihre Dokumentation, einschließlich eines Abschnitts „Callbacks“ für Ihre *Pfadoperation*, der zeigt, wie die *externe API* aussehen sollte:
+
+
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
new file mode 100644
index 000000000..c9cb82fe3
--- /dev/null
+++ b/docs/de/docs/advanced/path-operation-advanced-configuration.md
@@ -0,0 +1,224 @@
+# 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 Operationsobjekt 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 OpenAPI-Erweiterungen 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.
+
+
+
+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 geparst, 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:
+
+//// tab | Pydantic v2
+
+```Python hl_lines="17-22 24"
+{!> ../../../docs_src/path_operation_advanced_configuration/tutorial007.py!}
+```
+
+////
+
+//// tab | Pydantic v1
+
+```Python hl_lines="17-22 24"
+{!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!}
+```
+
+////
+
+/// info
+
+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:
+
+//// 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
+
+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.
+
+///
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.
diff --git a/docs/de/docs/advanced/response-cookies.md b/docs/de/docs/advanced/response-cookies.md
new file mode 100644
index 000000000..3d2043565
--- /dev/null
+++ b/docs/de/docs/advanced/response-cookies.md
@@ -0,0 +1,55 @@
+# 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 Dokumentation in Starlette an.
diff --git a/docs/de/docs/advanced/response-directly.md b/docs/de/docs/advanced/response-directly.md
new file mode 100644
index 000000000..377490b56
--- /dev/null
+++ b/docs/de/docs/advanced/response-directly.md
@@ -0,0 +1,69 @@
+# 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 XML-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.
diff --git a/docs/de/docs/advanced/response-headers.md b/docs/de/docs/advanced/response-headers.md
new file mode 100644
index 000000000..51a364f56
--- /dev/null
+++ b/docs/de/docs/advanced/response-headers.md
@@ -0,0 +1,45 @@
+# 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 mittels des Präfix 'X-' 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 Starlettes CORS-Dokumentation.
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..3e7aeb8a0
--- /dev/null
+++ b/docs/de/docs/advanced/security/http-basic-auth.md
@@ -0,0 +1,191 @@
+# HTTP Basic Auth
+
+Für die einfachsten Fälle können Sie HTTP Basic Auth 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`.
+
+//// tab | Python 3.9+
+
+```Python hl_lines="4 8 12"
+{!> ../../../docs_src/security/tutorial006_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="2 7 11"
+{!> ../../../docs_src/security/tutorial006_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="2 6 10"
+{!> ../../../docs_src/security/tutorial006.py!}
+```
+
+////
+
+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:
+
+
+
+## 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 `secrets`, 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.
+
+//// tab | Python 3.9+
+
+```Python hl_lines="1 12-24"
+{!> ../../../docs_src/security/tutorial007_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="1 12-24"
+{!> ../../../docs_src/security/tutorial007_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="1 11-21"
+{!> ../../../docs_src/security/tutorial007.py!}
+```
+
+////
+
+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:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="26-30"
+{!> ../../../docs_src/security/tutorial007_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="26-30"
+{!> ../../../docs_src/security/tutorial007_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="23-27"
+{!> ../../../docs_src/security/tutorial007.py!}
+```
+
+////
diff --git a/docs/de/docs/advanced/security/index.md b/docs/de/docs/advanced/security/index.md
new file mode 100644
index 000000000..380e48bbf
--- /dev/null
+++ b/docs/de/docs/advanced/security/index.md
@@ -0,0 +1,19 @@
+# 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.
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..f02707698
--- /dev/null
+++ b/docs/de/docs/advanced/security/oauth2-scopes.md
@@ -0,0 +1,786 @@
+# OAuth2-Scopes
+
+Sie können OAuth2-Scopes 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:
+
+//// 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"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="3 7 11 45 63 104 106-114 120-123 127-133 138 154"
+{!> ../../../docs_src/security/tutorial005_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155"
+{!> ../../../docs_src/security/tutorial005_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155"
+{!> ../../../docs_src/security/tutorial005.py!}
+```
+
+////
+
+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:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="62-65"
+{!> ../../../docs_src/security/tutorial005_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="62-65"
+{!> ../../../docs_src/security/tutorial005_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="63-66"
+{!> ../../../docs_src/security/tutorial005_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="61-64"
+{!> ../../../docs_src/security/tutorial005_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="62-65"
+{!> ../../../docs_src/security/tutorial005_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="62-65"
+{!> ../../../docs_src/security/tutorial005.py!}
+```
+
+////
+
+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:
+
+
+
+## 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.
+
+///
+
+//// tab | Python 3.10+
+
+```Python hl_lines="155"
+{!> ../../../docs_src/security/tutorial005_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="155"
+{!> ../../../docs_src/security/tutorial005_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="156"
+{!> ../../../docs_src/security/tutorial005_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="154"
+{!> ../../../docs_src/security/tutorial005_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="155"
+{!> ../../../docs_src/security/tutorial005_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="155"
+{!> ../../../docs_src/security/tutorial005.py!}
+```
+
+////
+
+## 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.
+
+///
+
+//// tab | Python 3.10+
+
+```Python hl_lines="4 139 170"
+{!> ../../../docs_src/security/tutorial005_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="4 139 170"
+{!> ../../../docs_src/security/tutorial005_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="4 140 171"
+{!> ../../../docs_src/security/tutorial005_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="3 138 167"
+{!> ../../../docs_src/security/tutorial005_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="4 139 168"
+{!> ../../../docs_src/security/tutorial005_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="4 139 168"
+{!> ../../../docs_src/security/tutorial005.py!}
+```
+
+////
+
+/// 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).
+
+//// tab | Python 3.10+
+
+```Python hl_lines="8 105"
+{!> ../../../docs_src/security/tutorial005_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="8 105"
+{!> ../../../docs_src/security/tutorial005_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="8 106"
+{!> ../../../docs_src/security/tutorial005_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="7 104"
+{!> ../../../docs_src/security/tutorial005_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="8 105"
+{!> ../../../docs_src/security/tutorial005_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="8 105"
+{!> ../../../docs_src/security/tutorial005.py!}
+```
+
+////
+
+## 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).
+
+//// tab | Python 3.10+
+
+```Python hl_lines="105 107-115"
+{!> ../../../docs_src/security/tutorial005_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="105 107-115"
+{!> ../../../docs_src/security/tutorial005_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="106 108-116"
+{!> ../../../docs_src/security/tutorial005_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="104 106-114"
+{!> ../../../docs_src/security/tutorial005_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="105 107-115"
+{!> ../../../docs_src/security/tutorial005_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="105 107-115"
+{!> ../../../docs_src/security/tutorial005.py!}
+```
+
+////
+
+## 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.
+
+//// tab | Python 3.10+
+
+```Python hl_lines="46 116-127"
+{!> ../../../docs_src/security/tutorial005_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="46 116-127"
+{!> ../../../docs_src/security/tutorial005_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="47 117-128"
+{!> ../../../docs_src/security/tutorial005_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="45 115-126"
+{!> ../../../docs_src/security/tutorial005_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="46 116-127"
+{!> ../../../docs_src/security/tutorial005_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="46 116-127"
+{!> ../../../docs_src/security/tutorial005.py!}
+```
+
+////
+
+## 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.
+
+//// tab | Python 3.10+
+
+```Python hl_lines="128-134"
+{!> ../../../docs_src/security/tutorial005_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="128-134"
+{!> ../../../docs_src/security/tutorial005_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="129-135"
+{!> ../../../docs_src/security/tutorial005_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="127-133"
+{!> ../../../docs_src/security/tutorial005_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="128-134"
+{!> ../../../docs_src/security/tutorial005_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="128-134"
+{!> ../../../docs_src/security/tutorial005.py!}
+```
+
+////
+
+## 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.
+
+
+
+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.
diff --git a/docs/de/docs/advanced/settings.md b/docs/de/docs/advanced/settings.md
new file mode 100644
index 000000000..3cd4c6c7d
--- /dev/null
+++ b/docs/de/docs/advanced/settings.md
@@ -0,0 +1,566 @@
+# 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 Umgebungsvariable (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:
+
+//// tab | Linux, macOS, Windows Bash
+
+
+
+Öffnen Sie dann die Dokumentation für die Unteranwendung unter http://127.0.0.1:8000/subapi/docs.
+
+Sie sehen die automatische API-Dokumentation für die Unteranwendung, welche nur deren eigene _Pfadoperationen_ anzeigt, alle unter dem korrekten Unterpfad-Präfix `/subapi`:
+
+
+
+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}.
diff --git a/docs/de/docs/advanced/templates.md b/docs/de/docs/advanced/templates.md
new file mode 100644
index 000000000..abc7624f1
--- /dev/null
+++ b/docs/de/docs/advanced/templates.md
@@ -0,0 +1,128 @@
+# 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`:
+
+
+
+Sie können Nachrichten in das Eingabefeld tippen und absenden:
+
+
+
+Und Ihre **FastAPI**-Anwendung mit WebSockets antwortet:
+
+
+
+Sie können viele Nachrichten senden (und empfangen):
+
+
+
+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*:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="68-69 82"
+{!> ../../../docs_src/websockets/tutorial002_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="68-69 82"
+{!> ../../../docs_src/websockets/tutorial002_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="69-70 83"
+{!> ../../../docs_src/websockets/tutorial002_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="66-67 79"
+{!> ../../../docs_src/websockets/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="68-69 81"
+{!> ../../../docs_src/websockets/tutorial002.py!}
+```
+
+////
+
+/// 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 gültigen Codes, die in der Spezifikation definiert sind.
+
+///
+
+### WebSockets mit Abhängigkeiten ausprobieren
+
+Wenn Ihre Datei `main.py` heißt, führen Sie Ihre Anwendung mit Folgendem aus:
+
+
+
+## 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.
+
+//// tab | Python 3.9+
+
+```Python hl_lines="79-81"
+{!> ../../../docs_src/websockets/tutorial003_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="81-83"
+{!> ../../../docs_src/websockets/tutorial003.py!}
+```
+
+////
+
+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 encode/broadcaster an.
+
+///
+
+## Mehr Informationen
+
+Weitere Informationen zu Optionen finden Sie in der Dokumentation von Starlette:
+
+* Die `WebSocket`-Klasse.
+* Klassen-basierte Handhabung von WebSockets.
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 http://localhost:8000/v1/ gehen, sehen Sie die Response von Flask:
+
+```txt
+Hello, World from Flask!
+```
+
+Und wenn Sie auf http://localhost:8000/v2 gehen, sehen Sie die Response von FastAPI:
+
+```JSON
+{
+ "message": "Hello World"
+}
+```
diff --git a/docs/de/docs/alternatives.md b/docs/de/docs/alternatives.md
new file mode 100644
index 000000000..286ef1723
--- /dev/null
+++ b/docs/de/docs/alternatives.md
@@ -0,0 +1,485 @@
+# 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
+
+### Django
+
+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 IoT-Geräten) verwendet werden, um mit ihm zu kommunizieren.
+
+### Django REST Framework
+
+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.
+
+///
+
+### Flask
+
+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.
+
+///
+
+### Requests
+
+**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.
+
+///
+
+### Swagger / OpenAPI
+
+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:
+
+* Swagger UI
+* ReDoc
+
+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.
+
+### Marshmallow
+
+Eine der von API-Systemen benötigen Hauptfunktionen ist die Daten-„Serialisierung“, 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 Schema 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.
+
+///
+
+### Webargs
+
+Eine weitere wichtige Funktion, die von APIs benötigt wird, ist das Parsen 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.
+
+///
+
+### APISpec
+
+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.
+
+///
+
+### Flask-apispec
+
+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:
+
+* https://github.com/tiangolo/full-stack
+* https://github.com/tiangolo/full-stack-flask-couchbase
+* https://github.com/tiangolo/full-stack-flask-couchdb
+
+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.
+
+///
+
+### NestJS (und Angular)
+
+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.
+
+///
+
+### Sanic
+
+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 `uvloop` 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).
+
+///
+
+### Falcon
+
+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.
+
+///
+
+### Molten
+
+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).
+
+///
+
+### Hug
+
+Hug war eines der ersten Frameworks, welches die Deklaration von API-Parametertypen mithilfe von Python-Typhinweisen implementierte. Das war eine großartige Idee, die andere Tools dazu inspirierte, dasselbe zu tun.
+
+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 `isort`, 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.
+
+///
+
+### APIStar (≦ 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**
+
+### Pydantic
+
+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.
+
+///
+
+### Starlette
+
+Starlette ist ein leichtgewichtiges ASGI-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.
+
+///
+
+### Uvicorn
+
+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}.
diff --git a/docs/de/docs/async.md b/docs/de/docs/async.md
new file mode 100644
index 000000000..74b6b6968
--- /dev/null
+++ b/docs/de/docs/async.md
@@ -0,0 +1,442 @@
+# 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?
+
+TL;DR:
+
+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 I/O-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 I/O-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. 😍
+
+
+
+Dann sind Sie an der Reihe und Sie bestellen zwei sehr schmackhafte Burger für Ihren Schwarm und Sie. 🍔🍔
+
+
+
+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).
+
+
+
+Sie bezahlen. 💸
+
+Der Kassierer gibt Ihnen die Nummer Ihrer Bestellung.
+
+
+
+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 ✨😍✨.
+
+
+
+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.
+
+
+
+Sie und Ihr Schwarm essen die Burger und haben eine schöne Zeit. ✨
+
+
+
+/// info
+
+Die wunderschönen Illustrationen stammen von Ketrina Thompson. 🎨
+
+///
+
+---
+
+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.
+
+
+
+Dann sind Sie endlich an der Reihe und bestellen zwei sehr leckere Burger für Ihren Schwarm und Sie.
+
+Sie zahlen 💸.
+
+
+
+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.
+
+
+
+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.
+
+
+
+Dann kommt Ihr Kassierer/Koch 👨🍳 endlich mit Ihren Burgern zurück, nachdem Sie lange vor der Theke gewartet 🕙 haben.
+
+
+
+Sie nehmen Ihre Burger und gehen mit Ihrem Schwarm an den Tisch.
+
+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 Ketrina Thompson. 🎨
+
+///
+
+---
+
+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 (alles dank Starlette).
+
+### 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 CPU 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 AnyIO, was bedeutet, es ist sowohl kompatibel mit der Python-Standardbibliothek asyncio, als auch mit Trio.
+
+Insbesondere können Sie AnyIO 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 AnyIO 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 Gevent 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 Callback-Hölle 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 I/O-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: In Eile?.
diff --git a/docs/de/docs/contributing.md b/docs/de/docs/contributing.md
new file mode 100644
index 000000000..58567ad7f
--- /dev/null
+++ b/docs/de/docs/contributing.md
@@ -0,0 +1,484 @@
+# Entwicklung – Mitwirken
+
+Vielleicht möchten Sie sich zuerst die grundlegenden Möglichkeiten anschauen, [FastAPI zu helfen und Hilfe zu erhalten](help-fastapi.md){.internal-link target=_blank}.
+
+## Entwicklung
+
+Wenn Sie das fastapi Repository bereits geklont haben und tief in den Code eintauchen möchten, hier einen Leitfaden zum Einrichten Ihrer Umgebung.
+
+### Virtuelle Umgebung mit `venv`
+
+Sie können mit dem Python-Modul `venv` in einem Verzeichnis eine isolierte virtuelle lokale Umgebung erstellen. Machen wir das im geklonten Repository (da wo sich die `requirements.txt` befindet):
+
+
+
+---
+
+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 **Worker** 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.
+
++ +**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). + ++ +## 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 Python-Entwickler-Umfrage, 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 **Pydantic** 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 **Starlette** 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. 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 Security through obscurity 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: + +
+
+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:
+
+
+
+## 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:
+
+
+
+## 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 Dokumentation für die Parameter der Swagger-Oberfläche.
+
+## 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.
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..e8750f7c2
--- /dev/null
+++ b/docs/de/docs/how-to/custom-docs-ui-assets.md
@@ -0,0 +1,205 @@
+# 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 CDN 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 CDN 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 http://127.0.0.1:8000/docs 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:
+
+* `swagger-ui-bundle.js`
+* `swagger-ui.css`
+
+Und **ReDoc** verwendet diese Datei:
+
+* `redoc.standalone.js`
+
+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 http://127.0.0.1:8000/static/redoc.standalone.js.
+
+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 http://127.0.0.1:8000/docs und laden Sie die Seite neu.
+
+Und selbst ohne Internet könnten Sie die Dokumentation für Ihre API sehen und damit interagieren.
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..a0c4a0e0c
--- /dev/null
+++ b/docs/de/docs/how-to/custom-request-and-route.md
@@ -0,0 +1,121 @@
+# 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. `msgpack`).
+* 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 Starlettes Dokumentation zu Requests 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!}
+```
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/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}.
diff --git a/docs/de/docs/how-to/graphql.md b/docs/de/docs/how-to/graphql.md
new file mode 100644
index 000000000..19af25bb3
--- /dev/null
+++ b/docs/de/docs/how-to/graphql.md
@@ -0,0 +1,62 @@
+# 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:
+
+* Strawberry 🍓
+ * Mit Dokumentation für FastAPI
+* Ariadne
+ * Mit Dokumentation für FastAPI
+* Tartiflette
+ * Mit Tartiflette ASGI, für ASGI-Integration
+* Graphene
+ * Mit starlette-graphene3
+
+## GraphQL mit Strawberry
+
+Wenn Sie mit **GraphQL** arbeiten möchten oder müssen, ist **Strawberry** 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 Strawberry-Dokumentation.
+
+Und auch die Dokumentation zu Strawberry mit FastAPI.
+
+## Ältere `GraphQLApp` von Starlette
+
+Frühere Versionen von Starlette enthielten eine `GraphQLApp`-Klasse zur Integration mit Graphene.
+
+Das wurde von Starlette deprecated, aber wenn Sie Code haben, der das verwendet, können Sie einfach zu starlette-graphene3 **migrieren**, welches denselben Anwendungsfall abdeckt und über eine **fast identische Schnittstelle** verfügt.
+
+/// tip | "Tipp"
+
+Wenn Sie GraphQL benötigen, würde ich Ihnen trotzdem empfehlen, sich Strawberry anzuschauen, da es auf Typannotationen basiert, statt auf benutzerdefinierten Klassen und Typen.
+
+///
+
+## Mehr darüber lernen
+
+Weitere Informationen zu **GraphQL** finden Sie in der offiziellen GraphQL-Dokumentation.
+
+Sie können auch mehr über jede der oben beschriebenen Bibliotheken in den jeweiligen Links lesen.
diff --git a/docs/de/docs/how-to/index.md b/docs/de/docs/how-to/index.md
new file mode 100644
index 000000000..75779a01c
--- /dev/null
+++ b/docs/de/docs/how-to/index.md
@@ -0,0 +1,13 @@
+# 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}.
+
+///
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..eaecb27de
--- /dev/null
+++ b/docs/de/docs/how-to/separate-openapi-schemas.md
@@ -0,0 +1,258 @@
+# 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:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="7"
+{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-7]!}
+
+# Code unterhalb weggelassen 👇
+```
+
+
+
+
+
+
++ FastAPI Framework, hochperformant, leicht zu erlernen, schnell zu programmieren, einsatzbereit +
+ + +--- + +**Dokumentation**: https://fastapi.tiangolo.com + +**Quellcode**: https://github.com/fastapi/fastapi + +--- + +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: + +* **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. Code-Vervollständigung ü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: OpenAPI (früher bekannt als Swagger) und JSON Schema. + +* Schätzung auf Basis von Tests in einem internen Entwicklungsteam, das Produktionsanwendungen erstellt. + +## Sponsoren + + + +{% if sponsors %} +{% for sponsor in sponsors.gold -%} +async def ...uvicorn main:app --reload ...email-validator - für E-Mail-Validierung.
+* pydantic-settings - für die Verwaltung von Einstellungen.
+* pydantic-extra-types - für zusätzliche Typen, mit Pydantic zu verwenden.
+
+Wird von Starlette verwendet:
+
+* httpx - erforderlich, wenn Sie den `TestClient` verwenden möchten.
+* jinja2 - erforderlich, wenn Sie die Standardkonfiguration für Templates verwenden möchten.
+* python-multipart - erforderlich, wenn Sie Formulare mittels `request.form()` „parsen“ möchten.
+* itsdangerous - erforderlich für `SessionMiddleware` Unterstützung.
+* pyyaml - erforderlich für Starlette's `SchemaGenerator` Unterstützung (Sie brauchen das wahrscheinlich nicht mit FastAPI).
+* ujson - erforderlich, wenn Sie `UJSONResponse` verwenden möchten.
+
+Wird von FastAPI / Starlette verwendet:
+
+* uvicorn - für den Server, der Ihre Anwendung lädt und serviert.
+* orjson - 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.
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
-
-
-
-
diff --git a/docs/de/docs/project-generation.md b/docs/de/docs/project-generation.md
new file mode 100644
index 000000000..c47bcb6d3
--- /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: https://github.com/tiangolo/full-stack-fastapi-postgresql
+
+### 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 **FastAPI**-Backend:
+ * **Schnell**: Sehr hohe Leistung, auf Augenhöhe mit **NodeJS** und **Go** (dank Starlette und Pydantic).
+ * **Intuitiv**: Hervorragende Editor-Unterstützung. Codevervollständigung ü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: OpenAPI und JSON Schema.
+ * **Viele weitere Funktionen**, 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: https://github.com/tiangolo/full-stack-fastapi-couchbase
+
+⚠️ **WARNUNG** ⚠️
+
+Wenn Sie ein neues Projekt von Grund auf starten, prüfen Sie die Alternativen hier.
+
+Zum Beispiel könnte der Projektgenerator Full Stack FastAPI PostgreSQL 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: https://github.com/microsoft/cookiecutter-spacy-fastapi
+
+### 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.
diff --git a/docs/de/docs/python-types.md b/docs/de/docs/python-types.md
new file mode 100644
index 000000000..9bbff83d3
--- /dev/null
+++ b/docs/de/docs/python-types.md
@@ -0,0 +1,596 @@
+# 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 Typ 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()`.
+* Verkettet 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:
+
+
+
+### 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:
+
+
+
+Hier können Sie durch die Optionen blättern, bis Sie diejenige finden, bei der es „Klick“ macht:
+
+
+
+## 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:
+
+
+
+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.
+
+//// tab | 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!}
+```
+
+////
+
+//// tab | 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:
+
+
+
+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`:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="1"
+{!> ../../../docs_src/python_types/tutorial007_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="1 4"
+{!> ../../../docs_src/python_types/tutorial007.py!}
+```
+
+////
+
+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`:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="1"
+{!> ../../../docs_src/python_types/tutorial008_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="1 4"
+{!> ../../../docs_src/python_types/tutorial008.py!}
+```
+
+////
+
+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).
+
+#### Union
+
+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 vertikalen Balken (`|`) aufzulisten.
+
+//// tab | Python 3.10+
+
+```Python hl_lines="1"
+{!> ../../../docs_src/python_types/tutorial008b_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="1 4"
+{!> ../../../docs_src/python_types/tutorial008b.py!}
+```
+
+////
+
+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:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="1"
+{!> ../../../docs_src/python_types/tutorial009_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="1 4"
+{!> ../../../docs_src/python_types/tutorial009.py!}
+```
+
+////
+
+//// tab | Python 3.8+ Alternative
+
+```Python hl_lines="1 4"
+{!> ../../../docs_src/python_types/tutorial009b.py!}
+```
+
+////
+
+#### `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.
+
+//// tab | 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 vertikalen Balken (`|`) verwenden, um Vereinigungen von Typen zu deklarieren, das ist besser und einfacher.
+
+////
+
+//// tab | 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.
+
+////
+
+//// tab | 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:
+
+
+
+Beachten Sie, das bedeutet: „`one_person` ist eine **Instanz** der Klasse `Person`“.
+
+Es bedeutet nicht: „`one_person` ist die **Klasse** genannt `Person`“.
+
+## Pydantic Modelle
+
+Pydantic 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:
+
+//// tab | Python 3.10+
+
+```Python
+{!> ../../../docs_src/python_types/tutorial011_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python
+{!> ../../../docs_src/python_types/tutorial011_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python
+{!> ../../../docs_src/python_types/tutorial011.py!}
+```
+
+////
+
+/// info
+
+Um mehr über Pydantic zu erfahren, schauen Sie sich dessen Dokumentation an.
+
+///
+
+**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 Required fields mehr erfahren.
+
+///
+
+## Typhinweise mit Metadaten-Annotationen
+
+Python bietet auch die Möglichkeit, **zusätzliche Metadaten** in Typhinweisen unterzubringen, mittels `Annotated`.
+
+//// 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!}
+```
+
+////
+
+//// tab | 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 der „Cheat Sheet“ von `mypy`.
+
+///
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/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/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/index.md b/docs/de/docs/reference/index.md
deleted file mode 100644
index e9362b962..000000000
--- a/docs/de/docs/reference/index.md
+++ /dev/null
@@ -1,8 +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/request.md b/docs/de/docs/reference/request.md
deleted file mode 100644
index b170c1e40..000000000
--- a/docs/de/docs/reference/request.md
+++ /dev/null
@@ -1,14 +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/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/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/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 ../../../docs_src/background_tasks/tutorial002_an_py310.py!}
- ```
+```Python hl_lines="13 15 22 25"
+{!> ../../../docs_src/background_tasks/tutorial002_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="13 15 22 25"
- {!> ../../../docs_src/background_tasks/tutorial002_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="13 15 22 25"
+{!> ../../../docs_src/background_tasks/tutorial002_an_py39.py!}
+```
- ```Python hl_lines="14 16 23 26"
- {!> ../../../docs_src/background_tasks/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="14 16 23 26"
+{!> ../../../docs_src/background_tasks/tutorial002_an.py!}
+```
- ```Python hl_lines="11 13 20 23"
- {!> ../../../docs_src/background_tasks/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="13 15 22 25"
- {!> ../../../docs_src/background_tasks/tutorial002.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="11 13 20 23"
+{!> ../../../docs_src/background_tasks/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="13 15 22 25"
+{!> ../../../docs_src/background_tasks/tutorial002.py!}
+```
+
+////
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
new file mode 100644
index 000000000..986a99a38
--- /dev/null
+++ b/docs/de/docs/tutorial/bigger-applications.md
@@ -0,0 +1,557 @@
+# 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`.
+
+
+
+## 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.
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!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="11-14"
+{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="12-15"
- {!> ../../../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="12-15"
+{!> ../../../docs_src/body_fields/tutorial001_an.py!}
+```
- ```Python hl_lines="9-12"
- {!> ../../../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="11-14"
- {!> ../../../docs_src/body_fields/tutorial001.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="9-12"
+{!> ../../../docs_src/body_fields/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="11-14"
+{!> ../../../docs_src/body_fields/tutorial001.py!}
+```
+
+////
`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+"
+////
- ```Python hl_lines="18-20"
- {!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="18-20"
+{!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="19-21"
- {!> ../../../docs_src/body_multiple_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="19-21"
+{!> ../../../docs_src/body_multiple_params/tutorial001_an.py!}
+```
- ```Python hl_lines="17-19"
- {!> ../../../docs_src/body_multiple_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="19-21"
- {!> ../../../docs_src/body_multiple_params/tutorial001.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-!!! note "Hinweis"
- Beachten Sie, dass in diesem Fall das `item`, welches vom Body genommen wird, optional ist. Da es `None` als Defaultwert hat.
+///
+
+```Python hl_lines="17-19"
+{!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="19-21"
+{!> ../../../docs_src/body_multiple_params/tutorial001.py!}
+```
+
+////
+
+/// 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!}
- ```
+```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!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="23"
+{!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!}
+```
- ```Python hl_lines="24"
- {!> ../../../docs_src/body_multiple_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="24"
+{!> ../../../docs_src/body_multiple_params/tutorial003_an.py!}
+```
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_multiple_params/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="22"
- {!> ../../../docs_src/body_multiple_params/tutorial003.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="20"
+{!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="22"
+{!> ../../../docs_src/body_multiple_params/tutorial003.py!}
+```
+
+////
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!}
+```
- ```Python hl_lines="28"
- {!> ../../../docs_src/body_multiple_params/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="28"
+{!> ../../../docs_src/body_multiple_params/tutorial004_an.py!}
+```
- ```Python hl_lines="25"
- {!> ../../../docs_src/body_multiple_params/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"
- ```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-!!! info
- `Body` hat die gleichen zusätzlichen Validierungs- und Metadaten-Parameter wie `Query` und `Path` und andere, die Sie später kennenlernen.
+///
+
+```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!}
+```
+
+////
+
+/// 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!}
- ```
+```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!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="17"
+{!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!}
+```
- ```Python hl_lines="18"
- {!> ../../../docs_src/body_multiple_params/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="18"
+{!> ../../../docs_src/body_multiple_params/tutorial005_an.py!}
+```
- ```Python hl_lines="15"
- {!> ../../../docs_src/body_multiple_params/tutorial005_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="17"
- {!> ../../../docs_src/body_multiple_params/tutorial005.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="15"
+{!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="17"
+{!> ../../../docs_src/body_multiple_params/tutorial005.py!}
+```
+
+////
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+"
+////
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```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!}
- ```
+```Python hl_lines="12"
+{!> ../../../docs_src/body_nested_models/tutorial002_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial002_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="14"
+{!> ../../../docs_src/body_nested_models/tutorial002_py39.py!}
+```
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial002.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```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 ../../../docs_src/body_nested_models/tutorial003_py310.py!}
- ```
+```Python hl_lines="12"
+{!> ../../../docs_src/body_nested_models/tutorial003_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial003_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="14"
+{!> ../../../docs_src/body_nested_models/tutorial003_py39.py!}
+```
- ```Python hl_lines="1 14"
- {!> ../../../docs_src/body_nested_models/tutorial003.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```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!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="9-11"
- {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="9-11"
+{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!}
+```
- ```Python hl_lines="9-11"
- {!> ../../../docs_src/body_nested_models/tutorial004.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```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 ../../../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+"
+////
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial006_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="20"
+{!> ../../../docs_src/body_nested_models/tutorial006_py39.py!}
+```
- ```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!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="9 14 20 23 27"
- {!> ../../../docs_src/body_nested_models/tutorial007_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="9 14 20 23 27"
+{!> ../../../docs_src/body_nested_models/tutorial007_py39.py!}
+```
- ```Python hl_lines="9 14 20 23 27"
- {!> ../../../docs_src/body_nested_models/tutorial007.py!}
- ```
+////
-!!! info
- Beachten Sie, wie `Offer` eine Liste von `Item`s hat, von denen jedes seinerseits eine optionale Liste von `Image`s hat.
+//// tab | Python 3.8+
+
+```Python hl_lines="9 14 20 23 27"
+{!> ../../../docs_src/body_nested_models/tutorial007.py!}
+```
+
+////
+
+/// 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+"
+////
- ```Python hl_lines="15"
- {!> ../../../docs_src/body_nested_models/tutorial008.py!}
- ```
+//// tab | Python 3.8+
+
+```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!}
- ```
+```Python hl_lines="7"
+{!> ../../../docs_src/body_nested_models/tutorial009_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/body_nested_models/tutorial009.py!}
- ```
+//// tab | Python 3.8+
-!!! tip "Tipp"
- Bedenken Sie, dass JSON nur `str` als Schlüssel unterstützt.
+```Python hl_lines="9"
+{!> ../../../docs_src/body_nested_models/tutorial009.py!}
+```
- 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.
+/// tip | "Tipp"
- Und das `dict` welches Sie als `weights` erhalten, wird `int`-Schlüssel und `float`-Werte haben.
+Bedenken Sie, dass JSON nur `str` als Schlüssel unterstützt.
+
+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.
+
+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
new file mode 100644
index 000000000..b83554914
--- /dev/null
+++ b/docs/de/docs/tutorial/body-updates.md
@@ -0,0 +1,204 @@
+# Body – Aktualisierungen
+
+## Ersetzendes Aktualisieren mit `PUT`
+
+Um einen Artikel zu aktualisieren, können Sie die HTTP `PUT` 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.
+
+//// tab | Python 3.10+
+
+```Python hl_lines="28-33"
+{!> ../../../docs_src/body_updates/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="30-35"
+{!> ../../../docs_src/body_updates/tutorial001_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="30-35"
+{!> ../../../docs_src/body_updates/tutorial001.py!}
+```
+
+////
+
+`PUT` 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 HTTP `PATCH` 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:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="32"
+{!> ../../../docs_src/body_updates/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="34"
+{!> ../../../docs_src/body_updates/tutorial002_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="34"
+{!> ../../../docs_src/body_updates/tutorial002.py!}
+```
+
+////
+
+### 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)`:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="33"
+{!> ../../../docs_src/body_updates/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="35"
+{!> ../../../docs_src/body_updates/tutorial002_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="35"
+{!> ../../../docs_src/body_updates/tutorial002.py!}
+```
+
+////
+
+### 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.
+
+//// tab | Python 3.10+
+
+```Python hl_lines="28-35"
+{!> ../../../docs_src/body_updates/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="30-37"
+{!> ../../../docs_src/body_updates/tutorial002_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="30-37"
+{!> ../../../docs_src/body_updates/tutorial002.py!}
+```
+
+////
+
+/// tip | "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.
+
+///
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 Pydantic-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!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="4"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```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
-!!! tip "Tipp"
- Wenn Sie PyCharm als Ihren Editor verwenden, probieren Sie das Pydantic PyCharm Plugin aus.
+/// tip | "Tipp"
- Es verbessert die Editor-Unterstützung für Pydantic-Modelle, mit:
+Wenn Sie PyCharm als Ihren Editor verwenden, probieren Sie das Pydantic PyCharm Plugin aus.
- * Code-Vervollständigung
- * Typüberprüfungen
- * Refaktorisierung
- * Suchen
- * Inspektionen
+Es verbessert die Editor-Unterstützung für Pydantic-Modelle, mit:
+
+* 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!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="21"
- {!> ../../../docs_src/body/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+
+```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+"
+////
- ```Python hl_lines="17-18"
- {!> ../../../docs_src/body/tutorial003.py!}
- ```
+//// tab | Python 3.8+
+
+```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+"
+////
- ```Python hl_lines="18"
- {!> ../../../docs_src/body/tutorial004.py!}
- ```
+//// tab | Python 3.8+
+
+```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"
- 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.
+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.
+
+///
## Ohne Pydantic
diff --git a/docs/de/docs/tutorial/cookie-params.md b/docs/de/docs/tutorial/cookie-params.md
new file mode 100644
index 000000000..0060db8e8
--- /dev/null
+++ b/docs/de/docs/tutorial/cookie-params.md
@@ -0,0 +1,135 @@
+# Cookie-Parameter
+
+So wie `Query`- und `Path`-Parameter können Sie auch Cookie-Parameter definieren.
+
+## `Cookie` importieren
+
+Importieren Sie zuerst `Cookie`:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/cookie_params/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | "Tipp"
+
+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
+
+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:
+
+//// 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!}
+```
+
+////
+
+//// tab | 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`.
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..0a9f05bf9
--- /dev/null
+++ b/docs/de/docs/tutorial/dependencies/classes-as-dependencies.md
@@ -0,0 +1,638 @@
+# 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:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="11"
+{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="12"
+{!> ../../../docs_src/dependencies/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="7"
+{!> ../../../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="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:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="11-15"
+{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="11-15"
+{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="12-16"
+{!> ../../../docs_src/dependencies/tutorial002_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```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:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="12"
+{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="12"
+{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="13"
+{!> ../../../docs_src/dependencies/tutorial002_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="10"
+{!> ../../../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="12"
+{!> ../../../docs_src/dependencies/tutorial002.py!}
+```
+
+////
+
+... sie hat die gleichen Parameter wie unsere vorherige `common_parameters`:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="8"
+{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/dependencies/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// 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!}
+```
+
+////
+
+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.
+
+//// tab | Python 3.10+
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="20"
+{!> ../../../docs_src/dependencies/tutorial002_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ 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
+
+/// 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:
+
+//// tab | Python 3.8+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | 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:
+
+//// tab | Python 3.8+
+
+```Python
+commons: Annotated[CommonQueryParams, ...
+```
+
+////
+
+//// tab | 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:
+
+//// tab | Python 3.8+
+
+```Python
+commons: Annotated[Any, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python
+commons = Depends(CommonQueryParams)
+```
+
+////
+
+... wie in:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial003_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial003_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="20"
+{!> ../../../docs_src/dependencies/tutorial003_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// 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
+
+/// 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:
+
+
+
+## Abkürzung
+
+Aber Sie sehen, dass wir hier etwas Codeduplizierung haben, indem wir `CommonQueryParams` zweimal schreiben:
+
+//// tab | Python 3.8+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | 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:
+
+//// tab | Python 3.8+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
+
+... schreiben Sie:
+
+//// tab | Python 3.8+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends()]
+```
+
+////
+
+//// tab | 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:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial004_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial004_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="20"
+{!> ../../../docs_src/dependencies/tutorial004_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="17"
+{!> ../../../docs_src/dependencies/tutorial004_py310.py!}
+```
+
+////
+
+//// tab | 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.
+
+///
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..47d6453c2
--- /dev/null
+++ b/docs/de/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
@@ -0,0 +1,181 @@
+# 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:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="18"
+{!> ../../../docs_src/dependencies/tutorial006_an.py!}
+```
+
+////
+
+//// tab | Python 3.8 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:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="8 13"
+{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="7 12"
+{!> ../../../docs_src/dependencies/tutorial006_an.py!}
+```
+
+////
+
+//// tab | Python 3.8 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:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="10 15"
+{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9 14"
+{!> ../../../docs_src/dependencies/tutorial006_an.py!}
+```
+
+////
+
+//// tab | Python 3.8 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:
+
+//// 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 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.
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..9c2e6dd86
--- /dev/null
+++ b/docs/de/docs/tutorial/dependencies/dependencies-with-yield.md
@@ -0,0 +1,342 @@
+# Abhängigkeiten mit yield
+
+FastAPI unterstützt Abhängigkeiten, die nach Abschluss einige zusätzliche Schritte ausführen.
+
+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:
+
+* `@contextlib.contextmanager` oder
+* `@contextlib.asynccontextmanager`
+
+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:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="6 14 22"
+{!> ../../../docs_src/dependencies/tutorial008_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="5 13 21"
+{!> ../../../docs_src/dependencies/tutorial008_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ 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.
+
+//// tab | Python 3.9+
+
+```Python hl_lines="18-19 26-27"
+{!> ../../../docs_src/dependencies/tutorial008_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="17-18 25-26"
+{!> ../../../docs_src/dependencies/tutorial008_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ 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 Kontextmanager.
+
+**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. 🤓
+
+///
+
+//// 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+ 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 `with` verwenden, um eine Datei auszulesen:
+
+```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 eine Klasse mit zwei Methoden erzeugen: `__enter__()` und `__exit__()`.
+
+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:
+
+* `@contextlib.contextmanager` oder
+* `@contextlib.asynccontextmanager`
+
+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.
+
+///
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..26e631b1c
--- /dev/null
+++ b/docs/de/docs/tutorial/dependencies/global-dependencies.md
@@ -0,0 +1,43 @@
+# 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:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="16"
+{!> ../../../docs_src/dependencies/tutorial012_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="16"
+{!> ../../../docs_src/dependencies/tutorial012_an.py!}
+```
+
+////
+
+//// tab | Python 3.8 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.
diff --git a/docs/de/docs/tutorial/dependencies/index.md b/docs/de/docs/tutorial/dependencies/index.md
new file mode 100644
index 000000000..f7d9ed510
--- /dev/null
+++ b/docs/de/docs/tutorial/dependencies/index.md
@@ -0,0 +1,421 @@
+# Abhängigkeiten
+
+**FastAPI** hat ein sehr mächtiges, aber intuitives **Dependency Injection** 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 („Dependable“)
+
+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*:
+//// tab | Python 3.10+
+
+```Python hl_lines="8-9"
+{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="8-11"
+{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9-12"
+{!> ../../../docs_src/dependencies/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="6-7"
+{!> ../../../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="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
+
+//// tab | Python 3.10+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/dependencies/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="1"
+{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="3"
+{!> ../../../docs_src/dependencies/tutorial001.py!}
+```
+
+////
+
+### Deklarieren der Abhängigkeit im „Dependant“
+
+So wie auch `Body`, `Query`, usw., verwenden Sie `Depends` mit den Parametern Ihrer *Pfadoperation-Funktion*:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="13 18"
+{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="15 20"
+{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="16 21"
+{!> ../../../docs_src/dependencies/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="11 16"
+{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="15 20"
+{!> ../../../docs_src/dependencies/tutorial001.py!}
+```
+
+////
+
+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:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="12 16 21"
+{!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="14 18 23"
+{!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="15 19 24"
+{!> ../../../docs_src/dependencies/tutorial001_02_an.py!}
+```
+
+////
+
+/// 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:
+
+
+
+## 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.
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..12664a8cd
--- /dev/null
+++ b/docs/de/docs/tutorial/dependencies/sub-dependencies.md
@@ -0,0 +1,255 @@
+# 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:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="8-9"
+{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="8-9"
+{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9-10"
+{!> ../../../docs_src/dependencies/tutorial005_an.py!}
+```
+
+////
+
+//// tab | Python 3.10 nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="6-7"
+{!> ../../../docs_src/dependencies/tutorial005_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8 nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="8-9"
+{!> ../../../docs_src/dependencies/tutorial005.py!}
+```
+
+////
+
+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):
+
+//// tab | Python 3.10+
+
+```Python hl_lines="13"
+{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="13"
+{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="14"
+{!> ../../../docs_src/dependencies/tutorial005_an.py!}
+```
+
+////
+
+//// tab | Python 3.10 nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="11"
+{!> ../../../docs_src/dependencies/tutorial005_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8 nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="13"
+{!> ../../../docs_src/dependencies/tutorial005.py!}
+```
+
+////
+
+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:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="23"
+{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="23"
+{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="24"
+{!> ../../../docs_src/dependencies/tutorial005_an.py!}
+```
+
+////
+
+//// tab | Python 3.10 nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial005_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8 nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="22"
+{!> ../../../docs_src/dependencies/tutorial005.py!}
+```
+
+////
+
+/// 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 „Cache“ 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:
+
+//// tab | Python 3.8+
+
+```Python hl_lines="1"
+async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]):
+ return {"fresh_value": fresh_value}
+```
+
+////
+
+//// tab | Python 3.8+ 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.
+
+///
diff --git a/docs/de/docs/tutorial/encoder.md b/docs/de/docs/tutorial/encoder.md
new file mode 100644
index 000000000..38a881b4f
--- /dev/null
+++ b/docs/de/docs/tutorial/encoder.md
@@ -0,0 +1,49 @@
+# 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 ISO-Format 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:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="4 21"
+{!> ../../../docs_src/encoder/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="5 22"
+{!> ../../../docs_src/encoder/tutorial001.py!}
+```
+
+////
+
+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-`json.dumps()` 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.
+
+///
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..334a232a8
--- /dev/null
+++ b/docs/de/docs/tutorial/extra-data-types.md
@@ -0,0 +1,162 @@
+# 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“, Weitere Informationen finden Sie in der Dokumentation.
+* `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: Pydantic data types.
+
+## Beispiel
+
+Hier ist ein Beispiel für eine *Pfadoperation* mit Parametern, die einige der oben genannten Typen verwenden.
+
+//// tab | Python 3.10+
+
+```Python hl_lines="1 3 12-16"
+{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="1 3 12-16"
+{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="1 3 13-17"
+{!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="1 2 11-15"
+{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="1 2 12-16"
+{!> ../../../docs_src/extra_data_types/tutorial001.py!}
+```
+
+////
+
+Beachten Sie, dass die Parameter innerhalb der Funktion ihren natürlichen Datentyp haben und Sie beispielsweise normale Datumsmanipulationen durchführen können, wie zum Beispiel:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="18-19"
+{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="18-19"
+{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="19-20"
+{!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="17-18"
+{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="18-19"
+{!> ../../../docs_src/extra_data_types/tutorial001.py!}
+```
+
+////
diff --git a/docs/de/docs/tutorial/extra-models.md b/docs/de/docs/tutorial/extra-models.md
new file mode 100644
index 000000000..cfd0230eb
--- /dev/null
+++ b/docs/de/docs/tutorial/extra-models.md
@@ -0,0 +1,289 @@
+# 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 gehashtes 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.
+
+//// 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!}
+```
+
+////
+
+/// 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):
+
+//// tab | Python 3.10+
+
+```Python hl_lines="7 13-14 17-18 21-22"
+{!> ../../../docs_src/extra_models/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9 15-16 19-20 23-24"
+{!> ../../../docs_src/extra_models/tutorial002.py!}
+```
+
+////
+
+## `Union`, oder `anyOf`
+
+Sie können deklarieren, dass eine Response eine `Union` mehrerer Typen ist, sprich, einer dieser Typen.
+
+Das wird in OpenAPI mit `anyOf` angezeigt.
+
+Um das zu tun, verwenden Sie Pythons Standard-Typhinweis `typing.Union`:
+
+/// note | "Hinweis"
+
+Listen Sie, wenn Sie eine `Union` definieren, denjenigen Typ zuerst, der am spezifischsten ist, gefolgt von den weniger spezifischen Typen. Im Beispiel oben, in `Union[PlaneItem, CarItem]` also den spezifischeren `PlaneItem` vor dem weniger spezifischen `CarItem`.
+
+///
+
+//// tab | Python 3.10+
+
+```Python hl_lines="1 14-15 18-20 33"
+{!> ../../../docs_src/extra_models/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="1 14-15 18-20 33"
+{!> ../../../docs_src/extra_models/tutorial003.py!}
+```
+
+////
+
+### `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):
+
+//// tab | Python 3.9+
+
+```Python hl_lines="18"
+{!> ../../../docs_src/extra_models/tutorial004_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="1 20"
+{!> ../../../docs_src/extra_models/tutorial004.py!}
+```
+
+////
+
+## 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):
+
+//// tab | Python 3.9+
+
+```Python hl_lines="6"
+{!> ../../../docs_src/extra_models/tutorial005_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="1 8"
+{!> ../../../docs_src/extra_models/tutorial005.py!}
+```
+
+////
+
+## 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.
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
get-Operation 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"
- **FastAPI** erzwingt keine bestimmte Bedeutung.
+Es steht Ihnen frei, jede Operation (HTTP-Methode) so zu verwenden, wie Sie es möchten.
- Die hier aufgeführten Informationen dienen als Leitfaden und sind nicht verbindlich.
+**FastAPI** erzwingt keine bestimmte Bedeutung.
- Wenn Sie beispielsweise GraphQL verwenden, führen Sie normalerweise alle Aktionen nur mit „POST“-Operationen durch.
+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.
+
+///
### 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
new file mode 100644
index 000000000..6ee47948c
--- /dev/null
+++ b/docs/de/docs/tutorial/handling-errors.md
@@ -0,0 +1,271 @@
+# 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 IoT-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-Exception 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 Exceptionhandler hinzufügen, mithilfe derselben Werkzeuge für Exceptions von Starlette.
+
+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 `ValidationError`.
+
+**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 „Internal Server Error“ 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.
diff --git a/docs/de/docs/tutorial/header-params.md b/docs/de/docs/tutorial/header-params.md
new file mode 100644
index 000000000..c8c3a4c57
--- /dev/null
+++ b/docs/de/docs/tutorial/header-params.md
@@ -0,0 +1,305 @@
+# Header-Parameter
+
+So wie `Query`-, `Path`-, und `Cookie`-Parameter können Sie auch Header-Parameter definieren.
+
+## `Header` importieren
+
+Importieren Sie zuerst `Header`:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/header_params/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/header_params/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/header_params/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="1"
+{!> ../../../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="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:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/header_params/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/header_params/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/header_params/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```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!}
+```
+
+////
+
+/// 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`.
+
+//// tab | Python 3.10+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/header_params/tutorial002_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="11"
+{!> ../../../docs_src/header_params/tutorial002_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="12"
+{!> ../../../docs_src/header_params/tutorial002_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="8"
+{!> ../../../docs_src/header_params/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | 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:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/header_params/tutorial003_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/header_params/tutorial003_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/header_params/tutorial003_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/header_params/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | 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!}
+```
+
+////
+
+//// 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!}
+```
+
+////
+
+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.
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
+```
- ```
- pip install "uvicorn[standard]"
- ```
+Installieren Sie auch `uvicorn` als Server:
- Das gleiche gilt für jede der optionalen Abhängigkeiten, die Sie verwenden möchten.
+```
+pip install "uvicorn[standard]"
+```
+
+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
new file mode 100644
index 000000000..3ab56ff3e
--- /dev/null
+++ b/docs/de/docs/tutorial/metadata.md
@@ -0,0 +1,132 @@
+# 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. Verfügbar seit OpenAPI 3.1.0, FastAPI 0.99.0. |
+| `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. contact-Felder| Parameter | Typ | Beschreibung |
|---|---|---|
name | str | Der identifizierende Name der Kontaktperson/Organisation. |
url | str | Die URL, die auf die Kontaktinformationen verweist. MUSS im Format einer URL vorliegen. |
email | str | Die E-Mail-Adresse der Kontaktperson/Organisation. MUSS im Format einer E-Mail-Adresse vorliegen. |
license_info-Felder| Parameter | Typ | Beschreibung |
|---|---|---|
name | str | ERFORDERLICH (wenn eine license_info festgelegt ist). Der für die API verwendete Lizenzname. |
identifier | str | Ein SPDX-Lizenzausdruck für die API. Das Feld identifier und das Feld url schließen sich gegenseitig aus. Verfügbar seit OpenAPI 3.1.0, FastAPI 0.99.0. |
url | str | Eine URL zur Lizenz, die für die API verwendet wird. MUSS im Format einer URL vorliegen. |
+
+## 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:
+
+
+
+### 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!}
+```
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. Verwenden Sie dafür das Präfix 'X-'.
+/// tip | "Tipp"
- 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 Starlette-CORS-Dokumentation dokumentiert ist.
+Beachten Sie, dass benutzerdefinierte proprietäre Header hinzugefügt werden können. Verwenden Sie dafür das Präfix 'X-'.
-!!! note "Technische Details"
- Sie könnten auch `from starlette.requests import Request` verwenden.
+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 Starlette-CORS-Dokumentation dokumentiert ist.
- **FastAPI** bietet es als Komfort für Sie, den Entwickler, an. Aber es stammt direkt von Starlette.
+///
+
+/// 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.
+
+///
### 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
new file mode 100644
index 000000000..03980b7dd
--- /dev/null
+++ b/docs/de/docs/tutorial/path-operation-configuration.md
@@ -0,0 +1,221 @@
+# 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:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="1 15"
+{!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="3 17"
+{!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="3 17"
+{!> ../../../docs_src/path_operation_configuration/tutorial001.py!}
+```
+
+////
+
+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`):
+
+//// tab | Python 3.10+
+
+```Python hl_lines="15 20 25"
+{!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="17 22 27"
+{!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="17 22 27"
+{!> ../../../docs_src/path_operation_configuration/tutorial002.py!}
+```
+
+////
+
+Diese werden zum OpenAPI-Schema hinzugefügt und von den automatischen Dokumentations-Benutzeroberflächen verwendet:
+
+
+
+### 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:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="18-19"
+{!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="20-21"
+{!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="20-21"
+{!> ../../../docs_src/path_operation_configuration/tutorial003.py!}
+```
+
+////
+
+## Beschreibung mittels Docstring
+
+Da Beschreibungen oft mehrere Zeilen lang sind, können Sie die Beschreibung der *Pfadoperation* im Docstring der Funktion deklarieren, und **FastAPI** wird sie daraus auslesen.
+
+Sie können im Docstring Markdown schreiben, es wird korrekt interpretiert und angezeigt (die Einrückung des Docstring beachtend).
+
+//// tab | Python 3.10+
+
+```Python hl_lines="17-25"
+{!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="19-27"
+{!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="19-27"
+{!> ../../../docs_src/path_operation_configuration/tutorial004.py!}
+```
+
+////
+
+In der interaktiven Dokumentation sieht das dann so aus:
+
+
+
+## Beschreibung der Response
+
+Die Response können Sie mit dem Parameter `response_description` beschreiben:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="19"
+{!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!}
+```
+
+////
+
+//// 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!}
+```
+
+////
+
+/// 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.
+
+///
+
+
+
+## Eine *Pfadoperation* deprecaten
+
+Wenn Sie eine *Pfadoperation* als deprecated kennzeichnen möchten, ohne sie zu entfernen, fügen Sie den Parameter `deprecated` hinzu:
+
+```Python hl_lines="16"
+{!../../../docs_src/path_operation_configuration/tutorial006.py!}
+```
+
+Sie wird in der interaktiven Dokumentation gut sichtbar als deprecated markiert werden:
+
+
+
+Vergleichen Sie, wie deprecatete und nicht-deprecatete *Pfadoperationen* aussehen:
+
+
+
+## Zusammenfassung
+
+Sie können auf einfache Weise Metadaten für Ihre *Pfadoperationen* definieren, indem Sie den *Pfadoperation-Dekoratoren* Parameter hinzufügen.
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..3908a0b2d
--- /dev/null
+++ b/docs/de/docs/tutorial/path-params-numeric-validations.md
@@ -0,0 +1,383 @@
+# 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`.
+
+//// tab | Python 3.10+
+
+```Python hl_lines="1 3"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="1 3"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="3-4"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ 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!}
+```
+
+////
+
+//// tab | 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:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="11"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ 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!}
+```
+
+////
+
+//// 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.
+
+///
+
+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:
+
+//// tab | 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.
+
+//// tab | Python 3.9+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!}
+```
+
+////
+
+## 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 Keyword-Argumente (Schlüssel-Wert-Paare), auch bekannt als kwargs, verwendet werden. Selbst wenn diese keinen Defaultwert haben.
+
+```Python hl_lines="7"
+{!../../../docs_src/path_params_numeric_validations/tutorial003.py!}
+```
+
+### 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.
+
+//// tab | Python 3.9+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!}
+```
+
+////
+
+## 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).
+//// tab | Python 3.9+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ 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
+
+//// tab | Python 3.9+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ 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 `float`-Werte.
+
+Hier wird es wichtig, in der Lage zu sein, gt zu deklarieren, und nicht nur ge, 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 lt.
+
+//// tab | Python 3.9+
+
+```Python hl_lines="13"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="12"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ 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.
+
+///
diff --git a/docs/de/docs/tutorial/path-params.md b/docs/de/docs/tutorial/path-params.md
new file mode 100644
index 000000000..2c1b691a8
--- /dev/null
+++ b/docs/de/docs/tutorial/path-params.md
@@ -0,0 +1,278 @@
+# Pfad-Parameter
+
+Sie können Pfad-„Parameter“ oder -„Variablen“ mit der gleichen Syntax deklarieren, welche in Python-Format-Strings verwendet wird:
+
+```Python hl_lines="6-7"
+{!../../../docs_src/path_params/tutorial001.py!}
+```
+
+Der Wert des Pfad-Parameters `item_id` wird Ihrer Funktion als das Argument `item_id` übergeben.
+
+Wenn Sie dieses Beispiel ausführen und auf http://127.0.0.1:8000/items/foo 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-Konversion
+
+Wenn Sie dieses Beispiel ausführen und Ihren Browser unter http://127.0.0.1:8000/items/3 ö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 „parsen“.
+
+///
+
+## Datenvalidierung
+
+Wenn Sie aber im Browser http://127.0.0.1:8000/items/foo 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: http://127.0.0.1:8000/items/4.2
+
+/// 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 http://127.0.0.1:8000/docs in Ihrem Browser öffnen, sehen Sie eine automatische, interaktive API-Dokumentation:
+
+
+
+/// 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 OpenAPI-Standard kommt, gibt es viele kompatible Tools.
+
+Zum Beispiel bietet **FastAPI** selbst eine alternative API-Dokumentation (verwendet ReDoc), welche Sie unter http://127.0.0.1:8000/redoc einsehen können:
+
+
+
+Und viele weitere kompatible Tools. Inklusive Codegenerierung für viele Sprachen.
+
+## Pydantic
+
+Die ganze Datenvalidierung wird hinter den Kulissen von Pydantic 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 `Enum` 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
+
+Enumerationen (oder kurz Enums) gibt es in Python seit Version 3.4.
+
+///
+
+/// tip | "Tipp"
+
+Falls Sie sich fragen, was „AlexNet“, „ResNet“ und „LeNet“ ist, das sind Namen von Modellen 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:
+
+
+
+### Mit Python-*Enums* arbeiten
+
+Der *Pfad-Parameter* wird ein *Member 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 "parsen"
+* 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).
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..ab30fc6cf
--- /dev/null
+++ b/docs/de/docs/tutorial/query-params-str-validations.md
@@ -0,0 +1,1179 @@
+# 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:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial001.py!}
+```
+
+////
+
+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)
+
+//// tab | 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!}
+```
+
+////
+
+//// tab | 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:
+
+//// tab | Python 3.10+
+
+```Python
+q: str | None = None
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python
+q: Union[str, None] = None
+```
+
+////
+
+Wir wrappen das nun in `Annotated`, sodass daraus wird:
+
+//// tab | Python 3.10+
+
+```Python
+q: Annotated[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`.
+
+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`:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!}
+```
+
+////
+
+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 0.95.0) benötigten `Query` als Defaultwert des Parameters, statt es innerhalb von `Annotated` unterzubringen. Die Chance ist groß, dass Sie Quellcode sehen, der das immer noch so macht, darum erkläre ich es Ihnen.
+
+/// tip | "Tipp"
+
+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:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial002.py!}
+```
+
+////
+
+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 Typer. 🚀
+
+## Mehr Validierungen hinzufügen
+
+Sie können auch einen Parameter `min_length` hinzufügen:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial003_an_py310.py!}
+```
+
+////
+
+//// 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+ 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!}
+```
+
+////
+
+//// 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/tutorial003.py!}
+```
+
+////
+
+## Reguläre Ausdrücke hinzufügen
+
+Sie können einen Regulären Ausdruck `pattern` definieren, mit dem der Parameter übereinstimmen muss:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="11"
+{!> ../../../docs_src/query_params_str_validations/tutorial004_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="11"
+{!> ../../../docs_src/query_params_str_validations/tutorial004_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="12"
+{!> ../../../docs_src/query_params_str_validations/tutorial004_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ 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!}
+```
+
+////
+
+//// tab | 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 deprecated.
+
+Sie könnten immer noch Code sehen, der den alten Namen verwendet:
+
+//// tab | Python 3.10+ Pydantic v1
+
+```Python hl_lines="11"
+{!> ../../../docs_src/query_params_str_validations/tutorial004_an_py310_regex.py!}
+```
+
+////
+
+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"`:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial005_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="8"
+{!> ../../../docs_src/query_params_str_validations/tutorial005_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ 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:
+
+//// tab | Annotiert
+
+```Python
+q: Annotated[Union[str, None], Query(min_length=3)] = None
+```
+
+////
+
+//// tab | 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:
+
+//// 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
+
+/// 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 Literal `...` setzen:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="8"
+{!> ../../../docs_src/query_params_str_validations/tutorial006b_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial006b.py!}
+```
+
+////
+
+/// info
+
+Falls Sie das `...` bisher noch nicht gesehen haben: Es ist ein spezieller einzelner Wert, Teil von Python und wird „Ellipsis“ genannt (Deutsch: Ellipse).
+
+Es wird von Pydantic und FastAPI verwendet, um explizit zu deklarieren, dass ein Wert erforderlich ist.
+
+///
+
+Dies wird **FastAPI** wissen lassen, dass dieser Parameter erforderlich ist.
+
+### Erforderlich, kann `None` sein
+
+Sie können deklarieren, dass ein Parameter `None` akzeptiert, aber dennoch erforderlich ist. Das zwingt Clients, den Wert zu senden, selbst wenn er `None` ist.
+
+Um das zu machen, deklarieren Sie, dass `None` ein gültiger Typ ist, aber verwenden Sie dennoch `...` als Default:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial006c_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial006c.py!}
+```
+
+////
+
+/// tip | "Tipp"
+
+Pydantic, welches die gesamte Datenvalidierung und Serialisierung in FastAPI antreibt, hat ein spezielles Verhalten, wenn Sie `Optional` oder `Union[Something, None]` ohne Defaultwert verwenden, Sie können mehr darüber in der Pydantic-Dokumentation unter Required fields erfahren.
+
+///
+
+/// tip | "Tipp"
+
+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:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial011_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial011_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial011_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial011_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial011.py!}
+```
+
+////
+
+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.
+
+
+
+### Query-Parameter-Liste / Mehrere Werte mit Defaults
+
+Und Sie können auch eine Default-`list`e von Werten definieren, wenn keine übergeben werden:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial012_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial012_an.py!}
+```
+
+////
+
+//// tab | Python 3.9+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial012.py!}
+```
+
+////
+
+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+):
+
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial013_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="8"
+{!> ../../../docs_src/query_params_str_validations/tutorial013_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial013.py!}
+```
+
+////
+
+/// 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`:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial007_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial007_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="11"
+{!> ../../../docs_src/query_params_str_validations/tutorial007_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="8"
+{!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial007.py!}
+```
+
+////
+
+Und eine Beschreibung – `description`:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="14"
+{!> ../../../docs_src/query_params_str_validations/tutorial008_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="14"
+{!> ../../../docs_src/query_params_str_validations/tutorial008_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="15"
+{!> ../../../docs_src/query_params_str_validations/tutorial008_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="11"
+{!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="13"
+{!> ../../../docs_src/query_params_str_validations/tutorial008.py!}
+```
+
+////
+
+## 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:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial009_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial009_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial009_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial009.py!}
+```
+
+////
+
+## 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 deprecated ist.
+
+In diesem Fall fügen Sie den Parameter `deprecated=True` zu `Query` hinzu.
+
+//// tab | Python 3.10+
+
+```Python hl_lines="19"
+{!> ../../../docs_src/query_params_str_validations/tutorial010_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="19"
+{!> ../../../docs_src/query_params_str_validations/tutorial010_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="20"
+{!> ../../../docs_src/query_params_str_validations/tutorial010_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="16"
+{!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="18"
+{!> ../../../docs_src/query_params_str_validations/tutorial010.py!}
+```
+
+////
+
+Die Dokumentation wird das so anzeigen:
+
+
+
+## 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`.
+
+//// tab | Python 3.10+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial014_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial014_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="11"
+{!> ../../../docs_src/query_params_str_validations/tutorial014_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="8"
+{!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial014.py!}
+```
+
+////
+
+## 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.
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!}
+```
-=== "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!}
+```
+
+////
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+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params/tutorial003.py!}
- ```
+//// tab | Python 3.8+
+
+```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!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="8 10"
- {!> ../../../docs_src/query_params/tutorial004.py!}
- ```
+//// tab | Python 3.8+
+
+```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
new file mode 100644
index 000000000..cf44df5f0
--- /dev/null
+++ b/docs/de/docs/tutorial/request-files.md
@@ -0,0 +1,418 @@
+# Dateien im Request
+
+Mit `File` können sie vom Client hochzuladende Dateien definieren.
+
+/// info
+
+Um hochgeladene Dateien zu empfangen, installieren Sie zuerst `python-multipart`.
+
+Z. B. `pip install python-multipart`.
+
+Das, weil hochgeladene Dateien als „Formulardaten“ gesendet werden.
+
+///
+
+## `File` importieren
+
+Importieren Sie `File` und `UploadFile` von `fastapi`:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/request_files/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="1"
+{!> ../../../docs_src/request_files/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="1"
+{!> ../../../docs_src/request_files/tutorial001.py!}
+```
+
+////
+
+## `File`-Parameter definieren
+
+Erstellen Sie Datei-Parameter, so wie Sie es auch mit `Body` und `Form` machen würden:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/request_files/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="8"
+{!> ../../../docs_src/request_files/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/request_files/tutorial001.py!}
+```
+
+////
+
+/// 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`:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="14"
+{!> ../../../docs_src/request_files/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="13"
+{!> ../../../docs_src/request_files/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="12"
+{!> ../../../docs_src/request_files/tutorial001.py!}
+```
+
+////
+
+`UploadFile` zu verwenden, hat mehrere Vorzüge gegenüber `bytes`:
+
+* Sie müssen `File()` nicht als Parameter-Defaultwert verwenden.
+* Es wird eine „Spool“-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 file-like `async`hrone Schnittstelle.
+* Es stellt ein tatsächliches Python-`SpooledTemporaryFile`-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 `SpooledTemporaryFile` (ein file-like 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 Threadpool 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 (``) 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 „media type“ `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 MDN-Webdokumentation für POST.
+
+///
+
+/// 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:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="9 17"
+{!> ../../../docs_src/request_files/tutorial001_02_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="9 17"
+{!> ../../../docs_src/request_files/tutorial001_02_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="10 18"
+{!> ../../../docs_src/request_files/tutorial001_02_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="7 15"
+{!> ../../../docs_src/request_files/tutorial001_02_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="9 17"
+{!> ../../../docs_src/request_files/tutorial001_02.py!}
+```
+
+////
+
+## `UploadFile` mit zusätzlichen Metadaten
+
+Sie können auch `File()` zusammen mit `UploadFile` verwenden, um zum Beispiel zusätzliche Metadaten zu setzen:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="9 15"
+{!> ../../../docs_src/request_files/tutorial001_03_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="8 14"
+{!> ../../../docs_src/request_files/tutorial001_03_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="7 13"
+{!> ../../../docs_src/request_files/tutorial001_03.py!}
+```
+
+////
+
+## 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:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="10 15"
+{!> ../../../docs_src/request_files/tutorial002_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="11 16"
+{!> ../../../docs_src/request_files/tutorial002_an.py!}
+```
+
+////
+
+//// tab | Python 3.9+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="8 13"
+{!> ../../../docs_src/request_files/tutorial002_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="10 15"
+{!> ../../../docs_src/request_files/tutorial002.py!}
+```
+
+////
+
+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`:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="11 18-20"
+{!> ../../../docs_src/request_files/tutorial003_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="12 19-21"
+{!> ../../../docs_src/request_files/tutorial003_an.py!}
+```
+
+////
+
+//// tab | Python 3.9+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="9 16"
+{!> ../../../docs_src/request_files/tutorial003_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="11 18"
+{!> ../../../docs_src/request_files/tutorial003.py!}
+```
+
+////
+
+## Zusammenfassung
+
+Verwenden Sie `File`, `bytes` und `UploadFile`, um hochladbare Dateien im Request zu deklarieren, die als Formulardaten gesendet werden.
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..e109595d1
--- /dev/null
+++ b/docs/de/docs/tutorial/request-forms-and-files.md
@@ -0,0 +1,93 @@
+# 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 `python-multipart`.
+
+Z. B. `pip install python-multipart`.
+
+///
+
+## `File` und `Form` importieren
+
+//// tab | Python 3.9+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="1"
+{!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="1"
+{!> ../../../docs_src/request_forms_and_files/tutorial001.py!}
+```
+
+////
+
+## `File` und `Form`-Parameter definieren
+
+Erstellen Sie Datei- und Formularparameter, so wie Sie es auch mit `Body` und `Query` machen würden:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="10-12"
+{!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9-11"
+{!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="8"
+{!> ../../../docs_src/request_forms_and_files/tutorial001.py!}
+```
+
+////
+
+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.
diff --git a/docs/de/docs/tutorial/request-forms.md b/docs/de/docs/tutorial/request-forms.md
new file mode 100644
index 000000000..391788aff
--- /dev/null
+++ b/docs/de/docs/tutorial/request-forms.md
@@ -0,0 +1,125 @@
+# Formulardaten
+
+Wenn Sie Felder aus Formularen statt JSON empfangen müssen, können Sie `Form` verwenden.
+
+/// info
+
+Um Formulare zu verwenden, installieren Sie zuerst `python-multipart`.
+
+Z. B. `pip install python-multipart`.
+
+///
+
+## `Form` importieren
+
+Importieren Sie `Form` von `fastapi`:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/request_forms/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="1"
+{!> ../../../docs_src/request_forms/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="1"
+{!> ../../../docs_src/request_forms/tutorial001.py!}
+```
+
+////
+
+## `Form`-Parameter definieren
+
+Erstellen Sie Formular-Parameter, so wie Sie es auch mit `Body` und `Query` machen würden:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/request_forms/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="8"
+{!> ../../../docs_src/request_forms/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/request_forms/tutorial001.py!}
+```
+
+////
+
+Zum Beispiel stellt eine der Möglichkeiten, die OAuth2 Spezifikation zu verwenden (genannt „password flow“), die Bedingung, einen `username` und ein `password` als Formularfelder zu senden.
+
+Die Spec 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 (``) 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 „media type“ `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 MDN-Webdokumentation für POST.
+
+///
+
+/// 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.
diff --git a/docs/de/docs/tutorial/response-model.md b/docs/de/docs/tutorial/response-model.md
new file mode 100644
index 000000000..b480780bc
--- /dev/null
+++ b/docs/de/docs/tutorial/response-model.md
@@ -0,0 +1,580 @@
+# Responsemodell – Rückgabetyp
+
+Sie können den Typ der Response 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.
+
+//// tab | Python 3.10+
+
+```Python hl_lines="16 21"
+{!> ../../../docs_src/response_model/tutorial001_01_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="18 23"
+{!> ../../../docs_src/response_model/tutorial001_01_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="18 23"
+{!> ../../../docs_src/response_model/tutorial001_01.py!}
+```
+
+////
+
+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 Server-Error 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.
+
+//// tab | Python 3.10+
+
+```Python hl_lines="17 22 24-27"
+{!> ../../../docs_src/response_model/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="17 22 24-27"
+{!> ../../../docs_src/response_model/tutorial001_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="17 22 24-27"
+{!> ../../../docs_src/response_model/tutorial001.py!}
+```
+
+////
+
+/// 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 `Any` 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:
+
+//// 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!}
+```
+
+////
+
+/// info
+
+Um `EmailStr` zu verwenden, installieren Sie zuerst `email-validator`.
+
+Z. B. `pip install email-validator`
+oder `pip install pydantic[email]`.
+
+///
+
+Wir verwenden dieses Modell, um sowohl unsere Eingabe- als auch Ausgabedaten zu deklarieren:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="16"
+{!> ../../../docs_src/response_model/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="18"
+{!> ../../../docs_src/response_model/tutorial002.py!}
+```
+
+////
+
+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:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="9 11 16"
+{!> ../../../docs_src/response_model/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9 11 16"
+{!> ../../../docs_src/response_model/tutorial003.py!}
+```
+
+////
+
+Obwohl unsere *Pfadoperation-Funktion* hier denselben `user` von der Eingabe zurückgibt, der das Passwort enthält:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="24"
+{!> ../../../docs_src/response_model/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="24"
+{!> ../../../docs_src/response_model/tutorial003.py!}
+```
+
+////
+
+... haben wir deklariert, dass `response_model` das Modell `UserOut` ist, welches das Passwort nicht enthält:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="22"
+{!> ../../../docs_src/response_model/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="22"
+{!> ../../../docs_src/response_model/tutorial003.py!}
+```
+
+////
+
+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.
+
+//// tab | Python 3.10+
+
+```Python hl_lines="7-10 13-14 18"
+{!> ../../../docs_src/response_model/tutorial003_01_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9-13 15-16 20"
+{!> ../../../docs_src/response_model/tutorial003_01.py!}
+```
+
+////
+
+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:
+
+
+
+Und beide Modelle werden auch in der interaktiven API-Dokumentation verwendet:
+
+
+
+## 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 Union mehrerer Typen haben, und einer oder mehrere sind nicht gültige Pydantic-Typen. Zum Beispiel funktioniert folgendes nicht 💥:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="8"
+{!> ../../../docs_src/response_model/tutorial003_04_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/response_model/tutorial003_04.py!}
+```
+
+////
+
+... 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:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="7"
+{!> ../../../docs_src/response_model/tutorial003_05_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/response_model/tutorial003_05.py!}
+```
+
+////
+
+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:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="9 11-12"
+{!> ../../../docs_src/response_model/tutorial004_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="11 13-14"
+{!> ../../../docs_src/response_model/tutorial004_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="11 13-14"
+{!> ../../../docs_src/response_model/tutorial004.py!}
+```
+
+////
+
+* `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:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="22"
+{!> ../../../docs_src/response_model/tutorial004_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="24"
+{!> ../../../docs_src/response_model/tutorial004_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="24"
+{!> ../../../docs_src/response_model/tutorial004.py!}
+```
+
+////
+
+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, mit dessen `exclude_unset`-Parameter, um das zu erreichen.
+
+///
+
+/// info
+
+Sie können auch:
+
+* `response_model_exclude_defaults=True`
+* `response_model_exclude_none=True`
+
+verwenden, wie in der Pydantic Dokumentation 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.
+
+///
+
+//// tab | Python 3.10+
+
+```Python hl_lines="29 35"
+{!> ../../../docs_src/response_model/tutorial005_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="31 37"
+{!> ../../../docs_src/response_model/tutorial005.py!}
+```
+
+////
+
+/// 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:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="29 35"
+{!> ../../../docs_src/response_model/tutorial006_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="31 37"
+{!> ../../../docs_src/response_model/tutorial006.py!}
+```
+
+////
+
+## 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.
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..5f96b83e4
--- /dev/null
+++ b/docs/de/docs/tutorial/response-status-code.md
@@ -0,0 +1,107 @@
+# 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 `http.HTTPStatus`.
+
+///
+
+Das wird:
+
+* Diesen Statuscode mit der Response zurücksenden.
+* Ihn als solchen im OpenAPI-Schema dokumentieren (und somit in den Benutzeroberflächen):
+
+
+
+/// 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 MDN Dokumentation über HTTP-Statuscodes.
+
+///
+
+## 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:
+
+
+
+/// 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.
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..07b4bb759
--- /dev/null
+++ b/docs/de/docs/tutorial/schema-extra-example.md
@@ -0,0 +1,408 @@
+# 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.
+
+//// tab | Python 3.10+ Pydantic v2
+
+```Python hl_lines="13-24"
+{!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.10+ Pydantic v1
+
+```Python hl_lines="13-23"
+{!> ../../../docs_src/schema_extra_example/tutorial001_py310_pv1.py!}
+```
+
+////
+
+//// tab | Python 3.8+ Pydantic v2
+
+```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.
+
+//// tab | Pydantic v2
+
+In Pydantic Version 2 würden Sie das Attribut `model_config` verwenden, das ein `dict` akzeptiert, wie beschrieben in Pydantic-Dokumentation: Configuration.
+
+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
+
+In Pydantic Version 1 würden Sie eine interne Klasse `Config` und `schema_extra` verwenden, wie beschrieben in Pydantic-Dokumentation: Schema customization.
+
+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 deprecated 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:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="2 8-11"
+{!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="4 10-13"
+{!> ../../../docs_src/schema_extra_example/tutorial002.py!}
+```
+
+////
+
+## `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:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="22-29"
+{!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="22-29"
+{!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="23-30"
+{!> ../../../docs_src/schema_extra_example/tutorial003_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="18-25"
+{!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="20-27"
+{!> ../../../docs_src/schema_extra_example/tutorial003.py!}
+```
+
+////
+
+### Beispiel in der Dokumentations-Benutzeroberfläche
+
+Mit jeder der oben genannten Methoden würde es in `/docs` so aussehen:
+
+
+
+### `Body` mit mehreren `examples`
+
+Sie können natürlich auch mehrere `examples` übergeben:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="23-38"
+{!> ../../../docs_src/schema_extra_example/tutorial004_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="23-38"
+{!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="24-39"
+{!> ../../../docs_src/schema_extra_example/tutorial004_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="19-34"
+{!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="21-36"
+{!> ../../../docs_src/schema_extra_example/tutorial004.py!}
+```
+
+////
+
+Wenn Sie das tun, werden die Beispiele Teil des internen **JSON-Schemas** für diese Body-Daten.
+
+Während dies geschrieben wird, 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:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="23-49"
+{!> ../../../docs_src/schema_extra_example/tutorial005_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="23-49"
+{!> ../../../docs_src/schema_extra_example/tutorial005_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="24-50"
+{!> ../../../docs_src/schema_extra_example/tutorial005_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="19-45"
+{!> ../../../docs_src/schema_extra_example/tutorial005_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="21-47"
+{!> ../../../docs_src/schema_extra_example/tutorial005.py!}
+```
+
+////
+
+### OpenAPI-Beispiele in der Dokumentations-Benutzeroberfläche
+
+Wenn `openapi_examples` zu `Body()` hinzugefügt wird, würde `/docs` so aussehen:
+
+
+
+## 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:
+
+* `Parameter Object` (in der Spezifikation), das verwendet wurde von FastAPIs:
+ * `Path()`
+ * `Query()`
+ * `Header()`
+ * `Cookie()`
+* `Request Body Object` im Feld `content` des `Media Type Object`s (in der Spezifikation), 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 `examples`-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. 😎
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..6bc42cf6c
--- /dev/null
+++ b/docs/de/docs/tutorial/security/first-steps.md
@@ -0,0 +1,281 @@
+# 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`:
+
+//// tab | Python 3.9+
+
+```Python
+{!> ../../../docs_src/security/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python
+{!> ../../../docs_src/security/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python
+{!> ../../../docs_src/security/tutorial001.py!}
+```
+
+////
+
+## Ausführen
+
+/// info
+
+Um hochgeladene Dateien zu empfangen, installieren Sie zuerst `python-multipart`.
+
+Z. B. `pip install python-multipart`.
+
+Das, weil **OAuth2** „Formulardaten“ zum Senden von `username` und `password` verwendet.
+
+///
+
+Führen Sie das Beispiel aus mit:
+
+
+
+/// 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):
+
+
+
+/// 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.
+
+//// tab | Python 3.9+
+
+```Python hl_lines="8"
+{!> ../../../docs_src/security/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="7"
+{!> ../../../docs_src/security/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="6"
+{!> ../../../docs_src/security/tutorial001.py!}
+```
+
+////
+
+/// 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.
+
+//// tab | Python 3.9+
+
+```Python hl_lines="12"
+{!> ../../../docs_src/security/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="11"
+{!> ../../../docs_src/security/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="10"
+{!> ../../../docs_src/security/tutorial001.py!}
+```
+
+////
+
+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:
+
+
+
+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.
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..8a68deeef
--- /dev/null
+++ b/docs/de/docs/tutorial/security/get-current-user.md
@@ -0,0 +1,383 @@
+# 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:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="12"
+{!> ../../../docs_src/security/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="11"
+{!> ../../../docs_src/security/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="10"
+{!> ../../../docs_src/security/tutorial001.py!}
+```
+
+////
+
+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:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="5 12-16"
+{!> ../../../docs_src/security/tutorial002_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="5 12-16"
+{!> ../../../docs_src/security/tutorial002_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="5 13-17"
+{!> ../../../docs_src/security/tutorial002_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="3 10-14"
+{!> ../../../docs_src/security/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="5 12-16"
+{!> ../../../docs_src/security/tutorial002.py!}
+```
+
+////
+
+## 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`:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="25"
+{!> ../../../docs_src/security/tutorial002_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="25"
+{!> ../../../docs_src/security/tutorial002_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="26"
+{!> ../../../docs_src/security/tutorial002_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="23"
+{!> ../../../docs_src/security/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="25"
+{!> ../../../docs_src/security/tutorial002.py!}
+```
+
+////
+
+## Den Benutzer holen
+
+`get_current_user` wird eine von uns erstellte (gefakte) Hilfsfunktion verwenden, welche einen Token vom Typ `str` entgegennimmt und unser Pydantic-`User`-Modell zurückgibt:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="19-22 26-27"
+{!> ../../../docs_src/security/tutorial002_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="19-22 26-27"
+{!> ../../../docs_src/security/tutorial002_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="20-23 27-28"
+{!> ../../../docs_src/security/tutorial002_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="17-20 24-25"
+{!> ../../../docs_src/security/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="19-22 26-27"
+{!> ../../../docs_src/security/tutorial002.py!}
+```
+
+////
+
+## Den aktuellen Benutzer einfügen
+
+Und jetzt können wir wiederum `Depends` mit unserem `get_current_user` in der *Pfadoperation* verwenden:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="31"
+{!> ../../../docs_src/security/tutorial002_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="31"
+{!> ../../../docs_src/security/tutorial002_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="32"
+{!> ../../../docs_src/security/tutorial002_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="29"
+{!> ../../../docs_src/security/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="31"
+{!> ../../../docs_src/security/tutorial002.py!}
+```
+
+////
+
+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:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="30-32"
+{!> ../../../docs_src/security/tutorial002_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="30-32"
+{!> ../../../docs_src/security/tutorial002_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="31-33"
+{!> ../../../docs_src/security/tutorial002_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="28-30"
+{!> ../../../docs_src/security/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="30-32"
+{!> ../../../docs_src/security/tutorial002.py!}
+```
+
+////
+
+## 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.
diff --git a/docs/de/docs/tutorial/security/index.md b/docs/de/docs/tutorial/security/index.md
new file mode 100644
index 000000000..ad0927361
--- /dev/null
+++ b/docs/de/docs/tutorial/security/index.md
@@ -0,0 +1,106 @@
+# 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.
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..88f0dbe42
--- /dev/null
+++ b/docs/de/docs/tutorial/security/oauth2-jwt.md
@@ -0,0 +1,475 @@
+# 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 JWT-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 https://jwt.io an.
+
+## `python-jose` installieren.
+
+Wir müssen `python-jose` installieren, um die JWT-Tokens in Python zu generieren und zu verifizieren:
+
+
+
+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.
+
+///
+
+
+
+Rufen Sie den Endpunkt `/users/me/` auf, Sie erhalten die Response:
+
+```JSON
+{
+ "username": "johndoe",
+ "email": "johndoe@example.com",
+ "full_name": "John Doe",
+ "disabled": false
+}
+```
+
+
+
+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:
+
+
+
+/// note | "Hinweis"
+
+Beachten Sie den Header `Authorization` mit einem Wert, der mit `Bearer` beginnt.
+
+///
+
+## Fortgeschrittene Verwendung mit `scopes`
+
+OAuth2 hat ein Konzept von „Scopes“.
+
+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.
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..3b1c4ae28
--- /dev/null
+++ b/docs/de/docs/tutorial/security/simple-oauth2.md
@@ -0,0 +1,539 @@
+# 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).
+
+### `scope`
+
+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`:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="4 78"
+{!> ../../../docs_src/security/tutorial003_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="4 78"
+{!> ../../../docs_src/security/tutorial003_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="4 79"
+{!> ../../../docs_src/security/tutorial003_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="2 74"
+{!> ../../../docs_src/security/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="4 76"
+{!> ../../../docs_src/security/tutorial003.py!}
+```
+
+////
+
+`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`:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="3 79-81"
+{!> ../../../docs_src/security/tutorial003_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="3 79-81"
+{!> ../../../docs_src/security/tutorial003_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="3 80-82"
+{!> ../../../docs_src/security/tutorial003_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="1 75-77"
+{!> ../../../docs_src/security/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="3 77-79"
+{!> ../../../docs_src/security/tutorial003.py!}
+```
+
+////
+
+### 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).
+
+//// tab | Python 3.10+
+
+```Python hl_lines="82-85"
+{!> ../../../docs_src/security/tutorial003_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="82-85"
+{!> ../../../docs_src/security/tutorial003_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="83-86"
+{!> ../../../docs_src/security/tutorial003_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="78-81"
+{!> ../../../docs_src/security/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="80-83"
+{!> ../../../docs_src/security/tutorial003.py!}
+```
+
+////
+
+#### Ü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 JWT-Tokens.
+
+Aber konzentrieren wir uns zunächst auf die spezifischen Details, die wir benötigen.
+
+///
+
+//// tab | Python 3.10+
+
+```Python hl_lines="87"
+{!> ../../../docs_src/security/tutorial003_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="87"
+{!> ../../../docs_src/security/tutorial003_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="88"
+{!> ../../../docs_src/security/tutorial003_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="83"
+{!> ../../../docs_src/security/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="85"
+{!> ../../../docs_src/security/tutorial003.py!}
+```
+
+////
+
+/// 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:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="58-66 69-74 94"
+{!> ../../../docs_src/security/tutorial003_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="58-66 69-74 94"
+{!> ../../../docs_src/security/tutorial003_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="59-67 70-75 95"
+{!> ../../../docs_src/security/tutorial003_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="56-64 67-70 88"
+{!> ../../../docs_src/security/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="58-66 69-72 90"
+{!> ../../../docs_src/security/tutorial003.py!}
+```
+
+////
+
+/// 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: http://127.0.0.1:8000/docs.
+
+### Authentifizieren
+
+Klicken Sie auf den Button „Authorize“.
+
+Verwenden Sie die Anmeldedaten:
+
+Benutzer: `johndoe`
+
+Passwort: `secret`.
+
+
+
+Nach der Authentifizierung im System sehen Sie Folgendes:
+
+
+
+### 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"
+}
+```
+
+
+
+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 JWT-Token verwenden.
diff --git a/docs/de/docs/tutorial/static-files.md b/docs/de/docs/tutorial/static-files.md
new file mode 100644
index 000000000..cca8cd0ea
--- /dev/null
+++ b/docs/de/docs/tutorial/static-files.md
@@ -0,0 +1,42 @@
+# 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 Dokumentation von Starlette zu statischen Dateien.
diff --git a/docs/de/docs/tutorial/testing.md b/docs/de/docs/tutorial/testing.md
new file mode 100644
index 000000000..43ced2aae
--- /dev/null
+++ b/docs/de/docs/tutorial/testing.md
@@ -0,0 +1,243 @@
+# Testen
+
+Dank Starlette ist das Testen von **FastAPI**-Anwendungen einfach und macht Spaß.
+
+Es basiert auf HTTPX, welches wiederum auf der Grundlage von requests konzipiert wurde, es ist also sehr vertraut und intuitiv.
+
+Damit können Sie pytest direkt mit **FastAPI** verwenden.
+
+## Verwendung von `TestClient`
+
+/// info
+
+Um `TestClient` zu verwenden, installieren Sie zunächst `httpx`.
+
+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.
+
+//// tab | Python 3.10+
+
+```Python
+{!> ../../../docs_src/app_testing/app_b_an_py310/main.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python
+{!> ../../../docs_src/app_testing/app_b_an_py39/main.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python
+{!> ../../../docs_src/app_testing/app_b_an/main.py!}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```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
+
+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 HTTPX-Dokumentation.
+
+/// 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:
+
+
-
-## 🌅 ℹ
-
-👆 💪 ✍ 🌅 🔃 `encode/databases` 🚮 📂 📃.
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` 🕐❔ 🛠️ 🔁 🔢 🤙 👆 💯 (✅ 🕐❔ ⚙️ ✳ MotorClient) 💭 🔗 🎚 👈 💪 🎉 ➰ 🕴 🏞 🔁 🔢, ✅ `'@app.on_event("startup")` ⏲.
+/// tip
+
+🚥 👆 ⚔ `RuntimeError: Task attached to a different loop` 🕐❔ 🛠️ 🔁 🔢 🤙 👆 💯 (✅ 🕐❔ ⚙️ ✳ MotorClient) 💭 🔗 🎚 👈 💪 🎉 ➰ 🕴 🏞 🔁 🔢, ✅ `'@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 12afe638c..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, ✅ ➡ 🔡: http://127.0.0.1:9999/api/v1/app.
@@ -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`.
+
+///
🩺 🎚 http://127.0.0.1:9999/api/v1/docs ⚫️ 🔜 👀 💖:
-!!! tip
- 🩺 🎚 🔜 🔗 ⏮️ 💽 👈 👆 🖊.
+/// tip
+
+🩺 🎚 🔜 🔗 ⏮️ 💽 👈 👆 🖊.
+
+///
### ❎ 🏧 💽 ⚪️➡️ `root_path`
@@ -341,6 +362,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/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
- 👉 💼, 🇺🇸🔍 🎚 `Content-Type` 🔜 ⚒ `application/json`.
+🔢 `response_class` 🔜 ⚙️ 🔬 "📻 🆎" 📨.
- & ⚫️ 🔜 📄 ✅ 🗄.
+👉 💼, 🇺🇸🔍 🎚 `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
-!!! info
- ↗️, ☑ `Content-Type` 🎚, 👔 📟, ♒️, 🔜 👟 ⚪️➡️ `Response` 🎚 👆 📨.
+`Response` 📨 🔗 👆 *➡ 🛠️ 🔢* 🏆 🚫 📄 🗄 (🖼, `Content-Type` 🏆 🚫 📄) & 🏆 🚫 ⭐ 🏧 🎓 🩺.
+
+///
+
+/// info
+
+↗️, ☑ `Content-Type` 🎚, 👔 📟, ♒️, 🔜 👟 ⚪️➡️ `Response` 🎚 👆 📨.
+
+///
### 📄 🗄 & 🔐 `Response`
@@ -103,10 +121,13 @@
✔️ 🤯 👈 👆 💪 ⚙️ `Response` 📨 🕳 🙆, ⚖️ ✍ 🛃 🎧-🎓.
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette.responses import HTMLResponse`.
+/// note | "📡 ℹ"
- **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃.
+👆 💪 ⚙️ `from starlette.responses import HTMLResponse`.
+
+**FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃.
+
+///
### `Response`
@@ -153,15 +174,21 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎
🎛 🎻 📨 ⚙️ `ujson`.
-!!! 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 671e81b18..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
-!!! tip
- 👀 👈 👉 💼 👥 ⚙️ 🐩 🐍 `open()` 🔢 👈 🔗 ⏮️ 📁.
+`open()` 🔢, `mode="a"` ⛓ "🎻",, ⏸ 🔜 🚮 ⏮️ ⚫️❔ 🔛 👈 📁, 🍵 📁 ⏮️ 🎚.
- , ⚫️ 🔌 👤/🅾 (🔢/🔢), 👈 🚚 "⌛" 👜 ✍ 💾.
+///
- ✋️ `open()` 🚫 ⚙️ `async` & `await`.
+/// tip
- , 👥 📣 🎉 🐕🦺 🔢 ⏮️ 🐩 `def` ↩️ `async def`.
+👀 👈 👉 💼 👥 ⚙️ 🐩 🐍 `open()` 🔢 👈 🔗 ⏮️ 📁.
-!!! info
- 👆 💪 ✍ 🌅 🔃 👫 🎉 🐕🦺 💃 🎉' 🩺.
+, ⚫️ 🔌 👤/🅾 (🔢/🔢), 👈 🚚 "⌛" 👜 ✍ 💾.
+
+✋️ `open()` 🚫 ⚙️ `async` & `await`.
+
+, 👥 📣 🎉 🐕🦺 🔢 ⏮️ 🐩 `def` ↩️ `async def`.
+
+///
+
+/// info
+
+👆 💪 ✍ 🌅 🔃 👫 🎉 🐕🦺 💃 🎉' 🩺.
+
+///
### `startup` & `shutdown` 👯♂️
@@ -157,4 +172,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/generate-clients.md b/docs/em/docs/advanced/generate-clients.md
index 30560c8c6..c8e044340 100644
--- a/docs/em/docs/advanced/generate-clients.md
+++ b/docs/em/docs/advanced/generate-clients.md
@@ -10,23 +10,27 @@
⚠ 🧰 🗄 🚂.
-🚥 👆 🏗 **🕸**, 📶 😌 🎛 🗄-📕-🇦🇪.
+🚥 👆 🏗 **🕸**, 📶 😌 🎛 🗄-📕-🇦🇪.
## 🏗 📕 🕸 👩💻
➡️ ▶️ ⏮️ 🙅 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️⃣ & 🔛"
+////
- ```Python hl_lines="7-9 12-13 16-17 21"
- {!> ../../../docs_src/generate_clients/tutorial001_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
+
+```Python hl_lines="7-9 12-13 16-17 21"
+{!> ../../../docs_src/generate_clients/tutorial001_py39.py!}
+```
+
+////
👀 👈 *➡ 🛠️* 🔬 🏷 👫 ⚙️ 📨 🚀 & 📨 🚀, ⚙️ 🏷 `Item` & `ResponseMessage`.
@@ -46,14 +50,14 @@
🔜 👈 👥 ✔️ 📱 ⏮️ 🏷, 👥 💪 🏗 👩💻 📟 🕸.
-#### ❎ `openapi-typescript-codegen`
+#### ❎ `openapi-ts`
-👆 💪 ❎ `openapi-typescript-codegen` 👆 🕸 📟 ⏮️:
+👆 💪 ❎ `openapi-ts` 👆 🕸 📟 ⏮️:
-!!! 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!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="21 26 34"
- {!> ../../../docs_src/generate_clients/tutorial002_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
+
+```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️⃣ & 🔛"
+////
- ```Python hl_lines="6-7 10"
- {!> ../../../docs_src/generate_clients/tutorial003_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
+
+```Python hl_lines="6-7 10"
+{!> ../../../docs_src/generate_clients/tutorial003_py39.py!}
+```
+
+////
### 🏗 📕 👩💻 ⏮️ 🛃 🛠️ 🆔
@@ -235,12 +250,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/em/docs/advanced/index.md b/docs/em/docs/advanced/index.md
index abe8d357c..48ef8e46d 100644
--- a/docs/em/docs/advanced/index.md
+++ b/docs/em/docs/advanced/index.md
@@ -2,18 +2,21 @@
## 🌖 ⚒
-👑 [🔰 - 👩💻 🦮](../tutorial/){.internal-link target=_blank} 🔜 🥃 🤝 👆 🎫 🔘 🌐 👑 ⚒ **FastAPI**.
+👑 [🔰 - 👩💻 🦮](../tutorial/index.md){.internal-link target=_blank} 🔜 🥃 🤝 👆 🎫 🔘 🌐 👑 ⚒ **FastAPI**.
⏭ 📄 👆 🔜 👀 🎏 🎛, 📳, & 🌖 ⚒.
-!!! tip
- ⏭ 📄 **🚫 🎯 "🏧"**.
+/// tip
- & ⚫️ 💪 👈 👆 ⚙️ 💼, ⚗ 1️⃣ 👫.
+⏭ 📄 **🚫 🎯 "🏧"**.
+
+ & ⚫️ 💪 👈 👆 ⚙️ 💼, ⚗ 1️⃣ 👫.
+
+///
## ✍ 🔰 🥇
-👆 💪 ⚙️ 🏆 ⚒ **FastAPI** ⏮️ 💡 ⚪️➡️ 👑 [🔰 - 👩💻 🦮](../tutorial/){.internal-link target=_blank}.
+👆 💪 ⚙️ 🏆 ⚒ **FastAPI** ⏮️ 💡 ⚪️➡️ 👑 [🔰 - 👩💻 🦮](../tutorial/index.md){.internal-link target=_blank}.
& ⏭ 📄 🤔 👆 ⏪ ✍ ⚫️, & 🤔 👈 👆 💭 👈 👑 💭.
diff --git a/docs/em/docs/advanced/middleware.md b/docs/em/docs/advanced/middleware.md
index b3e722ed0..e3cc389c6 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`
@@ -92,7 +95,6 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow")
🖼:
-* 🔫
* Uvicorn `ProxyHeadersMiddleware`
* 🇸🇲
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** 💪 🛠️ ⏮️ 🙆 ☁.
-
-📥 👥 🔜 👀 🖼 ⚙️ **🗄**, 📄 🧢 ☁ 💽.
-
-👆 💪 🛠️ ⚫️ 🙆 🎏 ☁ 💽 💖:
-
-* **✳**
-* **👸**
-* **✳**
-* **🇸🇲**
-* **✳**, ♒️.
-
-!!! tip
- 📤 🛂 🏗 🚂 ⏮️ **FastAPI** & **🗄**, 🌐 ⚓️ 🔛 **☁**, 🔌 🕸 & 🌖 🧰: https://github.com/tiangolo/full-stack-fastapi-couchbase
-
-## 🗄 🗄 🦲
-
-🔜, 🚫 💸 🙋 🎂, 🕴 🗄:
-
-```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` (⚖️ 🙆 🎏 🔢) 🔬 👆 *➡ 🛠️ 🔢*, 👆 💪 🌖 💪 🏤-⚙️ ⚫️ 💗 🍕 & 🚮 ⚒ 💯 ⚫️:
-
-```Python hl_lines="36-42"
-{!../../../docs_src/nosql_databases/tutorial001.py!}
-```
-
-### Ⓜ-🎻
-
-🚥 👆 🚫 😰 ⏮️ `f"userprofile::{username}"`, ⚫️ 🐍 "Ⓜ-🎻".
-
-🙆 🔢 👈 🚮 🔘 `{}` Ⓜ-🎻 🔜 ↔ / 💉 🎻.
-
-### `dict` 🏗
-
-🚥 👆 🚫 😰 ⏮️ `UserInDB(**result.value)`, ⚫️ ⚙️ `dict` "🏗".
-
-⚫️ 🔜 ✊ `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!}
-```
-
-### ✍ *➡ 🛠️ 🔢*
-
-👆 📟 🤙 🗄 & 👥 🚫 ⚙️ 🥼 🐍 await 🐕🦺, 👥 🔜 📣 👆 🔢 ⏮️ 😐 `def` ↩️ `async def`.
-
-, 🗄 👍 🚫 ⚙️ 👁 `Bucket` 🎚 💗 "🧵Ⓜ",, 👥 💪 🤚 🥡 🔗 & 🚶♀️ ⚫️ 👆 🚙 🔢:
-
-```Python hl_lines="49-53"
-{!../../../docs_src/nosql_databases/tutorial001.py!}
-```
-
-## 🌃
-
-👆 💪 🛠️ 🙆 🥉 🥳 ☁ 💽, ⚙️ 👫 🐩 📦.
-
-🎏 ✔ 🙆 🎏 🔢 🧰, ⚙️ ⚖️ 🛠️.
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 📛 🆎.
+/// tip
+
+`callback_url` 🔢 🔢 ⚙️ Pydantic 📛 🆎.
+
+///
🕴 🆕 👜 `callbacks=messages_callback_router.routes` ❌ *➡ 🛠️ 👨🎨*. 👥 🔜 👀 ⚫️❔ 👈 ⏭.
@@ -61,10 +64,13 @@ httpx.post(callback_url, json={"description": "Invoice paid", "paid": True})
👉 🖼 🚫 🛠️ ⏲ ⚫️ (👈 💪 ⏸ 📟), 🕴 🧾 🍕.
-!!! tip
- ☑ ⏲ 🇺🇸🔍 📨.
+/// tip
- 🕐❔ 🛠️ ⏲ 👆, 👆 💪 ⚙️ 🕳 💖 🇸🇲 ⚖️ 📨.
+☑ ⏲ 🇺🇸🔍 📨.
+
+🕐❔ 🛠️ ⏲ 👆, 👆 💪 ⚙️ 🕳 💖 🇸🇲 ⚖️ 📨.
+
+///
## ✍ ⏲ 🧾 📟
@@ -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 ec7231870..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
-!!! warning
- 🚥 👆 👉, 👆 ✔️ ⚒ 💭 🔠 1️⃣ 👆 *➡ 🛠️ 🔢* ✔️ 😍 📛.
+🚥 👆 ❎ 🤙 `app.openapi()`, 👆 🔜 ℹ `operationId`Ⓜ ⏭ 👈.
- 🚥 👫 🎏 🕹 (🐍 📁).
+///
+
+/// warning
+
+🚥 👆 👉, 👆 ✔️ ⚒ 💭 🔠 1️⃣ 👆 *➡ 🛠️ 🔢* ✔️ 😍 📛.
+
+🚥 👫 🎏 🕹 (🐍 📁).
+
+///
## 🚫 ⚪️➡️ 🗄
@@ -59,14 +68,17 @@
👆 💪 📣 🌖 📨 ⏮️ 👫 🏷, 👔 📟, ♒️.
-📤 🎂 📃 📥 🧾 🔃 ⚫️, 👆 💪 ✍ ⚫️ [🌖 📨 🗄](./additional-responses.md){.internal-link target=_blank}.
+📤 🎂 📃 📥 🧾 🔃 ⚫️, 👆 💪 ✍ ⚫️ [🌖 📨 🗄](additional-responses.md){.internal-link target=_blank}.
## 🗄 ➕
🕐❔ 👆 📣 *➡ 🛠️* 👆 🈸, **FastAPI** 🔁 🏗 🔗 🗃 🔃 👈 *➡ 🛠️* 🔌 🗄 🔗.
-!!! note "📡 ℹ"
- 🗄 🔧 ⚫️ 🤙 🛠️ 🎚.
+/// note | "📡 ℹ"
+
+🗄 🔧 ⚫️ 🤙 🛠️ 🎚.
+
+///
⚫️ ✔️ 🌐 ℹ 🔃 *➡ 🛠️* & ⚙️ 🏗 🏧 🧾.
@@ -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 | "📡 ℹ"
- **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/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 | "📡 ℹ"
- **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃.
+👆 💪 ⚙️ `from starlette.responses import JSONResponse`.
+
+**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 f2bb66df4..5cdc47505 100644
--- a/docs/em/docs/advanced/security/index.md
+++ b/docs/em/docs/advanced/security/index.md
@@ -2,15 +2,18 @@
## 🌖 ⚒
-📤 ➕ ⚒ 🍵 💂♂ ↖️ ⚪️➡️ 🕐 📔 [🔰 - 👩💻 🦮: 💂♂](../../tutorial/security/){.internal-link target=_blank}.
+📤 ➕ ⚒ 🍵 💂♂ ↖️ ⚪️➡️ 🕐 📔 [🔰 - 👩💻 🦮: 💂♂](../../tutorial/security/index.md){.internal-link target=_blank}.
-!!! tip
- ⏭ 📄 **🚫 🎯 "🏧"**.
+/// tip
- & ⚫️ 💪 👈 👆 ⚙️ 💼, ⚗ 1️⃣ 👫.
+⏭ 📄 **🚫 🎯 "🏧"**.
+
+ & ⚫️ 💪 👈 👆 ⚙️ 💼, ⚗ 1️⃣ 👫.
+
+///
## ✍ 🔰 🥇
-⏭ 📄 🤔 👆 ⏪ ✍ 👑 [🔰 - 👩💻 🦮: 💂♂](../../tutorial/security/){.internal-link target=_blank}.
+⏭ 📄 🤔 👆 ⏪ ✍ 👑 [🔰 - 👩💻 🦮: 💂♂](../../tutorial/security/index.md){.internal-link target=_blank}.
👫 🌐 ⚓️ 🔛 🎏 🔧, ✋️ ✔ ➕ 🛠️.
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`, **FastAPI** 🔜 💭 👈 ⚫️ 💪 📣 💂♂ ↔, ⚙️ 👫 🔘, & 📄 🛠️ ⏮️ 🗄.
+`Security` 🤙 🏿 `Depends`, & ⚫️ ✔️ 1️⃣ ➕ 🔢 👈 👥 🔜 👀 ⏪.
- ✋️ 🕐❔ 👆 🗄 `Query`, `Path`, `Depends`, `Security` & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓.
+✋️ ⚙️ `Security` ↩️ `Depends`, **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
- 🌐 ⚓️ 🔛 `scopes` 📣 🔠 *➡ 🛠️* & 🔠 🔗 🔗 🌲 👈 🎯 *➡ 🛠️*.
+⚠ & "🎱" 👜 📥 👈 `get_current_user` 🔜 ✔️ 🎏 📇 `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
+
+🚥 👆 ⏪ 💭 ⚫️❔ "🌐 🔢" & ❔ ⚙️ 👫, 💭 🆓 🚶 ⏭ 📄 🔛.
+
+///
🌐 🔢 (💭 "🇨🇻 {") 🔢 👈 🖖 🏞 🐍 📟, 🏃♂ ⚙️, & 💪 ✍ 👆 🐍 📟 (⚖️ 🎏 📋 👍).
👆 💪 ✍ & ⚙️ 🌐 🔢 🐚, 🍵 💆♂ 🐍:
-=== "💾, 🇸🇻, 🚪 🎉"
+//// tab | 💾, 🇸🇻, 🚪 🎉
-
-!!! info
- 🌹 🖼 👯 🍏. 👶
+/// info
+
+🌹 🖼 👯 🍏. 👶
+
+///
---
@@ -199,8 +205,11 @@ def results():
📤 🚫 🌅 💬 ⚖️ 😏 🌅 🕰 💸 ⌛ 👶 🚪 ⏲. 👶
-!!! info
- 🌹 🖼 👯 🍏. 👶
+/// info
+
+🌹 🖼 👯 🍏. 👶
+
+///
---
@@ -392,12 +401,15 @@ async def read_burgers():
## 📶 📡 ℹ
-!!! warning
- 👆 💪 🎲 🚶 👉.
+/// warning
- 👉 📶 📡 ℹ ❔ **FastAPI** 👷 🔘.
+👆 💪 🎲 🚶 👉.
- 🚥 👆 ✔️ 📡 💡 (🈶-🏋, 🧵, 🍫, ♒️.) & 😟 🔃 ❔ FastAPI 🍵 `async def` 🆚 😐 `def`, 🚶 ⤴️.
+👉 📶 📡 ℹ ❔ **FastAPI** 👷 🔘.
+
+🚥 👆 ✔️ 📡 💡 (🈶-🏋, 🧵, 🍫, ♒️.) & 😟 🔃 ❔ FastAPI 🍵 `async def` 🆚 😐 `def`, 🚶 ⤴️.
+
+///
### ➡ 🛠️ 🔢
@@ -405,15 +417,15 @@ async def read_burgers():
🚥 👆 👟 ⚪️➡️ ➕1️⃣ 🔁 🛠️ 👈 🔨 🚫 👷 🌌 🔬 🔛 & 👆 ⚙️ ⚖ 🙃 📊-🕴 *➡ 🛠️ 🔢* ⏮️ ✅ `def` 🤪 🎭 📈 (🔃 1️⃣0️⃣0️⃣ 💓), 🙏 🗒 👈 **FastAPI** ⭐ 🔜 🔄. 👫 💼, ⚫️ 👻 ⚙️ `async def` 🚥 👆 *➡ 🛠️ 🔢* ⚙️ 📟 👈 🎭 🚧 👤/🅾.
-, 👯♂️ ⚠, 🤞 👈 **FastAPI** 🔜 [⏩](/#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 +439,4 @@ async def read_burgers():
🔄, 👉 📶 📡 ℹ 👈 🔜 🎲 ⚠ 🚥 👆 👟 🔎 👫.
-⏪, 👆 🔜 👍 ⏮️ 📄 ⚪️➡️ 📄 🔛: 🏃 ❓.
+⏪, 👆 🔜 👍 ⏮️ 📄 ⚪️➡️ 📄 🔛: 🏃 ❓.
diff --git a/docs/em/docs/contributing.md b/docs/em/docs/contributing.md
index 748928f88..3ac1afda4 100644
--- a/docs/em/docs/contributing.md
+++ b/docs/em/docs/contributing.md
@@ -24,63 +24,73 @@ $ python -m venv env
🔓 🆕 🌐 ⏮️:
-=== "💾, 🇸🇻"
+//// tab | 💾, 🇸🇻
-
-
-
+
+
-
-
+
+
@@ -23,7 +29,7 @@
**🧾**: https://fastapi.tiangolo.com
-**ℹ 📟**: https://github.com/tiangolo/fastapi
+**ℹ 📟**: https://github.com/fastapi/fastapi
---
@@ -31,7 +37,7 @@ FastAPI 🏛, ⏩ (↕-🎭), 🕸 🛠️ 🏗 🛠️ ⏮️ 🐍 3️⃣.8️
🔑 ⚒:
-* **⏩**: 📶 ↕ 🎭, 🔛 🇷🇪 ⏮️ **✳** & **🚶** (👏 💃 & Pydantic). [1️⃣ ⏩ 🐍 🛠️ 💪](#performance).
+* **⏩**: 📶 ↕ 🎭, 🔛 🇷🇪 ⏮️ **✳** & **🚶** (👏 💃 & Pydantic). [1️⃣ ⏩ 🐍 🛠️ 💪](#_15).
* **⏩ 📟**: 📈 🚅 🛠️ ⚒ 🔃 2️⃣0️⃣0️⃣ 💯 3️⃣0️⃣0️⃣ 💯. *
* **👩❤👨 🐛**: 📉 🔃 4️⃣0️⃣ 💯 🗿 (👩💻) 📉 ❌. *
* **🏋️**: 👑 👨🎨 🐕🦺. 🛠️ 🌐. 🌘 🕰 🛠️.
@@ -63,7 +69,7 @@ FastAPI 🏛, ⏩ (↕-🎭), 🕸 🛠️ 🏗 🛠️ ⏮️ 🐍 3️⃣.8️
"_[...] 👤 ⚙️ **FastAPI** 📚 👫 📆. [...] 👤 🤙 📆 ⚙️ ⚫️ 🌐 👇 🏉 **⚗ 🐕🦺 🤸♂**. 👫 💆♂ 🛠️ 🔘 🐚 **🖥** 🏬 & **📠** 🏬._"
-
ujson - ⏩ 🎻 "🎻".
-* email_validator - 📧 🔬.
+* email-validator - 📧 🔬.
⚙️ 💃:
@@ -455,12 +460,12 @@ item: Item
* python-multipart - ✔ 🚥 👆 💚 🐕🦺 📨 "✍", ⏮️ `request.form()`.
* itsdangerous - ✔ `SessionMiddleware` 🐕🦺.
* pyyaml - ✔ 💃 `SchemaGenerator` 🐕🦺 (👆 🎲 🚫 💪 ⚫️ ⏮️ FastAPI).
-* ujson - ✔ 🚥 👆 💚 ⚙️ `UJSONResponse`.
⚙️ FastAPI / 💃:
* uvicorn - 💽 👈 📐 & 🍦 👆 🈸.
* orjson - ✔ 🚥 👆 💚 ⚙️ `ORJSONResponse`.
+* ujson - ✔ 🚥 👆 💚 ⚙️ `UJSONResponse`.
👆 💪 ❎ 🌐 👫 ⏮️ `pip install "fastapi[all]"`.
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 & 🐁.
-* 🐍 **FastAPI** 👩💻:
+* 🐍 **FastAPI** 👩💻:
* **⏩**: 📶 ↕ 🎭, 🔛 🇷🇪 ⏮️ **✳** & **🚶** (👏 💃 & Pydantic).
* **🏋️**: 👑 👨🎨 🐕🦺. 🛠️ 🌐. 🌘 🕰 🛠️.
* **⏩**: 🔧 ⏩ ⚙️ & 💡. 🌘 🕰 👂 🩺.
diff --git a/docs/em/docs/python-types.md b/docs/em/docs/python-types.md
index b8f61a113..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!}
- ```
+📇 🆎 👈 🔌 🔗 🆎, 👆 🚮 👫 ⬜ 🗜:
-!!! info
- 👈 🔗 🆎 ⬜ 🗜 🤙 "🆎 🔢".
+```Python hl_lines="1"
+{!> ../../../docs_src/python_types/tutorial006_py39.py!}
+```
- 👉 💼, `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!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial008_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
+
+```Python hl_lines="1"
+{!> ../../../docs_src/python_types/tutorial008_py39.py!}
+```
+
+////
👉 ⛓:
@@ -269,17 +290,21 @@ John Doe
🐍 3️⃣.1️⃣0️⃣ 📤 **🎛 ❕** 🌐❔ 👆 💪 🚮 💪 🆎 👽 ⏸ ⏸ (`|`).
-=== "🐍 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!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial008b_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```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️⃣ & 🔛 - 🎛"
+////
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial009b.py!}
- ```
+//// tab | 🐍 3️⃣.6️⃣ & 🔛 - 🎛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="1 4"
+{!> ../../../docs_src/python_types/tutorial009b.py!}
+```
- ```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`
+👆 💪 ⚙️ 🎏 💽 🆎 💊 (⏮️ ⬜ 🗜 & 🆎 🔘):
- & 🎏 ⏮️ 🐍 3️⃣.6️⃣, ⚪️➡️ `typing` 🕹:
+* `list`
+* `tuple`
+* `set`
+* `dict`
- * `Union`
- * `Optional`
- * ...& 🎏.
+ & 🎏 ⏮️ 🐍 3️⃣.6️⃣, ⚪️➡️ `typing` 🕹:
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+* `Union`
+* `Optional`
+* ...& 🎏.
- 👆 💪 ⚙️ 🎏 💽 🆎 💊 (⏮️ ⬜ 🗜 & 🆎 🔘):
+////
- * `list`
- * `tuple`
- * `set`
- * `dict`
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
- & 🎏 ⏮️ 🐍 3️⃣.6️⃣, ⚪️➡️ `typing` 🕹:
+👆 💪 ⚙️ 🎏 💽 🆎 💊 (⏮️ ⬜ 🗜 & 🆎 🔘):
- * `Union`
- * `Optional` (🎏 ⏮️ 🐍 3️⃣.6️⃣)
- * ...& 🎏.
+* `list`
+* `tuple`
+* `set`
+* `dict`
- 🐍 3️⃣.1️⃣0️⃣, 🎛 ⚙️ 💊 `Union` & `Optional`, 👆 💪 ⚙️ ⏸ ⏸ (`|`) 📣 🇪🇺 🆎.
+ & 🎏 ⏮️ 🐍 3️⃣.6️⃣, ⚪️➡️ `typing` 🕹:
+
+* `Union`
+* `Optional` (🎏 ⏮️ 🐍 3️⃣.6️⃣)
+* ...& 🎏.
+
+🐍 3️⃣.1️⃣0️⃣, 🎛 ⚙️ 💊 `Union` & `Optional`, 👆 💪 ⚙️ ⏸ ⏸ (`|`) 📣 🇪🇺 🆎.
+
+////
### 🎓 🆎
@@ -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!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python
- {!> ../../../docs_src/python_types/tutorial011_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python
+{!> ../../../docs_src/python_types/tutorial011_py39.py!}
+```
- ```Python
- {!> ../../../docs_src/python_types/tutorial011_py310.py!}
- ```
+////
-!!! info
- 💡 🌖 🔃 Pydantic, ✅ 🚮 🩺.
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python
+{!> ../../../docs_src/python_types/tutorial011_py310.py!}
+```
+
+////
+
+/// info
+
+💡 🌖 🔃 Pydantic, ✅ 🚮 🩺.
+
+///
**FastAPI** 🌐 ⚓️ 🔛 Pydantic.
👆 🔜 👀 📚 🌅 🌐 👉 💡 [🔰 - 👩💻 🦮](tutorial/index.md){.internal-link target=_blank}.
-!!! tip
- Pydantic ✔️ 🎁 🎭 🕐❔ 👆 ⚙️ `Optional` ⚖️ `Union[Something, None]` 🍵 🔢 💲, 👆 💪 ✍ 🌅 🔃 ⚫️ Pydantic 🩺 🔃 ✔ 📦 🏑.
+/// tip
+
+Pydantic ✔️ 🎁 🎭 🕐❔ 👆 ⚙️ `Optional` ⚖️ `Union[Something, None]` 🍵 🔢 💲, 👆 💪 ✍ 🌅 🔃 ⚫️ Pydantic 🩺 🔃 ✔ 📦 🏑.
+
+///
## 🆎 🔑 **FastAPI**
@@ -486,5 +535,8 @@ say_hi(name=None) # This works, None is valid 🎉
⚠ 👜 👈 ⚙️ 🐩 🐍 🆎, 👁 🥉 (↩️ ❎ 🌖 🎓, 👨🎨, ♒️), **FastAPI** 🔜 📚 👷 👆.
-!!! info
- 🚥 👆 ⏪ 🚶 🔘 🌐 🔰 & 👟 🔙 👀 🌅 🔃 🆎, 👍 ℹ "🎮 🎼" ⚪️➡️ `mypy`.
+/// info
+
+🚥 👆 ⏪ 🚶 🔘 🌐 🔰 & 👟 🔙 👀 🌅 🔃 🆎, 👍 ℹ "🎮 🎼" ⚪️➡️ `mypy`.
+
+///
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️⃣ & 🔛"
+////
- ```Python hl_lines="11 13 20 23"
- {!> ../../../docs_src/background_tasks/tutorial002_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```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 c30bba106..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
- 👉 ⚫️❔ ✔ 🏭 📟 ⚪️➡️ 1️⃣ 📁 🔘 ➕1️⃣.
+📤 📚 `__init__.py` 📁: 1️⃣ 🔠 📁 ⚖️ 📁.
- 🖼, `app/main.py` 👆 💪 ✔️ ⏸ 💖:
+👉 ⚫️❔ ✔ 🏭 📟 ⚪️➡️ 1️⃣ 📁 🔘 ➕1️⃣.
- ```
- from app.routers import items
- ```
+🖼, `app/main.py` 👆 💪 ✔️ ⏸ 💖:
+
+```
+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
-!!! check
- `prefix`, `tags`, `responses`, & `dependencies` 🔢 (📚 🎏 💼) ⚒ ⚪️➡️ **FastAPI** ℹ 👆 ❎ 📟 ❎.
+✔️ `dependencies` `APIRouter` 💪 ⚙️, 🖼, 🚚 🤝 🎂 👪 *➡ 🛠️*. 🚥 🔗 🚫 🚮 📦 🔠 1️⃣ 👫.
+
+///
+
+/// check
+
+`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
- & ⚫️ 🔜 ✔️ 👯♂️ 📨 🧾, 1️⃣ `404` & 1️⃣ `403`.
+👉 🏁 ➡ 🛠️ 🔜 ✔️ 🌀 🔖: `["items", "custom"]`.
+
+ & ⚫️ 🔜 ✔️ 👯♂️ 📨 🧾, 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
+```
+
+💡 🌅 🔃 🐍 📦 & 🕹, ✍ 🛂 🐍 🧾 🔃 🕹.
+
+///
### ❎ 📛 💥
@@ -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!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="9-12"
- {!> ../../../docs_src/body_fields/tutorial001_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```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️⃣ & 🔛"
+////
- ```Python hl_lines="17-19"
- {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-!!! note
- 👀 👈, 👉 💼, `item` 👈 🔜 ✊ ⚪️➡️ 💪 📦. ⚫️ ✔️ `None` 🔢 💲.
+```Python hl_lines="17-19"
+{!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!}
+```
+
+////
+
+/// 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!}
- ```
+```Python hl_lines="27"
+{!> ../../../docs_src/body_multiple_params/tutorial004.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="26"
- {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-!!! info
- `Body` ✔️ 🌐 🎏 ➕ 🔬 & 🗃 🔢 `Query`,`Path` & 🎏 👆 🔜 👀 ⏪.
+```Python hl_lines="26"
+{!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!}
+```
+
+////
+
+/// 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!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="15"
- {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```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️⃣ & 🔛"
+////
- ```Python hl_lines="12"
- {!> ../../../docs_src/body_nested_models/tutorial001_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```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!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial002_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="14"
+{!> ../../../docs_src/body_nested_models/tutorial002_py39.py!}
+```
- ```Python hl_lines="12"
- {!> ../../../docs_src/body_nested_models/tutorial002_py310.py!}
- ```
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```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!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial003_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="14"
+{!> ../../../docs_src/body_nested_models/tutorial003_py39.py!}
+```
- ```Python hl_lines="12"
- {!> ../../../docs_src/body_nested_models/tutorial003_py310.py!}
- ```
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```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!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="9-11"
- {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="9-11"
+{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!}
+```
- ```Python hl_lines="7-9"
- {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!}
- ```
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```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️⃣ & 🔛"
+////
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial006_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="20"
+{!> ../../../docs_src/body_nested_models/tutorial006_py39.py!}
+```
- ```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!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="9 14 20 23 27"
- {!> ../../../docs_src/body_nested_models/tutorial007_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="9 14 20 23 27"
+{!> ../../../docs_src/body_nested_models/tutorial007_py39.py!}
+```
- ```Python hl_lines="7 12 18 21 25"
- {!> ../../../docs_src/body_nested_models/tutorial007_py310.py!}
- ```
+////
-!!! info
- 👀 ❔ `Offer` ✔️ 📇 `Item`Ⓜ, ❔ 🔄 ✔️ 📦 📇 `Image`Ⓜ
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="7 12 18 21 25"
+{!> ../../../docs_src/body_nested_models/tutorial007_py310.py!}
+```
+
+////
+
+/// 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️⃣ & 🔛"
+////
- ```Python hl_lines="13"
- {!> ../../../docs_src/body_nested_models/tutorial008_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
+
+```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!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/body_nested_models/tutorial009.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/body_nested_models/tutorial009_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-!!! tip
- ✔️ 🤯 👈 🎻 🕴 🐕🦺 `str` 🔑.
+```Python hl_lines="7"
+{!> ../../../docs_src/body_nested_models/tutorial009_py39.py!}
+```
- ✋️ Pydantic ✔️ 🏧 💽 🛠️.
+////
- 👉 ⛓ 👈, ✋️ 👆 🛠️ 👩💻 💪 🕴 📨 🎻 🔑, 📏 👈 🎻 🔌 😁 🔢, Pydantic 🔜 🗜 👫 & ✔ 👫.
+/// tip
- & `dict` 👆 📨 `weights` 🔜 🤙 ✔️ `int` 🔑 & `float` 💲.
+✔️ 🤯 👈 🎻 🕴 🐕🦺 `str` 🔑.
+
+✋️ Pydantic ✔️ 🏧 💽 🛠️.
+
+👉 ⛓ 👈, ✋️ 👆 🛠️ 👩💻 💪 🕴 📨 🎻 🔑, 📏 👈 🎻 🔌 😁 🔢, Pydantic 🔜 🗜 👫 & ✔ 👫.
+
+ & `dict` 👆 📨 `weights` 🔜 🤙 ✔️ `int` 🔑 & `float` 💲.
+
+///
## 🌃
diff --git a/docs/em/docs/tutorial/body-updates.md b/docs/em/docs/tutorial/body-updates.md
index 98058ab52..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!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="30-35"
- {!> ../../../docs_src/body_updates/tutorial001_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="30-35"
+{!> ../../../docs_src/body_updates/tutorial001_py39.py!}
+```
- ```Python hl_lines="28-33"
- {!> ../../../docs_src/body_updates/tutorial001_py310.py!}
- ```
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="28-33"
+{!> ../../../docs_src/body_updates/tutorial001_py310.py!}
+```
+
+////
`PUT` ⚙️ 📨 💽 👈 🔜 ❎ ♻ 💽.
@@ -48,14 +54,17 @@
👉 ⛓ 👈 👆 💪 📨 🕴 💽 👈 👆 💚 ℹ, 🍂 🎂 🐣.
-!!! Note
- `PATCH` 🌘 🛎 ⚙️ & 💭 🌘 `PUT`.
+/// note
- & 📚 🏉 ⚙️ 🕴 `PUT`, 🍕 ℹ.
+`PATCH` 🌘 🛎 ⚙️ & 💭 🌘 `PUT`.
- 👆 **🆓** ⚙️ 👫 👐 👆 💚, **FastAPI** 🚫 🚫 🙆 🚫.
+ & 📚 🏉 ⚙️ 🕴 `PUT`, 🍕 ℹ.
- ✋️ 👉 🦮 🎦 👆, 🌖 ⚖️ 🌘, ❔ 👫 🎯 ⚙️.
+👆 **🆓** ⚙️ 👫 👐 👆 💚, **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️⃣ & 🔛"
+////
- ```Python hl_lines="34"
- {!> ../../../docs_src/body_updates/tutorial002_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="34"
+{!> ../../../docs_src/body_updates/tutorial002_py39.py!}
+```
- ```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!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="35"
- {!> ../../../docs_src/body_updates/tutorial002_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="35"
+{!> ../../../docs_src/body_updates/tutorial002_py39.py!}
+```
- ```Python hl_lines="33"
- {!> ../../../docs_src/body_updates/tutorial002_py310.py!}
- ```
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```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!}
- ```
+```Python hl_lines="30-37"
+{!> ../../../docs_src/body_updates/tutorial002.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="30-37"
- {!> ../../../docs_src/body_updates/tutorial002_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="30-37"
+{!> ../../../docs_src/body_updates/tutorial002_py39.py!}
+```
- ```Python hl_lines="28-35"
- {!> ../../../docs_src/body_updates/tutorial002_py310.py!}
- ```
+////
-!!! tip
- 👆 💪 🤙 ⚙️ 👉 🎏 ⚒ ⏮️ 🇺🇸🔍 `PUT` 🛠️.
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
- ✋️ 🖼 📥 ⚙️ `PATCH` ↩️ ⚫️ ✍ 👫 ⚙️ 💼.
+```Python hl_lines="28-35"
+{!> ../../../docs_src/body_updates/tutorial002_py310.py!}
+```
-!!! note
- 👀 👈 🔢 🏷 ✔.
+////
- , 🚥 👆 💚 📨 🍕 ℹ 👈 💪 🚫 🌐 🔢, 👆 💪 ✔️ 🏷 ⏮️ 🌐 🔢 ™ 📦 (⏮️ 🔢 💲 ⚖️ `None`).
+/// tip
- 🔬 ⚪️➡️ 🏷 ⏮️ 🌐 📦 💲 **ℹ** & 🏷 ⏮️ ✔ 💲 **🏗**, 👆 💪 ⚙️ 💭 🔬 [➕ 🏷](extra-models.md){.internal-link target=_blank}.
+👆 💪 🤙 ⚙️ 👉 🎏 ⚒ ⏮️ 🇺🇸🔍 `PUT` 🛠️.
+
+✋️ 🖼 📥 ⚙️ `PATCH` ↩️ ⚫️ ✍ 👫 ⚙️ 💼.
+
+///
+
+/// note
+
+👀 👈 🔢 🏷 ✔.
+
+, 🚥 👆 💚 📨 🍕 ℹ 👈 💪 🚫 🌐 🔢, 👆 💪 ✔️ 🏷 ⏮️ 🌐 🔢 ™ 📦 (⏮️ 🔢 💲 ⚖️ `None`).
+
+🔬 ⚪️➡️ 🏷 ⏮️ 🌐 📦 💲 **ℹ** & 🏷 ⏮️ ✔ 💲 **🏗**, 👆 💪 ⚙️ 💭 🔬 [➕ 🏷](extra-models.md){.internal-link target=_blank}.
+
+///
diff --git a/docs/em/docs/tutorial/body.md b/docs/em/docs/tutorial/body.md
index db850162a..79d8e716f 100644
--- a/docs/em/docs/tutorial/body.md
+++ b/docs/em/docs/tutorial/body.md
@@ -8,28 +8,35 @@
📣 **📨** 💪, 👆 ⚙️ Pydantic 🏷 ⏮️ 🌐 👫 🏋️ & 💰.
-!!! 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!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="2"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```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 @@
-!!! tip
- 🚥 👆 ⚙️ 🗒 👆 👨🎨, 👆 💪 ⚙️ Pydantic 🗒 📁.
+/// tip
- ⚫️ 📉 👨🎨 🐕🦺 Pydantic 🏷, ⏮️:
+🚥 👆 ⚙️ 🗒 👆 👨🎨, 👆 💪 ⚙️ 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!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="19"
- {!> ../../../docs_src/body/tutorial002_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```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️⃣ & 🔛"
+////
- ```Python hl_lines="15-16"
- {!> ../../../docs_src/body/tutorial003_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```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️⃣ & 🔛"
+////
- ```Python hl_lines="16"
- {!> ../../../docs_src/body/tutorial004_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="16"
+{!> ../../../docs_src/body/tutorial004_py310.py!}
+```
+
+////
🔢 🔢 🔜 🤔 ⏩:
@@ -203,11 +233,14 @@
* 🚥 🔢 **⭐ 🆎** (💖 `int`, `float`, `str`, `bool`, ♒️) ⚫️ 🔜 🔬 **🔢** 🔢.
* 🚥 🔢 📣 🆎 **Pydantic 🏷**, ⚫️ 🔜 🔬 📨 **💪**.
-!!! note
- FastAPI 🔜 💭 👈 💲 `q` 🚫 ✔ ↩️ 🔢 💲 `= None`.
+/// note
- `Union` `Union[str, None]` 🚫 ⚙️ FastAPI, ✋️ 🔜 ✔ 👆 👨🎨 🤝 👆 👍 🐕🦺 & 🔍 ❌.
+FastAPI 🔜 💭 👈 💲 `q` 🚫 ✔ ↩️ 🔢 💲 `= None`.
+
+ `Union` `Union[str, None]` 🚫 ⚙️ FastAPI, ✋️ 🔜 ✔ 👆 👨🎨 🤝 👆 👍 🐕🦺 & 🔍 ❌.
+
+///
## 🍵 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/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!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/cookie_params/tutorial001.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-!!! note "📡 ℹ"
- `Cookie` "👭" 🎓 `Path` & `Query`. ⚫️ 😖 ⚪️➡️ 🎏 ⚠ `Param` 🎓.
+```Python hl_lines="7"
+{!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
+```
- ✋️ 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, `Cookie` & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓.
+////
-!!! info
- 📣 🍪, 👆 💪 ⚙️ `Cookie`, ↩️ ⏪ 🔢 🔜 🔬 🔢 🔢.
+/// note | "📡 ℹ"
+
+`Cookie` "👭" 🎓 `Path` & `Query`. ⚫️ 😖 ⚪️➡️ 🎏 ⚠ `Param` 🎓.
+
+✋️ 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, `Cookie` & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓.
+
+///
+
+/// 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 @@
🌖 ℹ 🔃 ⚜, ✅ 🦎 ⚜ 🧾.
-!!! 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
- 🌅 ℹ, ✅ 🛂 🐍 🩺.
+/// info
+
+🌅 ℹ, ✅ 🛂 🐍 🩺.
+
+///
## 🏃 👆 📟 ⏮️ 👆 🕹
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️⃣ & 🔛"
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```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️⃣ & 🔛"
+////
- ```Python hl_lines="9-13"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```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️⃣ & 🔛"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```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!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="6"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```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!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```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️⃣ & 🔛"
+////
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial003_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```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️⃣ & 🔛"
+////
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial004_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```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 9617667f4..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 🐕🦺 🔗 👈 .
+/// tip
- ✋️ 🚥 👆 ✔️ 🛃 🎚 👈 👆 💚 👩💻 🖥 💪 👀, 👆 💪 🚮 👫 👆 ⚜ 📳 ([⚜ (✖️-🇨🇳 ℹ 🤝)](cors.md){.internal-link target=_blank}) ⚙️ 🔢 `expose_headers` 📄 💃 ⚜ 🩺.
+✔️ 🤯 👈 🛃 © 🎚 💪 🚮 ⚙️ '✖-' 🔡.
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette.requests import Request`.
+✋️ 🚥 👆 ✔️ 🛃 🎚 👈 👆 💚 👩💻 🖥 💪 👀, 👆 💪 🚮 👫 👆 ⚜ 📳 ([⚜ (✖️-🇨🇳 ℹ 🤝)](cors.md){.internal-link target=_blank}) ⚙️ 🔢 `expose_headers` 📄 💃 ⚜ 🩺.
- **FastAPI** 🚚 ⚫️ 🏪 👆, 👩💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃.
+///
+
+/// note | "📡 ℹ"
+
+👆 💪 ⚙️ `from starlette.requests import Request`.
+
+**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!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="3 17"
- {!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="3 17"
+{!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!}
+```
- ```Python hl_lines="1 15"
- {!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!}
- ```
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="1 15"
+{!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!}
+```
+
+////
👈 👔 📟 🔜 ⚙️ 📨 & 🔜 🚮 🗄 🔗.
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette import status`.
+/// note | "📡 ℹ"
- **FastAPI** 🚚 🎏 `starlette.status` `fastapi.status` 🏪 👆, 👩💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃.
+👆 💪 ⚙️ `from starlette import 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️⃣ & 🔛"
+////
- ```Python hl_lines="17 22 27"
- {!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="17 22 27"
+{!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!}
+```
- ```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!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="20-21"
- {!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="20-21"
+{!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!}
+```
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!}
- ```
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="18-19"
+{!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!}
+```
+
+////
## 📛 ⚪️➡️ #️⃣
@@ -104,23 +128,29 @@
👆 💪 ✍ ✍ #️⃣ , ⚫️ 🔜 🔬 & 🖥 ☑ (✊ 🔘 🏧 #️⃣ 📐).
-=== "🐍 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!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="19-27"
- {!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="19-27"
+{!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!}
+```
- ```Python hl_lines="17-25"
- {!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!}
- ```
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```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!}
- ```
+```Python hl_lines="21"
+{!> ../../../docs_src/path_operation_configuration/tutorial005.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="21"
- {!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="21"
+{!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!}
+```
- ```Python hl_lines="19"
- {!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!}
- ```
+////
-!!! info
- 👀 👈 `response_description` 🔗 🎯 📨, `description` 🔗 *➡ 🛠️* 🏢.
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-!!! check
- 🗄 ✔ 👈 🔠 *➡ 🛠️* 🚚 📨 📛.
+```Python hl_lines="19"
+{!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!}
+```
- , 🚥 👆 🚫 🚚 1️⃣, **FastAPI** 🔜 🔁 🏗 1️⃣ "🏆 📨".
+////
+
+/// info
+
+👀 👈 `response_description` 🔗 🎯 📨, `description` 🔗 *➡ 🛠️* 🏢.
+
+///
+
+/// check
+
+🗄 ✔ 👈 🔠 *➡ 🛠️* 🚚 📨 📛.
+
+, 🚥 👆 🚫 🚚 1️⃣, **FastAPI** 🔜 🔁 🏗 1️⃣ "🏆 📨".
+
+///
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️⃣ & 🔛"
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```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️⃣ & 🔛"
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-!!! note
- ➡ 🔢 🕧 ✔ ⚫️ ✔️ 🍕 ➡.
+```Python hl_lines="8"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
+```
- , 👆 🔜 📣 ⚫️ ⏮️ `...` ™ ⚫️ ✔.
+////
- 👐, 🚥 👆 📣 ⚫️ ⏮️ `None` ⚖️ ⚒ 🔢 💲, ⚫️ 🔜 🚫 📉 🕳, ⚫️ 🔜 🕧 🚚.
+/// note
+
+➡ 🔢 🕧 ✔ ⚫️ ✔️ 🍕 ➡.
+
+, 👆 🔜 📣 ⚫️ ⏮️ `...` ™ ⚫️ ✔.
+
+👐, 🚥 👆 📣 ⚫️ ⏮️ `None` ⚖️ ⚒ 🔢 💲, ⚫️ 🔜 🚫 📉 🕳, ⚫️ 🔜 🕧 🚚.
+
+///
## ✔ 🔢 👆 💪
@@ -121,18 +132,24 @@
* `lt`: `l`👭 `t`👲
* `le`: `l`👭 🌘 ⚖️ `e`🅾
-!!! info
- `Query`, `Path`, & 🎏 🎓 👆 🔜 👀 ⏪ 🏿 ⚠ `Param` 🎓.
+/// info
- 🌐 👫 💰 🎏 🔢 🌖 🔬 & 🗃 👆 ✔️ 👀.
+`Query`, `Path`, & 🎏 🎓 👆 🔜 👀 ⏪ 🏿 ⚠ `Param` 🎓.
-!!! note "📡 ℹ"
- 🕐❔ 👆 🗄 `Query`, `Path` & 🎏 ⚪️➡️ `fastapi`, 👫 🤙 🔢.
+🌐 👫 💰 🎏 🔢 🌖 🔬 & 🗃 👆 ✔️ 👀.
- 👈 🕐❔ 🤙, 📨 👐 🎓 🎏 📛.
+///
- , 👆 🗄 `Query`, ❔ 🔢. & 🕐❔ 👆 🤙 ⚫️, ⚫️ 📨 👐 🎓 🌟 `Query`.
+/// note | "📡 ℹ"
- 👫 🔢 📤 (↩️ ⚙️ 🎓 🔗) 👈 👆 👨🎨 🚫 ™ ❌ 🔃 👫 🆎.
+🕐❔ 👆 🗄 `Query`, `Path` & 🎏 ⚪️➡️ `fastapi`, 👫 🤙 🔢.
- 👈 🌌 👆 💪 ⚙️ 👆 😐 👨🎨 & 🛠️ 🧰 🍵 ✔️ 🚮 🛃 📳 🤷♂ 📚 ❌.
+👈 🕐❔ 🤙, 📨 👐 🎓 🎏 📛.
+
+, 👆 🗄 `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
+
+👉 🔜 🤝 👆 👨🎨 🐕🦺 🔘 👆 🔢, ⏮️ ❌ ✅, 🛠️, ♒️.
+
+///
## 💽 🛠️
@@ -35,10 +38,13 @@
{"item_id":3}
```
-!!! check
- 👀 👈 💲 👆 🔢 📨 (& 📨) `3`, 🐍 `int`, 🚫 🎻 `"3"`.
+/// check
- , ⏮️ 👈 🆎 📄, **FastAPI** 🤝 👆 🏧 📨 "✍".
+👀 👈 💲 👆 🔢 📨 (& 📨) `3`, 🐍 `int`, 🚫 🎻 `"3"`.
+
+, ⏮️ 👈 🆎 📄, **FastAPI** 🤝 👆 🏧 📨 "✍".
+
+///
## 💽 🔬
@@ -63,12 +69,15 @@
🎏 ❌ 🔜 😑 🚥 👆 🚚 `float` ↩️ `int`,: http://127.0.0.1:8000/items/4.2
-!!! check
- , ⏮️ 🎏 🐍 🆎 📄, **FastAPI** 🤝 👆 💽 🔬.
+/// check
- 👀 👈 ❌ 🎯 🇵🇸 ⚫️❔ ☝ 🌐❔ 🔬 🚫 🚶♀️.
+, ⏮️ 🎏 🐍 🆎 📄, **FastAPI** 🤝 👆 💽 🔬.
- 👉 🙃 👍 ⏪ 🛠️ & 🛠️ 📟 👈 🔗 ⏮️ 👆 🛠️.
+👀 👈 ❌ 🎯 🇵🇸 ⚫️❔ ☝ 🌐❔ 🔬 🚫 🚶♀️.
+
+👉 🙃 👍 ⏪ 🛠️ & 🛠️ 📟 👈 🔗 ⏮️ 👆 🛠️.
+
+///
## 🧾
@@ -76,10 +85,13 @@
-!!! check
- 🔄, ⏮️ 👈 🎏 🐍 🆎 📄, **FastAPI** 🤝 👆 🏧, 🎓 🧾 (🛠️ 🦁 🎚).
+/// check
- 👀 👈 ➡ 🔢 📣 🔢.
+🔄, ⏮️ 👈 🎏 🐍 🆎 📄, **FastAPI** 🤝 👆 🏧, 🎓 🧾 (🛠️ 🦁 🎚).
+
+👀 👈 ➡ 🔢 📣 🔢.
+
+///
## 🐩-⚓️ 💰, 🎛 🧾
@@ -139,11 +151,17 @@
{!../../../docs_src/path_params/tutorial005.py!}
```
-!!! info
- 🔢 (⚖️ 🔢) 💪 🐍 ↩️ ⏬ 3️⃣.4️⃣.
+/// info
-!!! tip
- 🚥 👆 💭, "📊", "🎓", & "🍏" 📛 🎰 🏫 🏷.
+🔢 (⚖️ 🔢) 💪 🐍 ↩️ ⏬ 3️⃣.4️⃣.
+
+///
+
+/// tip
+
+🚥 👆 💭, "📊", "🎓", & "🍏" 📛 🎰 🏫 🏷.
+
+///
### 📣 *➡ 🔢*
@@ -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
- 👈 💼, 📛 🔜: `/files//home/johndoe/myfile.txt`, ⏮️ 2️⃣✖️ 🔪 (`//`) 🖖 `files` & `home`.
+👆 💪 💪 🔢 🔌 `/home/johndoe/myfile.txt`, ⏮️ 🏁 🔪 (`/`).
+
+👈 💼, 📛 🔜: `/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!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```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
- `Union` `Union[str, None]` 🔜 ✔ 👆 👨🎨 🤝 👆 👍 🐕🦺 & 🔍 ❌.
+FastAPI 🔜 💭 👈 💲 `q` 🚫 ✔ ↩️ 🔢 💲 `= 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️⃣ & 🔛"
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```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!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```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)
- ```
+⚖️:
- ⚫️ 🔜 ⚙️ 👈 `None` 🔢 💲, & 👈 🌌 ⚒ 🔢 **🚫 ✔**.
+```Python
+= Query(default=None)
+```
- `Union[str, None]` 🍕 ✔ 👆 👨🎨 🚚 👻 🐕🦺, ✋️ ⚫️ 🚫 ⚫️❔ 💬 FastAPI 👈 👉 🔢 🚫 ✔.
+⚫️ 🔜 ⚙️ 👈 `None` 🔢 💲, & 👈 🌌 ⚒ 🔢 **🚫 ✔**.
+
+ `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!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!}
+```
+
+////
## 🚮 🥔 🧬
👆 💪 🔬 🥔 🧬 👈 🔢 🔜 🏏:
-=== "🐍 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️⃣ & 🔛"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```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
- 🚥 👆 🚫 👀 👈 `...` ⏭: ⚫️ 🎁 👁 💲, ⚫️ 🍕 🐍 & 🤙 "❕".
+/// info
- ⚫️ ⚙️ 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!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial006c.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-!!! tip
- Pydantic, ❔ ⚫️❔ 🏋️ 🌐 💽 🔬 & 🛠️ FastAPI, ✔️ 🎁 🎭 🕐❔ 👆 ⚙️ `Optional` ⚖️ `Union[Something, None]` 🍵 🔢 💲, 👆 💪 ✍ 🌅 🔃 ⚫️ Pydantic 🩺 🔃 ✔ 📦 🏑.
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!}
+```
+
+////
+
+/// tip
+
+Pydantic, ❔ ⚫️❔ 🏋️ 🌐 💽 🔬 & 🛠️ FastAPI, ✔️ 🎁 🎭 🕐❔ 👆 ⚙️ `Optional` ⚖️ `Union[Something, None]` 🍵 🔢 💲, 👆 💪 ✍ 🌅 🔃 ⚫️ Pydantic 🩺 🔃 ✔ 📦 🏑.
+
+///
### ⚙️ 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️⃣ & 🔛"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!}
+```
- ```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!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
+
+```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!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```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!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```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!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="16"
- {!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```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️⃣ & 🔛"
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```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 ccb235c15..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️⃣ & 🔛"
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params/tutorial002_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```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!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params/tutorial003_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```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!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="6 8"
- {!> ../../../docs_src/query_params/tutorial004_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```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#predefined-values){.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
- 📨 📂 📁, 🥇 ❎ `python-multipart`.
+/// info
- 🤶 Ⓜ. `pip install python-multipart`.
+📨 📂 📁, 🥇 ❎ `python-multipart`.
- 👉 ↩️ 📂 📁 📨 "📨 💽".
+🤶 Ⓜ. `pip install python-multipart`.
+
+👉 ↩️ 📂 📁 📨 "📨 💽".
+
+///
## 🗄 `File`
@@ -25,13 +28,19 @@
{!../../../docs_src/request_files/tutorial001.py!}
```
-!!! info
- `File` 🎓 👈 😖 🔗 ⚪️➡️ `Form`.
+/// info
- ✋️ 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, `File` & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓.
+`File` 🎓 👈 😖 🔗 ⚪️➡️ `Form`.
-!!! tip
- 📣 📁 💪, 👆 💪 ⚙️ `File`, ↩️ ⏪ 🔢 🔜 🔬 🔢 🔢 ⚖️ 💪 (🎻) 🔢.
+✋️ 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, `File` & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓.
+
+///
+
+/// tip
+
+📣 📁 💪, 👆 💪 ⚙️ `File`, ↩️ ⏪ 🔢 🔜 🔬 🔢 🔢 ⚖️ 💪 (🎻) 🔢.
+
+///
📁 🔜 📂 "📨 💽".
@@ -90,11 +99,17 @@ contents = await myfile.read()
contents = myfile.file.read()
```
-!!! note "`async` 📡 ℹ"
- 🕐❔ 👆 ⚙️ `async` 👩🔬, **FastAPI** 🏃 📁 👩🔬 🧵 & ⌛ 👫.
+/// note | "`async` 📡 ℹ"
-!!! note "💃 📡 ℹ"
- **FastAPI**'Ⓜ `UploadFile` 😖 🔗 ⚪️➡️ **💃**'Ⓜ `UploadFile`, ✋️ 🚮 💪 🍕 ⚒ ⚫️ 🔗 ⏮️ **Pydantic** & 🎏 🍕 FastAPI.
+🕐❔ 👆 ⚙️ `async` 👩🔬, **FastAPI** 🏃 📁 👩🔬 🧵 & ⌛ 👫.
+
+///
+
+/// note | "💃 📡 ℹ"
+
+**FastAPI**'Ⓜ `UploadFile` 😖 🔗 ⚪️➡️ **💃**'Ⓜ `UploadFile`, ✋️ 🚮 💪 🍕 ⚒ ⚫️ 🔗 ⏮️ **Pydantic** & 🎏 🍕 FastAPI.
+
+///
## ⚫️❔ "📨 💽"
@@ -102,33 +117,43 @@ contents = myfile.file.read()
**FastAPI** 🔜 ⚒ 💭 ✍ 👈 📊 ⚪️➡️ ▶️️ 🥉 ↩️ 🎻.
-!!! note "📡 ℹ"
- 📊 ⚪️➡️ 📨 🛎 🗜 ⚙️ "📻 🆎" `application/x-www-form-urlencoded` 🕐❔ ⚫️ 🚫 🔌 📁.
+/// note | "📡 ℹ"
- ✋️ 🕐❔ 📨 🔌 📁, ⚫️ 🗜 `multipart/form-data`. 🚥 👆 ⚙️ `File`, **FastAPI** 🔜 💭 ⚫️ ✔️ 🤚 📁 ⚪️➡️ ☑ 🍕 💪.
+📊 ⚪️➡️ 📨 🛎 🗜 ⚙️ "📻 🆎" `application/x-www-form-urlencoded` 🕐❔ ⚫️ 🚫 🔌 📁.
- 🚥 👆 💚 ✍ 🌖 🔃 👉 🔢 & 📨 🏑, 👳 🏇 🕸 🩺 POST.
+✋️ 🕐❔ 📨 🔌 📁, ⚫️ 🗜 `multipart/form-data`. 🚥 👆 ⚙️ `File`, **FastAPI** 🔜 💭 ⚫️ ✔️ 🤚 📁 ⚪️➡️ ☑ 🍕 💪.
-!!! warning
- 👆 💪 📣 💗 `File` & `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `multipart/form-data` ↩️ `application/json`.
+🚥 👆 💚 ✍ 🌖 🔃 👉 🔢 & 📨 🏑, 👳 🏇 🕸 🩺 POST.
- 👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️.
+///
+
+/// warning
+
+👆 💪 📣 💗 `File` & `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `multipart/form-data` ↩️ `application/json`.
+
+👉 🚫 🚫 **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️⃣ & 🔛"
+////
- ```Python hl_lines="7 14"
- {!> ../../../docs_src/request_files/tutorial001_02_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```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!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="8 13"
- {!> ../../../docs_src/request_files/tutorial002_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
+
+```Python hl_lines="8 13"
+{!> ../../../docs_src/request_files/tutorial002_py39.py!}
+```
+
+////
👆 🔜 📨, 📣, `list` `bytes` ⚖️ `UploadFile`Ⓜ.
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette.responses import HTMLResponse`.
+/// note | "📡 ℹ"
- **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃.
+👆 💪 ⚙️ `from starlette.responses import HTMLResponse`.
+
+**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️⃣ & 🔛"
+////
- ```Python hl_lines="16"
- {!> ../../../docs_src/request_files/tutorial003_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
+
+```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
- 📨 📂 📁 & /⚖️ 📨 📊, 🥇 ❎ `python-multipart`.
+/// info
- 🤶 Ⓜ. `pip install python-multipart`.
+📨 📂 📁 & /⚖️ 📨 📊, 🥇 ❎ `python-multipart`.
+
+🤶 Ⓜ. `pip install python-multipart`.
+
+///
## 🗄 `File` & `Form`
@@ -25,10 +28,13 @@
& 👆 💪 📣 📁 `bytes` & `UploadFile`.
-!!! warning
- 👆 💪 📣 💗 `File` & `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `multipart/form-data` ↩️ `application/json`.
+/// warning
- 👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️.
+👆 💪 📣 💗 `File` & `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `multipart/form-data` ↩️ `application/json`.
+
+👉 🚫 🚫 **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
- ⚙️ 📨, 🥇 ❎ `python-multipart`.
+/// info
- 🤶 Ⓜ. `pip install python-multipart`.
+⚙️ 📨, 🥇 ❎ `python-multipart`.
+
+🤶 Ⓜ. `pip install python-multipart`.
+
+///
## 🗄 `Form`
@@ -29,11 +32,17 @@
⏮️ `Form` 👆 💪 📣 🎏 📳 ⏮️ `Body` (& `Query`, `Path`, `Cookie`), 🔌 🔬, 🖼, 📛 (✅ `user-name` ↩️ `username`), ♒️.
-!!! info
- `Form` 🎓 👈 😖 🔗 ⚪️➡️ `Body`.
+/// info
-!!! tip
- 📣 📨 💪, 👆 💪 ⚙️ `Form` 🎯, ↩️ 🍵 ⚫️ 🔢 🔜 🔬 🔢 🔢 ⚖️ 💪 (🎻) 🔢.
+`Form` 🎓 👈 😖 🔗 ⚪️➡️ `Body`.
+
+///
+
+/// tip
+
+📣 📨 💪, 👆 💪 ⚙️ `Form` 🎯, ↩️ 🍵 ⚫️ 🔢 🔜 🔬 🔢 🔢 ⚖️ 💪 (🎻) 🔢.
+
+///
## 🔃 "📨 🏑"
@@ -41,17 +50,23 @@
**FastAPI** 🔜 ⚒ 💭 ✍ 👈 📊 ⚪️➡️ ▶️️ 🥉 ↩️ 🎻.
-!!! note "📡 ℹ"
- 📊 ⚪️➡️ 📨 🛎 🗜 ⚙️ "📻 🆎" `application/x-www-form-urlencoded`.
+/// note | "📡 ℹ"
- ✋️ 🕐❔ 📨 🔌 📁, ⚫️ 🗜 `multipart/form-data`. 👆 🔜 ✍ 🔃 🚚 📁 ⏭ 📃.
+📊 ⚪️➡️ 📨 🛎 🗜 ⚙️ "📻 🆎" `application/x-www-form-urlencoded`.
- 🚥 👆 💚 ✍ 🌖 🔃 👉 🔢 & 📨 🏑, 👳 🏇 🕸 🩺 POST.
+✋️ 🕐❔ 📨 🔌 📁, ⚫️ 🗜 `multipart/form-data`. 👆 🔜 ✍ 🔃 🚚 📁 ⏭ 📃.
-!!! warning
- 👆 💪 📣 💗 `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `application/x-www-form-urlencoded` ↩️ `application/json`.
+🚥 👆 💚 ✍ 🌖 🔃 👉 🔢 & 📨 🏑, 👳 🏇 🕸 🩺 POST.
- 👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️.
+///
+
+/// warning
+
+👆 💪 📣 💗 `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `application/x-www-form-urlencoded` ↩️ `application/json`.
+
+👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️.
+
+///
## 🌃
diff --git a/docs/em/docs/tutorial/response-model.md b/docs/em/docs/tutorial/response-model.md
index 7103e9176..9483508aa 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!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="18 23"
- {!> ../../../docs_src/response_model/tutorial001_01_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="18 23"
+{!> ../../../docs_src/response_model/tutorial001_01_py39.py!}
+```
- ```Python hl_lines="16 21"
- {!> ../../../docs_src/response_model/tutorial001_01_py310.py!}
- ```
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```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️⃣ & 🔛"
+////
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```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_py310.py!}
- ```
+////
-!!! note
- 👀 👈 `response_model` 🔢 "👨🎨" 👩🔬 (`get`, `post`, ♒️). 🚫 👆 *➡ 🛠️ 🔢*, 💖 🌐 🔢 & 💪.
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="17 22 24-27"
+{!> ../../../docs_src/response_model/tutorial001_py310.py!}
+```
+
+////
+
+/// note
+
+👀 👈 `response_model` 🔢 "👨🎨" 👩🔬 (`get`, `post`, ♒️). 🚫 👆 *➡ 🛠️ 🔢*, 💖 🌐 🔢 & 💪.
+
+///
`response_model` 📨 🎏 🆎 👆 🔜 📣 Pydantic 🏷 🏑,, ⚫️ 💪 Pydantic 🏷, ✋️ ⚫️ 💪, ✅ `list` Pydantic 🏷, 💖 `List[Item]`.
FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & **🗜 & ⛽ 🔢 📊** 🚮 🆎 📄.
-!!! tip
- 🚥 👆 ✔️ ⚠ 🆎 ✅ 👆 👨🎨, ✍, ♒️, 👆 💪 📣 🔢 📨 🆎 `Any`.
+/// tip
- 👈 🌌 👆 💬 👨🎨 👈 👆 😫 🛬 🕳. ✋️ FastAPI 🔜 💽 🧾, 🔬, 🖥, ♒️. ⏮️ `response_model`.
+🚥 👆 ✔️ ⚠ 🆎 ✅ 👆 👨🎨, ✍, ♒️, 👆 💪 📣 🔢 📨 🆎 `Any`.
+
+👈 🌌 👆 💬 👨🎨 👈 👆 😫 🛬 🕳. ✋️ 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!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="7 9"
- {!> ../../../docs_src/response_model/tutorial002_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-!!! info
- ⚙️ `EmailStr`, 🥇 ❎ `email_validator`.
+```Python hl_lines="7 9"
+{!> ../../../docs_src/response_model/tutorial002_py310.py!}
+```
- 🤶 Ⓜ. `pip install email-validator`
- ⚖️ `pip install pydantic[email]`.
+////
+
+/// info
+
+⚙️ `EmailStr`, 🥇 ❎ `email-validator`.
+
+🤶 Ⓜ. `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️⃣ & 🔛"
+////
- ```Python hl_lines="16"
- {!> ../../../docs_src/response_model/tutorial002_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```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!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="9 11 16"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```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️⃣ & 🔛"
+////
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```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️⃣ & 🔛"
+////
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```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!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="7-10 13-14 18"
- {!> ../../../docs_src/response_model/tutorial003_01_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="7-10 13-14 18"
+{!> ../../../docs_src/response_model/tutorial003_01_py310.py!}
+```
+
+////
⏮️ 👉, 👥 🤚 🏭 🐕🦺, ⚪️➡️ 👨🎨 & ✍ 👉 📟 ☑ ⚖ 🆎, ✋️ 👥 🤚 💽 🖥 ⚪️➡️ FastAPI.
@@ -278,17 +326,21 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓
🎏 🔜 🔨 🚥 👆 ✔️ 🕳 💖 🇪🇺 🖖 🎏 🆎 🌐❔ 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️⃣ & 🔛"
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/response_model/tutorial003_04_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```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️⃣ & 🔛"
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/response_model/tutorial003_05_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```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!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="11 13-14"
- {!> ../../../docs_src/response_model/tutorial004_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="11 13-14"
+{!> ../../../docs_src/response_model/tutorial004_py39.py!}
+```
- ```Python hl_lines="9 11-12"
- {!> ../../../docs_src/response_model/tutorial004_py310.py!}
- ```
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```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()` ⏮️ 🚮 `exclude_unset` 🔢 🏆 👉.
+/// info
-!!! info
- 👆 💪 ⚙️:
+FastAPI ⚙️ Pydantic 🏷 `.dict()` ⏮️ 🚮 `exclude_unset` 🔢 🏆 👉.
- * `response_model_exclude_defaults=True`
- * `response_model_exclude_none=True`
+///
- 🔬 Pydantic 🩺 `exclude_defaults` & `exclude_none`.
+/// info
+
+👆 💪 ⚙️:
+
+* `response_model_exclude_defaults=True`
+* `response_model_exclude_none=True`
+
+🔬 Pydantic 🩺 `exclude_defaults` & `exclude_none`.
+
+///
#### 📊 ⏮️ 💲 🏑 ⏮️ 🔢
@@ -421,10 +495,13 @@ FastAPI 🙃 🥃 (🤙, Pydantic 🙃 🥃) 🤔 👈, ✋️ `description`, `t
, 👫 🔜 🔌 🎻 📨.
-!!! tip
- 👀 👈 🔢 💲 💪 🕳, 🚫 🕴 `None`.
+/// tip
- 👫 💪 📇 (`[]`), `float` `10.5`, ♒️.
+👀 👈 🔢 💲 💪 🕳, 🚫 🕴 `None`.
+
+👫 💪 📇 (`[]`), `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` 🚫 🔢.
+✋️ ⚫️ 👍 ⚙️ 💭 🔛, ⚙️ 💗 🎓, ↩️ 👫 🔢.
- 👉 ✔ `response_model_by_alias` 👈 👷 ➡.
+👉 ↩️ 🎻 🔗 🏗 👆 📱 🗄 (& 🩺) 🔜 1️⃣ 🏁 🏷, 🚥 👆 ⚙️ `response_model_include` ⚖️ `response_model_exclude` 🚫 🔢.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+👉 ✔ `response_model_by_alias` 👈 👷 ➡.
- ```Python hl_lines="31 37"
- {!> ../../../docs_src/response_model/tutorial005.py!}
- ```
+///
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="29 35"
- {!> ../../../docs_src/response_model/tutorial005_py310.py!}
- ```
+```Python hl_lines="31 37"
+{!> ../../../docs_src/response_model/tutorial005.py!}
+```
-!!! tip
- ❕ `{"name", "description"}` ✍ `set` ⏮️ 📚 2️⃣ 💲.
+////
- ⚫️ 🌓 `set(["name", "description"])`.
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="29 35"
+{!> ../../../docs_src/response_model/tutorial005_py310.py!}
+```
+
+////
+
+/// tip
+
+❕ `{"name", "description"}` ✍ `set` ⏮️ 📚 2️⃣ 💲.
+
+⚫️ 🌓 `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️⃣ & 🔛"
+////
- ```Python hl_lines="29 35"
- {!> ../../../docs_src/response_model/tutorial006_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```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`, ✅ 🐍 `http.HTTPStatus`.
+/// info
+
+`status_code` 💪 👐 📨 `IntEnum`, ✅ 🐍 `http.HTTPStatus`.
+
+///
⚫️ 🔜:
@@ -27,15 +33,21 @@
-!!! note
- 📨 📟 (👀 ⏭ 📄) 🎦 👈 📨 🔨 🚫 ✔️ 💪.
+/// note
- FastAPI 💭 👉, & 🔜 🏭 🗄 🩺 👈 🇵🇸 📤 🙅♂ 📨 💪.
+📨 📟 (👀 ⏭ 📄) 🎦 👈 📨 🔨 🚫 ✔️ 💪.
+
+FastAPI 💭 👉, & 🔜 🏭 🗄 🩺 👈 🇵🇸 📤 🙅♂ 📨 💪.
+
+///
## 🔃 🇺🇸🔍 👔 📟
-!!! note
- 🚥 👆 ⏪ 💭 ⚫️❔ 🇺🇸🔍 👔 📟, 🚶 ⏭ 📄.
+/// note
+
+🚥 👆 ⏪ 💭 ⚫️❔ 🇺🇸🔍 👔 📟, 🚶 ⏭ 📄.
+
+///
🇺🇸🔍, 👆 📨 🔢 👔 📟 3️⃣ 9️⃣ 🍕 📨.
@@ -54,8 +66,11 @@
* 💊 ❌ ⚪️➡️ 👩💻, 👆 💪 ⚙️ `400`.
* `500` & 🔛 💽 ❌. 👆 🌖 🙅 ⚙️ 👫 🔗. 🕐❔ 🕳 🚶 ❌ 🍕 👆 🈸 📟, ⚖️ 💽, ⚫️ 🔜 🔁 📨 1️⃣ 👫 👔 📟.
-!!! tip
- 💭 🌅 🔃 🔠 👔 📟 & ❔ 📟 ⚫️❔, ✅ 🏇 🧾 🔃 🇺🇸🔍 👔 📟.
+/// tip
+
+💭 🌅 🔃 🔠 👔 📟 & ❔ 📟 ⚫️❔, ✅ 🏇 🧾 🔃 🇺🇸🔍 👔 📟.
+
+///
## ⌨ 💭 📛
@@ -79,10 +94,13 @@
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette import status`.
+/// note | "📡 ℹ"
- **FastAPI** 🚚 🎏 `starlette.status` `fastapi.status` 🏪 👆, 👩💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃.
+👆 💪 ⚙️ `from starlette import 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`, 🔬 Pydantic 🩺: 🔗 🛃:
-=== "🐍 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!}
- ```
+```Python hl_lines="4 10-13"
+{!> ../../../docs_src/schema_extra_example/tutorial002.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="2 8-11"
- {!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-!!! warning
- 🚧 🤯 👈 📚 ➕ ❌ 🚶♀️ 🏆 🚫 🚮 🙆 🔬, 🕴 ➕ ℹ, 🧾 🎯.
+```Python hl_lines="2 8-11"
+{!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!}
+```
+
+////
+
+/// 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️⃣ & 🔛"
+////
- ```Python hl_lines="18-23"
- {!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```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️⃣ & 🔛"
+////
- ```Python hl_lines="19-45"
- {!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```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
- 🥇 ❎ `python-multipart`.
+/// info
- 🤶 Ⓜ. `pip install python-multipart`.
+🥇 ❎ `python-multipart`.
- 👉 ↩️ **Oauth2️⃣** ⚙️ "📨 📊" 📨 `username` & `password`.
+🤶 Ⓜ. `pip install python-multipart`.
+
+👉 ↩️ **Oauth2️⃣** ⚙️ "📨 📊" 📨 `username` & `password`.
+
+///
🏃 🖼 ⏮️:
@@ -53,17 +56,23 @@ $ uvicorn main:app --reload
-!!! check "✔ 🔼 ❗"
- 👆 ⏪ ✔️ ✨ 🆕 "✔" 🔼.
+/// check | "✔ 🔼 ❗"
- & 👆 *➡ 🛠️* ✔️ 🐥 🔒 🔝-▶️️ ↩ 👈 👆 💪 🖊.
+👆 ⏪ ✔️ ✨ 🆕 "✔" 🔼.
+
+ & 👆 *➡ 🛠️* ✔️ 🐥 🔒 🔝-▶️️ ↩ 👈 👆 💪 🖊.
+
+///
& 🚥 👆 🖊 ⚫️, 👆 ✔️ 🐥 ✔ 📨 🆎 `username` & `password` (& 🎏 📦 🏑):
-!!! note
- ⚫️ 🚫 🤔 ⚫️❔ 👆 🆎 📨, ⚫️ 🏆 🚫 👷. ✋️ 👥 🔜 🤚 📤.
+/// note
+
+⚫️ 🚫 🤔 ⚫️❔ 👆 🆎 📨, ⚫️ 🏆 🚫 👷. ✋️ 👥 🔜 🤚 📤.
+
+///
👉 ↗️ 🚫 🕸 🏁 👩💻, ✋️ ⚫️ 👑 🏧 🧰 📄 🖥 🌐 👆 🛠️.
@@ -105,14 +114,17 @@ Oauth2️⃣ 🔧 👈 👩💻 ⚖️ 🛠️ 💪 🔬 💽 👈 🔓 👩
👉 🖼 👥 🔜 ⚙️ **Oauth2️⃣**, ⏮️ **🔐** 💧, ⚙️ **📨** 🤝. 👥 👈 ⚙️ `OAuth2PasswordBearer` 🎓.
-!!! info
- "📨" 🤝 🚫 🕴 🎛.
+/// info
- ✋️ ⚫️ 🏆 1️⃣ 👆 ⚙️ 💼.
+"📨" 🤝 🚫 🕴 🎛.
- & ⚫️ 💪 🏆 🏆 ⚙️ 💼, 🚥 👆 Oauth2️⃣ 🕴 & 💭 ⚫️❔ ⚫️❔ 📤 ➕1️⃣ 🎛 👈 ♣ 👻 👆 💪.
+✋️ ⚫️ 🏆 1️⃣ 👆 ⚙️ 💼.
- 👈 💼, **FastAPI** 🚚 👆 ⏮️ 🧰 🏗 ⚫️.
+ & ⚫️ 💪 🏆 🏆 ⚙️ 💼, 🚥 👆 Oauth2️⃣ 🕴 & 💭 ⚫️❔ ⚫️❔ 📤 ➕1️⃣ 🎛 👈 ♣ 👻 👆 💪.
+
+👈 💼, **FastAPI** 🚚 👆 ⏮️ 🧰 🏗 ⚫️.
+
+///
🕐❔ 👥 ✍ 👐 `OAuth2PasswordBearer` 🎓 👥 🚶♀️ `tokenUrl` 🔢. 👉 🔢 🔌 📛 👈 👩💻 (🕸 🏃 👩💻 🖥) 🔜 ⚙️ 📨 `username` & `password` ✔ 🤚 🤝.
@@ -120,21 +132,27 @@ Oauth2️⃣ 🔧 👈 👩💻 ⚖️ 🛠️ 💪 🔬 💽 👈 🔓 👩
{!../../../docs_src/security/tutorial001.py!}
```
-!!! tip
- 📥 `tokenUrl="token"` 🔗 ⚖ 📛 `token` 👈 👥 🚫 ✍. ⚫️ ⚖ 📛, ⚫️ 🌓 `./token`.
+/// tip
- ↩️ 👥 ⚙️ ⚖ 📛, 🚥 👆 🛠️ 🔎 `https://example.com/`, ⤴️ ⚫️ 🔜 🔗 `https://example.com/token`. ✋️ 🚥 👆 🛠️ 🔎 `https://example.com/api/v1/`, ⤴️ ⚫️ 🔜 🔗 `https://example.com/api/v1/token`.
+📥 `tokenUrl="token"` 🔗 ⚖ 📛 `token` 👈 👥 🚫 ✍. ⚫️ ⚖ 📛, ⚫️ 🌓 `./token`.
- ⚙️ ⚖ 📛 ⚠ ⚒ 💭 👆 🈸 🚧 👷 🏧 ⚙️ 💼 💖 [⛅ 🗳](../../advanced/behind-a-proxy.md){.internal-link target=_blank}.
+↩️ 👥 ⚙️ ⚖ 📛, 🚥 👆 🛠️ 🔎 `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}.
+
+///
👉 🔢 🚫 ✍ 👈 🔗 / *➡ 🛠️*, ✋️ 📣 👈 📛 `/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 | "📡 ℹ"
- 🌐 💂♂ 🚙 👈 🛠️ ⏮️ 🗄 (& 🏧 🛠️ 🩺) 😖 ⚪️➡️ `SecurityBase`, 👈 ❔ **FastAPI** 💪 💭 ❔ 🛠️ 👫 🗄.
+**FastAPI** 🔜 💭 👈 ⚫️ 💪 ⚙️ 🎓 `OAuth2PasswordBearer` (📣 🔗) 🔬 💂♂ ⚖ 🗄 ↩️ ⚫️ 😖 ⚪️➡️ `fastapi.security.oauth2.OAuth2`, ❔ 🔄 😖 ⚪️➡️ `fastapi.security.base.SecurityBase`.
+
+🌐 💂♂ 🚙 👈 🛠️ ⏮️ 🗄 (& 🏧 🛠️ 🩺) 😖 ⚪️➡️ `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!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="3 10-14"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```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!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="23"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```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!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="17-20 24-25"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```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!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="29"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="29"
+{!> ../../../docs_src/security/tutorial002_py310.py!}
+```
+
+////
👀 👈 👥 📣 🆎 `current_user` Pydantic 🏷 `User`.
👉 🔜 ℹ 🇺🇲 🔘 🔢 ⏮️ 🌐 🛠️ & 🆎 ✅.
-!!! tip
- 👆 5️⃣📆 💭 👈 📨 💪 📣 ⏮️ Pydantic 🏷.
+/// tip
- 📥 **FastAPI** 🏆 🚫 🤚 😨 ↩️ 👆 ⚙️ `Depends`.
+👆 5️⃣📆 💭 👈 📨 💪 📣 ⏮️ Pydantic 🏷.
-!!! check
- 🌌 👉 🔗 ⚙️ 🏗 ✔ 👥 ✔️ 🎏 🔗 (🎏 "☑") 👈 🌐 📨 `User` 🏷.
+📥 **FastAPI** 🏆 🚫 🤚 😨 ↩️ 👆 ⚙️ `Depends`.
- 👥 🚫 🚫 ✔️ 🕴 1️⃣ 🔗 👈 💪 📨 👈 🆎 💽.
+///
+
+/// check
+
+🌌 👉 🔗 ⚙️ 🏗 ✔ 👥 ✔️ 🎏 🔗 (🎏 "☑") 👈 🌐 📨 `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!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="28-30"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```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️⃣: )/⚛.
-!!! tip
- 👉 🔰 ⏪ ⚙️ PyJWT.
+/// tip
- ✋️ ⚫️ ℹ ⚙️ 🐍-🇩🇬 ↩️ ⚫️ 🚚 🌐 ⚒ ⚪️➡️ PyJWT ➕ ➕ 👈 👆 💪 💪 ⏪ 🕐❔ 🏗 🛠️ ⏮️ 🎏 🧰.
+👉 🔰 ⏪ ⚙️ PyJWT.
+
+✋️ ⚫️ ℹ ⚙️ 🐍-🇩🇬 ↩️ ⚫️ 🚚 🌐 ⚒ ⚪️➡️ PyJWT ➕ ➕ 👈 👆 💪 💪 ⏪ 🕐❔ 🏗 🛠️ ⏮️ 🎏 🧰.
+
+///
## 🔐 🔁
@@ -83,12 +86,15 @@ $ pip install "passlib[bcrypt]"
@@ -261,8 +292,11 @@ $ openssl rand -hex 32
-!!! 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 765d94039..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
- 🚥 👆 💪 🛠️ ⚫️, ⚙️ `OAuth2PasswordRequestFormStrict` ↩️ `OAuth2PasswordRequestForm`.
+Oauth2️⃣ 🔌 🤙 *🚚* 🏑 `grant_type` ⏮️ 🔧 💲 `password`, ✋️ `OAuth2PasswordRequestForm` 🚫 🛠️ ⚫️.
+
+🚥 👆 💪 🛠️ ⚫️, ⚙️ `OAuth2PasswordRequestFormStrict` ↩️ `OAuth2PasswordRequestForm`.
+
+///
* 📦 `client_id` (👥 🚫 💪 ⚫️ 👆 🖼).
* 📦 `client_secret` (👥 🚫 💪 ⚫️ 👆 🖼).
-!!! info
- `OAuth2PasswordRequestForm` 🚫 🎁 🎓 **FastAPI** `OAuth2PasswordBearer`.
+/// info
- `OAuth2PasswordBearer` ⚒ **FastAPI** 💭 👈 ⚫️ 💂♂ ⚖. ⚫️ 🚮 👈 🌌 🗄.
+`OAuth2PasswordRequestForm` 🚫 🎁 🎓 **FastAPI** `OAuth2PasswordBearer`.
- ✋️ `OAuth2PasswordRequestForm` 🎓 🔗 👈 👆 💪 ✔️ ✍ 👆, ⚖️ 👆 💪 ✔️ 📣 `Form` 🔢 🔗.
+`OAuth2PasswordBearer` ⚒ **FastAPI** 💭 👈 ⚫️ 💂♂ ⚖. ⚫️ 🚮 👈 🌌 🗄.
- ✋️ ⚫️ ⚠ ⚙️ 💼, ⚫️ 🚚 **FastAPI** 🔗, ⚒ ⚫️ ⏩.
+✋️ `OAuth2PasswordRequestForm` 🎓 🔗 👈 👆 💪 ✔️ ✍ 👆, ⚖️ 👆 💪 ✔️ 📣 `Form` 🔢 🔗.
+
+✋️ ⚫️ ⚠ ⚙️ 💼, ⚫️ 🚚 **FastAPI** 🔗, ⚒ ⚫️ ⏩.
+
+///
### ⚙️ 📨 💽
-!!! tip
- 👐 🔗 🎓 `OAuth2PasswordRequestForm` 🏆 🚫 ✔️ 🔢 `scope` ⏮️ 📏 🎻 👽 🚀, ↩️, ⚫️ 🔜 ✔️ `scopes` 🔢 ⏮️ ☑ 📇 🎻 🔠 ↔ 📨.
+/// tip
- 👥 🚫 ⚙️ `scopes` 👉 🖼, ✋️ 🛠️ 📤 🚥 👆 💪 ⚫️.
+👐 🔗 🎓 `OAuth2PasswordRequestForm` 🏆 🚫 ✔️ 🔢 `scope` ⏮️ 📏 🎻 👽 🚀, ↩️, ⚫️ 🔜 ✔️ `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!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="78-81"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="78-81"
+{!> ../../../docs_src/security/tutorial003_py310.py!}
+```
+
+////
#### 🔃 `**user_dict`
@@ -162,8 +186,11 @@ UserInDB(
)
```
-!!! info
- 🌅 🏁 🔑 `**👩💻_ #️⃣ ` ✅ 🔙 [🧾 **➕ 🏷**](../extra-models.md#about-user_indict){.internal-link target=_blank}.
+/// info
+
+🌅 🏁 🔑 `**👩💻_ #️⃣ ` ✅ 🔙 [🧾 **➕ 🏷**](../extra-models.md#user_indict){.internal-link target=_blank}.
+
+///
## 📨 🤝
@@ -175,31 +202,41 @@ UserInDB(
👉 🙅 🖼, 👥 🔜 🍕 😟 & 📨 🎏 `username` 🤝.
-!!! tip
- ⏭ 📃, 👆 🔜 👀 🎰 🔐 🛠️, ⏮️ 🔐 #️⃣ & 🥙 🤝.
+/// tip
- ✋️ 🔜, ➡️ 🎯 🔛 🎯 ℹ 👥 💪.
+⏭ 📃, 👆 🔜 👀 🎰 🔐 🛠️, ⏮️ 🔐 #️⃣ & 🥙 🤝.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+✋️ 🔜, ➡️ 🎯 🔛 🎯 ℹ 👥 💪.
- ```Python hl_lines="85"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+///
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="83"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+```Python hl_lines="85"
+{!> ../../../docs_src/security/tutorial003.py!}
+```
-!!! tip
- 🔌, 👆 🔜 📨 🎻 ⏮️ `access_token` & `token_type`, 🎏 👉 🖼.
+////
- 👉 🕳 👈 👆 ✔️ 👆 👆 📟, & ⚒ 💭 👆 ⚙️ 📚 🎻 🔑.
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
- ⚫️ 🌖 🕴 👜 👈 👆 ✔️ 💭 ☑ 👆, 🛠️ ⏮️ 🔧.
+```Python hl_lines="83"
+{!> ../../../docs_src/security/tutorial003_py310.py!}
+```
- 🎂, **FastAPI** 🍵 ⚫️ 👆.
+////
+
+/// tip
+
+🔌, 👆 🔜 📨 🎻 ⏮️ `access_token` & `token_type`, 🎏 👉 🖼.
+
+👉 🕳 👈 👆 ✔️ 👆 👆 📟, & ⚒ 💭 👆 ⚙️ 📚 🎻 🔑.
+
+⚫️ 🌖 🕴 👜 👈 👆 ✔️ 💭 ☑ 👆, 🛠️ ⏮️ 🔧.
+
+🎂, **FastAPI** 🍵 ⚫️ 👆.
+
+///
## ℹ 🔗
@@ -213,32 +250,39 @@ UserInDB(
, 👆 🔗, 👥 🔜 🕴 🤚 👩💻 🚥 👩💻 🔀, ☑ 🔓, & 🦁:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="58-66 69-72 90"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+```Python hl_lines="58-66 69-72 90"
+{!> ../../../docs_src/security/tutorial003.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="55-64 67-70 88"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-!!! info
- 🌖 🎚 `WWW-Authenticate` ⏮️ 💲 `Bearer` 👥 🛬 📥 🍕 🔌.
+```Python hl_lines="55-64 67-70 88"
+{!> ../../../docs_src/security/tutorial003_py310.py!}
+```
- 🙆 🇺🇸🔍 (❌) 👔 📟 4️⃣0️⃣1️⃣ "⛔" 🤔 📨 `WWW-Authenticate` 🎚.
+////
- 💼 📨 🤝 (👆 💼), 💲 👈 🎚 🔜 `Bearer`.
+/// info
- 👆 💪 🤙 🚶 👈 ➕ 🎚 & ⚫️ 🔜 👷.
+🌖 🎚 `WWW-Authenticate` ⏮️ 💲 `Bearer` 👥 🛬 📥 🍕 🔌.
- ✋️ ⚫️ 🚚 📥 🛠️ ⏮️ 🔧.
+🙆 🇺🇸🔍 (❌) 👔 📟 4️⃣0️⃣1️⃣ "⛔" 🤔 📨 `WWW-Authenticate` 🎚.
- , 📤 5️⃣📆 🧰 👈 ⌛ & ⚙️ ⚫️ (🔜 ⚖️ 🔮) & 👈 💪 ⚠ 👆 ⚖️ 👆 👩💻, 🔜 ⚖️ 🔮.
+💼 📨 🤝 (👆 💼), 💲 👈 🎚 🔜 `Bearer`.
- 👈 💰 🐩...
+👆 💪 🤙 🚶 👈 ➕ 🎚 & ⚫️ 🔜 👷.
+
+✋️ ⚫️ 🚚 📥 🛠️ ⏮️ 🔧.
+
+, 📤 5️⃣📆 🧰 👈 ⌛ & ⚙️ ⚫️ (🔜 ⚖️ 🔮) & 👈 💪 ⚠ 👆 ⚖️ 👆 👩💻, 🔜 ⚖️ 🔮.
+
+👈 💰 🐩...
+
+///
## 👀 ⚫️ 🎯
diff --git a/docs/em/docs/tutorial/sql-databases.md b/docs/em/docs/tutorial/sql-databases.md
index ef08fcf4b..2492c8708 100644
--- a/docs/em/docs/tutorial/sql-databases.md
+++ b/docs/em/docs/tutorial/sql-databases.md
@@ -18,13 +18,19 @@
⏪, 👆 🏭 🈸, 👆 💪 💚 ⚙️ 💽 💽 💖 **✳**.
-!!! tip
- 📤 🛂 🏗 🚂 ⏮️ **FastAPI** & **✳**, 🌐 ⚓️ 🔛 **☁**, 🔌 🕸 & 🌖 🧰: https://github.com/tiangolo/full-stack-fastapi-postgresql
+/// tip
-!!! note
- 👀 👈 📚 📟 🐩 `SQLAlchemy` 📟 👆 🔜 ⚙️ ⏮️ 🙆 🛠️.
+📤 🛂 🏗 🚂 ⏮️ **FastAPI** & **✳**, 🌐 ⚓️ 🔛 **☁**, 🔌 🕸 & 🌖 🧰: https://github.com/tiangolo/full-stack-fastapi-postgresql
- **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 🏷 🔬 🌅 ⚖️ 🌘 "🔗" (☑ 📊 💠).
+❎ 😨 🖖 🇸🇲 *🏷* & Pydantic *🏷*, 👥 🔜 ✔️ 📁 `models.py` ⏮️ 🇸🇲 🏷, & 📁 `schemas.py` ⏮️ 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!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="3 6-8 11-12 23-24 27-28"
- {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="3 6-8 11-12 23-24 27-28"
+{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
+```
- ```Python hl_lines="1 4-6 9-10 21-22 25-26"
- {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
- ```
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="1 4-6 9-10 21-22 25-26"
+{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
+```
+
+////
#### 🇸🇲 👗 & Pydantic 👗
@@ -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!}
- ```
+```Python hl_lines="15-17 31-34"
+{!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="15-17 31-34"
- {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```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!}
- ```
+////
-!!! tip
- 👀 👈 `User`, Pydantic *🏷* 👈 🔜 ⚙️ 🕐❔ 👂 👩💻 (🛬 ⚫️ ⚪️➡️ 🛠️) 🚫 🔌 `password`.
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="13-15 29-32"
+{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
+```
+
+////
+
+/// tip
+
+👀 👈 `User`, Pydantic *🏷* 👈 🔜 ⚙️ 🕐❔ 👂 👩💻 (🛬 ⚫️ ⚪️➡️ 🛠️) 🚫 🔌 `password`.
+
+///
### ⚙️ Pydantic `orm_mode`
@@ -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!}
- ```
+```Python hl_lines="15 19-20 31 36-37"
+{!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="15 19-20 31 36-37"
- {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="15 19-20 31 36-37"
+{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
+```
- ```Python hl_lines="13 17-18 29 34-35"
- {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
- ```
+////
-!!! tip
- 👀 ⚫️ ⚖ 💲 ⏮️ `=`, 💖:
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
- `orm_mode = True`
+```Python hl_lines="13 17-18 29 34-35"
+{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
+```
- ⚫️ 🚫 ⚙️ `:` 🆎 📄 ⏭.
+////
- 👉 ⚒ 📁 💲, 🚫 📣 🆎.
+/// tip
+
+👀 ⚫️ ⚖ 💲 ⏮️ `=`, 💖:
+
+`orm_mode = True`
+
+⚫️ 🚫 ⚙️ `:` 🆎 📄 ⏭.
+
+👉 ⚒ 📁 💲, 🚫 📣 🆎.
+
+///
Pydantic `orm_mode` 🔜 💬 Pydantic *🏷* ✍ 💽 🚥 ⚫️ 🚫 `dict`, ✋️ 🐜 🏷 (⚖️ 🙆 🎏 ❌ 🎚 ⏮️ 🔢).
@@ -426,8 +469,11 @@ current_user.items
{!../../../docs_src/sql_databases/sql_app/crud.py!}
```
-!!! tip
- 🏗 🔢 👈 🕴 💡 🔗 ⏮️ 💽 (🤚 👩💻 ⚖️ 🏬) 🔬 👆 *➡ 🛠️ 🔢*, 👆 💪 🌖 💪 ♻ 👫 💗 🍕 & 🚮 ⚒ 💯 👫.
+/// tip
+
+🏗 🔢 👈 🕴 💡 🔗 ⏮️ 💽 (🤚 👩💻 ⚖️ 🏬) 🔬 👆 *➡ 🛠️ 🔢*, 👆 💪 🌖 💪 ♻ 👫 💗 🍕 & 🚮 ⚒ 💯 👫.
+
+///
### ✍ 💽
@@ -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!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
+
+```Python hl_lines="7"
+{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
+```
+
+////
#### ⚗ 🗒
@@ -501,7 +560,7 @@ current_user.items
"🛠️" ⚒ 🔁 💪 🕐❔ 👆 🔀 📊 👆 🇸🇲 🏷, 🚮 🆕 🔢, ♒️. 🔁 👈 🔀 💽, 🚮 🆕 🏓, 🆕 🏓, ♒️.
-👆 💪 🔎 🖼 ⚗ FastAPI 🏗 📄 ⚪️➡️ [🏗 ⚡ - 📄](../project-generation.md){.internal-link target=_blank}. 🎯 `alembic` 📁 ℹ 📟.
+👆 💪 🔎 🖼 ⚗ FastAPI 🏗 📄 ⚪️➡️ [🏗 ⚡ - 📄](../project-generation.md){.internal-link target=_blank}. 🎯 `alembic` 📁 ℹ 📟.
### ✍ 🔗
@@ -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!}
- ```
+```Python hl_lines="15-20"
+{!> ../../../docs_src/sql_databases/sql_app/main.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="13-18"
- {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-!!! info
- 👥 🚮 🏗 `SessionLocal()` & 🚚 📨 `try` 🍫.
+```Python hl_lines="13-18"
+{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
+```
- & ⤴️ 👥 🔐 ⚫️ `finally` 🍫.
+////
- 👉 🌌 👥 ⚒ 💭 💽 🎉 🕧 📪 ⏮️ 📨. 🚥 📤 ⚠ ⏪ 🏭 📨.
+/// info
- ✋️ 👆 💪 🚫 🤚 ➕1️⃣ ⚠ ⚪️➡️ 🚪 📟 (⏮️ `yield`). 👀 🌖 [🔗 ⏮️ `yield` & `HTTPException`](./dependencies/dependencies-with-yield.md#dependencies-with-yield-and-httpexception){.internal-link target=_blank}
+👥 🚮 🏗 `SessionLocal()` & 🚚 📨 `try` 🍫.
+
+ & ⤴️ 👥 🔐 ⚫️ `finally` 🍫.
+
+👉 🌌 👥 ⚒ 💭 💽 🎉 🕧 📪 ⏮️ 📨. 🚥 📤 ⚠ ⏪ 🏭 📨.
+
+✋️ 👆 💪 🚫 🤚 ➕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!}
- ```
+```Python hl_lines="24 32 38 47 53"
+{!> ../../../docs_src/sql_databases/sql_app/main.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="22 30 36 45 51"
- {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-!!! info "📡 ℹ"
- 🔢 `db` 🤙 🆎 `SessionLocal`, ✋️ 👉 🎓 (✍ ⏮️ `sessionmaker()`) "🗳" 🇸🇲 `Session`,, 👨🎨 🚫 🤙 💭 ⚫️❔ 👩🔬 🚚.
+```Python hl_lines="22 30 36 45 51"
+{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
+```
- ✋️ 📣 🆎 `Session`, 👨🎨 🔜 💪 💭 💪 👩🔬 (`.add()`, `.query()`, `.commit()`, ♒️) & 💪 🚚 👍 🐕🦺 (💖 🛠️). 🆎 📄 🚫 📉 ☑ 🎚.
+////
+
+/// info | "📡 ℹ"
+
+🔢 `db` 🤙 🆎 `SessionLocal`, ✋️ 👉 🎓 (✍ ⏮️ `sessionmaker()`) "🗳" 🇸🇲 `Session`,, 👨🎨 🚫 🤙 💭 ⚫️❔ 👩🔬 🚚.
+
+✋️ 📣 🆎 `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!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="21-26 29-32 35-40 43-47 50-53"
- {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
+
+```Python hl_lines="21-26 29-32 35-40 43-47 50-53"
+{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
+```
+
+////
👥 🏗 💽 🎉 ⏭ 🔠 📨 🔗 ⏮️ `yield`, & ⤴️ 📪 ⚫️ ⏮️.
@@ -579,15 +656,21 @@ current_user.items
⏮️ 👈, 👥 💪 🤙 `crud.get_user` 🔗 ⚪️➡️ 🔘 *➡ 🛠️ 🔢* & ⚙️ 👈 🎉.
-!!! tip
- 👀 👈 💲 👆 📨 🇸🇲 🏷, ⚖️ 📇 🇸🇲 🏷.
+/// tip
- ✋️ 🌐 *➡ 🛠️* ✔️ `response_model` ⏮️ Pydantic *🏷* / 🔗 ⚙️ `orm_mode`, 💽 📣 👆 Pydantic 🏷 🔜 ⚗ ⚪️➡️ 👫 & 📨 👩💻, ⏮️ 🌐 😐 ⛽ & 🔬.
+👀 👈 💲 👆 📨 🇸🇲 🏷, ⚖️ 📇 🇸🇲 🏷.
-!!! tip
- 👀 👈 📤 `response_models` 👈 ✔️ 🐩 🐍 🆎 💖 `List[schemas.Item]`.
+✋️ 🌐 *➡ 🛠️* ✔️ `response_model` ⏮️ Pydantic *🏷* / 🔗 ⚙️ `orm_mode`, 💽 📣 👆 Pydantic 🏷 🔜 ⚗ ⚪️➡️ 👫 & 📨 👩💻, ⏮️ 🌐 😐 ⛽ & 🔬.
- ✋️ 🎚/🔢 👈 `List` Pydantic *🏷* ⏮️ `orm_mode`, 💽 🔜 🗃 & 📨 👩💻 🛎, 🍵 ⚠.
+///
+
+/// tip
+
+👀 👈 📤 `response_models` 👈 ✔️ 🐩 🐍 🆎 💖 `List[schemas.Item]`.
+
+✋️ 🎚/🔢 👈 `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#very-technical-details){.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!}
- ```
+```Python
+{!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python
- {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python
+{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
+```
- ```Python
- {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
- ```
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```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!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python
- {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
+
+```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!}
- ```
+```Python hl_lines="14-22"
+{!> ../../../docs_src/sql_databases/sql_app/alt_main.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="12-20"
- {!> ../../../docs_src/sql_databases/sql_app_py39/alt_main.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-!!! info
- 👥 🚮 🏗 `SessionLocal()` & 🚚 📨 `try` 🍫.
+```Python hl_lines="12-20"
+{!> ../../../docs_src/sql_databases/sql_app_py39/alt_main.py!}
+```
- & ⤴️ 👥 🔐 ⚫️ `finally` 🍫.
+////
- 👉 🌌 👥 ⚒ 💭 💽 🎉 🕧 📪 ⏮️ 📨. 🚥 📤 ⚠ ⏪ 🏭 📨.
+/// info
+
+👥 🚮 🏗 `SessionLocal()` & 🚚 📨 `try` 🍫.
+
+ & ⤴️ 👥 🔐 ⚫️ `finally` 🍫.
+
+👉 🌌 👥 ⚒ 💭 💽 🎉 🕧 📪 ⏮️ 📨. 🚥 📤 ⚠ ⏪ 🏭 📨.
+
+///
### 🔃 `request.state`
@@ -777,10 +885,16 @@ $ uvicorn sql_app.main:app --reload
* , 🔗 🔜 ✍ 🔠 📨.
* 🕐❔ *➡ 🛠️* 👈 🍵 👈 📨 🚫 💪 💽.
-!!! tip
- ⚫️ 🎲 👍 ⚙️ 🔗 ⏮️ `yield` 🕐❔ 👫 🥃 ⚙️ 💼.
+/// tip
-!!! info
- 🔗 ⏮️ `yield` 🚮 ⏳ **FastAPI**.
+⚫️ 🎲 👍 ⚙️ 🔗 ⏮️ `yield` 🕐❔ 👫 🥃 ⚙️ 💼.
- ⏮️ ⏬ 👉 🔰 🕴 ✔️ 🖼 ⏮️ 🛠️ & 📤 🎲 📚 🈸 ⚙️ 🛠️ 💽 🎉 🧾.
+///
+
+/// 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 999d67cd3..75dd2d295 100644
--- a/docs/em/docs/tutorial/testing.md
+++ b/docs/em/docs/tutorial/testing.md
@@ -8,10 +8,13 @@
## ⚙️ `TestClient`
-!!! info
- ⚙️ `TestClient`, 🥇 ❎ `httpx`.
+/// info
- 🤶 Ⓜ. `pip install httpx`.
+⚙️ `TestClient`, 🥇 ❎ `httpx`.
+
+🤶 Ⓜ. `pip install httpx`.
+
+///
🗄 `TestClient`.
@@ -27,20 +30,29 @@
{!../../../docs_src/app_testing/tutorial001.py!}
```
-!!! tip
- 👀 👈 🔬 🔢 😐 `def`, 🚫 `async def`.
+/// tip
- & 🤙 👩💻 😐 🤙, 🚫 ⚙️ `await`.
+👀 👈 🔬 🔢 😐 `def`, 🚫 `async def`.
- 👉 ✔ 👆 ⚙️ `pytest` 🔗 🍵 🤢.
+ & 🤙 👩💻 😐 🤙, 🚫 ⚙️ `await`.
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette.testclient import TestClient`.
+👉 ✔ 👆 ⚙️ `pytest` 🔗 🍵 🤢.
- **FastAPI** 🚚 🎏 `starlette.testclient` `fastapi.testclient` 🏪 👆, 👩💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃.
+///
-!!! tip
- 🚥 👆 💚 🤙 `async` 🔢 👆 💯 ↖️ ⚪️➡️ 📨 📨 👆 FastAPI 🈸 (✅ 🔁 💽 🔢), ✔️ 👀 [🔁 💯](../advanced/async-tests.md){.internal-link target=_blank} 🏧 🔰.
+/// note | "📡 ℹ"
+
+👆 💪 ⚙️ `from starlette.testclient import TestClient`.
+
+**FastAPI** 🚚 🎏 `starlette.testclient` `fastapi.testclient` 🏪 👆, 👩💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃.
+
+///
+
+/// tip
+
+🚥 👆 💚 🤙 `async` 🔢 👆 💯 ↖️ ⚪️➡️ 📨 📨 👆 FastAPI 🈸 (✅ 🔁 💽 🔢), ✔️ 👀 [🔁 💯](../advanced/async-tests.md){.internal-link target=_blank} 🏧 🔰.
+
+///
## 🎏 💯
@@ -50,7 +62,7 @@
### **FastAPI** 📱 📁
-➡️ 💬 👆 ✔️ 📁 📊 🔬 [🦏 🈸](./bigger-applications.md){.internal-link target=_blank}:
+➡️ 💬 👆 ✔️ 📁 📊 🔬 [🦏 🈸](bigger-applications.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!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python
- {!> ../../../docs_src/app_testing/app_b_py310/main.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python
+{!> ../../../docs_src/app_testing/app_b_py310/main.py!}
+```
+
+////
### ↔ 🔬 📁
@@ -144,10 +160,13 @@
🌖 ℹ 🔃 ❔ 🚶♀️ 💽 👩💻 (⚙️ `httpx` ⚖️ `TestClient`) ✅ 🇸🇲 🧾.
-!!! info
- 🗒 👈 `TestClient` 📨 💽 👈 💪 🗜 🎻, 🚫 Pydantic 🏷.
+/// info
- 🚥 👆 ✔️ Pydantic 🏷 👆 💯 & 👆 💚 📨 🚮 💽 🈸 ⏮️ 🔬, 👆 💪 ⚙️ `jsonable_encoder` 🔬 [🎻 🔗 🔢](encoder.md){.internal-link target=_blank}.
+🗒 👈 `TestClient` 📨 💽 👈 💪 🗜 🎻, 🚫 Pydantic 🏷.
+
+🚥 👆 ✔️ Pydantic 🏷 👆 💯 & 👆 💚 📨 🚮 💽 🈸 ⏮️ 🔬, 👆 💪 ⚙️ `jsonable_encoder` 🔬 [🎻 🔗 🔢](encoder.md){.internal-link target=_blank}.
+
+///
## 🏃 ⚫️
diff --git a/docs/en/data/external_links.yml b/docs/en/data/external_links.yml
index 827581de5..15f6169ee 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
@@ -24,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
@@ -257,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
@@ -347,6 +354,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
diff --git a/docs/en/data/github_sponsors.yml b/docs/en/data/github_sponsors.yml
index fb690708f..5f0be61c2 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,9 +11,15 @@ 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
+ - 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
@@ -62,21 +65,12 @@ sponsors:
- - 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
- login: mangualero
avatarUrl: https://avatars.githubusercontent.com/u/3422968?u=c59272d7b5a912d6126fd6c6f17db71e20f506eb&v=4
url: https://github.com/mangualero
@@ -92,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
@@ -101,18 +98,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: 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
- - 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
@@ -122,6 +119,9 @@ sponsors:
- login: ProteinQure
avatarUrl: https://avatars.githubusercontent.com/u/33707203?v=4
url: https://github.com/ProteinQure
+ - login: catherinenelson1
+ avatarUrl: https://avatars.githubusercontent.com/u/11951946?u=e714b957185b8cf3d301cced7fc3ad2842122c6a&v=4
+ url: https://github.com/catherinenelson1
- login: jsoques
avatarUrl: https://avatars.githubusercontent.com/u/12414216?u=620921d94196546cc8b9eae2cc4cbc3f95bab42f&v=4
url: https://github.com/jsoques
@@ -137,21 +137,18 @@ 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
- 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: 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
@@ -164,12 +161,18 @@ 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
- login: apitally
avatarUrl: https://avatars.githubusercontent.com/u/138365043?v=4
url: https://github.com/apitally
- - login: thenickben
- avatarUrl: https://avatars.githubusercontent.com/u/40610922?u=1e907d904041b7c91213951a3cb344cd37c14aaf&v=4
- url: https://github.com/thenickben
+ - login: logic-automation
+ avatarUrl: https://avatars.githubusercontent.com/u/144732884?v=4
+ url: https://github.com/logic-automation
- login: ddilidili
avatarUrl: https://avatars.githubusercontent.com/u/42176885?u=c0a849dde06987434653197b5f638d3deb55fc6c&v=4
url: https://github.com/ddilidili
@@ -182,15 +185,12 @@ sponsors:
- 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
- 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,12 +209,27 @@ 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: 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
- 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
@@ -233,9 +248,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,15 +260,6 @@ sponsors:
- 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
@@ -266,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
@@ -276,14 +282,11 @@ 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
@@ -293,6 +296,12 @@ sponsors:
- - login: pawamoy
avatarUrl: https://avatars.githubusercontent.com/u/3999221?u=b030e4c89df2f3a36bc4710b925bdeb6745c9856&v=4
url: https://github.com/pawamoy
+ - login: SebTota
+ avatarUrl: https://avatars.githubusercontent.com/u/25122511?v=4
+ url: https://github.com/SebTota
+ - login: nisutec
+ avatarUrl: https://avatars.githubusercontent.com/u/25281462?u=e562484c451fdfc59053163f64405f8eb262b8b0&v=4
+ url: https://github.com/nisutec
- login: hoenie-ams
avatarUrl: https://avatars.githubusercontent.com/u/25708487?u=cda07434f0509ac728d9edf5e681117c0f6b818b&v=4
url: https://github.com/hoenie-ams
@@ -302,21 +311,18 @@ 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
- login: engineerjoe440
avatarUrl: https://avatars.githubusercontent.com/u/33275230?u=eb223cad27017bb1e936ee9b429b450d092d0236&v=4
url: https://github.com/engineerjoe440
- login: bnkc
- avatarUrl: https://avatars.githubusercontent.com/u/34930566?u=fa1dc8db3e920cf5c5636b97180a6f811fa01aaf&v=4
+ avatarUrl: https://avatars.githubusercontent.com/u/34930566?u=db5e6f4f87836cad26c2aa90ce390ce49041c5a9&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: DevOpsKev
+ avatarUrl: https://avatars.githubusercontent.com/u/36336550?u=6ccd5978fdaab06f37e22f2a14a7439341df7f67&v=4
+ url: https://github.com/DevOpsKev
+ - login: petercool
+ avatarUrl: https://avatars.githubusercontent.com/u/37613029?u=81c525232bb35780945a68e88afd96bb2cdad9c4&v=4
+ url: https://github.com/petercool
- login: JimFawkes
avatarUrl: https://avatars.githubusercontent.com/u/12075115?u=dc58ecfd064d72887c34bf500ddfd52592509acd&v=4
url: https://github.com/JimFawkes
@@ -332,42 +338,33 @@ 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: 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: 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
- - 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: zk-Call
+ avatarUrl: https://avatars.githubusercontent.com/u/147117264?v=4
+ url: https://github.com/zk-Call
- login: kristiangronberg
avatarUrl: https://avatars.githubusercontent.com/u/42678548?v=4
url: https://github.com/kristiangronberg
@@ -377,21 +374,27 @@ 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
+ - 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=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: 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
- login: miguelgr
avatarUrl: https://avatars.githubusercontent.com/u/1484589?u=54556072b8136efa12ae3b6902032ea2a39ace4b&v=4
url: https://github.com/miguelgr
@@ -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
@@ -434,9 +434,6 @@ sponsors:
- 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
@@ -452,8 +449,11 @@ 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
+ 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
@@ -476,9 +476,15 @@ 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
+ - 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
@@ -489,7 +495,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,21 +503,30 @@ sponsors:
- login: jakeecolution
avatarUrl: https://avatars.githubusercontent.com/u/5884696?u=4a7c7883fb064b593b50cb6697b54687e6f7aafe&v=4
url: https://github.com/jakeecolution
+ - login: stephane-rbn
+ avatarUrl: https://avatars.githubusercontent.com/u/5939522?u=eb7ffe768fa3bcbcd04de14fe4a47444cc00ec4c&v=4
+ url: https://github.com/stephane-rbn
- - login: danburonline
avatarUrl: https://avatars.githubusercontent.com/u/34251194?u=94935cccfbec58083ab1e535212d54f1bf2c978a&v=4
url: https://github.com/danburonline
+ - login: AliYmn
+ avatarUrl: https://avatars.githubusercontent.com/u/18416653?u=0de5a262e8b4dc0a08d065f30f7a39941e246530&v=4
+ url: https://github.com/AliYmn
- login: sadikkuzu
avatarUrl: https://avatars.githubusercontent.com/u/23168063?u=d179c06bb9f65c4167fcab118526819f8e0dac17&v=4
url: https://github.com/sadikkuzu
+ - login: tran-hai-long
+ avatarUrl: https://avatars.githubusercontent.com/u/119793901?u=3b173a845dcf099b275bdc9713a69cbbc36040ce&v=4
+ url: https://github.com/tran-hai-long
- login: rwxd
avatarUrl: https://avatars.githubusercontent.com/u/40308458?u=cd04a39e3655923be4f25c2ba8a5a07b3da3230a&v=4
url: https://github.com/rwxd
- - 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/members.yml b/docs/en/data/members.yml
new file mode 100644
index 000000000..0069f8c75
--- /dev/null
+++ b/docs/en/data/members.yml
@@ -0,0 +1,19 @@
+members:
+- login: tiangolo
+ avatar_url: https://avatars.githubusercontent.com/u/1326112
+ url: https://github.com/tiangolo
+- login: Kludex
+ avatar_url: https://avatars.githubusercontent.com/u/7353520
+ url: https://github.com/Kludex
+- login: alejsdev
+ avatar_url: https://avatars.githubusercontent.com/u/90076947
+ url: https://github.com/alejsdev
+- login: svlandeg
+ avatar_url: https://avatars.githubusercontent.com/u/8796347
+ url: https://github.com/svlandeg
+- login: estebanx64
+ avatar_url: https://avatars.githubusercontent.com/u/10840422
+ url: https://github.com/estebanx64
+- login: patrick91
+ avatar_url: https://avatars.githubusercontent.com/u/667029
+ url: https://github.com/patrick91
diff --git a/docs/en/data/people.yml b/docs/en/data/people.yml
index 710c650fd..02d1779e0 100644
--- a/docs/en/data/people.yml
+++ b/docs/en/data/people.yml
@@ -1,12 +1,12 @@
maintainers:
- login: tiangolo
- answers: 1878
- prs: 550
+ answers: 1885
+ prs: 577
avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=740f11212a731f56798f558ceddb0bd07642afa7&v=4
url: https://github.com/tiangolo
experts:
- login: Kludex
- count: 596
+ 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: 232
+ 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=bba5af018423a2858d49309bed2a899bb5c34ac5&v=4
+ avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=29682e4b6ac7d5293742ccf818188394b9a82972&v=4
url: https://github.com/ycd
- login: JarroVGIT
count: 193
@@ -41,42 +41,50 @@ 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: 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: 64
+ 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: 52
- avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4
- url: https://github.com/JavierSanchezCastro
- login: n8sty
- count: 52
+ count: 56
avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4
url: https://github.com/n8sty
+- login: acidjunk
+ count: 50
+ avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4
+ url: https://github.com/acidjunk
+- login: yinziyan1206
+ count: 49
+ avatarUrl: https://avatars.githubusercontent.com/u/37829370?u=da44ca53aefd5c23f346fab8e9fd2e108294c179&v=4
+ url: https://github.com/yinziyan1206
- login: sm-Fifteen
count: 49
avatarUrl: https://avatars.githubusercontent.com/u/516999?u=437c0c5038558c67e887ccd863c1ba0f846c03da&v=4
url: https://github.com/sm-Fifteen
-- login: 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: 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
@@ -85,10 +93,6 @@ experts:
count: 45
avatarUrl: https://avatars.githubusercontent.com/u/1755071?u=612704256e38d6ac9cbed24f10e4b6ac2da74ecb&v=4
url: https://github.com/adriangb
-- login: insomnes
- count: 45
- avatarUrl: https://avatars.githubusercontent.com/u/16958893?u=f8be7088d5076d963984a21f95f44e559192d912&v=4
- url: https://github.com/insomnes
- login: frankie567
count: 43
avatarUrl: https://avatars.githubusercontent.com/u/1144727?u=c159fe047727aedecbbeeaa96a1b03ceb9d39add&v=4
@@ -121,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
@@ -129,10 +137,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
@@ -141,14 +145,14 @@ experts:
count: 23
avatarUrl: https://avatars.githubusercontent.com/u/9435877?u=719327b7d2c4c62212456d771bfa7c6b8dbb9eac&v=4
url: https://github.com/SirTelemak
+- login: nymous
+ count: 22
+ 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
@@ -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,112 +189,257 @@ 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
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: 24
+ count: 29
avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4
url: https://github.com/YuriiMotov
+- 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: 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/160476156?u=7a8e44f4a43d3bba636f795bb7d9476c9233b4d8&v=4
+ url: https://github.com/PhysicallyActive
+- login: n8sty
+ count: 2
+ avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4
+ url: https://github.com/n8sty
+- login: pedroconceicao
+ count: 2
+ avatarUrl: https://avatars.githubusercontent.com/u/32837064?u=5a0e6559bc391442629a28b6923790b54deb4464&v=4
+ url: https://github.com/pedroconceicao
+- login: PREPONDERANCE
+ count: 2
+ 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/2835374?u=3c3ed29aa8b09ccaf8d66def0ce82bc2f7e5aab6&v=4
+ url: https://github.com/aanchlia
+- login: 0sahil
+ count: 2
+ 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/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4
+ url: https://github.com/jgould22
+three_months_experts:
+- login: YuriiMotov
+ 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: 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: 11
+ count: 14
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: killjoy1221
+ count: 8
+ avatarUrl: https://avatars.githubusercontent.com/u/3409962?u=723662989f2027755e67d200137c13c53ae154ac&v=4
+ url: https://github.com/killjoy1221
+- login: hasansezertasan
+ count: 8
+ avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4
+ url: https://github.com/hasansezertasan
+- login: PhysicallyActive
+ count: 6
+ avatarUrl: https://avatars.githubusercontent.com/u/160476156?u=7a8e44f4a43d3bba636f795bb7d9476c9233b4d8&v=4
+ url: https://github.com/PhysicallyActive
- login: n8sty
- count: 4
+ count: 5
avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4
url: https://github.com/n8sty
-- login: flo-at
+- login: sehraramiz
count: 4
- avatarUrl: https://avatars.githubusercontent.com/u/564288?v=4
- url: https://github.com/flo-at
+ avatarUrl: https://avatars.githubusercontent.com/u/14166324?v=4
+ url: https://github.com/sehraramiz
+- login: acidjunk
+ count: 4
+ avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4
+ url: https://github.com/acidjunk
- login: estebanx64
- count: 4
+ count: 3
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: PREPONDERANCE
+ count: 3
+ avatarUrl: https://avatars.githubusercontent.com/u/112809059?u=30ab12dc9ddba2f94ab90e6ad4ad8bc5cfa7fccd&v=4
+ url: https://github.com/PREPONDERANCE
- login: chrisK824
- count: 2
+ count: 3
avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4
url: https://github.com/chrisK824
+- login: ryanisn
+ count: 3
+ avatarUrl: https://avatars.githubusercontent.com/u/53449841?v=4
+ url: https://github.com/ryanisn
+- login: pythonweb2
+ 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: 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: 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: sm-Fifteen
+ count: 2
+ 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/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: 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: 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:
+six_months_experts:
+- login: YuriiMotov
+ count: 104
+ avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4
+ url: https://github.com/YuriiMotov
- login: Kludex
- count: 90
+ count: 104
avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4
url: https://github.com/Kludex
- login: JavierSanchezCastro
- count: 28
+ count: 40
avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4
url: https://github.com/JavierSanchezCastro
- login: jgould22
- count: 28
+ count: 40
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: 12
- avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4
- url: https://github.com/n8sty
- login: hasansezertasan
- count: 12
+ count: 21
avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4
url: https://github.com/hasansezertasan
+- login: n8sty
+ count: 19
+ avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4
+ url: https://github.com/n8sty
+- login: killjoy1221
+ count: 9
+ avatarUrl: https://avatars.githubusercontent.com/u/3409962?u=723662989f2027755e67d200137c13c53ae154ac&v=4
+ url: https://github.com/killjoy1221
+- login: aanchlia
+ count: 8
+ avatarUrl: https://avatars.githubusercontent.com/u/2835374?u=3c3ed29aa8b09ccaf8d66def0ce82bc2f7e5aab6&v=4
+ url: https://github.com/aanchlia
+- login: estebanx64
+ count: 7
+ avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4
+ url: https://github.com/estebanx64
+- login: PhysicallyActive
+ count: 6
+ avatarUrl: https://avatars.githubusercontent.com/u/160476156?u=7a8e44f4a43d3bba636f795bb7d9476c9233b4d8&v=4
+ url: https://github.com/PhysicallyActive
- login: dolfinus
count: 6
avatarUrl: https://avatars.githubusercontent.com/u/4661021?u=a51b39001a2e5e7529b45826980becf786de2327&v=4
url: https://github.com/dolfinus
-- login: 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: 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
@@ -303,400 +452,219 @@ 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: ahmedabdou14
+- login: PREPONDERANCE
count: 3
- avatarUrl: https://avatars.githubusercontent.com/u/104530599?u=05365b155a1ff911532e8be316acfad2e0736f98&v=4
- url: https://github.com/ahmedabdou14
+ 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
+ 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: 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: ryanisn
+ count: 3
+ avatarUrl: https://avatars.githubusercontent.com/u/53449841?v=4
+ url: https://github.com/ryanisn
- login: JoshYuJump
- count: 2
+ count: 3
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: 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: bogdan-coman-uv
- count: 2
+ count: 3
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: mskrip
+ count: 2
+ 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: DJoepie
+- login: pedroconceicao
count: 2
- avatarUrl: https://avatars.githubusercontent.com/u/78362619?u=fe6e8d05f94d8d4c0679a4da943955a686f96177&v=4
- url: https://github.com/DJoepie
-- login: alex-pobeditel-2004
+ 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/14791483?v=4
- url: https://github.com/alex-pobeditel-2004
+ 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
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: 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
+- login: mastizada
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/1975818?u=0751a06d7271c8bf17cb73b1b845644ab4d2c6dc&v=4
+ url: https://github.com/mastizada
+- login: sm-Fifteen
count: 2
- avatarUrl: https://avatars.githubusercontent.com/u/996689?v=4
- url: https://github.com/jcphlux
-- login: Matthieu-LAURENT39
+ avatarUrl: https://avatars.githubusercontent.com/u/516999?u=437c0c5038558c67e887ccd863c1ba0f846c03da&v=4
+ url: https://github.com/sm-Fifteen
+- login: amacfie
count: 2
- avatarUrl: https://avatars.githubusercontent.com/u/91389613?v=4
- url: https://github.com/Matthieu-LAURENT39
-- login: bhumkong
+ 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/13270137?u=1490432e6a0184fbc3d5c8d1b5df553ca92e7e5b&v=4
- url: https://github.com/bhumkong
-- login: falkben
+ 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/653031?u=ad9838e089058c9e5a0bab94c0eec7cc181e0cd0&v=4
- url: https://github.com/falkben
-- login: mielvds
+ avatarUrl: https://avatars.githubusercontent.com/u/199592?v=4
+ url: https://github.com/methane
+- login: konstantinos1981
count: 2
- avatarUrl: https://avatars.githubusercontent.com/u/1032980?u=722c96b0a234752df23f04df150ef36441ceb43c&v=4
- url: https://github.com/mielvds
-- login: admo1
+ avatarUrl: https://avatars.githubusercontent.com/u/39465388?v=4
+ url: https://github.com/konstantinos1981
+- login: druidance
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
+ avatarUrl: https://avatars.githubusercontent.com/u/160344534?v=4
+ url: https://github.com/druidance
one_year_experts:
- login: Kludex
- count: 231
+ count: 207
avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4
url: https://github.com/Kludex
- login: jgould22
- count: 132
+ count: 118
avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4
url: https://github.com/jgould22
+- login: YuriiMotov
+ count: 104
+ avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4
+ url: https://github.com/YuriiMotov
- login: JavierSanchezCastro
- count: 52
+ count: 59
avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4
url: https://github.com/JavierSanchezCastro
- login: n8sty
- count: 39
+ count: 40
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
+ count: 27
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: chrisK824
+ count: 16
+ avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4
+ url: https://github.com/chrisK824
- login: ahmedabdou14
count: 13
avatarUrl: https://avatars.githubusercontent.com/u/104530599?u=05365b155a1ff911532e8be316acfad2e0736f98&v=4
url: https://github.com/ahmedabdou14
-- login: 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
+- login: killjoy1221
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
+ 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: yinziyan1206
+- login: iudeen
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
+ 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: 6
+ 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: pythonweb2
+ count: 7
+ avatarUrl: https://avatars.githubusercontent.com/u/32141163?v=4
+ url: https://github.com/pythonweb2
- login: romabozhanovgithub
count: 6
avatarUrl: https://avatars.githubusercontent.com/u/67696229?u=e4b921eef096415300425aca249348f8abb78ad7&v=4
url: https://github.com/romabozhanovgithub
+- login: PhysicallyActive
+ count: 6
+ avatarUrl: https://avatars.githubusercontent.com/u/160476156?u=7a8e44f4a43d3bba636f795bb7d9476c9233b4d8&v=4
+ url: https://github.com/PhysicallyActive
+- login: mikeedjones
+ count: 6
+ avatarUrl: https://avatars.githubusercontent.com/u/4087139?u=cc4a242896ac2fcf88a53acfaf190d0fe0a1f0c9&v=4
+ url: https://github.com/mikeedjones
+- login: dolfinus
+ count: 6
+ avatarUrl: https://avatars.githubusercontent.com/u/4661021?u=a51b39001a2e5e7529b45826980becf786de2327&v=4
+ url: https://github.com/dolfinus
+- login: ebottos94
+ count: 6
+ avatarUrl: https://avatars.githubusercontent.com/u/100039558?u=e2c672da5a7977fd24d87ce6ab35f8bf5b1ed9fa&v=4
+ url: https://github.com/ebottos94
- login: Ventura94
count: 6
avatarUrl: https://avatars.githubusercontent.com/u/43103937?u=ccb837005aaf212a449c374618c4339089e2f733&v=4
@@ -705,18 +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: 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: acidjunk
count: 5
- avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=540f30c937a6450812628b9592a1dfe91bbe148e&v=4
- url: https://github.com/dmontagu
+ 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: alex-pobeditel-2004
count: 5
avatarUrl: https://avatars.githubusercontent.com/u/14791483?v=4
@@ -725,101 +693,97 @@ 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: adriangb
+- login: abhint
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
+ 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
url: https://github.com/anthonycepeda
-- login: 9en9i
+- login: GodMoonGoodman
count: 4
- avatarUrl: https://avatars.githubusercontent.com/u/44907258?u=297d0f31ea99c22b718118c1deec82001690cadb&v=4
- url: https://github.com/9en9i
-- login: AlexanderPodorov
+ 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/54511144?v=4
- url: https://github.com/AlexanderPodorov
-- login: sharonyogev
+ 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/31185192?u=b13ea64b3cdaf3903390c555793aba4aff45c5e6&v=4
- url: https://github.com/sharonyogev
+ avatarUrl: https://avatars.githubusercontent.com/u/37829370?u=da44ca53aefd5c23f346fab8e9fd2e108294c179&v=4
+ url: https://github.com/yinziyan1206
+- login: amacfie
+ count: 4
+ avatarUrl: https://avatars.githubusercontent.com/u/889657?u=d70187989940b085bcbfa3bedad8dbc5f3ab1fe7&v=4
+ url: https://github.com/amacfie
+- login: commonism
+ count: 4
+ avatarUrl: https://avatars.githubusercontent.com/u/164513?v=4
+ url: https://github.com/commonism
+- login: dmontagu
+ count: 4
+ avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=540f30c937a6450812628b9592a1dfe91bbe148e&v=4
+ url: https://github.com/dmontagu
+- login: sanzoghenzo
+ count: 4
+ avatarUrl: https://avatars.githubusercontent.com/u/977953?v=4
+ url: https://github.com/sanzoghenzo
+- login: lucasgadams
+ count: 3
+ 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
+ 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: jinluyang
+- login: ryanisn
count: 3
- avatarUrl: https://avatars.githubusercontent.com/u/15670327?v=4
- url: https://github.com/jinluyang
-- login: mht2953658596
+ avatarUrl: https://avatars.githubusercontent.com/u/53449841?v=4
+ url: https://github.com/ryanisn
+- login: theobouwman
count: 3
- avatarUrl: https://avatars.githubusercontent.com/u/59814105?v=4
- url: https://github.com/mht2953658596
+ 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
top_contributors:
- login: nilslindemann
- count: 30
+ count: 130
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,17 +791,21 @@ 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: 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: 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
@@ -854,25 +822,25 @@ top_contributors:
count: 12
avatarUrl: https://avatars.githubusercontent.com/u/11489395?u=4adb6986bf3debfc2b8216ae701f2bd47d73da7d&v=4
url: https://github.com/mariacamilagl
-- login: hasansezertasan
+- login: AlertRED
count: 12
- avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4
- url: https://github.com/hasansezertasan
+ avatarUrl: https://avatars.githubusercontent.com/u/15695000?u=f5a4944c6df443030409c88da7d7fa0b7ead985c&v=4
+ url: https://github.com/AlertRED
- login: Smlep
count: 11
avatarUrl: https://avatars.githubusercontent.com/u/16785985?v=4
url: https://github.com/Smlep
-- login: AlertRED
+- login: alejsdev
count: 11
- avatarUrl: https://avatars.githubusercontent.com/u/15695000?u=f5a4944c6df443030409c88da7d7fa0b7ead985c&v=4
- url: https://github.com/AlertRED
+ avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=9ca449ad5161af12766ddd1a22988e9b14315f5c&v=4
+ url: https://github.com/alejsdev
- login: hard-coders
count: 10
avatarUrl: https://avatars.githubusercontent.com/u/9651103?u=95db33927bbff1ed1c07efddeb97ac2ff33068ed&v=4
url: https://github.com/hard-coders
- login: KaniKim
count: 10
- avatarUrl: https://avatars.githubusercontent.com/u/19832624?u=d8ff6fca8542d22f94388cd2c4292e76e3898584&v=4
+ avatarUrl: https://avatars.githubusercontent.com/u/19832624?u=40f8f7f3f36d5f2365ba2ad0b40693e60958ce70&v=4
url: https://github.com/KaniKim
- login: xzmeng
count: 9
@@ -906,10 +874,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
@@ -924,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
@@ -944,7 +908,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=29682e4b6ac7d5293742ccf818188394b9a82972&v=4
url: https://github.com/ycd
- login: komtaki
count: 4
@@ -1000,7 +964,7 @@ top_contributors:
url: https://github.com/pawamoy
top_reviewers:
- login: Kludex
- count: 155
+ count: 158
avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4
url: https://github.com/Kludex
- login: BilalAlpaslan
@@ -1008,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
@@ -1023,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
@@ -1033,19 +1001,15 @@ 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=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: 37
- avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=1ee3a9fbef27abc9448ef5951350f99c7d76f7af&v=4
+ count: 38
+ avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=9ca449ad5161af12766ddd1a22988e9b14315f5c&v=4
url: https://github.com/alejsdev
- login: JarroVGIT
count: 34
@@ -1071,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 +1059,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
@@ -1107,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
@@ -1115,6 +1083,10 @@ 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
@@ -1131,6 +1103,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
@@ -1139,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
@@ -1147,26 +1131,18 @@ top_reviewers:
count: 15
avatarUrl: https://avatars.githubusercontent.com/u/63476957?u=6c86e59b48e0394d4db230f37fc9ad4d7e2c27c7&v=4
url: https://github.com/delhi09
-- login: Aruelius
+- login: wdh99
count: 14
- avatarUrl: https://avatars.githubusercontent.com/u/25380989?u=574f8cfcda3ea77a3f81884f6b26a97068e36a9d&v=4
- url: https://github.com/Aruelius
+ 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
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
@@ -1183,33 +1159,21 @@ 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
- 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: 146
+ avatarUrl: https://avatars.githubusercontent.com/u/4954856?v=4
+ url: https://github.com/s111d
- login: Xewus
count: 128
avatarUrl: https://avatars.githubusercontent.com/u/85196001?u=f8e2dc7e5104f109cef944af79050ea8d1b8f914&v=4
url: https://github.com/Xewus
-- login: 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
+ count: 91
avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4
url: https://github.com/hasansezertasan
- login: AlertRED
@@ -1240,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
@@ -1248,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=0688c1dc00988150a82d299106062c062ed1ba13&v=4
- url: https://github.com/alperiox
- login: lsglucas
count: 36
avatarUrl: https://avatars.githubusercontent.com/u/61513630?u=320e43fe4dc7bc6efc64e9b8f325f8075634fd20&v=4
@@ -1276,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
@@ -1284,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
@@ -1300,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
@@ -1336,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=bba5af018423a2858d49309bed2a899bb5c34ac5&v=4
+ avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=29682e4b6ac7d5293742ccf818188394b9a82972&v=4
url: https://github.com/ycd
- login: delhi09
count: 20
@@ -1362,8 +1334,12 @@ 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
+ 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
@@ -1372,23 +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
-- 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/data/sponsors.yml b/docs/en/data/sponsors.yml
index 85ac30d6d..8c0956ac5 100644
--- a/docs/en/data/sponsors.yml
+++ b/docs/en/data/sponsors.yml
@@ -11,32 +11,38 @@ 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
- 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
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
+ - 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://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
- 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/
@@ -45,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/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/advanced/additional-responses.md b/docs/en/docs/advanced/additional-responses.md
index 41b39c18e..674f0672c 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
-!!! info
- The `model` key is not part of OpenAPI.
+Keep in mind that you have to return the `JSONResponse` directly.
- **FastAPI** will take the Pydantic model from there, generate the `JSON Schema`, and put it in the correct place.
+///
- The correct place is:
+/// info
- * 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 `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.
+
+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.
+
+///
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
-!!! 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`).
+Notice that you have to return the image using a `FileResponse` directly.
- 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.
+///
+
+/// 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.
+
+///
## Combining information
@@ -224,7 +239,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:
@@ -236,5 +251,5 @@ For example:
To see what exactly you can include in the responses, you can check these sections in the OpenAPI specification:
-* OpenAPI Responses Object, it includes the `Response Object`.
-* OpenAPI Response Object, 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`.
+* OpenAPI Responses Object, it includes the `Response Object`.
+* OpenAPI Response Object, 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`.
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!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="11"
- {!> ../../../docs_src/dependencies/tutorial011_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="11"
+{!> ../../../docs_src/dependencies/tutorial011_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/dependencies/tutorial011.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="10"
+{!> ../../../docs_src/dependencies/tutorial011.py!}
+```
+
+////
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!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/dependencies/tutorial011.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/dependencies/tutorial011.py!}
+```
+
+////
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!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial011_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="17"
+{!> ../../../docs_src/dependencies/tutorial011_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="16"
- {!> ../../../docs_src/dependencies/tutorial011.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="16"
+{!> ../../../docs_src/dependencies/tutorial011.py!}
+```
+
+////
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+"
+////
- ```Python hl_lines="21"
- {!> ../../../docs_src/dependencies/tutorial011_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="21"
+{!> ../../../docs_src/dependencies/tutorial011_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="20"
- {!> ../../../docs_src/dependencies/tutorial011.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-!!! tip
- All this might seem contrived. And it might not be very clear how is it useful yet.
+/// tip
- These examples are intentionally simple, but show how it all works.
+Prefer to use the `Annotated` version if possible.
- 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.
+```Python hl_lines="20"
+{!> ../../../docs_src/dependencies/tutorial011.py!}
+```
+
+////
+
+/// 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.
+
+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.
+
+///
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
-!!! warning
- If your application relies on lifespan events, the `AsyncClient` won't trigger these events. To ensure they are triggered, use `LifespanManager` from florimondmanca/asgi-lifespan.
+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 florimondmanca/asgi-lifespan.
+
+///
## 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 MongoDB's MotorClient) 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 MongoDB's MotorClient) 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 4da2ddefc..5ff64016c 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.
@@ -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:
@@ -63,7 +66,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 +75,7 @@ To achieve this, you can use the command line option `--root-path` like:
-!!! 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`
@@ -345,6 +366,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..8a6555dba 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`
@@ -23,7 +26,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.
@@ -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
- In this case, the HTTP header `Content-Type` will be set to `application/json`.
+The parameter `response_class` will also be used to define the "media type" of the response.
- And it will be documented as such in OpenAPI.
+In this case, the HTTP header `Content-Type` will be set to `application/json`.
-!!! tip
- The `ORJSONResponse` is currently only available in FastAPI, not in Starlette.
+And it will be documented as such in OpenAPI.
+
+///
+
+/// 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
- In this case, the HTTP header `Content-Type` will be set to `text/html`.
+The parameter `response_class` will also be used to define the "media type" of the response.
- And it will be documented as such in OpenAPI.
+In this case, the HTTP header `Content-Type` will be set to `text/html`.
+
+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
-!!! info
- Of course, the actual `Content-Type` header, status code, etc, will come from the `Response` object your returned.
+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.
+
+///
### 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"
- **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 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.
+
+///
### `Response`
@@ -149,19 +170,37 @@ This is the default response used in **FastAPI**, as you read above.
A fast alternative JSON response using `orjson`, as you read above.
+/// info
+
+This requires installing `orjson` for example with `pip install orjson`.
+
+///
+
### `UJSONResponse`
An alternative JSON response using `ujson`.
-!!! warning
- `ujson` is less careful than Python's built-in implementation in how it handles some edge-cases.
+/// 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.
+
+///
```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`
@@ -216,14 +255,17 @@ 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
- 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`
@@ -292,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 481bf5e69..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`
@@ -77,7 +80,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 `async` and `await`.
+ 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..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
- You can probably skip this part.
+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.
+
+///
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
-!!! tip
- Notice that in this case we are using a standard Python `open()` function that interacts with a file.
+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.
- 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`.
+/// tip
- So, we declare the event handler function with standard `def` instead of `async def`.
+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.
+
+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,11 +164,14 @@ Just a technical detail for the curious nerds. 🤓
Underneath, in the ASGI technical specification, this is part of the Lifespan Protocol, and it defines events called `startup` and `shutdown`.
-!!! info
- You can read more about the Starlette `lifespan` handlers in Starlette's Lifespan' docs.
+/// info
- Including how to handle lifespan state that can be used in other areas of your code.
+You can read more about the Starlette `lifespan` handlers in Starlette's Lifespan' docs.
+
+Including how to handle lifespan state that can be used in other areas of your code.
+
+///
## 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 3a810baee..faa7c323f 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 OpenAPI Generator.
-If you are building a **frontend**, a very interesting alternative is openapi-typescript-codegen.
+If you are building a **frontend**, a very interesting alternative is openapi-ts.
## Client and SDK Generators - Sponsor
@@ -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 Speakeasy.
+For example, you might want to try:
+
+* Speakeasy
+* Stainless
+* liblab
There are also several other companies offering similar services that you can search and find online. 🤓
@@ -28,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+"
+////
- ```Python hl_lines="9-11 14-15 18 19 23"
- {!> ../../../docs_src/generate_clients/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```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`.
@@ -58,14 +66,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:
-!!! 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:
@@ -140,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!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="23 28 36"
- {!> ../../../docs_src/generate_clients/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="23 28 36"
+{!> ../../../docs_src/generate_clients/tutorial002.py!}
+```
+
+////
### Generate a TypeScript Client with Tags
@@ -197,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+"
+////
- ```Python hl_lines="8-9 12"
- {!> ../../../docs_src/generate_clients/tutorial003.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="8-9 12"
+{!> ../../../docs_src/generate_clients/tutorial003.py!}
+```
+
+////
### Generate a TypeScript Client with Custom Operation IDs
@@ -229,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"
+////
- ```Python
- {!> ../../../docs_src/generate_clients/tutorial004.js!}
- ```
+//// tab | Node.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.
@@ -254,12 +277,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"
}
}
@@ -271,7 +294,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/index.md b/docs/en/docs/advanced/index.md
index d8dcd4ca6..36f0720c0 100644
--- a/docs/en/docs/advanced/index.md
+++ b/docs/en/docs/advanced/index.md
@@ -2,24 +2,27 @@
## 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.
-!!! 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
-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/middleware.md b/docs/en/docs/advanced/middleware.md
index 9219f1d2c..70415adca 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`
@@ -85,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
@@ -92,7 +96,6 @@ There are many other ASGI middlewares.
For example:
-* Sentry
* Uvicorn's `ProxyHeadersMiddleware`
* MessagePack
diff --git a/docs/en/docs/advanced/openapi-callbacks.md b/docs/en/docs/advanced/openapi-callbacks.md
index fb7a6d917..7fead2ed9 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 URL type.
+/// tip
+
+The `callback_url` query parameter uses a Pydantic Url 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
- When implementing the callback yourself, you could use something like HTTPX or Requests.
+The actual callback is just an HTTP request.
+
+When implementing the callback yourself, you could use something like HTTPX or Requests.
+
+///
## 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
- 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*.
+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*.
+
+///
### Create a callback `APIRouter`
@@ -131,7 +140,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
@@ -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,13 +179,16 @@ 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
-Now you can start your app with Uvicorn and go to http://127.0.0.1:8000/docs.
+Now you can start your app and go to http://127.0.0.1:8000/docs.
-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:
diff --git a/docs/en/docs/advanced/openapi-webhooks.md b/docs/en/docs/advanced/openapi-webhooks.md
index 63cbdc610..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`.
@@ -44,7 +50,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 http://127.0.0.1:8000/docs.
+Now you can start your app and go to http://127.0.0.1:8000/docs.
You will see your docs have the normal *path operations* and now also some **webhooks**:
diff --git a/docs/en/docs/advanced/path-operation-advanced-configuration.md b/docs/en/docs/advanced/path-operation-advanced-configuration.md
index 8b79bfe22..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
-!!! warning
- If you do this, you have to make sure each one of your *path operation functions* has a unique name.
+If you manually call `app.openapi()`, you should update the `operationId`s before that.
- Even if they are in different modules (Python files).
+///
+
+/// 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).
+
+///
## Exclude from OpenAPI
@@ -59,14 +68,17 @@ 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
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 Operation Object.
+/// note | "Technical details"
+
+In the OpenAPI specification it is called the Operation Object.
+
+///
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
- 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}.
+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}.
+
+///
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!}
- ```
+```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!}
- ```
+//// tab | Pydantic v1
-!!! 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()`.
+```Python hl_lines="17-22 24"
+{!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!}
+```
+
+////
+
+/// 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!}
- ```
+```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!}
- ```
+//// tab | Pydantic v1
-!!! 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()`.
+```Python hl_lines="26-33"
+{!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!}
+```
-!!! tip
- Here we re-use the same Pydantic model.
+////
- But the same way, we could have validated it in some other way.
+/// 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()`.
+
+///
+
+/// tip
+
+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/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"
- **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`.
+
+///
To see all the available parameters and options, check the documentation in Starlette.
diff --git a/docs/en/docs/advanced/response-directly.md b/docs/en/docs/advanced/response-directly.md
index 8836140ec..73071ed1b 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"
- **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 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.
+
+///
## Returning a custom `Response`
@@ -48,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 XML 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/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!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="2 7 11"
- {!> ../../../docs_src/security/tutorial006_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="2 7 11"
+{!> ../../../docs_src/security/tutorial006_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="2 6 10"
- {!> ../../../docs_src/security/tutorial006.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="2 6 10"
+{!> ../../../docs_src/security/tutorial006.py!}
+```
+
+////
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!}
- ```
+```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!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="1 12-24"
+{!> ../../../docs_src/security/tutorial007_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="1 11-21"
- {!> ../../../docs_src/security/tutorial007.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="1 11-21"
+{!> ../../../docs_src/security/tutorial007.py!}
+```
+
+////
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!}
- ```
+```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!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="26-30"
+{!> ../../../docs_src/security/tutorial007_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="23-27"
- {!> ../../../docs_src/security/tutorial007.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="23-27"
+{!> ../../../docs_src/security/tutorial007.py!}
+```
+
+////
diff --git a/docs/en/docs/advanced/security/index.md b/docs/en/docs/advanced/security/index.md
index c18baf64b..edb42132e 100644
--- a/docs/en/docs/advanced/security/index.md
+++ b/docs/en/docs/advanced/security/index.md
@@ -2,15 +2,18 @@
## 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"**.
+/// 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
-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/advanced/security/oauth2-scopes.md b/docs/en/docs/advanced/security/oauth2-scopes.md
index b93d2991c..ff52d7bb8 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
- 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.
+
+///
## 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="4 8 12 46 64 105 107-115 121-124 128-134 139 155"
- {!> ../../../docs_src/security/tutorial005_an_py310.py!}
- ```
+```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"
- {!> ../../../docs_src/security/tutorial005_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```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="2 4 8 12 47 65 106 108-116 122-125 129-135 140 156"
- {!> ../../../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="2 5 9 13 48 66 107 109-117 123-126 130-136 141 157"
+{!> ../../../docs_src/security/tutorial005_an.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.9+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155"
- {!> ../../../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="4 8 12 46 64 105 107-115 121-124 128-134 139 155"
+{!> ../../../docs_src/security/tutorial005_py310.py!}
+```
- ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155"
- {!> ../../../docs_src/security/tutorial005.py!}
- ```
+////
+
+//// tab | Python 3.9+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156"
+{!> ../../../docs_src/security/tutorial005_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156"
+{!> ../../../docs_src/security/tutorial005.py!}
+```
+
+////
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="62-65"
- {!> ../../../docs_src/security/tutorial005_an_py310.py!}
- ```
+```Python hl_lines="63-66"
+{!> ../../../docs_src/security/tutorial005_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="62-65"
- {!> ../../../docs_src/security/tutorial005_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="63-66"
+{!> ../../../docs_src/security/tutorial005_an_py39.py!}
+```
- ```Python hl_lines="63-66"
- {!> ../../../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="64-67"
+{!> ../../../docs_src/security/tutorial005_an.py!}
+```
- ```Python hl_lines="61-64"
- {!> ../../../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="62-65"
- {!> ../../../docs_src/security/tutorial005_py39.py!}
- ```
+///
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="62-65"
+{!> ../../../docs_src/security/tutorial005_py310.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="62-65"
- {!> ../../../docs_src/security/tutorial005.py!}
- ```
+//// tab | Python 3.9+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="63-66"
+{!> ../../../docs_src/security/tutorial005_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="63-66"
+{!> ../../../docs_src/security/tutorial005.py!}
+```
+
+////
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
- 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.
+For simplicity, here we are just adding the scopes received directly to the token.
-=== "Python 3.10+"
+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 hl_lines="155"
- {!> ../../../docs_src/security/tutorial005_an_py310.py!}
- ```
+///
-=== "Python 3.9+"
+//// tab | Python 3.10+
- ```Python hl_lines="155"
- {!> ../../../docs_src/security/tutorial005_an_py39.py!}
- ```
+```Python hl_lines="156"
+{!> ../../../docs_src/security/tutorial005_an_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="156"
- {!> ../../../docs_src/security/tutorial005_an.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.10+ non-Annotated"
+```Python hl_lines="156"
+{!> ../../../docs_src/security/tutorial005_an_py39.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="154"
- {!> ../../../docs_src/security/tutorial005_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.9+ non-Annotated"
+```Python hl_lines="157"
+{!> ../../../docs_src/security/tutorial005_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="155"
- {!> ../../../docs_src/security/tutorial005_py39.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="155"
- {!> ../../../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
- We are doing it here to demonstrate how **FastAPI** handles scopes declared at different levels.
+You don't necessarily need to add different scopes in different places.
-=== "Python 3.10+"
+We are doing it here to demonstrate how **FastAPI** handles scopes declared at different levels.
- ```Python hl_lines="4 139 170"
- {!> ../../../docs_src/security/tutorial005_an_py310.py!}
- ```
+///
-=== "Python 3.9+"
+//// tab | Python 3.10+
- ```Python hl_lines="4 139 170"
- {!> ../../../docs_src/security/tutorial005_an_py39.py!}
- ```
+```Python hl_lines="5 140 171"
+{!> ../../../docs_src/security/tutorial005_an_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="4 140 171"
- {!> ../../../docs_src/security/tutorial005_an.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.10+ non-Annotated"
+```Python hl_lines="5 140 171"
+{!> ../../../docs_src/security/tutorial005_an_py39.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="3 138 167"
- {!> ../../../docs_src/security/tutorial005_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.9+ non-Annotated"
+```Python hl_lines="5 141 172"
+{!> ../../../docs_src/security/tutorial005_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="4 139 168"
- {!> ../../../docs_src/security/tutorial005_py39.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="4 139 168"
- {!> ../../../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.
+```Python hl_lines="4 139 168"
+{!> ../../../docs_src/security/tutorial005_py310.py!}
+```
- 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.
+//// tab | Python 3.9+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="5 140 169"
+{!> ../../../docs_src/security/tutorial005_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="5 140 169"
+{!> ../../../docs_src/security/tutorial005.py!}
+```
+
+////
+
+/// info | "Technical Details"
+
+`Security` is actually a subclass of `Depends`, and it has just one extra parameter that we'll see later.
+
+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`
@@ -300,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.
@@ -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="8 105"
- {!> ../../../docs_src/security/tutorial005_an_py310.py!}
- ```
+```Python hl_lines="9 106"
+{!> ../../../docs_src/security/tutorial005_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="8 105"
- {!> ../../../docs_src/security/tutorial005_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="9 106"
+{!> ../../../docs_src/security/tutorial005_an_py39.py!}
+```
- ```Python hl_lines="8 106"
- {!> ../../../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="9 107"
+{!> ../../../docs_src/security/tutorial005_an.py!}
+```
- ```Python hl_lines="7 104"
- {!> ../../../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="8 105"
- {!> ../../../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="8 105"
+{!> ../../../docs_src/security/tutorial005_py310.py!}
+```
- ```Python hl_lines="8 105"
- {!> ../../../docs_src/security/tutorial005.py!}
- ```
+////
+
+//// tab | Python 3.9+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="9 106"
+{!> ../../../docs_src/security/tutorial005_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="9 106"
+{!> ../../../docs_src/security/tutorial005.py!}
+```
+
+////
## Use the `scopes`
@@ -361,54 +480,75 @@ 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).
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="105 107-115"
- {!> ../../../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="105 107-115"
- {!> ../../../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="106 108-116"
- {!> ../../../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="104 106-114"
- {!> ../../../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="105 107-115"
- {!> ../../../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="105 107-115"
- {!> ../../../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="46 116-127"
- {!> ../../../docs_src/security/tutorial005_an_py310.py!}
- ```
+```Python hl_lines="47 117-128"
+{!> ../../../docs_src/security/tutorial005_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="46 116-127"
- {!> ../../../docs_src/security/tutorial005_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="47 117-128"
+{!> ../../../docs_src/security/tutorial005_an_py39.py!}
+```
- ```Python hl_lines="47 117-128"
- {!> ../../../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="48 118-129"
+{!> ../../../docs_src/security/tutorial005_an.py!}
+```
- ```Python hl_lines="45 115-126"
- {!> ../../../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="46 116-127"
- {!> ../../../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="46 116-127"
+{!> ../../../docs_src/security/tutorial005_py310.py!}
+```
- ```Python hl_lines="46 116-127"
- {!> ../../../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="128-134"
- {!> ../../../docs_src/security/tutorial005_an_py310.py!}
- ```
+```Python hl_lines="129-135"
+{!> ../../../docs_src/security/tutorial005_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="128-134"
- {!> ../../../docs_src/security/tutorial005_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="129-135"
+{!> ../../../docs_src/security/tutorial005_an_py39.py!}
+```
- ```Python hl_lines="129-135"
- {!> ../../../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="130-136"
+{!> ../../../docs_src/security/tutorial005_an.py!}
+```
- ```Python hl_lines="127-133"
- {!> ../../../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="128-134"
- {!> ../../../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="128-134"
+{!> ../../../docs_src/security/tutorial005_py310.py!}
+```
- ```Python hl_lines="128-134"
- {!> ../../../docs_src/security/tutorial005.py!}
- ```
+////
+
+//// tab | Python 3.9+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="129-135"
+{!> ../../../docs_src/security/tutorial005_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="129-135"
+{!> ../../../docs_src/security/tutorial005.py!}
+```
+
+////
## Dependency tree and scopes
@@ -543,12 +725,15 @@ 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
- 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
- All depending on the `scopes` declared in each *path operation* and each dependency in the dependency tree for that specific *path operation*.
+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*.
+
+///
## 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
- But in the end, they are implementing the same OAuth2 standard.
+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.
+
+///
**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 f6db8d2b1..22bf7de20 100644
--- a/docs/en/docs/advanced/settings.md
+++ b/docs/en/docs/advanced/settings.md
@@ -6,130 +6,25 @@ 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
-!!! tip
- If you already know what "environment variables" are and how to use them, feel free to skip to the next section below.
+To understand environment variables you can read [Environment Variables](../environment-variables.md){.internal-link target=_blank}.
-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).
+///
-You can create and use environment variables in the shell, without needing Python:
-
-=== "Linux, macOS, Windows Bash"
-
-
-!!! info
- Beautiful illustrations by Ketrina Thompson. 🎨
+/// info
+
+Beautiful illustrations by Ketrina Thompson. 🎨
+
+///
---
@@ -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 Ketrina Thompson. 🎨
+/// info
+
+Beautiful illustrations by Ketrina Thompson. 🎨
+
+///
---
@@ -222,7 +231,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
@@ -360,6 +369,8 @@ In particular, you can directly use AnyIO 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**: Asyncer. 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.
@@ -392,12 +403,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
- These are very technical details of how **FastAPI** works underneath.
+You can probably skip this.
- 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.
+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.
+
+///
### Path operation functions
@@ -405,15 +419,15 @@ 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 I/O.
-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
-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 one of the fastest Python frameworks available, only below Starlette and Uvicorn themselves (used internally by FastAPI). (*)
+Independent TechEmpower benchmarks show **FastAPI** applications running under Uvicorn as one of the fastest Python frameworks available, 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/contributing.md b/docs/en/docs/contributing.md
index 2d308a9db..91d5724a8 100644
--- a/docs/en/docs/contributing.md
+++ b/docs/en/docs/contributing.md
@@ -4,106 +4,15 @@ First, you might want to see the basic ways to [help FastAPI and get help](help-
## Developing
-If you already cloned the fastapi repository and you want to deep dive in the code, here are some guidelines to set up your environment.
+If you already cloned the fastapi repository 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):
-
-
-
-
+
+
-
-
+
+
@@ -32,11 +29,11 @@ hide:
**Documentation**: https://fastapi.tiangolo.com
-**Source Code**: https://github.com/tiangolo/fastapi
+**Source Code**: https://github.com/fastapi/fastapi
---
-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:
@@ -72,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._"
-
uvicorn main:app --reload...fastapi dev main.py...email_validator - for email validation.
-* pydantic-settings - for settings management.
-* pydantic-extra-types - for extra types to be used with Pydantic.
+* email-validator - for email validation.
Used by Starlette:
* httpx - Required if you want to use the `TestClient`.
* jinja2 - Required if you want to use the default template configuration.
* python-multipart - Required if you want to support form "parsing", with `request.form()`.
-* itsdangerous - Required for `SessionMiddleware` support.
-* pyyaml - Required for Starlette's `SchemaGenerator` support (you probably don't need it with FastAPI).
-* ujson - Required if you want to use `UJSONResponse`.
Used by FastAPI / Starlette:
-* uvicorn - for the server that loads and serves your application.
-* orjson - Required if you want to use `ORJSONResponse`.
+* uvicorn - 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.
-You can install all of these with `pip install "fastapi[all]"`.
+### Without `standard` Dependencies
+
+If you don't want to include the `standard` optional dependencies, you can install with `pip install fastapi` instead of `pip install "fastapi[standard]"`.
+
+### Additional Optional Dependencies
+
+There are some additional dependencies you might want to install.
+
+Additional optional Pydantic dependencies:
+
+* pydantic-settings - for settings management.
+* pydantic-extra-types - for extra types to be used with Pydantic.
+
+Additional optional FastAPI dependencies:
+
+* orjson - Required if you want to use `ORJSONResponse`.
+* ujson - Required if you want to use `UJSONResponse`.
## License
diff --git a/docs/en/docs/js/custom.js b/docs/en/docs/js/custom.js
index 8e3be4c13..ff17710e2 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");
@@ -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
}
@@ -163,7 +163,7 @@ async function main() {
div.innerHTML = 'get operation
-!!! info "`@decorator` Info"
- That `@something` syntax in Python is called a "decorator".
+/// info | "`@decorator` Info"
- You put it on top of a function. Like a pretty decorative hat (I guess that's where the term came from).
+That `@something` syntax in Python is called a "decorator".
- A "decorator" takes the function below and does something with it.
+You put it on top of a function. Like a pretty decorative hat (I guess that's where the term came from).
- In our case, this decorator tells **FastAPI** that the function below corresponds to the **path** `/` with an **operation** `get`.
+A "decorator" takes the function below and does something with it.
- It is the "**path operation decorator**".
+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**".
+
+///
You can also use the other operations:
@@ -274,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
- **FastAPI** doesn't enforce any specific meaning.
+You are free to use each operation (HTTP method) as you wish.
- The information here is presented as a guideline, not a requirement.
+**FastAPI** doesn't enforce any specific meaning.
- For example, when using GraphQL you normally perform all the actions using only `POST` operations.
+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.
+
+///
### Step 4: define the **path operation function**
@@ -309,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
@@ -328,6 +340,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`.
diff --git a/docs/en/docs/tutorial/handling-errors.md b/docs/en/docs/tutorial/handling-errors.md
index 98ac55d1f..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"
- **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`.
+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`.
+
+///
## 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 `ValidationError`.
@@ -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"
- **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 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.
+
+///
### Use the `RequestValidationError` body
@@ -248,12 +260,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.
diff --git a/docs/en/docs/tutorial/header-params.md b/docs/en/docs/tutorial/header-params.md
index bbba90998..2e07fe0e6 100644
--- a/docs/en/docs/tutorial/header-params.md
+++ b/docs/en/docs/tutorial/header-params.md
@@ -6,91 +6,129 @@ 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+"
+////
- ```Python hl_lines="3"
- {!> ../../../docs_src/header_params/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="3"
+{!> ../../../docs_src/header_params/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="3"
- {!> ../../../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="3"
+{!> ../../../docs_src/header_params/tutorial001_an.py!}
+```
- ```Python hl_lines="1"
- {!> ../../../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="3"
- {!> ../../../docs_src/header_params/tutorial001.py!}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="1"
+{!> ../../../docs_src/header_params/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="3"
+{!> ../../../docs_src/header_params/tutorial001.py!}
+```
+
+////
## Declare `Header` parameters
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:
-=== "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!}
+```
-!!! info
- To declare headers, you need to use `Header`, because otherwise the parameters would be interpreted as query parameters.
+////
+
+//// 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!}
+```
+
+////
+
+/// 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!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="11"
- {!> ../../../docs_src/header_params/tutorial002_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="11"
+{!> ../../../docs_src/header_params/tutorial002_an_py39.py!}
+```
- ```Python hl_lines="12"
- {!> ../../../docs_src/header_params/tutorial002_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="12"
+{!> ../../../docs_src/header_params/tutorial002_an.py!}
+```
- ```Python hl_lines="8"
- {!> ../../../docs_src/header_params/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="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="8"
+{!> ../../../docs_src/header_params/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="10"
+{!> ../../../docs_src/header_params/tutorial002.py!}
+```
+
+////
+
+/// 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!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/header_params/tutorial003_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="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="7"
+{!> ../../../docs_src/header_params/tutorial003_py310.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial003.py!}
- ```
+////
+
+//// tab | Python 3.9+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/header_params/tutorial003_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/header_params/tutorial003.py!}
+```
+
+////
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 75665324d..386fe5de9 100644
--- a/docs/en/docs/tutorial/index.md
+++ b/docs/en/docs/tutorial/index.md
@@ -4,26 +4,59 @@ 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
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:
diff --git a/docs/en/docs/tutorial/path-params-numeric-validations.md b/docs/en/docs/tutorial/path-params-numeric-validations.md
index b5b13cfbe..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!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="1 3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="1 3"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="3-4"
- {!> ../../../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="3-4"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
+```
- ```Python hl_lines="1"
- {!> ../../../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="3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-!!! 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`.
+```Python hl_lines="1"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
+```
- 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`.
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="3"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
+```
+
+////
+
+/// 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`.
+
+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,53 +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.
+///
- So, you should declare it with `...` to mark it as required.
+```Python hl_lines="8"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
+```
- Nevertheless, even if you declared it with `None` or set a default value, it would not affect anything, it would still be always required.
+////
+
+//// 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`.
@@ -117,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
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="7"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```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+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!}
- ```
+//// tab | Python 3.8+
+
+```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.
@@ -168,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+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!}
+```
+
+////
## Number validations: greater than or equal
@@ -186,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!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="9"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="8"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!}
+```
+
+////
## Number validations: greater than and less than or equal
@@ -214,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!}
- ```
+```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!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="9"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!}
+```
+
+////
## Number validations: floats, greater than and less than
@@ -245,26 +316,35 @@ So, `0.5` would be a valid value. But `0.0` or `0` would not.
And the same for lt.
-=== "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
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="11"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="11"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!}
+```
+
+////
## Recap
@@ -277,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
- All of them share the same parameters for additional validation and metadata you have seen.
+`Query`, `Path`, and other classes you will see later are subclasses of a common `Param` class.
-!!! note "Technical Details"
- When you import `Query`, `Path` and others from `fastapi`, they are actually functions.
+All of them share the same parameters for additional validation and metadata you have seen.
- 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`.
+/// note | "Technical Details"
- These functions are there (instead of just using the classes directly) so that your editor doesn't mark errors about their types.
+When you import `Query`, `Path` and others from `fastapi`, they are actually functions.
- That way you can use your normal editor and coding tools without having to add custom configurations to disregard those errors.
+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`.
+
+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.
+
+///
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 conversion
@@ -35,10 +38,13 @@ If you run this example and open your browser at "parsing".
+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 "parsing".
+
+///
## 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: http://127.0.0.1:8000/items/4.2
-!!! 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
-!!! check
- Again, just with that same Python type declaration, **FastAPI** gives you automatic, interactive documentation (integrating Swagger UI).
+/// check
- Notice that the path parameter is declared to be an integer.
+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.
+
+///
## 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
- Enumerations (or enums) are available in Python since version 3.4.
+/// info
-!!! tip
- If you are wondering, "AlexNet", "ResNet", and "LeNet" are just names of Machine Learning models.
+Enumerations (or enums) are available in Python since version 3.4.
+
+///
+
+/// tip
+
+If you are wondering, "AlexNet", "ResNet", and "LeNet" are just names of Machine Learning models.
+
+///
### 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
- In that case, the URL would be: `/files//home/johndoe/myfile.txt`, with a double slash (`//`) between `files` and `home`.
+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`.
+
+///
## Recap
diff --git a/docs/en/docs/tutorial/query-params-str-validations.md b/docs/en/docs/tutorial/query-params-str-validations.md
index 24784efad..859242d93 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+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```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`.
+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!}
- ```
+```Python hl_lines="1 3"
+{!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!}
+```
-=== "Python 3.8+"
+////
- In versions of Python below Python 3.9 you import `Annotated` from `typing_extensions`.
+//// tab | Python 3.8+
- It will already be installed with FastAPI.
+In versions of Python below Python 3.9 you import `Annotated` from `typing_extensions`.
- ```Python hl_lines="3-4"
- {!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!}
- ```
+It will already be installed with FastAPI.
-!!! info
- FastAPI added support for `Annotated` (and started recommending it) in version 0.95.0.
+```Python hl_lines="3-4"
+{!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!}
+```
- 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`.
+/// 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`.
+
+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`.
@@ -99,23 +121,33 @@ 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+"
+//// 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 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:
@@ -123,26 +155,33 @@ 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 0.95.0) 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!}
+```
-=== "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!}
+```
+
+////
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).
@@ -170,24 +209,27 @@ 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
- 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)
+```
- 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.
+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.
+
+///
Then, we can pass more parameters to `Query`. In this case, the `max_length` parameter that applies to strings:
@@ -239,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!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial003_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial003_an_py39.py!}
+```
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial003_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/query_params_str_validations/tutorial003_an.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/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="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial003.py!}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial003.py!}
+```
+
+////
## Add regular expressions
You can define a regular expression `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!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```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.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial004.py!}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="11"
+{!> ../../../docs_src/query_params_str_validations/tutorial004.py!}
+```
+
+////
This specific regular expression pattern checks that the received parameter value:
@@ -331,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`. 🤓
@@ -345,31 +421,43 @@ 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!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial005_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="8"
+{!> ../../../docs_src/query_params_str_validations/tutorial005_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial005.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-!!! note
- Having a default value of any type, including `None`, makes the parameter optional (not required).
+/// tip
-## Make it required
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial005.py!}
+```
+
+////
+
+/// note
+
+Having a default value of any type, including `None`, makes the parameter optional (not 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:
@@ -385,125 +473,175 @@ 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"
+////
- ```Python
- q: Union[str, None] = Query(default=None, min_length=3)
- ```
+//// tab | non-Annotated
+
+```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!}
- ```
+```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+ non-Annotated"
+```Python hl_lines="8"
+{!> ../../../docs_src/query_params_str_validations/tutorial006_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial006.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
- !!! 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()`.
+/// tip
- Still, probably better to use the `Annotated` version. 😉
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial006.py!}
+```
+
+/// tip
+
+Notice that, even though in this case the `Query()` is used as the function parameter default value, we don't pass the `default=None` to `Query()`.
+
+Still, probably better to use the `Annotated` version. 😉
+
+///
+
+////
### 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!}
- ```
+```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!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="8"
+{!> ../../../docs_src/query_params_str_validations/tutorial006b_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial006b.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-!!! info
- If you hadn't seen that `...` before: it is a special single value, it is part of Python and is called "Ellipsis".
+/// tip
- It is used by Pydantic and FastAPI to explicitly declare that a value is required.
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial006b.py!}
+```
+
+////
+
+/// info
+
+If you hadn't seen that `...` before: it is a special single value, it is part of Python and is called "Ellipsis".
+
+It is used by Pydantic and FastAPI to explicitly declare that a value is required.
+
+///
This will let **FastAPI** know that this parameter is required.
-### Required 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`.
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+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial006c_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/query_params_str_validations/tutorial006c_an.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial006c_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/query_params_str_validations/tutorial006c.py!}
- ```
+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 Required Optional fields.
+///
-!!! tip
- Remember that in most of the cases, when something is required, you can simply omit the default, so you normally don't have to use `...`.
+```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
+
+Pydantic, which is what powers all the data validation and serialization in FastAPI, has a special behavior when you use `Optional` or `Union[Something, None]` without a default value, you can read more about it in the Pydantic docs about Required fields.
+
+///
+
+/// tip
+
+Remember that in most of the cases, when something is required, you can simply omit the default, so you normally don't have to use `...`.
+
+///
## Query parameter list / multiple values
@@ -511,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!}
- ```
+```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!}
- ```
+//// tab | Python 3.9+
-=== "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.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial011_an.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial011_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="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial011_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="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial011_py310.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial011.py!}
- ```
+////
+
+//// tab | Python 3.9+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial011.py!}
+```
+
+////
Then, with a URL like:
@@ -575,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:
@@ -586,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!}
- ```
+```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+ non-Annotated"
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial012_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!}
- ```
+//// tab | Python 3.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"
- {!> ../../../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+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial012.py!}
+```
+
+////
If you go to:
@@ -633,35 +809,47 @@ 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+):
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial013_an_py39.py!}
- ```
+```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!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="8"
+{!> ../../../docs_src/query_params_str_validations/tutorial013_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial013.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-!!! note
- Keep in mind that in this case, FastAPI won't check the contents of the list.
+/// tip
- For example, `List[int]` would check (and document) that the contents of the list are integers. But `list` alone wouldn't.
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial013.py!}
+```
+
+////
+
+/// note
+
+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.
+
+///
## Declare more metadata
@@ -669,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
- 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.
+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.
+
+///
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!}
- ```
+```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!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial007_an_py39.py!}
+```
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial007_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/query_params_str_validations/tutorial007_an.py!}
+```
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial007_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/query_params_str_validations/tutorial007.py!}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="8"
+{!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial007.py!}
+```
+
+////
And a `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!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="14"
- {!> ../../../docs_src/query_params_str_validations/tutorial008_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="14"
+{!> ../../../docs_src/query_params_str_validations/tutorial008_an_py39.py!}
+```
- ```Python hl_lines="15"
- {!> ../../../docs_src/query_params_str_validations/tutorial008_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```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.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="13"
- {!> ../../../docs_src/query_params_str_validations/tutorial008.py!}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="11"
+{!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="13"
+{!> ../../../docs_src/query_params_str_validations/tutorial008.py!}
+```
+
+////
## Alias parameters
@@ -768,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!}
- ```
+```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!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial009_an_py39.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial009_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/query_params_str_validations/tutorial009_an.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial009_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/query_params_str_validations/tutorial009.py!}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial009.py!}
+```
+
+////
## Deprecating parameters
@@ -812,85 +1051,117 @@ 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!}
- ```
+```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!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="19"
+{!> ../../../docs_src/query_params_str_validations/tutorial010_an_py39.py!}
+```
- ```Python hl_lines="20"
- {!> ../../../docs_src/query_params_str_validations/tutorial010_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="20"
+{!> ../../../docs_src/query_params_str_validations/tutorial010_an.py!}
+```
- ```Python hl_lines="16"
- {!> ../../../docs_src/query_params_str_validations/tutorial010_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="18"
- {!> ../../../docs_src/query_params_str_validations/tutorial010.py!}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="16"
+{!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="18"
+{!> ../../../docs_src/query_params_str_validations/tutorial010.py!}
+```
+
+////
The docs will show it like this:
-## 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`:
-=== "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!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial014_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial014_an_py39.py!}
+```
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial014_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/query_params_str_validations/tutorial014_an.py!}
+```
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial014_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/query_params_str_validations/tutorial014.py!}
- ```
+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!}
+```
+
+////
## 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!}
+```
-=== "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!}
+```
+
+////
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+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params/tutorial003.py!}
- ```
+//// tab | Python 3.8+
+
+```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!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="8 10"
- {!> ../../../docs_src/query_params/tutorial004.py!}
- ```
+//// tab | Python 3.8+
+
+```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..9f19596a8 100644
--- a/docs/en/docs/tutorial/request-files.md
+++ b/docs/en/docs/tutorial/request-files.md
@@ -2,70 +2,101 @@
You can define files to be uploaded by the client using `File`.
-!!! info
- To receive uploaded files, first install `python-multipart`.
+/// info
- E.g. `pip install python-multipart`.
+To receive uploaded files, first install `python-multipart`.
- This is because uploaded files are sent as "form data".
+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".
+
+///
## 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!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/request_files/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="1"
+{!> ../../../docs_src/request_files/tutorial001_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/request_files/tutorial001.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="1"
+{!> ../../../docs_src/request_files/tutorial001.py!}
+```
+
+////
## 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!}
- ```
+```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!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="8"
+{!> ../../../docs_src/request_files/tutorial001_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/request_files/tutorial001.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-!!! 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.
+Prefer to use the `Annotated` version if possible.
-!!! tip
- To declare File bodies, you need to use `File`, because otherwise the parameters would be interpreted as query parameters or body (JSON) parameters.
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/request_files/tutorial001.py!}
+```
+
+////
+
+/// info
+
+`File` is a class that inherits directly from `Form`.
+
+But remember that when you import `Query`, `Path`, `File` and others from `fastapi`, those are actually functions that return special classes.
+
+///
+
+/// 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 +110,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!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="13"
- {!> ../../../docs_src/request_files/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="13"
+{!> ../../../docs_src/request_files/tutorial001_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="12"
- {!> ../../../docs_src/request_files/tutorial001.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="12"
+{!> ../../../docs_src/request_files/tutorial001.py!}
+```
+
+////
Using `UploadFile` has several advantages over `bytes`:
@@ -116,7 +156,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 `SpooledTemporaryFile` (a file-like 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 `SpooledTemporaryFile` (a file-like 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`).
@@ -141,11 +181,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"
-!!! 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.
+When you use the `async` methods, **FastAPI** runs the file methods in a threadpool and awaits for them.
+
+///
+
+/// 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.
+
+///
## What is "Form Data"
@@ -153,82 +199,113 @@ The way HTML forms (``) sends the data to the server normally uses
**FastAPI** will make sure to read that data from the right place instead of JSON.
-!!! note "Technical Details"
- Data from forms is normally encoded using the "media type" `application/x-www-form-urlencoded` when it doesn't include files.
+/// note | "Technical Details"
- 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.
+Data from forms is normally encoded using the "media type" `application/x-www-form-urlencoded` when it doesn't include files.
- If you want to read more about these encodings and form fields, head to the MDN web docs for POST.
+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
- 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`.
+If you want to read more about these encodings and form fields, head to the MDN web docs for POST.
- This is not a limitation of **FastAPI**, it's part of the HTTP protocol.
+///
+
+/// 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.
+
+///
## 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!}
- ```
+```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!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="9 17"
+{!> ../../../docs_src/request_files/tutorial001_02_an_py39.py!}
+```
- ```Python hl_lines="10 18"
- {!> ../../../docs_src/request_files/tutorial001_02_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="10 18"
+{!> ../../../docs_src/request_files/tutorial001_02_an.py!}
+```
- ```Python hl_lines="7 15"
- {!> ../../../docs_src/request_files/tutorial001_02_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 17"
- {!> ../../../docs_src/request_files/tutorial001_02.py!}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="7 15"
+{!> ../../../docs_src/request_files/tutorial001_02_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="9 17"
+{!> ../../../docs_src/request_files/tutorial001_02.py!}
+```
+
+////
## `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!}
- ```
+```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!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="8 14"
+{!> ../../../docs_src/request_files/tutorial001_03_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="7 13"
- {!> ../../../docs_src/request_files/tutorial001_03.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="7 13"
+{!> ../../../docs_src/request_files/tutorial001_03.py!}
+```
+
+////
## Multiple File Uploads
@@ -238,76 +315,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+"
+////
- ```Python hl_lines="11 16"
- {!> ../../../docs_src/request_files/tutorial002_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.9+ non-Annotated"
+```Python hl_lines="11 16"
+{!> ../../../docs_src/request_files/tutorial002_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="8 13"
- {!> ../../../docs_src/request_files/tutorial002_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="10 15"
- {!> ../../../docs_src/request_files/tutorial002.py!}
- ```
+///
+
+```Python hl_lines="8 13"
+{!> ../../../docs_src/request_files/tutorial002_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="10 15"
+{!> ../../../docs_src/request_files/tutorial002.py!}
+```
+
+////
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"
- **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 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.
+
+///
### 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="11 18"
- {!> ../../../docs_src/request_files/tutorial003.py!}
- ```
+///
+
+```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!}
+```
+
+////
## 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..7830a2ba4 100644
--- a/docs/en/docs/tutorial/request-forms-and-files.md
+++ b/docs/en/docs/tutorial/request-forms-and-files.md
@@ -2,67 +2,95 @@
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 `python-multipart`.
+/// info
- E.g. `pip install python-multipart`.
+To receive uploaded files and/or form data, first 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
+```
+
+///
## 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!}
- ```
+```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!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="1"
+{!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="1"
- {!> ../../../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="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
- This is not a limitation of **FastAPI**, it's part of the HTTP protocol.
+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.
+
+///
## Recap
diff --git a/docs/en/docs/tutorial/request-forms.md b/docs/en/docs/tutorial/request-forms.md
index 5f8f7b148..87cfdefbc 100644
--- a/docs/en/docs/tutorial/request-forms.md
+++ b/docs/en/docs/tutorial/request-forms.md
@@ -2,60 +2,85 @@
When you need to receive form fields instead of JSON, you can use `Form`.
-!!! info
- To use forms, first install `python-multipart`.
+/// info
- E.g. `pip install python-multipart`.
+To use forms, first 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
+```
+
+///
## 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!}
- ```
+```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!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="1"
+{!> ../../../docs_src/request_forms/tutorial001_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/request_forms/tutorial001.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="1"
+{!> ../../../docs_src/request_forms/tutorial001.py!}
+```
+
+////
## 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!}
- ```
+```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!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="8"
+{!> ../../../docs_src/request_forms/tutorial001_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/request_forms/tutorial001.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/request_forms/tutorial001.py!}
+```
+
+////
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 +88,17 @@ The spec 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
-!!! 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.
+`Form` is a class that inherits directly from `Body`.
+
+///
+
+/// 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.
+
+///
## About "Form Fields"
@@ -75,17 +106,23 @@ The way HTML forms (``) sends the data to the server normally uses
**FastAPI** will make sure to read that data from the right place instead of JSON.
-!!! note "Technical Details"
- Data from forms is normally encoded using the "media type" `application/x-www-form-urlencoded`.
+/// note | "Technical Details"
- But when the form includes files, it is encoded as `multipart/form-data`. You'll read about handling files in the next chapter.
+Data from forms is normally encoded using the "media type" `application/x-www-form-urlencoded`.
- If you want to read more about these encodings and form fields, head to the MDN web docs for POST.
+But when the form includes files, it is encoded as `multipart/form-data`. You'll read about handling files in the next chapter.
-!!! 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`.
+If you want to read more about these encodings and form fields, head to the MDN web docs for POST.
- This is not a limitation of **FastAPI**, it's part of the HTTP protocol.
+///
+
+/// 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.
+
+///
## Recap
diff --git a/docs/en/docs/tutorial/response-model.md b/docs/en/docs/tutorial/response-model.md
index 0e6292629..6a2093e6d 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!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="18 23"
- {!> ../../../docs_src/response_model/tutorial001_01_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="18 23"
+{!> ../../../docs_src/response_model/tutorial001_01_py39.py!}
+```
- ```Python hl_lines="18 23"
- {!> ../../../docs_src/response_model/tutorial001_01.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```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+"
+////
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```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.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.
+//// 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.
+
+///
`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
- 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`.
+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`.
+
+///
### `response_model` Priority
@@ -95,37 +113,57 @@ 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!}
- ```
+```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!}
- ```
+//// tab | Python 3.8+
-!!! info
- To use `EmailStr`, first install `email_validator`.
+```Python hl_lines="9 11"
+{!> ../../../docs_src/response_model/tutorial002.py!}
+```
- E.g. `pip install email-validator`
- or `pip install pydantic[email]`.
+////
+
+/// info
+
+To use `EmailStr`, first install `email-validator`.
+
+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]"
+```
+
+///
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!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="18"
- {!> ../../../docs_src/response_model/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+
+```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 +171,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+"
+////
- ```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!}
+```
+
+////
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+"
+////
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+//// tab | Python 3.8+
+
+```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!}
+```
-=== "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!}
+```
+
+////
So, **FastAPI** will take care of filtering out all the data that is not declared in the output model (using Pydantic).
@@ -192,9 +245,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.
@@ -202,17 +255,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!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9-13 15-16 20"
- {!> ../../../docs_src/response_model/tutorial003_01.py!}
- ```
+//// tab | Python 3.8+
+
+```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.
@@ -258,7 +315,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.
@@ -278,17 +335,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 union 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!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/response_model/tutorial003_04.py!}
- ```
+//// tab | Python 3.8+
+
+```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 +361,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+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/response_model/tutorial003_05.py!}
- ```
+//// tab | Python 3.8+
+
+```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,27 +383,33 @@ 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!}
+```
- ```Python hl_lines="11 13-14"
- {!> ../../../docs_src/response_model/tutorial004.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```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`.
-* `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.
@@ -348,23 +419,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!}
+```
-=== "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!}
+```
+
+////
and those default values won't be included in the response, only the values actually set.
@@ -377,21 +454,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
- 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()`.
-!!! info
- FastAPI uses Pydantic model's `.dict()` with its `exclude_unset` parameter 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
- You can also use:
+///
- * `response_model_exclude_defaults=True`
- * `response_model_exclude_none=True`
+/// info
- as described in the Pydantic docs for `exclude_defaults` and `exclude_none`.
+FastAPI uses Pydantic model's `.dict()` with its `exclude_unset` parameter to achieve this.
+
+///
+
+/// info
+
+You can also use:
+
+* `response_model_exclude_defaults=True`
+* `response_model_exclude_none=True`
+
+as described in the Pydantic docs for `exclude_defaults` and `exclude_none`.
+
+///
#### Data with values for fields with defaults
@@ -426,10 +512,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
- They can be a list (`[]`), a `float` of `10.5`, etc.
+Notice that the default values can be anything, not only `None`.
+
+They can be a list (`[]`), a `float` of `10.5`, etc.
+
+///
### `response_model_include` and `response_model_exclude`
@@ -439,45 +528,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+"
+////
- ```Python hl_lines="31 37"
- {!> ../../../docs_src/response_model/tutorial006.py!}
- ```
+//// tab | Python 3.8+
+
+```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 `http.HTTPStatus`.
+/// info
+
+`status_code` can alternatively also receive an `IntEnum`, such as Python's `http.HTTPStatus`.
+
+///
It will:
@@ -27,15 +33,21 @@ It will:
-!!! note
- Some response codes (see the next section) indicate that the response does not have a body.
+/// note
- FastAPI knows this, and will produce OpenAPI docs that state there is no response body.
+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.
+
+///
## 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 MDN documentation about HTTP status codes.
+/// tip
+
+To know more about each status code and which code is for what, check the MDN documentation about HTTP status codes.
+
+///
## 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
-!!! note "Technical Details"
- You could also use `from starlette import status`.
+/// note | "Technical Details"
- **FastAPI** provides the same `starlette.status` as `fastapi.status` just as a convenience for you, the developer. But it comes directly from Starlette.
+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.
+
+///
## Changing the default
diff --git a/docs/en/docs/tutorial/schema-extra-example.md b/docs/en/docs/tutorial/schema-extra-example.md
index 9bb9ba4e3..70745b048 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 Pydantic's docs: Model Config.
+In Pydantic version 2, you would use the attribute `model_config`, that takes a `dict` as described in Pydantic's docs: Configuration.
- 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`.
+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`.
-=== "Pydantic v1"
+////
- In Pydantic version 1, you would use an internal class `Config` and `schema_extra`, as described in Pydantic's docs: Schema customization.
+//// tab | Pydantic v1
- 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`.
+In Pydantic version 1, you would use an internal class `Config` and `schema_extra`, as described in Pydantic's docs: Schema customization.
-!!! tip
- You could use the same technique to extend the JSON Schema and add your own custom extra info.
+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`.
- For example you could use it to add metadata for a frontend user interface, etc.
+////
-!!! info
- OpenAPI 3.1.0 (used since FastAPI 0.99.0) added support for `examples`, which is part of the **JSON Schema** standard.
+/// tip
- 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 could use the same technique to extend the JSON Schema and add your own custom extra info.
- You can read more at the end of this page.
+For example you could use it to add metadata for a frontend user interface, etc.
+
+///
+
+/// 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!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="4 10-13"
- {!> ../../../docs_src/schema_extra_example/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+
+```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!}
- ```
+```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!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="23-38"
+{!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!}
+```
- ```Python hl_lines="24-39"
- {!> ../../../docs_src/schema_extra_example/tutorial004_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="24-39"
+{!> ../../../docs_src/schema_extra_example/tutorial004_an.py!}
+```
- ```Python hl_lines="19-34"
- {!> ../../../docs_src/schema_extra_example/tutorial004_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="21-36"
- {!> ../../../docs_src/schema_extra_example/tutorial004.py!}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="19-34"
+{!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="21-36"
+{!> ../../../docs_src/schema_extra_example/tutorial004.py!}
+```
+
+////
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!}
- ```
+```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!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="23-49"
+{!> ../../../docs_src/schema_extra_example/tutorial005_an_py39.py!}
+```
- ```Python hl_lines="24-50"
- {!> ../../../docs_src/schema_extra_example/tutorial005_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="24-50"
+{!> ../../../docs_src/schema_extra_example/tutorial005_an.py!}
+```
- ```Python hl_lines="19-45"
- {!> ../../../docs_src/schema_extra_example/tutorial005_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="21-47"
- {!> ../../../docs_src/schema_extra_example/tutorial005.py!}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="19-45"
+{!> ../../../docs_src/schema_extra_example/tutorial005_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="21-47"
+{!> ../../../docs_src/schema_extra_example/tutorial005.py!}
+```
+
+////
### 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
- They are more relevant for older versions, before OpenAPI 3.1.0 was available.
+If you are already using **FastAPI** version **0.99.0 or above**, you can probably **skip** these details.
- 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.
-!!! warning
- These are very technical details about the standards **JSON Schema** and **OpenAPI**.
+You can consider this a brief OpenAPI and JSON Schema **history lesson**. 🤓
- 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.
+///
+
+/// warning
+
+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.
+
+///
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,14 +377,17 @@ 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
- Because of that, versions of FastAPI previous to 0.99.0 still used versions of OpenAPI lower than 3.1.0.
+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.
+
+///
### 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/first-steps.md b/docs/en/docs/tutorial/security/first-steps.md
index 7d86e453e..4bd026caf 100644
--- a/docs/en/docs/tutorial/security/first-steps.md
+++ b/docs/en/docs/tutorial/security/first-steps.md
@@ -20,43 +20,60 @@ 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!}
+```
-=== "Python 3.8+"
+////
- ```Python
- {!> ../../../docs_src/security/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python
+{!> ../../../docs_src/security/tutorial001_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python
- {!> ../../../docs_src/security/tutorial001.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python
+{!> ../../../docs_src/security/tutorial001.py!}
+```
+
+////
## Run it
-!!! info
- First install `python-multipart`.
+/// info
- E.g. `pip install python-multipart`.
+The `python-multipart` package is automatically installed with **FastAPI** when you run the `pip install "fastapi[standard]"` command.
- This is because **OAuth2** uses "form data" for sending the `username` and `password`.
+However, if you use the `pip install fastapi` command, the `python-multipart` package is not included by default.
+
+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`.
+
+///
Run the example with:
-!!! check "Authorize button!"
- You already have a shiny new "Authorize" button.
+/// check | "Authorize button!"
- And your *path operation* has a little lock in the top-right corner that you can click.
+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 if you click it, you have a little authorization form to type a `username` and `password` (and other optional fields):
-!!! 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.
@@ -123,53 +146,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
- But it's the best one for our use case.
+A "bearer" token is not the only option.
- 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.
+But it's the best one for our use case.
- In that case, **FastAPI** also provides you with the tools to build it.
+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.
+
+///
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!}
- ```
+```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+ non-Annotated"
+```Python hl_lines="7"
+{!> ../../../docs_src/security/tutorial001_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="6"
- {!> ../../../docs_src/security/tutorial001.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-!!! 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`.
+/// tip
- 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`.
+Prefer to use the `Annotated` version if possible.
- 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}.
+///
+
+```Python hl_lines="6"
+{!> ../../../docs_src/security/tutorial001.py!}
+```
+
+////
+
+/// 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`.
+
+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
- 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.
+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.
+
+///
The `oauth2_scheme` variable is an instance of `OAuth2PasswordBearer`, but it is also a "callable".
@@ -185,35 +226,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!}
+```
-=== "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!}
+```
+
+////
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"
- 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.
+**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.
+
+///
## 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!}
- ```
+```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!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="5 12-16"
+{!> ../../../docs_src/security/tutorial002_an_py39.py!}
+```
- ```Python hl_lines="5 13-17"
- {!> ../../../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="5 13-17"
+{!> ../../../docs_src/security/tutorial002_an.py!}
+```
- ```Python hl_lines="3 10-14"
- {!> ../../../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="5 12-16"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="3 10-14"
+{!> ../../../docs_src/security/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="5 12-16"
+{!> ../../../docs_src/security/tutorial002.py!}
+```
+
+////
## 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!}
- ```
+```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!}
- ```
+//// tab | Python 3.9+
-=== "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.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="20-23 27-28"
+{!> ../../../docs_src/security/tutorial002_an.py!}
+```
- ```Python hl_lines="17-20 24-25"
- {!> ../../../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="19-22 26-27"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="17-20 24-25"
+{!> ../../../docs_src/security/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="19-22 26-27"
+{!> ../../../docs_src/security/tutorial002.py!}
+```
+
+////
## 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!}
- ```
+```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!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="31"
+{!> ../../../docs_src/security/tutorial002_an_py39.py!}
+```
- ```Python hl_lines="32"
- {!> ../../../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="32"
+{!> ../../../docs_src/security/tutorial002_an.py!}
+```
- ```Python hl_lines="29"
- {!> ../../../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="31"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="29"
+{!> ../../../docs_src/security/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="31"
+{!> ../../../docs_src/security/tutorial002.py!}
+```
+
+////
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!}
- ```
+```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!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="30-32"
+{!> ../../../docs_src/security/tutorial002_an_py39.py!}
+```
- ```Python hl_lines="31-33"
- {!> ../../../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="31-33"
+{!> ../../../docs_src/security/tutorial002_an.py!}
+```
- ```Python hl_lines="28-30"
- {!> ../../../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="30-32"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="28-30"
+{!> ../../../docs_src/security/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="30-32"
+{!> ../../../docs_src/security/tutorial002.py!}
+```
+
+////
## 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
- 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.
+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.
+
+///
## **FastAPI** utilities
diff --git a/docs/en/docs/tutorial/security/oauth2-jwt.md b/docs/en/docs/tutorial/security/oauth2-jwt.md
index 1c792e3d9..ba2bfef29 100644
--- a/docs/en/docs/tutorial/security/oauth2-jwt.md
+++ b/docs/en/docs/tutorial/security/oauth2-jwt.md
@@ -26,28 +26,29 @@ 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 https://jwt.io.
-## 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.
+
+Make sure you create a [virtual environment](../../virtual-environments.md){.internal-link target=_blank}, activate it, and then install `pyjwt`:
@@ -357,8 +434,11 @@ If you open the developer tools, you could see how the data sent only includes t
-!!! 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`
@@ -384,7 +464,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/en/docs/tutorial/security/simple-oauth2.md b/docs/en/docs/tutorial/security/simple-oauth2.md
index 88edc9eab..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!}
- ```
+```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!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="4 78"
+{!> ../../../docs_src/security/tutorial003_an_py39.py!}
+```
- ```Python hl_lines="4 79"
- {!> ../../../docs_src/security/tutorial003_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="4 79"
+{!> ../../../docs_src/security/tutorial003_an.py!}
+```
- ```Python hl_lines="2 74"
- {!> ../../../docs_src/security/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="4 76"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="2 74"
+{!> ../../../docs_src/security/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="4 76"
+{!> ../../../docs_src/security/tutorial003.py!}
+```
+
+////
`OAuth2PasswordRequestForm` is a class dependency that declares a form body with:
@@ -92,71 +111,96 @@ 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
- If you need to enforce it, use `OAuth2PasswordRequestFormStrict` instead of `OAuth2PasswordRequestForm`.
+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`.
+
+///
* 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
- `OAuth2PasswordBearer` makes **FastAPI** know that it is a security scheme. So it is added that way to OpenAPI.
+The `OAuth2PasswordRequestForm` is not a special class for **FastAPI** as is `OAuth2PasswordBearer`.
- But `OAuth2PasswordRequestForm` is just a class dependency that you could have written yourself, or you could have declared `Form` parameters directly.
+`OAuth2PasswordBearer` makes **FastAPI** know that it is a security scheme. So it is added that way to OpenAPI.
- But as it's a common use case, it is provided by **FastAPI** directly, just to make it easier.
+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.
+
+///
### 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
- We are not using `scopes` in this example, but the functionality is there if you need it.
+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.
+
+///
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`:
-=== "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!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="3 79-81"
- {!> ../../../docs_src/security/tutorial003_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="3 79-81"
+{!> ../../../docs_src/security/tutorial003_an_py39.py!}
+```
- ```Python hl_lines="3 80-82"
- {!> ../../../docs_src/security/tutorial003_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="3 80-82"
+{!> ../../../docs_src/security/tutorial003_an.py!}
+```
- ```Python hl_lines="1 75-77"
- {!> ../../../docs_src/security/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="3 77-79"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="1 75-77"
+{!> ../../../docs_src/security/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="3 77-79"
+{!> ../../../docs_src/security/tutorial003.py!}
+```
+
+////
### 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!}
- ```
+```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!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="82-85"
+{!> ../../../docs_src/security/tutorial003_an_py39.py!}
+```
- ```Python hl_lines="83-86"
- {!> ../../../docs_src/security/tutorial003_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="83-86"
+{!> ../../../docs_src/security/tutorial003_an.py!}
+```
- ```Python hl_lines="78-81"
- {!> ../../../docs_src/security/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="80-83"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="78-81"
+{!> ../../../docs_src/security/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="80-83"
+{!> ../../../docs_src/security/tutorial003.py!}
+```
+
+////
#### 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 JWT tokens.
+/// tip
- But for now, let's focus on the specific details we need.
+In the next chapter, you will see a real secure implementation, with password hashing and JWT tokens.
-=== "Python 3.10+"
+But for now, let's focus on the specific details we need.
- ```Python hl_lines="87"
- {!> ../../../docs_src/security/tutorial003_an_py310.py!}
- ```
+///
-=== "Python 3.9+"
+//// tab | Python 3.10+
- ```Python hl_lines="87"
- {!> ../../../docs_src/security/tutorial003_an_py39.py!}
- ```
+```Python hl_lines="87"
+{!> ../../../docs_src/security/tutorial003_an_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="88"
- {!> ../../../docs_src/security/tutorial003_an.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.10+ non-Annotated"
+```Python hl_lines="87"
+{!> ../../../docs_src/security/tutorial003_an_py39.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="83"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="88"
+{!> ../../../docs_src/security/tutorial003_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="85"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+//// tab | Python 3.10+ non-Annotated
-!!! tip
- By the spec, you should return a JSON with an `access_token` and a `token_type`, the same as in this example.
+/// tip
- This is something that you have to do yourself in your code, and make sure you use those JSON keys.
+Prefer to use the `Annotated` version if possible.
- 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.
+```Python hl_lines="83"
+{!> ../../../docs_src/security/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="85"
+{!> ../../../docs_src/security/tutorial003.py!}
+```
+
+////
+
+/// 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!}
+```
- ```Python hl_lines="59-67 70-75 95"
- {!> ../../../docs_src/security/tutorial003_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="59-67 70-75 95"
+{!> ../../../docs_src/security/tutorial003_an.py!}
+```
- ```Python hl_lines="56-64 67-70 88"
- {!> ../../../docs_src/security/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="58-66 69-72 90"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-!!! 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.
+```Python hl_lines="56-64 67-70 88"
+{!> ../../../docs_src/security/tutorial003_py310.py!}
+```
- 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.
+//// tab | Python 3.8+ non-Annotated
- But it's provided here to be compliant with the specifications.
+/// tip
- 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.
+Prefer to use the `Annotated` version if possible.
- That's the benefit of standards...
+///
+
+```Python hl_lines="58-66 69-72 90"
+{!> ../../../docs_src/security/tutorial003.py!}
+```
+
+////
+
+/// 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.
+
+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.
+
+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.
+
+That's the benefit of standards...
+
+///
## See it in action
@@ -416,7 +520,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..56971bf9d 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 SQLModel (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 SQLModel (which is also based on SQLAlchemy) once it is updated to use Pydantic v2 as well.
+
+///
**FastAPI** doesn't require you to use a SQL (relational) database.
@@ -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: https://github.com/tiangolo/full-stack-fastapi-postgresql
+/// tip
-!!! note
- Notice that most of the code is the standard `SQLAlchemy` code you would use with any framework.
+There is an official project generator with **FastAPI** and **PostgreSQL**, all based on **Docker**, including a frontend and more tools: https://github.com/tiangolo/full-stack-fastapi-postgresql
- The **FastAPI** specific code is as small as always.
+///
+
+/// note
+
+Notice that most of the code is the standard `SQLAlchemy` code you would use with any framework.
+
+The **FastAPI** specific code is as small as always.
+
+///
## ORMs
@@ -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
@@ -89,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:
-
-
+
+
+
+
+
+
+
+
-!!! info
- Las ilustraciones fueron creados por Ketrina Thompson. 🎨
+/// info | Información
+
+Las ilustraciones fueron creados por Ketrina Thompson. 🎨
+
+///
---
@@ -190,7 +196,7 @@ Luego, el cajero / cocinero 👨🍳 finalmente regresa con tus hamburguesas
-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 🍔 ⏹.
@@ -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 Ketrina Thompson. 🎨
+/// info | Información
+
+Las ilustraciones fueron creados por Ketrina Thompson. 🎨
+
+///
---
@@ -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
- Estos son detalles muy técnicos de cómo **FastAPI** funciona a muy bajo nivel.
+Probablemente puedas saltarte esto.
- 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.
+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.
+
+///
### Path operation functions
@@ -400,7 +412,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 I/O.
-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#rendimiento){.Internal-link target=_blank} que (o al menos comparable) a tu framework anterior.
### Dependencias
diff --git a/docs/es/docs/deployment/versions.md b/docs/es/docs/deployment/versions.md
index d8719d6bd..74243da89 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 "PATCH" version es para solucionar errores y *non-breaking changes*.
-!!! tip
- El "PATCH" es el último número, por ejemplo, en `0.2.3`, la PATCH version es `3`.
+/// tip | Consejo
+
+El "PATCH" es el último número, por ejemplo, en `0.2.3`, la PATCH version es `3`.
+
+///
Entonces, deberías fijar la versión así:
@@ -53,8 +56,11 @@ fastapi>=0.45.0,<0.46.0
En versiones "MINOR" son añadidas nuevas características y posibles breaking changes.
-!!! tip
- La versión "MINOR" es el número en el medio, por ejemplo, en `0.2.3`, la "MINOR" version es `2`.
+/// tip | Consejo
+
+La versión "MINOR" es el número en el medio, por ejemplo, en `0.2.3`, la "MINOR" version es `2`.
+
+///
## Actualizando las versiones de FastAPI
diff --git a/docs/es/docs/external-links.md b/docs/es/docs/external-links.md
deleted file mode 100644
index cfbdd68a6..000000000
--- a/docs/es/docs/external-links.md
+++ /dev/null
@@ -1,33 +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 Pull Request agregándolo.
-
-{% 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 %}
-
-* {{ item.title }} by {{ item.author }}.
-
-{% endfor %}
-{% endfor %}
-{% endfor %}
-
-## Projects
-
-Últimos proyectos de GitHub con el tema `fastapi`:
-
-
-
-
+
+
-
-
+
+
@@ -20,10 +26,10 @@
**Documentación**: https://fastapi.tiangolo.com
-**Código Fuente**: https://github.com/tiangolo/fastapi
+**Código Fuente**: https://github.com/fastapi/fastapi
---
-FastAPI es un web framework moderno y rápido (de alto rendimiento) para construir APIs con Python 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:
@@ -60,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._"
-
email_validator - para validación de emails.
+* email-validator - para validación de emails.
Usados por Starlette:
@@ -443,12 +447,12 @@ Usados por Starlette:
* itsdangerous - Requerido para dar soporte a `SessionMiddleware`.
* pyyaml - Requerido para dar soporte al `SchemaGenerator` de Starlette (probablemente no lo necesites con FastAPI).
* graphene - Requerido para dar soporte a `GraphQLApp`.
-* ujson - Requerido si quieres usar `UJSONResponse`.
Usado por FastAPI / Starlette:
* uvicorn - para el servidor que carga y sirve tu aplicación.
* orjson - Requerido si quieres usar `ORJSONResponse`.
+* ujson - Requerido si quieres usar `UJSONResponse`.
Puedes instalarlos con `pip install fastapi[all]`.
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
-
-
-
-
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.
diff --git a/docs/es/docs/python-types.md b/docs/es/docs/python-types.md
index 89edbb31e..4015dbb05 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 Pydantic mira su documentación.
+/// info | Información
+
+Para aprender más sobre Pydantic mira su documentación.
+
+///
**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 la "cheat sheet" de `mypy`.
+/// info | Información
+
+Si ya pasaste por todo el tutorial y volviste a la sección de los tipos, una buena referencia es la "cheat sheet" de `mypy`.
+
+///
diff --git a/docs/es/docs/tutorial/cookie-params.md b/docs/es/docs/tutorial/cookie-params.md
new file mode 100644
index 000000000..3eaea31f9
--- /dev/null
+++ b/docs/es/docs/tutorial/cookie-params.md
@@ -0,0 +1,135 @@
+# 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`:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/cookie_params/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip | Consejo
+
+Es preferible utilizar la versión `Annotated` si es posible.
+
+///
+
+```Python hl_lines="1"
+{!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | Consejo
+
+Es preferible utilizar la versión `Annotated` si es posible.
+
+///
+
+```Python hl_lines="3"
+{!> ../../../docs_src/cookie_params/tutorial001.py!}
+```
+
+////
+
+## 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:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/cookie_params/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip | Consejo
+
+Es preferible utilizar la versión `Annotated` si es posible.
+
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | Consejo
+
+Es preferible utilizar la versión `Annotated` si es posible.
+
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/cookie_params/tutorial001.py!}
+```
+
+////
+
+/// 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`.
diff --git a/docs/es/docs/tutorial/first-steps.md b/docs/es/docs/tutorial/first-steps.md
index 2cb7e6308..8d8909b97 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
get
-!!! 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
- **FastAPI** no impone ningún significado específico.
+Tienes la libertad de usar cada operación (método de HTTP) como quieras.
- La información que está presentada aquí es una guía, no un requerimiento.
+**FastAPI** no impone ningún significado específico.
- Por ejemplo, cuando usas GraphQL normalmente realizas todas las acciones usando únicamente operaciones `POST`.
+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`.
+
+///
### 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#in-a-hurry){.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 f0dff02b4..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.
-!!! 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
+```
- ```
- pip install "uvicorn[standard]"
- ```
+También debes instalar `uvicorn` para que funcione como tu servidor:
- Y lo mismo para cada una de las dependencias opcionales que quieras utilizar.
+```
+pip install "uvicorn[standard]"
+```
+
+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..e09e0381f 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.
+
+///
## Conversión de datos
@@ -35,10 +38,13 @@ Si corres este ejemplo y abres tu navegador en "parsing" automático del request.
+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 "parsing" 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: http://127.0.0.1:8000/items/4.2
-!!! check "Revisa"
- Así, con la misma declaración de tipo de Python, **FastAPI** te da validación de datos.
+/// 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
-!!! 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
- Observa que el parámetro de path está declarado como un integer.
+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.
+
+///
## 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 Enumerations (o enums) están disponibles en Python desde la versión 3.4.
+/// info | Información
-!!! tip "Consejo"
- Si lo estás dudando, "AlexNet", "ResNet", y "LeNet" son solo nombres de modelos de Machine Learning.
+Las Enumerations (o enums) están disponibles en Python desde la versión 3.4.
+
+///
+
+/// tip | Consejo
+
+Si lo estás dudando, "AlexNet", "ResNet", y "LeNet" son solo nombres de modelos de Machine Learning.
+
+///
### 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
- En este caso la URL sería `/files//home/johndoe/myfile.txt` con un slash doble (`//`) entre `files` y `home`.
+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`.
+
+///
## Repaso
diff --git a/docs/es/docs/tutorial/query-params.md b/docs/es/docs/tutorial/query-params.md
index 482af8dc0..6f88fd617 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#predefined-values){.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/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/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/index.md b/docs/fa/docs/index.md
index e5231ec8d..1ae566a9f 100644
--- a/docs/fa/docs/index.md
+++ b/docs/fa/docs/index.md
@@ -1,3 +1,9 @@
+# FastAPI
+
+
+
@@ -5,11 +11,11 @@
فریمورک FastAPI، کارایی بالا، یادگیری آسان، کدنویسی سریع، آماده برای استفاده در محیط پروداکشن
-
-
+
+
-
-
+
+
@@ -23,14 +29,14 @@
**مستندات**: https://fastapi.tiangolo.com
-**کد منبع**: https://github.com/tiangolo/fastapi
+**کد منبع**: https://github.com/fastapi/fastapi
---
FastAPI یک وب فریمورک مدرن و سریع (با کارایی بالا) برای ایجاد APIهای متنوع (وب، وبسوکت و غبره) با زبان پایتون نسخه +۳.۶ است. این فریمورک با رعایت کامل راهنمای نوع داده (Type Hint) ایجاد شده است.
ویژگیهای کلیدی این فریمورک عبارتند از:
-* **سرعت**: کارایی بسیار بالا و قابل مقایسه با **NodeJS** و **Go** (با تشکر از Starlette و Pydantic). [یکی از سریعترین فریمورکهای پایتونی موجود](#performance).
+* **سرعت**: کارایی بسیار بالا و قابل مقایسه با **NodeJS** و **Go** (با تشکر از Starlette و Pydantic). [یکی از سریعترین فریمورکهای پایتونی موجود](#_10).
* **کدنویسی سریع**: افزایش ۲۰۰ تا ۳۰۰ درصدی سرعت توسعه قابلیتهای جدید. *
* **باگ کمتر**: کاهش ۴۰ درصدی خطاهای انسانی (برنامهنویسی). *
@@ -60,7 +66,7 @@ FastAPI یک وب فریمورک مدرن و سریع (با کارایی با
email_validator - برای اعتبارسنجی آدرسهای ایمیل.
+* email-validator - برای اعتبارسنجی آدرسهای ایمیل.
استفاده شده توسط Starlette:
@@ -447,12 +453,12 @@ item: Item
* itsdangerous - در صورتی که بخواید از `SessionMiddleware` پشتیبانی کنید.
* pyyaml - برای پشتیبانی `SchemaGenerator` در Starlet (به احتمال زیاد برای کار کردن با FastAPI به آن نیازی پیدا نمیکنید).
* graphene - در صورتی که از `GraphQLApp` پشتیبانی میکنید.
-* ujson - در صورتی که بخواهید از `UJSONResponse` استفاده کنید.
استفاده شده توسط FastAPI / Starlette:
* uvicorn - برای سرور اجرا کننده برنامه وب.
* orjson - در صورتی که بخواهید از `ORJSONResponse` استفاده کنید.
+* ujson - در صورتی که بخواهید از `UJSONResponse` استفاده کنید.
میتوان همه این موارد را با استفاده از دستور `pip install fastapi[all]`. به صورت یکجا نصب کرد.
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` که در مستندات CORS از Starlette توضیح داده شده است، به پیکربندی CORS خود اضافه کنید.
+اما اگر هدرهای سفارشی دارید که میخواهید مرورگر کاربر بتواند آنها را ببیند، باید آنها را با استفاده از پارامتر `expose_headers` که در مستندات CORS از Starlette توضیح داده شده است، به پیکربندی CORS خود اضافه کنید.
-!!! توجه "جزئیات فنی"
- شما همچنین میتوانید از `from starlette.requests import Request` استفاده کنید.
+///
- **FastAPI** این را به عنوان یک سهولت برای شما به عنوان برنامهنویس فراهم میکند. اما این مستقیما از Starlette به دست میآید.
+/// توجه | "جزئیات فنی"
+
+شما همچنین میتوانید از `from starlette.requests import Request` استفاده کنید.
+
+**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 35b57594d..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
-!!! 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!}
```
-!!! Remarque
- Gardez à l'esprit que vous devez renvoyer directement `JSONResponse`.
+/// note | "Remarque"
-!!! Info
- La clé `model` ne fait pas partie d'OpenAPI.
+Gardez à l'esprit que vous devez renvoyer directement `JSONResponse`.
- **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 :
+/// info
- * 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.
+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.
+
+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.
+
+///
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!}
```
-!!! Remarque
- Notez que vous devez retourner l'image en utilisant directement un `FileResponse`.
+/// note | "Remarque"
-!!! 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`).
+Notez que vous devez retourner l'image en utilisant directement un `FileResponse`.
- 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.
+///
+
+/// 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.
+
+///
## Combinaison d'informations
@@ -206,7 +221,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 +231,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..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!}
```
-!!! 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 f4fa5ecf6..198fa8c30 100644
--- a/docs/fr/docs/advanced/index.md
+++ b/docs/fr/docs/advanced/index.md
@@ -2,18 +2,21 @@
## 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.
-!!! Note
- 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
-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/advanced/path-operation-advanced-configuration.md b/docs/fr/docs/advanced/path-operation-advanced-configuration.md
index 7ded97ce1..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
-!!! 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!}
```
-!!! Astuce
- Si vous appelez manuellement `app.openapi()`, vous devez mettre à jour les `operationId` avant.
+/// tip | "Astuce"
-!!! Attention
- Pour faire cela, vous devez vous assurer que chacun de vos *chemin* ait un nom unique.
+Si vous appelez manuellement `app.openapi()`, vous devez mettre à jour les `operationId` avant.
- Même s'ils se trouvent dans des modules différents (fichiers Python).
+///
+
+/// 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).
+
+///
## Exclusion d'OpenAPI
@@ -59,14 +68,17 @@ 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
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 Objets d'opération.
+/// note | "Détails techniques"
+
+La spécification OpenAPI appelle ces métadonnées des Objets d'opération.
+
+///
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.
-!!! 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!}
```
-!!! Astuce
- Ici, nous réutilisons le même modèle Pydantic.
+/// tip | "Astuce"
- Mais nous aurions pu tout aussi bien pu le valider d'une autre manière.
+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..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
- `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"
- **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.
+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.
+
+///
## 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.
+///
+
### Flask
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.
+///
+
### Requests
**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.
+
+///
### Swagger / OpenAPI
@@ -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 :
- * Swagger UI
- * ReDoc
+* Swagger UI
+* ReDoc
- 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 schéma, vous devez utiliser des utilitaires et des classes spécifiques fournies par Marshmallow.
-!!! check "A inspiré **FastAPI** à"
+/// check | "A inspiré **FastAPI** à"
+
Utilisez du code pour définir des "schémas" qui fournissent automatiquement les types de données et la validation.
+///
+
### Webargs
Une autre grande fonctionnalité requise par les API est le APISpec
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.
+///
+
### Flask-apispec
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.
+///
+
### NestJS (et Angular)
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.
+
+///
### Sanic
C'était l'un des premiers frameworks Python extrêmement rapides basés sur `asyncio`. Il a été conçu pour être très similaire à Flask.
-!!! note "Détails techniques"
+/// note | "Détails techniques"
+
Il utilisait `uvloop` au lieu du système par défaut de Python `asyncio`. C'est ce qui l'a rendu si rapide.
- 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).
+
+///
### Falcon
@@ -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.
+
+///
### Molten
@@ -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).
+
+///
### Hug
@@ -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 `isort`, 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.
+
+///
### APIStar (<= 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.
+
+///
### Starlette
@@ -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.
+
+///
### Uvicorn
@@ -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 af4d6ca06..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`.
+
+///
---
@@ -103,24 +106,44 @@ 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.
+
+
Puis vient votre tour, vous commandez alors 2 magnifiques burgers 🍔 pour votre crush 😍 et vous.
-Vous payez 💸.
+
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).
+
+
+Vous payez 💸.
+
Le serveur 💁 vous donne le numéro assigné à votre commande.
+
+
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 ✨😍✨.
+
+
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.
+
+
Vous et votre crush 😍 mangez les burgers 🍔 et passez un bon moment ✨.
+
+
+/// info
+
+Illustrations proposées par Ketrina Thompson. 🎨
+
+///
+
---
Imaginez que vous êtes l'ordinateur / le programme 🤖 dans cette histoire.
@@ -149,26 +172,44 @@ 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.
+
+
Puis c'est enfin votre tour, vous commandez 2 magnifiques burgers 🍔 pour vous et votre crush 😍.
Vous payez 💸.
+
+
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.
+
+
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.
+
+
Puis le serveur/cuisinier 👨🍳 revient enfin avec vos burgers 🍔, après un long moment d'attente 🕙 devant le comptoir.
+
+
Vous prenez vos burgers 🍔 et allez à une table avec votre crush 😍
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 Ketrina Thompson. 🎨
+
+///
+
---
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.
@@ -352,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 !"
- Ce sont des détails très poussés sur comment **FastAPI** fonctionne en arrière-plan.
+Vous pouvez probablement ignorer cela.
- 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.
+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.
+
+///
### Fonctions de chemin
@@ -365,7 +409,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 I/O 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/fr/docs/contributing.md b/docs/fr/docs/contributing.md
index 8292f14bb..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
-
-
-
+
+
-
-
+
+
@@ -23,11 +29,11 @@
**Documentation** : https://fastapi.tiangolo.com
-**Code Source** : https://github.com/tiangolo/fastapi
+**Code Source** : https://github.com/fastapi/fastapi
---
-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 :
@@ -63,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**._"
-
email_validator - pour la validation des adresses email.
+* email-validator - pour la validation des adresses email.
Utilisées par Starlette :
@@ -454,12 +458,12 @@ Utilisées par Starlette :
* python-multipart - Obligatoire si vous souhaitez supporter le "décodage" de formulaire avec `request.form()`.
* itsdangerous - Obligatoire pour la prise en charge de `SessionMiddleware`.
* pyyaml - Obligatoire pour le support `SchemaGenerator` de Starlette (vous n'en avez probablement pas besoin avec FastAPI).
-* ujson - Obligatoire si vous souhaitez utiliser `UJSONResponse`.
Utilisées par FastAPI / Starlette :
* uvicorn - Pour le serveur qui charge et sert votre application.
* orjson - Obligatoire si vous voulez utiliser `ORJSONResponse`.
+* ujson - Obligatoire si vous souhaitez utiliser `UJSONResponse`.
Vous pouvez tout installer avec `pip install fastapi[all]`.
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. 😎
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 : Swarm
* Intégration **Docker Compose** et optimisation pour développement local.
* Serveur web Python **prêt au déploiement** utilisant Uvicorn et Gunicorn.
-* Backend Python **FastAPI** :
+* Backend Python **FastAPI** :
* **Rapide** : Très hautes performances, comparables à **NodeJS** ou **Go** (grâce à Starlette et Pydantic).
* **Intuitif** : Excellent support des éditeurs. Complétion 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/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"
- Ici, `str` est un paramètre de type passé à `List`.
+Ces types internes entre crochets sont appelés des "paramètres de type".
+
+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 Pydantic, allez jeter un coup d'oeil à sa documentation.
+/// info
+
+Pour en savoir plus à propos de Pydantic, allez jeter un coup d'oeil à sa documentation.
+
+///
**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 "cheat sheet" de `mypy`.
+/// info
+
+Si vous avez déjà lu le tutoriel et êtes revenus ici pour voir plus sur les types, une bonne ressource est la "cheat sheet" de `mypy`.
+
+///
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..fd8e5d688
--- /dev/null
+++ b/docs/fr/docs/tutorial/body-multiple-params.md
@@ -0,0 +1,384 @@
+# 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` :
+
+//// tab | Python 3.10+
+
+```Python hl_lines="18-20"
+{!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="18-20"
+{!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="19-21"
+{!> ../../../docs_src/body_multiple_params/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip
+
+Préférez utiliser la version `Annotated` si possible.
+
+///
+
+```Python hl_lines="17-19"
+{!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Préférez utiliser la version `Annotated` si possible.
+
+///
+
+```Python hl_lines="19-21"
+{!> ../../../docs_src/body_multiple_params/tutorial001.py!}
+```
+
+////
+
+/// 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 :
+
+//// tab | Python 3.10+
+
+```Python hl_lines="20"
+{!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="22"
+{!> ../../../docs_src/body_multiple_params/tutorial002.py!}
+```
+
+////
+
+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` :
+//// tab | Python 3.10+
+
+```Python hl_lines="23"
+{!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="23"
+{!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="24"
+{!> ../../../docs_src/body_multiple_params/tutorial003_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip
+
+Préférez utiliser la version `Annotated` si possible.
+
+///
+
+```Python hl_lines="20"
+{!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Préférez utiliser la version `Annotated` si possible.
+
+///
+
+```Python hl_lines="22"
+{!> ../../../docs_src/body_multiple_params/tutorial003.py!}
+```
+
+////
+
+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 :
+
+//// tab | Python 3.10+
+
+```Python hl_lines="27"
+{!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="27"
+{!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="28"
+{!> ../../../docs_src/body_multiple_params/tutorial004_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip
+
+Préférez utiliser la version `Annotated` si possible.
+
+///
+
+```Python hl_lines="25"
+{!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Préférez utiliser la version `Annotated` si possible.
+
+///
+
+```Python hl_lines="27"
+{!> ../../../docs_src/body_multiple_params/tutorial004.py!}
+```
+
+////
+
+/// 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 :
+
+//// tab | Python 3.10+
+
+```Python hl_lines="17"
+{!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="17"
+{!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="18"
+{!> ../../../docs_src/body_multiple_params/tutorial005_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip
+
+Préférez utiliser la version `Annotated` si possible.
+
+///
+
+```Python hl_lines="15"
+{!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Préférez utiliser la version `Annotated` si possible.
+
+///
+
+```Python hl_lines="17"
+{!> ../../../docs_src/body_multiple_params/tutorial005.py!}
+```
+
+////
+
+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é.
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 Pydantic 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
-!!! tip "Astuce"
- Si vous utilisez PyCharm comme éditeur, vous pouvez utiliser le Plugin Pydantic PyCharm Plugin.
+/// tip | "Astuce"
- Ce qui améliore le support pour les modèles Pydantic avec :
+Si vous utilisez PyCharm comme éditeur, vous pouvez utiliser le Plugin Pydantic PyCharm Plugin.
- * de l'auto-complétion
- * des vérifications de type
- * du "refactoring" (ou remaniement de code)
- * de la recherche
- * de l'inspection
+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
+
+///
## 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
- 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.
+**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.
+
+///
## 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 la documentation officielle de Python.
+///
+
## Exécutez votre code avec votre débogueur
Parce que vous exécutez le serveur Uvicorn directement depuis votre code, vous pouvez appeler votre programme Python (votre application FastAPI) directement depuis le débogueur.
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
get
-!!! info "`@décorateur` Info"
- Cette syntaxe `@something` en Python est appelée un "décorateur".
+/// info | "`@décorateur` Info"
- Vous la mettez au dessus d'une fonction. Comme un joli chapeau décoratif (j'imagine que ce terme vient de là 🤷🏻♂).
+Cette syntaxe `@something` en Python est appelée un "décorateur".
- Un "décorateur" prend la fonction en dessous et en fait quelque chose.
+Vous la mettez au dessus d'une fonction. Comme un joli chapeau décoratif (j'imagine que ce terme vient de là 🤷🏻♂).
- Dans notre cas, ce décorateur dit à **FastAPI** que la fonction en dessous correspond au **chemin** `/` avec l'**opération** `get`.
+Un "décorateur" prend la fonction en dessous et en fait quelque chose.
- C'est le "**décorateur d'opération de chemin**".
+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**".
+
+///
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"
- **FastAPI** n'impose pas de sens spécifique à chacune d'elle.
+Vous êtes libres d'utiliser chaque opération (méthode HTTP) comme vous le désirez.
- Les informations qui sont présentées ici forment une directive générale, pas des obligations.
+**FastAPI** n'impose pas de sens spécifique à chacune d'elle.
- Par exemple, quand l'on utilise **GraphQL**, toutes les actions sont effectuées en utilisant uniquement des opérations `POST`.
+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`.
+
+///
### É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
+```
- ```
- pip install uvicorn
- ```
+Installez également `uvicorn` pour qu'il fonctionne comme serveur :
- Et la même chose pour chacune des dépendances facultatives que vous voulez utiliser.
+```
+pip install uvicorn
+```
+
+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
new file mode 100644
index 000000000..eedd59f91
--- /dev/null
+++ b/docs/fr/docs/tutorial/path-params-numeric-validations.md
@@ -0,0 +1,417 @@
+# 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` :
+
+//// tab | Python 3.10+
+
+```Python hl_lines="1 3"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="1 3"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="3-4"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip
+
+Préférez utiliser la version `Annotated` si possible.
+
+///
+
+```Python hl_lines="1"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Préférez utiliser la version `Annotated` si possible.
+
+///
+
+```Python hl_lines="3"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
+```
+
+////
+
+/// 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 :
+
+//// tab | Python 3.10+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="11"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip
+
+Préférez utiliser la version `Annotated` si possible.
+
+///
+
+```Python hl_lines="8"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Préférez utiliser la version `Annotated` si possible.
+
+///
+
+```Python hl_lines="10"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
+```
+
+////
+
+/// 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 :
+
+//// tab | Python 3.8 non-Annotated
+
+/// tip
+
+Préférez utiliser la version `Annotated` si possible.
+
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!}
+```
+
+////
+
+Mais gardez à l'esprit que si vous utilisez `Annotated`, vous n'aurez pas ce problème, cela n'aura pas d'importance car vous n'utilisez pas les valeurs par défaut des paramètres de fonction pour `Query()` ou `Path()`.
+
+//// tab | Python 3.9+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!}
+```
+
+////
+
+## 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 kwargs. Même s'ils n'ont pas de valeur par défaut.
+
+```Python hl_lines="7"
+{!../../../docs_src/path_params_numeric_validations/tutorial003.py!}
+```
+
+# Avec `Annotated`
+
+Gardez à l'esprit que si vous utilisez `Annotated`, comme vous n'utilisez pas les valeurs par défaut des paramètres de fonction, vous n'aurez pas ce problème, et vous n'aurez probablement pas besoin d'utiliser `*`.
+
+//// tab | Python 3.9+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!}
+```
+
+////
+
+## 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`.
+
+//// tab | Python 3.9+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="8"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!}
+```
+
+////
+
+## 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
+
+//// tab | Python 3.9+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Préférez utiliser la version `Annotated` si possible.
+
+///
+
+```Python hl_lines="8"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!}
+```
+
+////
+
+## 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
+
+//// tab | Python 3.9+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Préférez utiliser la version `Annotated` si possible.
+
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!}
+```
+
+////
+
+## 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 gt et pas seulement ge. 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 lt.
+
+//// tab | Python 3.9+
+
+```Python hl_lines="13"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="12"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Préférez utiliser la version `Annotated` si possible.
+
+///
+
+```Python hl_lines="11"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!}
+```
+
+////
+
+## 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.
+
+///
diff --git a/docs/fr/docs/tutorial/path-params.md b/docs/fr/docs/tutorial/path-params.md
index 817545c1c..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`.
-!!! hint "Astuce"
- 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.
+
+///
## Conversion de données
@@ -40,12 +43,15 @@ Si vous exécutez cet exemple et allez sur "parsing" automatique.
+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
+"parsing" 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
http://127.0.0.1:8000/items/4.2.
-!!! hint "Astuce"
- 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 :
-!!! info
- À nouveau, en utilisant uniquement les déclarations de type Python, **FastAPI** vous fournit automatiquement une documentation interactive (via Swagger UI).
+/// info
- On voit bien dans la documentation que `item_id` est déclaré comme entier.
+À 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.
+
+///
## 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
- Les énumérations (ou enums) sont disponibles en Python depuis la version 3.4.
+/// info
-!!! tip "Astuce"
- Pour ceux qui se demandent, "AlexNet", "ResNet", et "LeNet" sont juste des noms de modèles de Machine Learning.
+Les énumérations (ou enums) sont disponibles en Python depuis la version 3.4.
+
+///
+
+/// tip | "Astuce"
+
+Pour ceux qui se demandent, "AlexNet", "ResNet", et "LeNet" sont juste des noms de modèles 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"
- Dans ce cas, l'URL serait : `/files//home/johndoe/myfile.txt`, avec un double slash (`//`) entre `files` et `home`.
+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`.
+
+///
## 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)
+```
- Le `Union[str, None]` est uniquement là pour permettre à votre éditeur un meilleur support.
+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.
+
+///
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 appelée "Ellipsis".
+/// info
+
+Si vous n'avez jamais vu ce `...` auparavant : c'est une des constantes natives de Python appelée "Ellipsis".
+
+///
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
- 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.
+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.
+
+///
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/he/docs/index.md b/docs/he/docs/index.md
index 335a22743..23a2eb824 100644
--- a/docs/he/docs/index.md
+++ b/docs/he/docs/index.md
@@ -1,3 +1,9 @@
+# FastAPI
+
+
+
@@ -5,11 +11,11 @@
תשתית FastAPI, ביצועים גבוהים, קלה ללמידה, מהירה לתכנות, מוכנה לסביבת ייצור
-
-
+
+
-
-
+
+
@@ -23,7 +29,7 @@
**תיעוד**: https://fastapi.tiangolo.com
-**קוד**: https://github.com/tiangolo/fastapi
+**קוד**: https://github.com/fastapi/fastapi
---
@@ -31,7 +37,7 @@ FastAPI היא תשתית רשת מודרנית ומהירה (ביצועים ג
תכונות המפתח הן:
-- **מהירה**: ביצועים גבוהים מאוד, בקנה אחד עם NodeJS ו - Go (תודות ל - Starlette ו - Pydantic). [אחת מתשתיות הפייתון המהירות ביותר](#performance).
+- **מהירה**: ביצועים גבוהים מאוד, בקנה אחד עם NodeJS ו - Go (תודות ל - Starlette ו - Pydantic). [אחת מתשתיות הפייתון המהירות ביותר](#_14).
- **מהירה לתכנות**: הגבירו את מהירות פיתוח התכונות החדשות בכ - %200 עד %300. \*
- **פחות שגיאות**: מנעו כ - %40 משגיאות אנוש (מפתחים). \*
@@ -64,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._"
-
email_validator - לאימות כתובות אימייל.
+- email-validator - לאימות כתובות אימייל.
בשימוש Starlette:
@@ -449,12 +455,12 @@ item: Item
- python-multipart - דרוש אם ברצונכם לתמוך ב "פרסור" טפסים, באצמעות request.form().
- itsdangerous - דרוש אם ברצונכם להשתמש ב - `SessionMiddleware`.
- pyyaml - דרוש אם ברצונכם להשתמש ב - `SchemaGenerator` של Starlette (כנראה שאתם לא צריכים את זה עם FastAPI).
-- ujson - דרוש אם ברצונכם להשתמש ב - `UJSONResponse`.
בשימוש FastAPI / Starlette:
- uvicorn - לשרת שטוען ומגיש את האפליקציה שלכם.
- orjson - דרוש אם ברצונכם להשתמש ב - `ORJSONResponse`.
+- ujson - דרוש אם ברצונכם להשתמש ב - `UJSONResponse`.
תוכלו להתקין את כל אלו באמצעות pip install "fastapi[all]".
diff --git a/docs/hu/docs/index.md b/docs/hu/docs/index.md
index 75ea88c4d..8e326a78b 100644
--- a/docs/hu/docs/index.md
+++ b/docs/hu/docs/index.md
@@ -5,11 +5,11 @@
FastAPI keretrendszer, nagy teljesítmény, könnyen tanulható, gyorsan kódolható, productionre kész
-
-
+
+
-
-
+
+
@@ -23,10 +23,10 @@
**Dokumentáció**: https://fastapi.tiangolo.com
-**Forrás kód**: https://github.com/tiangolo/fastapi
+**Forrás kód**: https://github.com/fastapi/fastapi
---
-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:
@@ -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._"
-
email_validator - e-mail validációkra.
+* email-validator - e-mail validációkra.
* pydantic-settings - Beállítások követésére.
* pydantic-extra-types - Extra típusok Pydantic-hoz.
@@ -456,12 +454,12 @@ Starlette által használt:
* python-multipart - Követelmény ha "parsing"-ot akarsz támogatni, `request.form()`-al.
* itsdangerous - Követelmény `SessionMiddleware` támogatáshoz.
* pyyaml - 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).
-* ujson - Követelmény ha `UJSONResponse`-t akarsz használni.
FastAPI / Starlette által használt
* uvicorn - Szerverekhez amíg betöltik és szolgáltatják az applikációdat.
* orjson - Követelmény ha `ORJSONResponse`-t akarsz használni.
+* ujson - Követelmény ha `UJSONResponse`-t akarsz használni.
Ezeket mind telepítheted a `pip install "fastapi[all]"` paranccsal.
diff --git a/docs/id/docs/tutorial/index.md b/docs/id/docs/tutorial/index.md
index b8ed96ae1..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.
-!!! 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
+```
- ```
- pip install "uvicorn[standard]"
- ```
+Juga install `uvicorn` untuk menjalankan server"
- Dan demikian juga untuk pilihan dependensi yang hendak kamu gunakan.
+```
+pip install "uvicorn[standard]"
+```
+
+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 a69008d2b..57940f0ed 100644
--- a/docs/it/docs/index.md
+++ b/docs/it/docs/index.md
@@ -1,4 +1,3 @@
-
{!../../../docs/missing-translation.md!}
@@ -9,11 +8,11 @@
FastAPI framework, alte prestazioni, facile da imparare, rapido da implementare, pronto per il rilascio in produzione
-
-
+
+
-
-
+
+
@@ -24,7 +23,7 @@
**Documentazione**: https://fastapi.tiangolo.com
-**Codice Sorgente**: https://github.com/tiangolo/fastapi
+**Codice Sorgente**: https://github.com/fastapi/fastapi
---
@@ -64,7 +63,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._"
-
ujson - per un "parsing" di JSON più veloce.
-* email_validator - per la validazione di email.
+* email-validator - per la validazione di email.
Usate da Starlette:
@@ -450,12 +448,12 @@ Usate da Starlette:
* itsdangerous - Richiesto per usare `SessionMiddleware`.
* pyyaml - Richiesto per il supporto dello `SchemaGenerator` di Starlette (probabilmente non ti serve con FastAPI).
* graphene - Richiesto per il supporto di `GraphQLApp`.
-* ujson - Richiesto se vuoi usare `UJSONResponse`.
Usate da FastAPI / Starlette:
* uvicorn - per il server che carica e serve la tua applicazione.
* orjson - ichiesto se vuoi usare `ORJSONResponse`.
+* ujson - Richiesto se vuoi usare `UJSONResponse`.
Puoi installarle tutte con `pip install fastapi[all]`.
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 | "情報"
- この場合、HTTPヘッダー `Content-Type` には `application/json` がセットされます。
+パラメータ `response_class` は、レスポンスの「メディアタイプ」を定義するために利用することもできます。
- そして、OpenAPIにはそのようにドキュメントされます。
+この場合、HTTPヘッダー `Content-Type` には `application/json` がセットされます。
-!!! tip "豆知識"
- `ORJSONResponse` は、現在はFastAPIのみで利用可能で、Starletteでは利用できません。
+そして、OpenAPIにはそのようにドキュメントされます。
+
+///
+
+/// 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 | "注意"
-!!! info "情報"
- もちろん、実際の `Content-Type` ヘッダーやステータスコードなどは、返された `Response` オブジェクトに由来しています。
+*path operation関数* から直接返される `Response` は、OpenAPIにドキュメントされず (例えば、 `Content-Type` がドキュメントされない) 、自動的な対話的ドキュメントからも閲覧できません。
+
+///
+
+/// info | "情報"
+
+もちろん、実際の `Content-Type` ヘッダーやステータスコードなどは、返された `Response` オブジェクトに由来しています。
+
+///
### OpenAPIドキュメントと `Response` のオーバーライド
@@ -97,10 +115,13 @@
`Response` を使って他の何かを返せますし、カスタムのサブクラスも作れることを覚えておいてください。
-!!! note "技術詳細"
- `from starlette.responses import HTMLResponse` も利用できます。
+/// note | "技術詳細"
- **FastAPI** は開発者の利便性のために `fastapi.responses` として `starlette.responses` と同じものを提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。
+`from starlette.responses import HTMLResponse` も利用できます。
+
+**FastAPI** は開発者の利便性のために `fastapi.responses` として `starlette.responses` と同じものを提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。
+
+///
### `Response`
@@ -147,15 +168,21 @@ FastAPI (実際にはStarlette) は自動的にContent-Lengthヘッダーを含
`ujson`を使った、代替の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 0732fc405..da3c2a2bf 100644
--- a/docs/ja/docs/advanced/index.md
+++ b/docs/ja/docs/advanced/index.md
@@ -2,18 +2,21 @@
## さらなる機能
-[チュートリアル - ユーザーガイド](../tutorial/){.internal-link target=_blank}により、**FastAPI**の主要な機能は十分に理解できたことでしょう。
+[チュートリアル - ユーザーガイド](../tutorial/index.md){.internal-link target=_blank}により、**FastAPI**の主要な機能は十分に理解できたことでしょう。
以降のセクションでは、チュートリアルでは説明しきれなかったオプションや設定、および機能について説明します。
-!!! tip "豆知識"
- 以降のセクションは、 **必ずしも"応用編"ではありません**。
+/// tip | "豆知識"
- ユースケースによっては、その中から解決策を見つけられるかもしれません。
+以降のセクションは、 **必ずしも"応用編"ではありません**。
+
+ユースケースによっては、その中から解決策を見つけられるかもしれません。
+
+///
## 先にチュートリアルを読む
-[チュートリアル - ユーザーガイド](../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** はあらゆる NoSQLと統合することもできます。
-
-ここではドキュメントベースのNoSQLデータベースである**Couchbase**を使用した例を見てみましょう。
-
-他にもこれらのNoSQLデータベースを利用することが出来ます:
-
-* **MongoDB**
-* **Cassandra**
-* **CouchDB**
-* **ArangoDB**
-* **ElasticSearch** など。
-
-!!! tip "豆知識"
- **FastAPI**と**Couchbase**を使った公式プロジェクト・ジェネレータがあります。すべて**Docker**ベースで、フロントエンドやその他のツールも含まれています: https://github.com/tiangolo/full-stack-fastapi-couchbase
-
-## 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を取得することだけに特化した関数を作成することで、より簡単に複数の部分で再利用したりユニットテストを追加することができます。
-
-```Python hl_lines="36-42"
-{!../../../docs_src/nosql_databases/tutorial001.py!}
-```
-
-### f-strings
-
-`f"userprofile::{username}"` という記載に馴染みがありませんか?これは Python の"f-string"と呼ばれるものです。
-
-f-stringの`{}`の中に入れられた変数は、文字列の中に展開/注入されます。
-
-### `dict` アンパック
-
-`UserInDB(**result.value)`という記載に馴染みがありませんか?これは`dict`の"アンパック"と呼ばれるものです。
-
-これは`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を呼び出しており、実験的なPython awaitを使用していないので、私たちは`async def`ではなく通常の`def`で関数を宣言する必要があります。
-
-また、Couchbaseは単一の`Bucket`オブジェクトを複数のスレッドで使用しないことを推奨していますので、単に直接Bucketを取得して関数に渡すことが出来ます。
-
-```Python hl_lines="49-53"
-{!../../../docs_src/nosql_databases/tutorial001.py!}
-```
-
-## まとめ
-
-他のサードパーティ製のNoSQLデータベースを利用する場合でも、そのデータベースの標準ライブラリを利用するだけで利用できます。
-
-他の外部ツール、システム、APIについても同じことが言えます。
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 | "豆知識"
-!!! warning "注意"
- この方法をとる場合、各 *path operation関数* が一意な名前である必要があります。
+`app.openapi()` を手動でコールする場合、その前に`operationId`を更新する必要があります。
- それらが異なるモジュール (Pythonファイル) にあるとしてもです。
+///
+
+/// warning | "注意"
+
+この方法をとる場合、各 *path operation関数* が一意な名前である必要があります。
+
+それらが異なるモジュール (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 | "技術詳細"
- **FastAPI** は開発者の利便性のために `fastapi.responses` という `starlette.responses` と同じものを提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。
+また、`from starlette.responses import JSONResponse` も利用できます。
+
+**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の接続を直接閉じる方がよいでしょう。
- 将来的には、どこからでも `raise` できる `WebSocketException` が用意され、専用の例外ハンドラを追加できるようになる予定です。これは、Starlette の PR #527 に依存するものです。
+クロージングコードは、仕様で定義された有効なコードの中から使用することができます。
+
+将来的には、どこからでも `raise` できる `WebSocketException` が用意され、専用の例外ハンドラを追加できるようになる予定です。これは、Starlette の PR #527 に依存するものです。
+
+///
### 依存関係を用いて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などでサポートされている、より堅牢なものが必要なら、encode/broadcaster を確認してください。
+しかし、すべての接続がメモリ内の単一のリストで処理されるため、プロセスの実行中にのみ機能し、単一のプロセスでのみ機能することに注意してください。
+
+もしFastAPIと簡単に統合できて、RedisやPostgreSQLなどでサポートされている、より堅牢なものが必要なら、encode/broadcaster を確認してください。
+
+///
## その他のドキュメント
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ユーザーインターフェースを持っている点。
+
+///
### Flask
@@ -50,11 +56,13 @@ Flask は「マイクロフレームワーク」であり、データベース
Flaskのシンプルさを考えると、APIを構築するのに適しているように思えました。次に見つけるべきは、Flask 用の「Django REST Framework」でした。
-!!! check "**FastAPI**へ与えたインスピレーション"
- マイクロフレームワークであること。ツールやパーツを目的に合うように簡単に組み合わせられる点。
+/// check | "**FastAPI**へ与えたインスピレーション"
- シンプルで簡単なルーティングの仕組みを持っている点。
+マイクロフレームワークであること。ツールやパーツを目的に合うように簡単に組み合わせられる点。
+シンプルで簡単なルーティングの仕組みを持っている点。
+
+///
### Requests
@@ -90,11 +98,13 @@ def read_url():
`requests.get(...)` と`@app.get(...)` には類似点が見受けられます。
-!!! check "**FastAPI**へ与えたインスピレーション"
- * シンプルで直感的なAPIを持っている点。
- * HTTPメソッド名を直接利用し、単純で直感的である。
- * 適切なデフォルト値を持ちつつ、強力なカスタマイズ性を持っている。
+/// check | "**FastAPI**へ与えたインスピレーション"
+* シンプルで直感的なAPIを持っている点。
+* HTTPメソッド名を直接利用し、単純で直感的である。
+* 適切なデフォルト値を持ちつつ、強力なカスタマイズ性を持っている。
+
+///
### Swagger / OpenAPI
@@ -108,15 +118,18 @@ def read_url():
そのため、バージョン2.0では「Swagger」、バージョン3以上では「OpenAPI」と表記するのが一般的です。
-!!! check "**FastAPI**へ与えたインスピレーション"
- 独自のスキーマの代わりに、API仕様のオープンな標準を採用しました。
+/// check | "**FastAPI**へ与えたインスピレーション"
- そして、標準に基づくユーザーインターフェースツールを統合しています。
+独自のスキーマの代わりに、API仕様のオープンな標準を採用しました。
- * Swagger UI
- * ReDoc
+そして、標準に基づくユーザーインターフェースツールを統合しています。
- この二つは人気で安定したものとして選択されましたが、少し検索してみると、 (**FastAPI**と同時に使用できる) OpenAPIのための多くの代替となるツールを見つけることができます。
+* Swagger UI
+* ReDoc
+
+この二つは人気で安定したものとして選択されましたが、少し検索してみると、 (**FastAPI**と同時に使用できる) OpenAPIのための多くの代替となるツールを見つけることができます。
+
+///
### Flask REST フレームワーク
@@ -134,8 +147,11 @@ APIが必要とするもう一つの大きな機能はデータのバリデー
しかし、それはPythonの型ヒントが存在する前に作られたものです。そのため、すべてのスキーマを定義するためには、Marshmallowが提供する特定のユーティリティやクラスを使用する必要があります。
-!!! check "**FastAPI**へ与えたインスピレーション"
- コードで「スキーマ」を定義し、データの型やバリデーションを自動で提供する点。
+/// check | "**FastAPI**へ与えたインスピレーション"
+
+コードで「スキーマ」を定義し、データの型やバリデーションを自動で提供する点。
+
+///
### Webargs
@@ -147,11 +163,17 @@ WebargsはFlaskをはじめとするいくつかのフレームワークの上
素晴らしいツールで、私も**FastAPI**を持つ前はよく使っていました。
-!!! info "情報"
- Webargsは、Marshmallowと同じ開発者により作られました。
+/// info | "情報"
-!!! check "**FastAPI**へ与えたインスピレーション"
- 受信したデータに対する自動的なバリデーションを持っている点。
+Webargsは、Marshmallowと同じ開発者により作られました。
+
+///
+
+/// check | "**FastAPI**へ与えたインスピレーション"
+
+受信したデータに対する自動的なバリデーションを持っている点。
+
+///
### APISpec
@@ -171,11 +193,17 @@ Flask, Starlette, Responderなどにおいてはそのように動作します
エディタでは、この問題を解決することはできません。また、パラメータやMarshmallowスキーマを変更したときに、YAMLのdocstringを変更するのを忘れてしまうと、生成されたスキーマが古くなってしまいます。
-!!! info "情報"
- APISpecは、Marshmallowと同じ開発者により作成されました。
+/// info | "情報"
-!!! check "**FastAPI**へ与えたインスピレーション"
- OpenAPIという、APIについてのオープンな標準をサポートしている点。
+APISpecは、Marshmallowと同じ開発者により作成されました。
+
+///
+
+/// check | "**FastAPI**へ与えたインスピレーション"
+
+OpenAPIという、APIについてのオープンな標準をサポートしている点。
+
+///
### Flask-apispec
@@ -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スキーマを自動的に生成する点。
+
+///
### NestJS (とAngular)
@@ -217,24 +251,33 @@ Angular 2にインスピレーションを受けた、統合された依存性
入れ子になったモデルをうまく扱えません。そのため、リクエストのJSONボディが内部フィールドを持つJSONオブジェクトで、それが順番にネストされたJSONオブジェクトになっている場合、適切にドキュメント化やバリデーションをすることができません。
-!!! check "**FastAPI**へ与えたインスピレーション"
- 素晴らしいエディターの補助を得るために、Pythonの型ヒントを利用している点。
+/// check | "**FastAPI**へ与えたインスピレーション"
- 強力な依存性注入の仕組みを持ち、コードの繰り返しを最小化する方法を見つけた点。
+素晴らしいエディターの補助を得るために、Pythonの型ヒントを利用している点。
+
+強力な依存性注入の仕組みを持ち、コードの繰り返しを最小化する方法を見つけた点。
+
+///
### Sanic
`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に基づいている理由です。
+
+///
### Falcon
@@ -246,12 +289,15 @@ Pythonのウェブフレームワーク標準規格 (WSGI) を使用していま
そのため、データのバリデーション、シリアライゼーション、ドキュメント化は、自動的にできずコードの中で行わなければなりません。あるいは、HugのようにFalconの上にフレームワークとして実装されなければなりません。このような分断は、パラメータとして1つのリクエストオブジェクトと1つのレスポンスオブジェクトを持つというFalconのデザインにインスピレーションを受けた他のフレームワークでも起こります。
-!!! check "**FastAPI**へ与えたインスピレーション"
- 素晴らしい性能を得るための方法を見つけた点。
+/// check | "**FastAPI**へ与えたインスピレーション"
- Hug (HugはFalconをベースにしています) と一緒に、**FastAPI**が`response`引数を関数に持つことにインスピレーションを与えました。
+素晴らしい性能を得るための方法を見つけた点。
- **FastAPI**では任意ですが、ヘッダーやCookieやステータスコードを設定するために利用されています。
+Hug (HugはFalconをベースにしています) と一緒に、**FastAPI**が`response`引数を関数に持つことにインスピレーションを与えました。
+
+**FastAPI**では任意ですが、ヘッダーやCookieやステータスコードを設定するために利用されています。
+
+///
### Molten
@@ -269,10 +315,13 @@ Pydanticのようなデータのバリデーション、シリアライゼーシ
ルーティングは一つの場所で宣言され、他の場所で宣言された関数を使用します (エンドポイントを扱う関数のすぐ上に配置できるデコレータを使用するのではなく) 。これはFlask (やStarlette) よりも、Djangoに近いです。これは、比較的緊密に結合されているものをコードの中で分離しています。
-!!! check "**FastAPI**へ与えたインスピレーション"
- モデルの属性の「デフォルト」値を使用したデータ型の追加バリデーションを定義します。これはエディタの補助を改善するもので、以前はPydanticでは利用できませんでした。
+/// check | "**FastAPI**へ与えたインスピレーション"
- 同様の方法でのバリデーションの宣言をサポートするよう、Pydanticを部分的にアップデートするインスピーレションを与えました。(現在はこれらの機能は全てPydanticで可能となっています。)
+モデルの属性の「デフォルト」値を使用したデータ型の追加バリデーションを定義します。これはエディタの補助を改善するもので、以前はPydanticでは利用できませんでした。
+
+同様の方法でのバリデーションの宣言をサポートするよう、Pydanticを部分的にアップデートするインスピーレションを与えました。(現在はこれらの機能は全てPydanticで可能となっています。)
+
+///
### Hug
@@ -288,15 +337,21 @@ OpenAPIやJSON Schemaのような標準に基づいたものではありませ
以前のPythonの同期型Webフレームワーク標準 (WSGI) をベースにしているため、Websocketなどは扱えませんが、それでも高性能です。
-!!! info "情報"
- HugはTimothy Crosleyにより作成されました。彼は`isort`など、Pythonのファイル内のインポートの並び替えを自動的におこうなう素晴らしいツールの開発者です。
+/// info | "情報"
-!!! check "**FastAPI**へ与えたインスピレーション"
- HugはAPIStarに部分的なインスピレーションを与えており、私が発見した中ではAPIStarと同様に最も期待の持てるツールの一つでした。
+HugはTimothy Crosleyにより作成されました。彼は`isort`など、Pythonのファイル内のインポートの並び替えを自動的におこうなう素晴らしいツールの開発者です。
- Hugは、**FastAPI**がPythonの型ヒントを用いてパラメータを宣言し自動的にAPIを定義するスキーマを生成することを触発しました。
+///
- Hugは、**FastAPI**がヘッダーやクッキーを設定するために関数に `response`引数を宣言することにインスピレーションを与えました。
+/// check | "**FastAPI**へ与えたインスピレーション"
+
+HugはAPIStarに部分的なインスピレーションを与えており、私が発見した中ではAPIStarと同様に最も期待の持てるツールの一つでした。
+
+Hugは、**FastAPI**がPythonの型ヒントを用いてパラメータを宣言し自動的にAPIを定義するスキーマを生成することを触発しました。
+
+Hugは、**FastAPI**がヘッダーやクッキーを設定するために関数に `response`引数を宣言することにインスピレーションを与えました。
+
+///
### APIStar (<= 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**での使用用途"
- **FastAPI**はJSON SchemaのデータをOpenAPIに利用します。
+データのバリデーション、データのシリアライゼーション、自動的なモデルの (JSON Schemaに基づいた) ドキュメント化の全てを扱えます。
+
+**FastAPI**はJSON SchemaのデータをOpenAPIに利用します。
+
+///
### Starlette
@@ -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**で直接可能です。
+
+///
### Uvicorn
@@ -403,12 +473,15 @@ Uvicornは非常に高速なASGIサーバーで、uvloopとhttptoolsにより構
Starletteや**FastAPI**のサーバーとして推奨されています。
-!!! check "**FastAPI**が推奨する理由"
- **FastAPI**アプリケーションを実行するメインのウェブサーバーである点。
+/// check | "**FastAPI**が推奨する理由"
- Gunicornと組み合わせることで、非同期でマルチプロセスなサーバーを持つことがきます。
+**FastAPI**アプリケーションを実行するメインのウェブサーバーである点。
- 詳細は[デプロイ](deployment/index.md){.internal-link target=_blank}の項目で確認してください。
+Gunicornと組み合わせることで、非同期でマルチプロセスなサーバーを持つことがきます。
+
+詳細は[デプロイ](deployment/index.md){.internal-link target=_blank}の項目で確認してください。
+
+///
## ベンチマーク と スピード
diff --git a/docs/ja/docs/async.md b/docs/ja/docs/async.md
index 8fac2cb38..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が `async def` と通常の `def` をどのように処理するか知りたい場合は、先に進んでください。
+この部分は**FastAPI**の仕組みに関する非常に技術的な詳細です。
+
+かなりの技術知識 (コルーチン、スレッド、ブロッキングなど) があり、FastAPIが `async def` と通常の `def` をどのように処理するか知りたい場合は、先に進んでください。
+
+///
### Path operation 関数
@@ -368,7 +374,7 @@ async def read_burgers():
上記の方法と違った方法の別の非同期フレームワークから来ており、小さなパフォーマンス向上 (約100ナノ秒) のために通常の `def` を使用して些細な演算のみ行う *path operation 関数* を定義するのに慣れている場合は、**FastAPI**ではまったく逆の効果になることに注意してください。このような場合、*path operation 関数* がブロッキングI/Oを実行しないのであれば、`async def` の使用をお勧めします。
-それでも、どちらの状況でも、**FastAPI**が過去のフレームワークよりも (またはそれに匹敵するほど) [高速になる](/#performance){.internal-link target=_blank}可能性があります。
+それでも、どちらの状況でも、**FastAPI**が過去のフレームワークよりも (またはそれに匹敵するほど) [高速になる](index.md#_10){.internal-link target=_blank}可能性があります。
### 依存関係
@@ -390,4 +396,4 @@ async def read_burgers():
繰り返しになりますが、これらは非常に技術的な詳細であり、検索して辿り着いた場合は役立つでしょう。
-それ以外の場合は、上記のセクションのガイドラインで問題ないはずです: 急いでいますか?。
+それ以外の場合は、上記のセクションのガイドラインで問題ないはずです: 急いでいますか?。
diff --git a/docs/ja/docs/contributing.md b/docs/ja/docs/contributing.md
index 31db51c52..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
-
-
-
+
+
-
-
+
+
@@ -20,15 +26,15 @@
**ドキュメント**: https://fastapi.tiangolo.com
-**ソースコード**: https://github.com/tiangolo/fastapi
+**ソースコード**: https://github.com/fastapi/fastapi
---
-FastAPI は、Pythonの標準である型ヒントに基づいてPython 3.8 以降でAPI を構築するための、モダンで、高速(高パフォーマンス)な、Web フレームワークです。
+FastAPI は、Pythonの標準である型ヒントに基づいてPython 以降でAPI を構築するための、モダンで、高速(高パフォーマンス)な、Web フレームワークです。
主な特徴:
-- **高速**: **NodeJS** や **Go** 並みのとても高いパフォーマンス (Starlette と Pydantic のおかげです)。 [最も高速な Python フレームワークの一つです](#performance).
+- **高速**: **NodeJS** や **Go** 並みのとても高いパフォーマンス (Starlette と Pydantic のおかげです)。 [最も高速な Python フレームワークの一つです](#_10).
- **高速なコーディング**: 開発速度を約 200%~300%向上させます。 \*
- **少ないバグ**: 開発者起因のヒューマンエラーを約 40%削減します。 \*
@@ -61,7 +67,7 @@ FastAPI は、Pythonの標準である型ヒントに基づいてPython 3.8 以
"_[...] 最近 **FastAPI** を使っています。 [...] 実際に私のチームの全ての **Microsoft の機械学習サービス** で使用する予定です。 そのうちのいくつかのコアな**Windows**製品と**Office**製品に統合されつつあります。_"
-
email_validator - E メールの検証
+- email-validator - E メールの検証
Starlette によって使用されるもの:
@@ -441,12 +445,12 @@ Starlette によって使用されるもの:
- itsdangerous - `SessionMiddleware` サポートのためには必要です。
- pyyaml - Starlette の `SchemaGenerator` サポートのために必要です。 (FastAPI では必要ないでしょう。)
- graphene - `GraphQLApp` サポートのためには必要です。
-- ujson - `UJSONResponse`を使用する場合は必須です。
FastAPI / Starlette に使用されるもの:
- uvicorn - アプリケーションをロードしてサーブするサーバーのため。
- orjson - `ORJSONResponse`を使用したい場合は必要です。
+- ujson - `UJSONResponse`を使用する場合は必須です。
これらは全て `pip install fastapi[all]`でインストールできます。
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を学習するにあたっての**書籍**や**コース**であり、**公式**かつ推奨される方法とみなすことができます 😎
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: **FastAPI** バックエンド:
+* Python **FastAPI** バックエンド:
* **高速**: **NodeJS** や **Go** 並みのとても高いパフォーマンス (Starlette と Pydantic のおかげ)。
* **直感的**: 素晴らしいエディタのサポートや 補完。 デバッグ時間の短縮。
* **簡単**: 簡単に利用、習得できるようなデザイン。ドキュメントを読む時間を削減。
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についてより学びたい方はドキュメントを参照してください.
+/// info | "情報"
+
+Pydanticについてより学びたい方はドキュメントを参照してください.
+
+///
**FastAPI** はすべてPydanticをベースにしています。
@@ -311,5 +320,8 @@ Pydanticの公式ドキュメントから引用:
重要なのは、Pythonの標準的な型を使うことで、(クラスやデコレータなどを追加するのではなく)1つの場所で **FastAPI** が多くの作業を代わりにやってくれているということです。
-!!! info "情報"
- すでにすべてのチュートリアルを終えて、型についての詳細を見るためにこのページに戻ってきた場合は、`mypy`のチートシートを参照してください
+/// info | "情報"
+
+すでにすべてのチュートリアルを終えて、型についての詳細を見るためにこのページに戻ってきた場合は、`mypy`のチートシートを参照してください
+
+///
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 | "技術詳細"
- また、Pydanticの`Field`は`FieldInfo`のインスタンスも返します。
+実際には次に見る`Query`や`Path`などは、共通の`Param`クラスのサブクラスのオブジェクトを作成しますが、それ自体はPydanticの`FieldInfo`クラスのサブクラスです。
- `Body`は`FieldInfo`のサブクラスのオブジェクトを直接返すこともできます。そして、他にも`Body`クラスのサブクラスであるものがあります。
+また、Pydanticの`Field`は`FieldInfo`のインスタンスも返します。
- `fastapi`から`Query`や`Path`などをインポートする場合、これらは実際には特殊なクラスを返す関数であることに注意してください。
+`Body`は`FieldInfo`のサブクラスのオブジェクトを直接返すこともできます。そして、他にも`Body`クラスのサブクラスであるものがあります。
-!!! tip "豆知識"
- 型、デフォルト値、`Field`を持つ各モデルの属性が、`Path`や`Query`、`Body`の代わりに`Field`を持つ、*path operation 関数の*パラメータと同じ構造になっていることに注目してください。
+`fastapi`から`Query`や`Path`などをインポートする場合、これらは実際には特殊なクラスを返す関数であることに注意してください。
+
+///
+
+/// 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 | "豆知識"
- しかしPydanticには自動データ変換機能があります。
+JSONはキーとして`str`しかサポートしていないことに注意してください。
- これは、APIクライアントがキーとして文字列しか送信できなくても、それらの文字列に純粋な整数が含まれている限り、Pydanticが変換して検証することを意味します。
+しかしPydanticには自動データ変換機能があります。
- そして、`weights`として受け取る`dict`は、実際には`int`のキーと`float`の値を持つことになります。
+これは、APIクライアントがキーとして文字列しか送信できなくても、それらの文字列に純粋な整数が含まれている限り、Pydanticが変換して検証することを意味します。
+
+そして、`weights`として受け取る`dict`は、実際には`int`のキーと`float`の値を持つことになります。
+
+///
## まとめ
diff --git a/docs/ja/docs/tutorial/body-updates.md b/docs/ja/docs/tutorial/body-updates.md
index 7a56ef2b9..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 | "豆知識"
- しかし、これらのユースケースのために作成されたので、ここでの例では`PATCH`を使用しています。
+実際には、HTTPの`PUT`操作でも同じテクニックを使用することができます。
-!!! note "備考"
- 入力モデルがまだ検証されていることに注目してください。
+しかし、これらのユースケースのために作成されたので、ここでの例では`PATCH`を使用しています。
- そのため、すべての属性を省略できる部分的な変更を受け取りたい場合は、すべての属性をオプションとしてマークしたモデルを用意する必要があります(デフォルト値または`None`を使用して)。
+///
- **更新** のためのオプション値がすべて設定されているモデルと、**作成** のための必須値が設定されているモデルを区別するには、[追加モデル](extra-models.md){.internal-link target=_blank}で説明されている考え方を利用することができます。
+/// note | "備考"
+
+入力モデルがまだ検証されていることに注目してください。
+
+そのため、すべての属性を省略できる部分的な変更を受け取りたい場合は、すべての属性をオプションとしてマークしたモデルを用意する必要があります(デフォルト値または`None`を使用して)。
+
+**更新** のためのオプション値がすべて設定されているモデルと、**作成** のための必須値が設定されているモデルを区別するには、[追加モデル](extra-models.md){.internal-link target=_blank}で説明されている考え方を利用することができます。
+
+///
diff --git a/docs/ja/docs/tutorial/body.md b/docs/ja/docs/tutorial/body.md
index 12332991d..017ff8986 100644
--- a/docs/ja/docs/tutorial/body.md
+++ b/docs/ja/docs/tutorial/body.md
@@ -8,12 +8,15 @@ APIはほとんどの場合 **レスポンス** ボディを送らなければ
**リクエスト** ボディを宣言するために Pydantic モデルを使用します。そして、その全てのパワーとメリットを利用します。
-!!! 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はほとんどの場合 **レスポンス** ボディを送らなければ
-!!! tip "豆知識"
- PyCharmエディタを使用している場合は、Pydantic PyCharm Pluginが使用可能です。
+/// tip | "豆知識"
- 以下のエディターサポートが強化されます:
+PyCharmエディタを使用している場合は、Pydantic PyCharm Pluginが使用可能です。
- * 自動補完
- * 型チェック
- * リファクタリング
- * 検索
- * インスペクション
+以下のエディターサポートが強化されます:
+
+* 自動補完
+* 型チェック
+* リファクタリング
+* 検索
+* インスペクション
+
+///
## モデルの使用
@@ -155,11 +161,14 @@ APIはほとんどの場合 **レスポンス** ボディを送らなければ
* パラメータが**単数型** (`int`、`float`、`str`、`bool` など)の場合は**クエリ**パラメータとして解釈されます。
* パラメータが **Pydantic モデル**型で宣言された場合、リクエスト**ボディ**として解釈されます。
-!!! note "備考"
- FastAPIは、`= None`があるおかげで、`q`がオプショナルだとわかります。
+/// note | "備考"
- `Optional[str]` の`Optional` はFastAPIでは使用されていません(FastAPIは`str`の部分のみ使用します)。しかし、`Optional[str]` はエディタがコードのエラーを見つけるのを助けてくれます。
+FastAPIは、`= None`があるおかげで、`q`がオプショナルだとわかります。
+
+`Optional[str]` の`Optional` はFastAPIでは使用されていません(FastAPIは`str`の部分のみ使用します)。しかし、`Optional[str]` はエディタがコードのエラーを見つけるのを助けてくれます。
+
+///
## 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/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 @@
CORSについてより詳しい情報は、Mozilla CORS documentation を参照して下さい。
-!!! 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 "情報"
- より詳しい情報は、公式Pythonドキュメントを参照してください。
+/// info | "情報"
+
+より詳しい情報は、公式Pythonドキュメントを参照してください。
+
+///
## デバッガーでコードを実行
diff --git a/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md
index 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 2a89e51d2..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は、いくつかのしてカスタムの独自ヘッダーを追加できます。
+/// tip | "豆知識"
- ただし、ブラウザのクライアントに表示させたいカスタムヘッダーがある場合は、StarletteのCORSドキュメントに記載されているパラメータ `expose_headers` を使用して、それらをCORS設定に追加する必要があります ([CORS (オリジン間リソース共有)](cors.md){.internal-link target=_blank})
+'X-'プレフィックスを使用してカスタムの独自ヘッダーを追加できます。
-!!! note "技術詳細"
- `from starlette.requests import Request` を使用することもできます。
+ただし、ブラウザのクライアントに表示させたいカスタムヘッダーがある場合は、StarletteのCORSドキュメントに記載されているパラメータ `expose_headers` を使用して、それらをCORS設定に追加する必要があります ([CORS (オリジン間リソース共有)](cors.md){.internal-link target=_blank})
- **FastAPI**は、開発者の便利のためにこれを提供していますが、Starletteから直接きています。
+///
+
+/// note | "技術詳細"
+
+`from starlette.requests import Request` を使用することもできます。
+
+**FastAPI**は、開発者の便利のためにこれを提供していますが、Starletteから直接きています。
+
+///
### `response` の前後
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..def12bd08
--- /dev/null
+++ b/docs/ja/docs/tutorial/path-operation-configuration.md
@@ -0,0 +1,109 @@
+# 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スキーマに追加され、自動ドキュメントのインターフェースで使用されます:
+
+
+
+## 概要と説明
+
+`summary`と`description`を追加できます:
+
+```Python hl_lines="20-21"
+{!../../../docs_src/path_operation_configuration/tutorial003.py!}
+```
+
+## docstringを用いた説明
+
+説明文は長くて複数行におよぶ傾向があるので、関数docstring内に*path operation*の説明文を宣言できます。すると、**FastAPI** は説明文を読み込んでくれます。
+
+docstringにMarkdownを記述すれば、正しく解釈されて表示されます。(docstringのインデントを考慮して)
+
+```Python hl_lines="19-27"
+{!../../../docs_src/path_operation_configuration/tutorial004.py!}
+```
+
+これは対話的ドキュメントで使用されます:
+
+
+
+## レスポンスの説明
+
+`response_description`パラメータでレスポンスの説明をすることができます。
+
+```Python hl_lines="21"
+{!../../../docs_src/path_operation_configuration/tutorial005.py!}
+```
+
+/// info | "情報"
+
+`respnse_description`は具体的にレスポンスを参照し、`description`は*path operation*全般を参照していることに注意してください。
+
+///
+
+/// check | "確認"
+
+OpenAPIは*path operation*ごとにレスポンスの説明を必要としています。
+
+そのため、それを提供しない場合は、**FastAPI** が自動的に「成功のレスポンス」を生成します。
+
+///
+
+
+
+## 非推奨の*path operation*
+
+*path operation*をdeprecatedとしてマークする必要があるが、それを削除しない場合は、`deprecated`パラメータを渡します:
+
+```Python hl_lines="16"
+{!../../../docs_src/path_operation_configuration/tutorial006.py!}
+```
+
+対話的ドキュメントでは非推奨と明記されます:
+
+
+
+*path operations*が非推奨である場合とそうでない場合でどのように見えるかを確認してください:
+
+
+
+## まとめ
+
+*path operationデコレータ*にパラメータを渡すことで、*path operations*のメタデータを簡単に設定・追加することができます。
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`などをインポートすると、これらは実際には関数です。
+そして、それらすべては、これまで見てきた追加のバリデーションとメタデータと同じパラメータを共有しています。
- 呼び出されると、同じ名前のクラスのインスタンスを返します。
+///
- そのため、関数である`Query`をインポートし、それを呼び出すと、`Query`という名前のクラスのインスタンスが返されます。
+/// note | "技術詳細"
- これらの関数は(クラスを直接使うのではなく)エディタが型についてエラーとしないようにするために存在します。
+`fastapi`から`Query`、`Path`などをインポートすると、これらは実際には関数です。
- この方法によって、これらのエラーを無視するための設定を追加することなく、通常のエディタやコーディングツールを使用することができます。
+呼び出されると、同じ名前のクラスのインスタンスを返します。
+
+そのため、関数である`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 | "確認"
+
+これにより、関数内でのエディターサポート (エラーチェックや補完など) が提供されます。
+
+///
## データ変換
@@ -35,10 +38,13 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー
{"item_id":3}
```
-!!! check "確認"
- 関数が受け取った(および返した)値は、文字列の `"3"` ではなく、Pythonの `int` としての `3` であることに注意してください。
+/// check | "確認"
- したがって、型宣言を使用すると、**FastAPI**は自動リクエスト "解析" を行います。
+関数が受け取った(および返した)値は、文字列の `"3"` ではなく、Pythonの `int` としての `3` であることに注意してください。
+
+したがって、型宣言を使用すると、**FastAPI**は自動リクエスト "解析" を行います。
+
+///
## データバリデーション
@@ -63,12 +69,15 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー
http://127.0.0.1:8000/items/4.2 で見られるように、intのかわりに `float` が与えられた場合にも同様なエラーが表示されます。
-!!! check "確認"
- したがって、Pythonの型宣言を使用することで、**FastAPI**はデータのバリデーションを行います。
+/// check | "確認"
- 表示されたエラーには問題のある箇所が明確に指摘されていることに注意してください。
+したがって、Pythonの型宣言を使用することで、**FastAPI**はデータのバリデーションを行います。
- これは、APIに関連するコードの開発およびデバッグに非常に役立ちます。
+表示されたエラーには問題のある箇所が明確に指摘されていることに注意してください。
+
+これは、APIに関連するコードの開発およびデバッグに非常に役立ちます。
+
+///
## ドキュメント
@@ -76,10 +85,13 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー
-!!! 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 "情報"
- Enumerations (もしくは、enums)はPython 3.4以降で利用できます。
+/// info | "情報"
-!!! tip "豆知識"
- "AlexNet"、"ResNet"そして"LeNet"は機械学習モデルの名前です。
+Enumerations (もしくは、enums)はPython 3.4以降で利用できます。
+
+///
+
+/// tip | "豆知識"
+
+"AlexNet"、"ResNet"そして"LeNet"は機械学習モデルの名前です。
+
+///
### *パスパラメータ*の宣言
@@ -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 | "豆知識"
- この場合、URLは `files` と `home` の間にダブルスラッシュ (`//`) のある、 `/files//home/johndoe/myfile.txt` になります。
+最初のスラッシュ (`/`)が付いている `/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 | "情報"
- ```Python
- = None
- ```
+FastAPIは以下の部分を気にすることを覚えておいてください:
- もしくは:
+```Python
+= None
+```
- ```Python
- = Query(default=None)
- ```
+もしくは:
- そして、 `None` を利用することでクエリパラメータが必須ではないと検知します。
+```Python
+= Query(default=None)
+```
- `Optional` の部分は、エディターによるより良いサポートを可能にします。
+そして、 `None` を利用することでクエリパラメータが必須ではないと検知します。
+
+`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 "情報"
- これまで`...`を見たことがない方へ: これは特殊な単一値です。Pythonの一部であり、"Ellipsis"と呼ばれています。
+/// info | "情報"
+
+これまで`...`を見たことがない方へ: これは特殊な単一値です。Pythonの一部であり、"Ellipsis"と呼ばれています。
+
+///
これは **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 5202009ef..c0eb2d096 100644
--- a/docs/ja/docs/tutorial/query-params.md
+++ b/docs/ja/docs/tutorial/query-params.md
@@ -1,4 +1,3 @@
-
# クエリパラメータ
パスパラメータではない関数パラメータを宣言すると、それらは自動的に "クエリ" パラメータとして解釈されます。
@@ -70,13 +69,11 @@ http://127.0.0.1:8000/items/?skip=20
この場合、関数パラメータ `q` はオプショナルとなり、デフォルトでは `None` になります。
-!!! check "確認"
- パスパラメータ `item_id` はパスパラメータであり、`q` はそれとは違ってクエリパラメータであると判別できるほど**FastAPI** が賢いということにも注意してください。
+/// check | "確認"
-!!! note "備考"
- FastAPIは、`= None`があるおかげで、`q`がオプショナルだとわかります。
+パスパラメータ `item_id` はパスパラメータであり、`q` はそれとは違ってクエリパラメータであると判別できるほど**FastAPI** が賢いということにも注意してください。
- `Optional[str]` の`Optional` はFastAPIでは使用されていません(FastAPIは`str`の部分のみ使用します)。しかし、`Optional[str]` はエディタがコードのエラーを見つけるのを助けてくれます。
+///
## クエリパラメータの型変換
@@ -194,6 +191,8 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
* `skip`、デフォルト値を `0` とする `int` 。
* `limit`、オプショナルな `int` 。
-!!! tip "豆知識"
+/// 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/request-forms-and-files.md b/docs/ja/docs/tutorial/request-forms-and-files.md
new file mode 100644
index 000000000..d8effc219
--- /dev/null
+++ b/docs/ja/docs/tutorial/request-forms-and-files.md
@@ -0,0 +1,41 @@
+# リクエストフォームとファイル
+
+`File`と`Form`を同時に使うことでファイルとフォームフィールドを定義することができます。
+
+/// info | "情報"
+
+アップロードされたファイルやフォームデータを受信するには、まず`python-multipart`をインストールします。
+
+例えば、`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`を一緒に使用します。
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 "情報"
- フォームを使うためには、まず`python-multipart`をインストールします。
+/// info | "情報"
- たとえば、`pip install python-multipart`のように。
+フォームを使うためには、まず`python-multipart`をインストールします。
+
+たとえば、`pip install python-multipart`のように。
+
+///
## `Form`のインポート
@@ -29,11 +32,17 @@ JSONの代わりにフィールドを受け取る場合は、`Form`を使用し
`Form`では`Body`(および`Query`や`Path`、`Cookie`)と同じメタデータとバリデーションを宣言することができます。
-!!! info "情報"
- `Form`は`Body`を直接継承するクラスです。
+/// info | "情報"
-!!! tip "豆知識"
- フォームのボディを宣言するには、明示的に`Form`を使用する必要があります。なぜなら、これを使わないと、パラメータはクエリパラメータやボディ(JSON)パラメータとして解釈されるからです。
+`Form`は`Body`を直接継承するクラスです。
+
+///
+
+/// tip | "豆知識"
+
+フォームのボディを宣言するには、明示的に`Form`を使用する必要があります。なぜなら、これを使わないと、パラメータはクエリパラメータやボディ(JSON)パラメータとして解釈されるからです。
+
+///
## 「フォームフィールド」について
@@ -41,17 +50,23 @@ HTMLフォーム(``)がサーバにデータを送信する方
**FastAPI** は、JSONの代わりにそのデータを適切な場所から読み込むようにします。
-!!! note "技術詳細"
- フォームからのデータは通常、`application/x-www-form-urlencoded`の「media type」を使用してエンコードされます。
+/// note | "技術詳細"
- しかし、フォームがファイルを含む場合は、`multipart/form-data`としてエンコードされます。ファイルの扱いについては次の章で説明します。
+フォームからのデータは通常、`application/x-www-form-urlencoded`の「media type」を使用してエンコードされます。
- これらのエンコーディングやフォームフィールドの詳細については、MDNのPOSTのウェブドキュメントを参照してください。
+しかし、フォームがファイルを含む場合は、`multipart/form-data`としてエンコードされます。ファイルの扱いについては次の章で説明します。
-!!! warning "注意"
- *path operation*で複数の`Form`パラメータを宣言することができますが、JSONとして受け取ることを期待している`Body`フィールドを宣言することはできません。なぜなら、リクエストは`application/json`の代わりに`application/x-www-form-urlencoded`を使ってボディをエンコードするからです。
+これらのエンコーディングやフォームフィールドの詳細については、MDNのPOSTのウェブドキュメントを参照してください。
- これは **FastAPI**の制限ではなく、HTTPプロトコルの一部です。
+///
+
+/// warning | "注意"
+
+*path operation*で複数の`Form`パラメータを宣言することができますが、JSONとして受け取ることを期待している`Body`フィールドを宣言することはできません。なぜなら、リクエストは`application/json`の代わりに`application/x-www-form-urlencoded`を使ってボディをエンコードするからです。
+
+これは **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()`をその`exclude_unset`パラメータで使用しています。
+/// info | "情報"
-!!! info "情報"
- 以下も使用することができます:
+FastAPIはこれをするために、Pydanticモデルの`.dict()`をその`exclude_unset`パラメータで使用しています。
- * `response_model_exclude_defaults=True`
- * `response_model_exclude_none=True`
+///
- `exclude_defaults`と`exclude_none`については、Pydanticのドキュメントで説明されている通りです。
+/// info | "情報"
+
+以下も使用することができます:
+
+* `response_model_exclude_defaults=True`
+* `response_model_exclude_none=True`
+
+`exclude_defaults`と`exclude_none`については、Pydanticのドキュメントで説明されている通りです。
+
+///
#### デフォルト値を持つフィールドの値を持つデータ
@@ -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 | "豆知識"
- これは`set(["name", "description"])`と同等です。
+`{"name", "description"}`の構文はこれら2つの値をもつ`set`を作成します。
+
+これは`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の`http.HTTPStatus`のように、`IntEnum`を受け取ることもできます。
+/// info | "情報"
+
+`status_code`は代わりに、Pythonの`http.HTTPStatus`のように、`IntEnum`を受け取ることもできます。
+
+///
これは:
@@ -27,15 +33,21 @@
-!!! note "備考"
- いくつかのレスポンスコード(次のセクションを参照)は、レスポンスにボディがないことを示しています。
+/// note | "備考"
- FastAPIはこれを知っていて、レスポンスボディがないというOpenAPIドキュメントを生成します。
+いくつかのレスポンスコード(次のセクションを参照)は、レスポンスにボディがないことを示しています。
+
+FastAPIはこれを知っていて、レスポンスボディがないというOpenAPIドキュメントを生成します。
+
+///
## HTTPステータスコードについて
-!!! note "備考"
- すでにHTTPステータスコードが何であるかを知っている場合は、次のセクションにスキップしてください。
+/// note | "備考"
+
+すでにHTTPステータスコードが何であるかを知っている場合は、次のセクションにスキップしてください。
+
+///
HTTPでは、レスポンスの一部として3桁の数字のステータスコードを送信します。
@@ -54,8 +66,11 @@ HTTPでは、レスポンスの一部として3桁の数字のステータス
* クライアントからの一般的なエラーについては、`400`を使用することができます。
* `500`以上はサーバーエラーのためのものです。これらを直接使うことはほとんどありません。アプリケーションコードやサーバーのどこかで何か問題が発生した場合、これらのステータスコードのいずれかが自動的に返されます。
-!!! tip "豆知識"
- それぞれのステータスコードとどのコードが何のためのコードなのかについて詳細はMDN HTTP レスポンスステータスコードについてのドキュメントを参照してください。
+/// tip | "豆知識"
+
+それぞれのステータスコードとどのコードが何のためのコードなのかについて詳細はMDN HTTP レスポンスステータスコードについてのドキュメントを参照してください。
+
+///
## 名前を覚えるための近道
@@ -79,10 +94,13 @@ HTTPでは、レスポンスの一部として3桁の数字のステータス
-!!! note "技術詳細"
- また、`from starlette import status`を使うこともできます。
+/// note | "技術詳細"
- **FastAPI** は、`開発者の利便性を考慮して、fastapi.status`と同じ`starlette.status`を提供しています。しかし、これはStarletteから直接提供されています。
+また、`from starlette import status`を使うこともできます。
+
+**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 f1c43b7b4..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 "情報"
- まず`python-multipart`をインストールします。
+/// info | "情報"
- 例えば、`pip install python-multipart`。
+まず`python-multipart`をインストールします。
- これは、**OAuth2**が `ユーザー名` や `パスワード` を送信するために、「フォームデータ」を使うからです。
+例えば、`pip install python-multipart`。
+
+これは、**OAuth2**が `ユーザー名` や `パスワード` を送信するために、「フォームデータ」を使うからです。
+
+///
例を実行します:
@@ -53,17 +56,23 @@ $ uvicorn main:app --reload
-!!! check "Authorizeボタン!"
- すでにピカピカの新しい「Authorize」ボタンがあります。
+/// check | "Authorizeボタン!"
- そして、あなたの*path operation*には、右上にクリックできる小さな鍵アイコンがあります。
+すでにピカピカの新しい「Authorize」ボタンがあります。
+
+そして、あなたの*path operation*には、右上にクリックできる小さな鍵アイコンがあります。
+
+///
それをクリックすると、`ユーザー名`と`パスワード` (およびその他のオプションフィールド) を入力する小さな認証フォームが表示されます:
-!!! note "備考"
- フォームに何を入力しても、まだうまくいきません。ですが、これから動くようになります。
+/// note | "備考"
+
+フォームに何を入力しても、まだうまくいきません。ですが、これから動くようになります。
+
+///
もちろんエンドユーザーのためのフロントエンドではありません。しかし、すべてのAPIをインタラクティブにドキュメント化するための素晴らしい自動ツールです。
@@ -105,14 +114,17 @@ OAuth2は、バックエンドやAPIがユーザーを認証するサーバー
この例では、**Bearer**トークンを使用して**OAuth2**を**パスワード**フローで使用します。これには`OAuth2PasswordBearer`クラスを使用します。
-!!! info "情報"
- 「bearer」トークンが、唯一の選択肢ではありません。
+/// info | "情報"
- しかし、私たちのユースケースには最適です。
+「bearer」トークンが、唯一の選択肢ではありません。
- あなたがOAuth2の専門家で、あなたのニーズに適した別のオプションがある理由を正確に知っている場合を除き、ほとんどのユースケースに最適かもしれません。
+しかし、私たちのユースケースには最適です。
- その場合、**FastAPI**はそれを構築するためのツールも提供します。
+あなたがOAuth2の専門家で、あなたのニーズに適した別のオプションがある理由を正確に知っている場合を除き、ほとんどのユースケースに最適かもしれません。
+
+その場合、**FastAPI**はそれを構築するためのツールも提供します。
+
+///
`OAuth2PasswordBearer` クラスのインスタンスを作成する時に、パラメーター`tokenUrl`を渡します。このパラメーターには、クライアント (ユーザーのブラウザで動作するフロントエンド) がトークンを取得するために`ユーザー名`と`パスワード`を送信するURLを指定します。
@@ -120,21 +132,27 @@ OAuth2は、バックエンドやAPIがユーザーを認証するサーバー
{!../../../docs_src/security/tutorial001.py!}
```
-!!! tip "豆知識"
- ここで、`tokenUrl="token"`は、まだ作成していない相対URL`token`を指します。相対URLなので、`./token`と同じです。
+/// tip | "豆知識"
- 相対URLを使っているので、APIが`https://example.com/`にある場合、`https://example.com/token`を参照します。しかし、APIが`https://example.com/api/v1/`にある場合は`https://example.com/api/v1/token`を参照することになります。
+ここで、`tokenUrl="token"`は、まだ作成していない相対URL`token`を指します。相対URLなので、`./token`と同じです。
- 相対 URL を使うことは、[プロキシと接続](./.../advanced/behind-a-proxy.md){.internal-link target=_blank}のような高度なユースケースでもアプリケーションを動作させ続けるために重要です。
+相対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}のような高度なユースケースでもアプリケーションを動作させ続けるために重要です。
+
+///
このパラメーターはエンドポイント/ *path operation*を作成しません。しかし、URL`/token`はクライアントがトークンを取得するために使用するものであると宣言します。この情報は OpenAPI やインタラクティブな API ドキュメントシステムで使われます。
実際のpath operationもすぐに作ります。
-!!! info "情報"
- 非常に厳格な「Pythonista」であれば、パラメーター名のスタイルが`token_url`ではなく`tokenUrl`であることを気に入らないかもしれません。
+/// info | "情報"
- それはOpenAPI仕様と同じ名前を使用しているからです。そのため、これらのセキュリティスキームについてもっと調べる必要がある場合は、それをコピーして貼り付ければ、それについての詳細な情報を見つけることができます。
+非常に厳格な「Pythonista」であれば、パラメーター名のスタイルが`token_url`ではなく`tokenUrl`であることを気に入らないかもしれません。
+
+それは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 | "技術詳細"
- OpenAPIと統合するセキュリティユーティリティ (および自動APIドキュメント) はすべて`SecurityBase`を継承しています。それにより、**FastAPI**はそれらをOpenAPIに統合する方法を知ることができます。
+**FastAPI**は、`OAuth2PasswordBearer` クラス (依存関係で宣言されている) を使用してOpenAPIのセキュリティスキームを定義できることを知っています。これは`fastapi.security.oauth2.OAuth2`、`fastapi.security.base.SecurityBase`を継承しているからです。
+
+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 | "豆知識"
- 最も複雑な問題は、それらのような認証/認可プロバイダを構築することですが、**FastAPI**は、あなたのために重い仕事をこなしながら、それを簡単に行うためのツールを提供します。
+Google、Facebook、Twitter、GitHubなど、他の認証/認可プロバイダを統合することも可能で、比較的簡単です。
+
+最も複雑な問題は、それらのような認証/認可プロバイダを構築することですが、**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]
ここでは、推奨されているものを使用します:pyca/cryptography。
-!!! tip "豆知識"
- このチュートリアルでは以前、PyJWTを使用していました。
+/// tip | "豆知識"
- しかし、Python-joseは、PyJWTのすべての機能に加えて、後に他のツールと統合して構築する際におそらく必要となる可能性のあるいくつかの追加機能を提供しています。そのため、代わりにPython-joseを使用するように更新されました。
+このチュートリアルでは以前、PyJWTを使用していました。
+
+しかし、Python-joseは、PyJWTのすべての機能に加えて、後に他のツールと統合して構築する際におそらく必要となる可能性のあるいくつかの追加機能を提供しています。そのため、代わりにPython-joseを使用するように更新されました。
+
+///
## パスワードのハッシュ化
@@ -83,13 +86,15 @@ $ pip install passlib[bcrypt]
@@ -230,8 +244,11 @@ Password: `secret`
-!!! 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+"
+////
- ```Python
- {!> ../../../docs_src/app_testing/app_b/main.py!}
- ```
+//// tab | Python 3.6+
+
+```Python
+{!> ../../../docs_src/app_testing/app_b/main.py!}
+```
+
+////
### 拡張版テストファイル
@@ -108,10 +121,13 @@
(`httpx` または `TestClient` を使用して) バックエンドにデータを渡す方法の詳細は、HTTPXのドキュメントを確認してください。
-!!! info "情報"
- `TestClient` は、Pydanticモデルではなく、JSONに変換できるデータを受け取ることに注意してください。
+/// info | "情報"
- テストにPydanticモデルがあり、テスト中にそのデータをアプリケーションに送信したい場合は、[JSON互換エンコーダ](encoder.md){.internal-link target=_blank} で説明されている `jsonable_encoder` が利用できます。
+`TestClient` は、Pydanticモデルではなく、JSONに変換できるデータを受け取ることに注意してください。
+
+テストに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
new file mode 100644
index 000000000..e155f41f1
--- /dev/null
+++ b/docs/ko/docs/advanced/events.md
@@ -0,0 +1,57 @@
+# 이벤트: 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 | "정보"
+
+이벤트 핸들러에 관한 내용은 Starlette 이벤트 문서에서 추가로 확인할 수 있습니다.
+
+///
diff --git a/docs/ko/docs/advanced/index.md b/docs/ko/docs/advanced/index.md
index 5e23e2809..cb628fa10 100644
--- a/docs/ko/docs/advanced/index.md
+++ b/docs/ko/docs/advanced/index.md
@@ -2,18 +2,21 @@
## 추가 기능
-메인 [자습서 - 사용자 안내서](../tutorial/){.internal-link target=_blank}는 여러분이 **FastAPI**의 모든 주요 기능을 둘러보시기에 충분할 것입니다.
+메인 [자습서 - 사용자 안내서](../tutorial/index.md){.internal-link target=_blank}는 여러분이 **FastAPI**의 모든 주요 기능을 둘러보시기에 충분할 것입니다.
이어지는 장에서는 여러분이 다른 옵션, 구성 및 추가 기능을 보실 수 있습니다.
-!!! tip "팁"
- 다음 장들이 **반드시 "심화"**인 것은 아닙니다.
+/// tip | "팁"
- 그리고 여러분의 사용 사례에 대한 해결책이 그중 하나에 있을 수 있습니다.
+다음 장들이 **반드시 "심화"**인 것은 아닙니다.
+
+그리고 여러분의 사용 사례에 대한 해결책이 그중 하나에 있을 수 있습니다.
+
+///
## 자습서를 먼저 읽으십시오
-여러분은 메인 [자습서 - 사용자 안내서](../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..dfc2caa78 100644
--- a/docs/ko/docs/async.md
+++ b/docs/ko/docs/async.md
@@ -2,7 +2,7 @@
*경로 작동 함수*에서의 `async def` 문법에 대한 세부사항과 비동기 코드, 동시성 및 병렬성에 대한 배경
-## 바쁘신 경우
+## 바쁘신 경우
요약
@@ -21,8 +21,11 @@ async def read_results():
return results
```
-!!! note "참고"
- `async def`로 생성된 함수 내부에서만 `await`를 사용할 수 있습니다.
+/// note | "참고"
+
+`async def`로 생성된 함수 내부에서만 `await`를 사용할 수 있습니다.
+
+///
---
@@ -263,7 +266,7 @@ CPU에 묶인 연산에 관한 흔한 예시는 복잡한 수학 처리를 필
파이썬이 **데이터 사이언스**, 머신러닝과 특히 딥러닝에 의 주된 언어라는 간단한 사실에 더해서, 이것은 FastAPI를 데이터 사이언스 / 머신러닝 웹 API와 응용프로그램에 (다른 것들보다) 좋은 선택지가 되게 합니다.
-배포시 병렬을 어떻게 가능하게 하는지 알고싶다면, [배포](/ko/deployment){.internal-link target=_blank}문서를 참고하십시오.
+배포시 병렬을 어떻게 가능하게 하는지 알고싶다면, [배포](deployment/index.md){.internal-link target=_blank}문서를 참고하십시오.
## `async`와 `await`
@@ -366,12 +369,15 @@ FastAPI를 사용하지 않더라도, 높은 호환성 및 I/O를 수행하는 코드를 사용하지 않는 한 `async def`를 사용하는 편이 더 낫습니다.
-하지만 두 경우 모두, FastAPI가 당신이 전에 사용하던 프레임워크보다 [더 빠를](/#performance){.internal-link target=_blank} (최소한 비견될) 확률이 높습니다.
+하지만 두 경우 모두, FastAPI가 당신이 전에 사용하던 프레임워크보다 [더 빠를](index.md#_11){.internal-link target=_blank} (최소한 비견될) 확률이 높습니다.
### 의존성
@@ -401,4 +407,4 @@ FastAPI를 사용하지 않더라도, 높은 호환성 및
-
-
+
+
-
-
+
+
@@ -20,15 +26,15 @@
**문서**: https://fastapi.tiangolo.com
-**소스 코드**: https://github.com/tiangolo/fastapi
+**소스 코드**: https://github.com/fastapi/fastapi
---
-FastAPI는 현대적이고, 빠르며(고성능), 파이썬 표준 타입 힌트에 기초한 Python3.8+의 API를 빌드하기 위한 웹 프레임워크입니다.
+FastAPI는 현대적이고, 빠르며(고성능), 파이썬 표준 타입 힌트에 기초한 Python의 API를 빌드하기 위한 웹 프레임워크입니다.
주요 특징으로:
-* **빠름**: (Starlette과 Pydantic 덕분에) **NodeJS** 및 **Go**와 대등할 정도로 매우 높은 성능. [사용 가능한 가장 빠른 파이썬 프레임워크 중 하나](#performance).
+* **빠름**: (Starlette과 Pydantic 덕분에) **NodeJS** 및 **Go**와 대등할 정도로 매우 높은 성능. [사용 가능한 가장 빠른 파이썬 프레임워크 중 하나](#_11).
* **빠른 코드 작성**: 약 200%에서 300%까지 기능 개발 속도 증가. *
* **적은 버그**: 사람(개발자)에 의한 에러 약 40% 감소. *
@@ -61,7 +67,7 @@ FastAPI는 현대적이고, 빠르며(고성능), 파이썬 표준 타입 힌트
"_[...] 저는 요즘 **FastAPI**를 많이 사용하고 있습니다. [...] 사실 우리 팀의 **마이크로소프트 ML 서비스** 전부를 바꿀 계획입니다. 그중 일부는 핵심 **Windows**와 몇몇의 **Office** 제품들이 통합되고 있습니다._"
-
email_validator - 이메일 유효성 검사.
+* email-validator - 이메일 유효성 검사.
Starlette이 사용하는:
@@ -447,12 +451,12 @@ Starlette이 사용하는:
* itsdangerous - `SessionMiddleware` 지원을 위해 필요.
* pyyaml - Starlette의 `SchemaGenerator` 지원을 위해 필요 (FastAPI와 쓸때는 필요 없을 것입니다).
* graphene - `GraphQLApp` 지원을 위해 필요.
-* ujson - `UJSONResponse`를 사용하려면 필요.
FastAPI / Starlette이 사용하는:
* uvicorn - 애플리케이션을 로드하고 제공하는 서버.
* orjson - `ORJSONResponse`을 사용하려면 필요.
+* ujson - `UJSONResponse`를 사용하려면 필요.
`pip install fastapi[all]`를 통해 이 모두를 설치 할 수 있습니다.
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 | "팁"
- 이번 예제에서는 `str`이 `List`에 들어간 타입 매개변수 입니다.
+대괄호 안의 내부 타입은 "타입 매개변수(type paramters)"라고 합니다.
+
+이번 예제에서는 `str`이 `List`에 들어간 타입 매개변수 입니다.
+
+///
이는 "`items`은 `list`인데, 배열에 들어있는 아이템 각각은 `str`이다"라는 뜻입니다.
@@ -281,9 +287,11 @@ Pydantic 공식 문서 예시:
{!../../../docs_src/python_types/tutorial011.py!}
```
-!!! info "정보"
- Pydantic<에 대해 더 배우고 싶다면 공식 문서를 참고하세요.
+/// info | "정보"
+Pydantic<에 대해 더 배우고 싶다면 공식 문서를 참고하세요.
+
+///
**FastAPI**는 모두 Pydantic을 기반으로 되어 있습니다.
@@ -311,5 +319,8 @@ Pydantic 공식 문서 예시:
가장 중요한 건, 표준 파이썬 타입을 한 곳에서(클래스를 더하거나, 데코레이터 사용하는 대신) 사용함으로써 **FastAPI**가 당신을 위해 많은 일을 해준다는 사실이죠.
-!!! info "정보"
- 만약 모든 자습서를 다 보았음에도 타입에 대해서 더 보고자 방문한 경우에는 `mypy`에서 제공하는 "cheat sheet"이 좋은 자료가 될 겁니다.
+/// info | "정보"
+
+만약 모든 자습서를 다 보았음에도 타입에 대해서 더 보고자 방문한 경우에는 `mypy`에서 제공하는 "cheat sheet"이 좋은 자료가 될 겁니다.
+
+///
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"
+////
- ```Python hl_lines="11 13 20 23"
- {!> ../../../docs_src/background_tasks/tutorial002_py310.py!}
- ```
+//// tab | Python 3.10 and above
+
+```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 fc7209726..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+
- !!! 팁
- 가능하다면 `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!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="11-14"
+{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="12-15"
- {!> ../../../docs_src/body_fields/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ Annotated가 없는 경우"
+//// tab | Python 3.8+
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+```Python hl_lines="12-15"
+{!> ../../../docs_src/body_fields/tutorial001_an.py!}
+```
- ```Python hl_lines="9-12"
- {!> ../../../docs_src/body_fields/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ Annotated가 없는 경우"
+//// tab | Python 3.10+ Annotated가 없는 경우
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+/// tip | "팁"
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001.py!}
- ```
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
+
+///
+
+```Python hl_lines="9-12"
+{!> ../../../docs_src/body_fields/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ Annotated가 없는 경우
+
+/// tip | "팁"
+
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
+
+///
+
+```Python hl_lines="11-14"
+{!> ../../../docs_src/body_fields/tutorial001.py!}
+```
+
+////
`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 edf1a5f77..4d785f64b 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`이 있습니다.
@@ -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 | "팁"
- 하지만 Pydantic은 자동 데이터 변환이 있습니다.
+JSON은 오직 `str`형 키만 지원한다는 것을 염두에 두세요.
- 즉, API 클라이언트가 문자열을 키로 보내더라도 해당 문자열이 순수한 정수를 포함하는한 Pydantic은 이를 변환하고 검증합니다.
+하지만 Pydantic은 자동 데이터 변환이 있습니다.
- 그러므로 `weights`로 받은 `dict`는 실제로 `int` 키와 `float` 값을 가집니다.
+즉, API 클라이언트가 문자열을 키로 보내더라도 해당 문자열이 순수한 정수를 포함하는한 Pydantic은 이를 변환하고 검증합니다.
+
+그러므로 `weights`로 받은 `dict`는 실제로 `int` 키와 `float` 값을 가집니다.
+
+///
## 요약
diff --git a/docs/ko/docs/tutorial/body.md b/docs/ko/docs/tutorial/body.md
index 8b98284bb..337218eb4 100644
--- a/docs/ko/docs/tutorial/body.md
+++ b/docs/ko/docs/tutorial/body.md
@@ -8,28 +8,35 @@
**요청** 본문을 선언하기 위해서 모든 강력함과 이점을 갖춘 Pydantic 모델을 사용합니다.
-!!! 정보
- 데이터를 보내기 위해, (좀 더 보편적인) `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!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="4"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```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 @@
-!!! 팁
- 만약 PyCharm를 편집기로 사용한다면, Pydantic PyCharm Plugin을 사용할 수 있습니다.
+/// tip | "팁"
- 다음 사항을 포함해 Pydantic 모델에 대한 편집기 지원을 향상시킵니다:
+만약 PyCharm를 편집기로 사용한다면, Pydantic PyCharm Plugin을 사용할 수 있습니다.
- * 자동 완성
- * 타입 확인
- * 리팩토링
- * 검색
- * 점검
+다음 사항을 포함해 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+"
+////
- ```Python hl_lines="21"
- {!> ../../../docs_src/body/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+
+```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+"
+////
- ```Python hl_lines="17-18"
- {!> ../../../docs_src/body/tutorial003.py!}
- ```
+//// tab | Python 3.8+
+
+```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+"
+////
- ```Python hl_lines="18"
- {!> ../../../docs_src/body/tutorial004.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="18"
+{!> ../../../docs_src/body/tutorial004.py!}
+```
+
+////
함수 매개변수는 다음을 따라서 인지하게 됩니다:
@@ -203,11 +233,14 @@
* 만약 매개변수가 (`int`, `float`, `str`, `bool` 등과 같은) **유일한 타입**으로 되어있으면, **쿼리** 매개변수로 해석될 것입니다.
* 만약 매개변수가 **Pydantic 모델** 타입으로 선언되어 있으면, 요청 **본문**으로 해석될 것입니다.
-!!! 참고
- FastAPI는 `q`의 값이 필요없음을 알게 될 것입니다. 기본 값이 `= None`이기 때문입니다.
+/// note | "참고"
- `Union[str, None]`에 있는 `Union`은 FastAPI에 의해 사용된 것이 아니지만, 편집기로 하여금 더 나은 지원과 에러 탐지를 지원할 것입니다.
+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/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!}
- ```
+```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!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="9"
+{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/cookie_params/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ Annotated가 없는 경우"
+//// tab | Python 3.8+
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+```Python hl_lines="10"
+{!> ../../../docs_src/cookie_params/tutorial001_an.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ Annotated가 없는 경우"
+//// tab | Python 3.10+ Annotated가 없는 경우
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+/// tip | "팁"
- ```Python hl_lines="9"
- {!> ../../../docs_src/cookie_params/tutorial001.py!}
- ```
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
-!!! note "기술 세부사항"
- `Cookie`는 `Path` 및 `Query`의 "자매"클래스입니다. 이 역시 동일한 공통 `Param` 클래스를 상속합니다.
+///
- `Query`, `Path`, `Cookie` 그리고 다른 것들은 `fastapi`에서 임포트 할 때, 실제로는 특별한 클래스를 반환하는 함수임을 기억하세요.
+```Python hl_lines="7"
+{!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
+```
-!!! info "정보"
- 쿠키를 선언하기 위해서는 `Cookie`를 사용해야 합니다. 그렇지 않으면 해당 매개변수를 쿼리 매개변수로 해석하기 때문입니다.
+////
+
+//// tab | Python 3.8+ Annotated가 없는 경우
+
+/// tip | "팁"
+
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
+
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/cookie_params/tutorial001.py!}
+```
+
+////
+
+/// note | "기술 세부사항"
+
+`Cookie`는 `Path` 및 `Query`의 "자매"클래스입니다. 이 역시 동일한 공통 `Param` 클래스를 상속합니다.
+
+`Query`, `Path`, `Cookie` 그리고 다른 것들은 `fastapi`에서 임포트 할 때, 실제로는 특별한 클래스를 반환하는 함수임을 기억하세요.
+
+///
+
+/// 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 @@
CORS에 대한 더 많은 정보를 알고싶다면, Mozilla CORS 문서를 참고하기 바랍니다.
-!!! 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
new file mode 100644
index 000000000..cb45e5169
--- /dev/null
+++ b/docs/ko/docs/tutorial/debugging.md
@@ -0,0 +1,115 @@
+# 디버깅
+
+예를 들면 Visual Studio Code 또는 PyCharm을 사용하여 편집기에서 디버거를 연결할 수 있습니다.
+
+## `uvicorn` 호출
+
+FastAPI 애플리케이션에서 `uvicorn`을 직접 임포트하여 실행합니다
+
+```Python hl_lines="1 15"
+{!../../../docs_src/debugging/tutorial001.py!}
+```
+
+### `__name__ == "__main__"` 에 대하여
+
+`__name__ == "__main__"`의 주요 목적은 다음과 같이 파일이 호출될 때 실행되는 일부 코드를 갖는 것입니다.
+
+
+
+---
+
+Pycharm을 사용하는 경우 다음을 수행할 수 있습니다
+
+* "Run" 메뉴를 엽니다
+* "Debug..." 옵션을 선택합니다.
+* 그러면 상황에 맞는 메뉴가 나타납니다.
+* 디버그할 파일을 선택합니다(이 경우 `main.py`).
+
+그런 다음 **FastAPI** 코드로 서버를 시작하고 중단점 등에서 중지합니다.
+
+다음과 같이 표시됩니다.
+
+
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 이상"
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+//// tab | 파이썬 3.10 이상
+
+```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 이상"
+////
- ```Python hl_lines="9-13"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
+//// tab | 파이썬 3.10 이상
+
+```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 이상"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
+//// tab | 파이썬 3.10 이상
+
+```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!}
+```
-=== "파이썬 3.10 이상"
+////
- ```Python hl_lines="6"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+//// tab | 파이썬 3.10 이상
+
+```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!}
+```
-=== "파이썬 3.10 이상"
+////
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
+//// tab | 파이썬 3.10 이상
+
+```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 이상"
+////
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial003_py310.py!}
- ```
+//// tab | 파이썬 3.10 이상
+
+```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 이상"
+////
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial004_py310.py!}
- ```
+//// tab | 파이썬 3.10 이상
+
+```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!}
- ```
+```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!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8 Annotated가 없는 경우"
+```Python hl_lines="7 12"
+{!> ../../../docs_src/dependencies/tutorial006_an.py!}
+```
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+////
- ```Python hl_lines="6 11"
- {!> ../../../docs_src/dependencies/tutorial006.py!}
- ```
+//// tab | Python 3.8 Annotated가 없는 경우
+
+/// tip | "팁"
+
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
+
+///
+
+```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!}
- ```
+```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!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8 Annotated가 없는 경우"
+```Python hl_lines="9 14"
+{!> ../../../docs_src/dependencies/tutorial006_an.py!}
+```
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+////
- ```Python hl_lines="8 13"
- {!> ../../../docs_src/dependencies/tutorial006.py!}
- ```
+//// tab | Python 3.8 Annotated가 없는 경우
+
+/// tip | "팁"
+
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
+
+///
+
+```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!}
- ```
+```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!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8 Annotated가 없는 경우"
+```Python hl_lines="10 15"
+{!> ../../../docs_src/dependencies/tutorial006_an.py!}
+```
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+////
- ```Python hl_lines="9 14"
- {!> ../../../docs_src/dependencies/tutorial006.py!}
- ```
+//// tab | Python 3.8 Annotated가 없는 경우
+
+/// tip | "팁"
+
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
+
+///
+
+```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 c56dddae3..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!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="8-11"
- {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "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.10+ Annotated가 없는 경우"
+//// tab | Python 3.8+
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+```Python hl_lines="9-12"
+{!> ../../../docs_src/dependencies/tutorial001_an.py!}
+```
- ```Python hl_lines="6-7"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ Annotated가 없는 경우"
+//// tab | Python 3.10+ Annotated가 없는 경우
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+/// tip | "팁"
- ```Python hl_lines="8-11"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
+
+///
+
+```Python hl_lines="6-7"
+{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ Annotated가 없는 경우
+
+/// tip | "팁"
+
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
+
+///
+
+```Python hl_lines="8-11"
+{!> ../../../docs_src/dependencies/tutorial001.py!}
+```
+
+////
이게 다입니다.
@@ -85,90 +101,125 @@
그 후 위의 값을 포함한 `dict` 자료형으로 반환할 뿐입니다.
-!!! 정보
- FastAPI는 0.95.0 버전부터 `Annotated`에 대한 지원을 (그리고 이를 사용하기 권장합니다) 추가했습니다.
+/// info | "정보"
- 옛날 버전을 가지고 있는 경우, `Annotated`를 사용하려 하면 에러를 맞이하게 될 것입니다.
+FastAPI는 0.95.0 버전부터 `Annotated`에 대한 지원을 (그리고 이를 사용하기 권장합니다) 추가했습니다.
- `Annotated`를 사용하기 전에 최소 0.95.1로 [FastAPI 버전 업그레이드](../../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank}를 확실하게 하세요.
+옛날 버전을 가지고 있는 경우, `Annotated`를 사용하려 하면 에러를 맞이하게 될 것입니다.
+
+`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!}
- ```
+```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!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="3"
+{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="3"
- {!> ../../../docs_src/dependencies/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ Annotated가 없는 경우"
+//// tab | Python 3.8+
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+```Python hl_lines="3"
+{!> ../../../docs_src/dependencies/tutorial001_an.py!}
+```
- ```Python hl_lines="1"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ Annotated가 없는 경우"
+//// tab | Python 3.10+ Annotated가 없는 경우
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+/// tip | "팁"
- ```Python hl_lines="3"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
+
+///
+
+```Python hl_lines="1"
+{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ Annotated가 없는 경우
+
+/// tip | "팁"
+
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
+
+///
+
+```Python hl_lines="3"
+{!> ../../../docs_src/dependencies/tutorial001.py!}
+```
+
+////
### "의존자"에 의존성 명시하기
*경로 작동 함수*의 매개변수로 `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!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="15 20"
- {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="15 20"
+{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="16 21"
- {!> ../../../docs_src/dependencies/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ Annotated가 없는 경우"
+//// tab | Python 3.8+
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+```Python hl_lines="16 21"
+{!> ../../../docs_src/dependencies/tutorial001_an.py!}
+```
- ```Python hl_lines="11 16"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ Annotated가 없는 경우"
+//// tab | Python 3.10+ Annotated가 없는 경우
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+/// tip | "팁"
- ```Python hl_lines="15 20"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+가능하다면 `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!}
+```
+
+////
비록 `Body`, `Query` 등을 사용하는 것과 같은 방식으로 여러분의 함수의 매개변수에 있는 `Depends`를 사용하지만, `Depends`는 약간 다르게 작동합니다.
@@ -180,8 +231,11 @@
그리고 그 함수는 *경로 작동 함수*가 작동하는 것과 같은 방식으로 매개변수를 받습니다.
-!!! tip "팁"
- 여러분은 다음 장에서 함수를 제외하고서, "다른 것들"이 어떻게 의존성으로 사용되는지 알게 될 것입니다.
+/// tip | "팁"
+
+여러분은 다음 장에서 함수를 제외하고서, "다른 것들"이 어떻게 의존성으로 사용되는지 알게 될 것입니다.
+
+///
새로운 요청이 도착할 때마다, **FastAPI**는 다음을 처리합니다:
@@ -202,10 +256,13 @@ common_parameters --> read_users
이렇게 하면 공용 코드를 한번만 적어도 되며, **FastAPI**는 *경로 작동*을 위해 이에 대한 호출을 처리합니다.
-!!! check "확인"
- 특별한 클래스를 만들지 않아도 되며, 이러한 것 혹은 비슷한 종류를 **FastAPI**에 "등록"하기 위해 어떤 곳에 넘겨주지 않아도 됩니다.
+/// check | "확인"
- 단순히 `Depends`에 넘겨주기만 하면 되며, **FastAPI**는 나머지를 어찌할지 알고 있습니다.
+특별한 클래스를 만들지 않아도 되며, 이러한 것 혹은 비슷한 종류를 **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!}
+```
-=== "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 "팁"
- 이는 그저 표준 파이썬이고 "type alias"라고 부르며 사실 **FastAPI**에 국한되는 것은 아닙니다.
+//// tab | Python 3.8+
- 하지만, `Annotated`를 포함하여, **FastAPI**가 파이썬 표준을 기반으로 하고 있기에, 이를 여러분의 코드 트릭으로 사용할 수 있습니다. 😎
+```Python hl_lines="15 19 24"
+{!> ../../../docs_src/dependencies/tutorial001_02_an.py!}
+```
+
+////
+
+/// tip | "팁"
+
+이는 그저 표준 파이썬이고 "type alias"라고 부르며 사실 **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
new file mode 100644
index 000000000..df3c7a06e
--- /dev/null
+++ b/docs/ko/docs/tutorial/extra-data-types.md
@@ -0,0 +1,162 @@
+# 추가 데이터 자료형
+
+지금까지 일반적인 데이터 자료형을 사용했습니다. 예를 들면 다음과 같습니다:
+
+* `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 시차 인코딩"으로 표현하는 것 또한 허용합니다. 더 많은 정보는 이 문서에서 확인하십시오..
+* `frozenset`:
+ * 요청과 응답에서 `set`와 동일하게 취급됩니다:
+ * 요청 시, 리스트를 읽어 중복을 제거하고 `set`로 변환합니다.
+ * 응답 시, `set`는 `list`로 변환됩니다.
+ * 생성된 스키마는 (JSON 스키마의 `uniqueItems`를 이용해) `set`의 값이 고유함을 명시합니다.
+* `bytes`:
+ * 표준 파이썬의 `bytes`.
+ * 요청과 응답에서 `str`로 취급됩니다.
+ * 생성된 스키마는 이것이 `binary` "형식"의 `str`임을 명시합니다.
+* `Decimal`:
+ * 표준 파이썬의 `Decimal`.
+ * 요청과 응답에서 `float`와 동일하게 다뤄집니다.
+* 여기에서 모든 유효한 pydantic 데이터 자료형을 확인할 수 있습니다: Pydantic 데이터 자료형.
+
+## 예시
+
+위의 몇몇 자료형을 매개변수로 사용하는 *경로 작동* 예시입니다.
+
+//// tab | Python 3.10+
+
+```Python hl_lines="1 3 12-16"
+{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="1 3 12-16"
+{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="1 3 13-17"
+{!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="1 2 11-15"
+{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="1 2 12-16"
+{!> ../../../docs_src/extra_data_types/tutorial001.py!}
+```
+
+////
+
+함수 안의 매개변수가 그들만의 데이터 자료형을 가지고 있으며, 예를 들어, 다음과 같이 날짜를 조작할 수 있음을 참고하십시오:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="18-19"
+{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="18-19"
+{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="19-20"
+{!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="17-18"
+{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="18-19"
+{!> ../../../docs_src/extra_data_types/tutorial001.py!}
+```
+
+////
diff --git a/docs/ko/docs/tutorial/first-steps.md b/docs/ko/docs/tutorial/first-steps.md
index e3b42bce7..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
get 작동 사용
-!!! info "`@decorator` 정보"
- 이 `@something` 문법은 파이썬에서 "데코레이터"라 부릅니다.
+/// info | "`@decorator` 정보"
- 마치 예쁜 장식용(Decorative) 모자처럼(개인적으로 이 용어가 여기서 유래한 것 같습니다) 함수 맨 위에 놓습니다.
+이 `@something` 문법은 파이썬에서 "데코레이터"라 부릅니다.
- "데코레이터"는 아래 있는 함수를 받아 그것으로 무언가를 합니다.
+마치 예쁜 장식용(Decorative) 모자처럼(개인적으로 이 용어가 여기서 유래한 것 같습니다) 함수 맨 위에 놓습니다.
- 우리의 경우, 이 데코레이터는 **FastAPI**에게 아래 함수가 **경로** `/`의 `get` **작동**에 해당한다고 알려줍니다.
+"데코레이터"는 아래 있는 함수를 받아 그것으로 무언가를 합니다.
- 이것이 "**경로 작동 데코레이터**"입니다.
+우리의 경우, 이 데코레이터는 **FastAPI**에게 아래 함수가 **경로** `/`의 `get` **작동**에 해당한다고 알려줍니다.
+
+이것이 "**경로 작동 데코레이터**"입니다.
+
+///
다른 작동도 사용할 수 있습니다:
@@ -274,14 +286,17 @@ API를 설계할 때 일반적으로 특정 행동을 수행하기 위해 특정
* `@app.patch()`
* `@app.trace()`
-!!! tip "팁"
- 각 작동(HTTP 메소드)을 원하는 대로 사용해도 됩니다.
+/// tip | "팁"
- **FastAPI**는 특정 의미를 강제하지 않습니다.
+각 작동(HTTP 메소드)을 원하는 대로 사용해도 됩니다.
- 여기서 정보는 지침서일뿐 강제사항이 아닙니다.
+**FastAPI**는 특정 의미를 강제하지 않습니다.
- 예를 들어 GraphQL을 사용하는 경우, 일반적으로 `POST` 작동만 사용하여 모든 행동을 수행합니다.
+여기서 정보는 지침서일뿐 강제사항이 아닙니다.
+
+예를 들어 GraphQL을 사용하는 경우, 일반적으로 `POST` 작동만 사용하여 모든 행동을 수행합니다.
+
+///
### 4 단계: **경로 작동 함수** 정의
@@ -309,8 +324,11 @@ URL "`/`"에 대한 `GET` 작동을 사용하는 요청을 받을 때마다 **Fa
{!../../../docs_src/first_steps/tutorial003.py!}
```
-!!! note "참고"
- 차이점을 모르겠다면 [Async: *"In a hurry?"*](../async.md#in-a-hurry){.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
+```
- ```
- pip install uvicorn
- ```
+추가로 서버 역할을 하는 `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 "팁"
- 사용자 정의 헤더는 'X-' 접두사를 사용하여 추가할 수 있습니다.
+/// tip | "팁"
- 그러나 만약 클라이언트의 브라우저에서 볼 수 있는 사용자 정의 헤더를 가지고 있다면, 그것들을 CORS 설정([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank})에 Starlette CORS 문서에 명시된 `expose_headers` 매개변수를 이용하여 헤더들을 추가하여야합니다.
+사용자 정의 헤더는 'X-' 접두사를 사용하여 추가할 수 있습니다.
-!!! note "기술적 세부사항"
- `from starlette.requests import request`를 사용할 수도 있습니다.
+그러나 만약 클라이언트의 브라우저에서 볼 수 있는 사용자 정의 헤더를 가지고 있다면, 그것들을 CORS 설정([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank})에 Starlette CORS 문서에 명시된 `expose_headers` 매개변수를 이용하여 헤더들을 추가하여야합니다.
- **FastAPI**는 개발자에게 편의를 위해 이를 제공합니다. 그러나 Starlette에서 직접 파생되었습니다.
+///
+
+/// note | "기술적 세부사항"
+
+`from starlette.requests import request`를 사용할 수도 있습니다.
+
+**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 | "기술적 세부사항"
- **FastAPI**는 개발자 여러분의 편의를 위해서 `starlette.status`와 동일한 `fastapi.status`를 제공합니다. 하지만 Starlette에서 직접 온 것입니다.
+다음과 같이 임포트하셔도 좋습니다. `from starlette import status`.
+
+**FastAPI**는 개발자 여러분의 편의를 위해서 `starlette.status`와 동일한 `fastapi.status`를 제공합니다. 하지만 Starlette에서 직접 온 것입니다.
+
+///
## 태그
@@ -66,13 +72,19 @@
{!../../../docs_src/path_operation_configuration/tutorial005.py!}
```
-!!! info "정보"
- `response_description`은 구체적으로 응답을 지칭하며, `description`은 일반적인 *경로 작동*을 지칭합니다.
+/// info | "정보"
-!!! check "확인"
- OpenAPI는 각 *경로 작동*이 응답에 관한 설명을 요구할 것을 명시합니다.
+`response_description`은 구체적으로 응답을 지칭하며, `description`은 일반적인 *경로 작동*을 지칭합니다.
- 따라서, 응답에 관한 설명이 없을경우, **FastAPI**가 자동으로 "성공 응답" 중 하나를 생성합니다.
+///
+
+/// check | "확인"
+
+OpenAPI는 각 *경로 작동*이 응답에 관한 설명을 요구할 것을 명시합니다.
+
+따라서, 응답에 관한 설명이 없을경우, **FastAPI**가 자동으로 "성공 응답" 중 하나를 생성합니다.
+
+///
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` 등을 임포트 할 때, 이것들은 실제로 함수입니다.
+그리고 이들 모두는 여태까지 본 추가 검증과 메타데이터의 동일한 모든 매개변수를 공유합니다.
- 호출되면 동일한 이름의 클래스의 인스턴스를 반환합니다.
+///
- 즉, 함수인 `Query`를 임포트한 겁니다. 그리고 호출하면 `Query`라는 이름을 가진 클래스의 인스턴스를 반환합니다.
+/// note | "기술 세부사항"
- 편집기에서 타입에 대한 오류를 표시하지 않도록 하기 위해 (클래스를 직접 사용하는 대신) 이러한 함수들이 있습니다.
+`fastapi`에서 `Query`, `Path` 등을 임포트 할 때, 이것들은 실제로 함수입니다.
- 이렇게 하면 오류를 무시하기 위한 사용자 설정을 추가하지 않고도 일반 편집기와 코딩 도구를 사용할 수 있습니다.
+호출되면 동일한 이름의 클래스의 인스턴스를 반환합니다.
+
+즉, 함수인 `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 | "확인"
+
+이 기능은 함수 내에서 오류 검사, 자동완성 등의 편집기 기능을 활용할 수 있게 해줍니다.
+
+///
## 데이터 변환
@@ -35,10 +38,13 @@
{"item_id":3}
```
-!!! check "확인"
- 함수가 받은(반환도 하는) 값은 문자열 `"3"`이 아니라 파이썬 `int` 형인 `3`입니다.
+/// check | "확인"
- 즉, 타입 선언을 하면 **FastAPI**는 자동으로 요청을 "파싱"합니다.
+함수가 받은(반환도 하는) 값은 문자열 `"3"`이 아니라 파이썬 `int` 형인 `3`입니다.
+
+즉, 타입 선언을 하면 **FastAPI**는 자동으로 요청을 "파싱"합니다.
+
+///
## 데이터 검증
@@ -63,12 +69,15 @@
`int`가 아닌 `float`을 전달하는 경우에도 동일한 오류가 나타납니다: http://127.0.0.1:8000/items/4.2
-!!! check "확인"
- 즉, 파이썬 타입 선언을 하면 **FastAPI**는 데이터 검증을 합니다.
+/// check | "확인"
- 오류에는 정확히 어느 지점에서 검증을 통과하지 못했는지 명시됩니다.
+즉, 파이썬 타입 선언을 하면 **FastAPI**는 데이터 검증을 합니다.
- 이는 API와 상호 작용하는 코드를 개발하고 디버깅하는 데 매우 유용합니다.
+오류에는 정확히 어느 지점에서 검증을 통과하지 못했는지 명시됩니다.
+
+이는 API와 상호 작용하는 코드를 개발하고 디버깅하는 데 매우 유용합니다.
+
+///
## 문서화
@@ -76,10 +85,13 @@
-!!! check "확인"
- 그저 파이썬 타입 선언을 하기만 하면 **FastAPI**는 자동 대화형 API 문서(Swagger UI)를 제공합니다.
+/// check | "확인"
- 경로 매개변수가 정수형으로 명시된 것을 확인할 수 있습니다.
+그저 파이썬 타입 선언을 하기만 하면 **FastAPI**는 자동 대화형 API 문서(Swagger UI)를 제공합니다.
+
+경로 매개변수가 정수형으로 명시된 것을 확인할 수 있습니다.
+
+///
## 표준 기반의 이점, 대체 문서
@@ -131,11 +143,17 @@
{!../../../docs_src/path_params/tutorial005.py!}
```
-!!! info "정보"
- 열거형(또는 enums)은 파이썬 버전 3.4 이후로 사용 가능합니다.
+/// info | "정보"
-!!! tip "팁"
- 혹시 궁금하다면, "AlexNet", "ResNet", 그리고 "LeNet"은 그저 기계 학습 모델들의 이름입니다.
+열거형(또는 enums)은 파이썬 버전 3.4 이후로 사용 가능합니다.
+
+///
+
+/// tip | "팁"
+
+혹시 궁금하다면, "AlexNet", "ResNet", 그리고 "LeNet"은 그저 기계 학습 모델들의 이름입니다.
+
+///
### *경로 매개변수* 선언
@@ -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 | "팁"
- 이 경우 URL은: `/files//home/johndoe/myfile.txt`이며 `files`과 `home` 사이에 이중 슬래시(`//`)가 생깁니다.
+매개변수가 가져야 하는 값이 `/home/johndoe/myfile.txt`와 같이 슬래시로 시작(`/`)해야 할 수 있습니다.
+
+이 경우 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)
+```
- `Optional` 부분은 편집기에게 더 나은 지원을 제공하기 위해서만 사용됩니다.
+그리고 `None`을 사용하여 쿼라 매개변수가 필수적이지 않다는 것을 파악합니다.
+
+`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 "정보"
- 이전에 `...`를 본적이 없다면: 특별한 단일값으로, 파이썬의 일부이며 "Ellipsis"라 부릅니다.
+/// info | "정보"
+
+이전에 `...`를 본적이 없다면: 특별한 단일값으로, 파이썬의 일부이며 "Ellipsis"라 부릅니다.
+
+///
이렇게 하면 **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 8c7f9167b..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#predefined-values){.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 "정보"
- 업로드된 파일을 전달받기 위해 먼저 `python-multipart`를 설치해야합니다.
+/// info | "정보"
- 예시) `pip install python-multipart`.
+업로드된 파일을 전달받기 위해 먼저 `python-multipart`를 설치해야합니다.
- 업로드된 파일들은 "폼 데이터"의 형태로 전송되기 때문에 이 작업이 필요합니다.
+예시) `pip install python-multipart`.
+
+업로드된 파일들은 "폼 데이터"의 형태로 전송되기 때문에 이 작업이 필요합니다.
+
+///
## `File` 임포트
@@ -25,13 +28,19 @@
{!../../../docs_src/request_files/tutorial001.py!}
```
-!!! info "정보"
- `File` 은 `Form` 으로부터 직접 상속된 클래스입니다.
+/// info | "정보"
- 하지만 `fastapi`로부터 `Query`, `Path`, `File` 등을 임포트 할 때, 이것들은 특별한 클래스들을 반환하는 함수라는 것을 기억하기 바랍니다.
+`File` 은 `Form` 으로부터 직접 상속된 클래스입니다.
-!!! tip "팁"
- File의 본문을 선언할 때, 매개변수가 쿼리 매개변수 또는 본문(JSON) 매개변수로 해석되는 것을 방지하기 위해 `File` 을 사용해야합니다.
+하지만 `fastapi`로부터 `Query`, `Path`, `File` 등을 임포트 할 때, 이것들은 특별한 클래스들을 반환하는 함수라는 것을 기억하기 바랍니다.
+
+///
+
+/// tip | "팁"
+
+File의 본문을 선언할 때, 매개변수가 쿼리 매개변수 또는 본문(JSON) 매개변수로 해석되는 것을 방지하기 위해 `File` 을 사용해야합니다.
+
+///
파일들은 "폼 데이터"의 형태로 업로드 됩니다.
@@ -89,11 +98,17 @@ contents = await myfile.read()
contents = myfile.file.read()
```
-!!! note "`async` 기술적 세부사항"
- `async` 메소드들을 사용할 때 **FastAPI**는 스레드풀에서 파일 메소드들을 실행하고 그들을 기다립니다.
+/// note | "`async` 기술적 세부사항"
-!!! note "Starlette 기술적 세부사항"
- **FastAPI**의 `UploadFile` 은 **Starlette**의 `UploadFile` 을 직접적으로 상속받지만, **Pydantic** 및 FastAPI의 다른 부분들과의 호환성을 위해 필요한 부분들이 추가되었습니다.
+`async` 메소드들을 사용할 때 **FastAPI**는 스레드풀에서 파일 메소드들을 실행하고 그들을 기다립니다.
+
+///
+
+/// note | "Starlette 기술적 세부사항"
+
+**FastAPI**의 `UploadFile` 은 **Starlette**의 `UploadFile` 을 직접적으로 상속받지만, **Pydantic** 및 FastAPI의 다른 부분들과의 호환성을 위해 필요한 부분들이 추가되었습니다.
+
+///
## "폼 데이터"란
@@ -101,17 +116,23 @@ HTML의 폼들(``)이 서버에 데이터를 전송하는 방식은
**FastAPI**는 JSON 대신 올바른 위치에서 데이터를 읽을 수 있도록 합니다.
-!!! note "기술적 세부사항"
- 폼의 데이터는 파일이 포함되지 않은 경우 일반적으로 "미디어 유형" `application/x-www-form-urlencoded` 을 사용해 인코딩 됩니다.
+/// note | "기술적 세부사항"
- 하지만 파일이 포함된 경우, `multipart/form-data`로 인코딩됩니다. `File`을 사용하였다면, **FastAPI**는 본문의 적합한 부분에서 파일을 가져와야 한다는 것을 인지합니다.
+폼의 데이터는 파일이 포함되지 않은 경우 일반적으로 "미디어 유형" `application/x-www-form-urlencoded` 을 사용해 인코딩 됩니다.
- 인코딩과 폼 필드에 대해 더 알고싶다면, POST에 관한MDN웹 문서 를 참고하기 바랍니다,.
+하지만 파일이 포함된 경우, `multipart/form-data`로 인코딩됩니다. `File`을 사용하였다면, **FastAPI**는 본문의 적합한 부분에서 파일을 가져와야 한다는 것을 인지합니다.
-!!! warning "경고"
- 다수의 `File` 과 `Form` 매개변수를 한 *경로 작동*에 선언하는 것이 가능하지만, 요청의 본문이 `application/json` 가 아닌 `multipart/form-data` 로 인코딩 되기 때문에 JSON으로 받아야하는 `Body` 필드를 함께 선언할 수는 없습니다.
+인코딩과 폼 필드에 대해 더 알고싶다면, POST에 관한MDN웹 문서 를 참고하기 바랍니다,.
- 이는 **FastAPI**의 한계가 아니라, HTTP 프로토콜에 의한 것입니다.
+///
+
+/// warning | "경고"
+
+다수의 `File` 과 `Form` 매개변수를 한 *경로 작동*에 선언하는 것이 가능하지만, 요청의 본문이 `application/json` 가 아닌 `multipart/form-data` 로 인코딩 되기 때문에 JSON으로 받아야하는 `Body` 필드를 함께 선언할 수는 없습니다.
+
+이는 **FastAPI**의 한계가 아니라, HTTP 프로토콜에 의한 것입니다.
+
+///
## 다중 파일 업로드
@@ -127,17 +148,23 @@ HTML의 폼들(``)이 서버에 데이터를 전송하는 방식은
선언한대로, `bytes` 의 `list` 또는 `UploadFile` 들을 전송받을 것입니다.
-!!! note "참고"
- 2019년 4월 14일부터 Swagger UI가 하나의 폼 필드로 다수의 파일을 업로드하는 것을 지원하지 않습니다. 더 많은 정보를 원하면, #4276과 #3641을 참고하세요.
+/// note | "참고"
- 그럼에도, **FastAPI**는 표준 Open API를 사용해 이미 호환이 가능합니다.
+2019년 4월 14일부터 Swagger UI가 하나의 폼 필드로 다수의 파일을 업로드하는 것을 지원하지 않습니다. 더 많은 정보를 원하면, #4276과 #3641을 참고하세요.
- 따라서 Swagger UI 또는 기타 그 외의 OpenAPI를 지원하는 툴이 다중 파일 업로드를 지원하는 경우, 이들은 **FastAPI**와 호환됩니다.
+그럼에도, **FastAPI**는 표준 Open API를 사용해 이미 호환이 가능합니다.
-!!! note "기술적 세부사항"
- `from starlette.responses import HTMLResponse` 역시 사용할 수 있습니다.
+따라서 Swagger UI 또는 기타 그 외의 OpenAPI를 지원하는 툴이 다중 파일 업로드를 지원하는 경우, 이들은 **FastAPI**와 호환됩니다.
- **FastAPI**는 개발자의 편의를 위해 `fastapi.responses` 와 동일한 `starlette.responses` 도 제공합니다. 하지만 대부분의 응답들은 Starlette로부터 직접 제공됩니다.
+///
+
+/// note | "기술적 세부사항"
+
+`from starlette.responses import HTMLResponse` 역시 사용할 수 있습니다.
+
+**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 "정보"
- 파일과 폼 데이터를 함께, 또는 각각 업로드하기 위해 먼저 `python-multipart`를 설치해야합니다.
+/// info | "정보"
- 예 ) `pip install python-multipart`.
+파일과 폼 데이터를 함께, 또는 각각 업로드하기 위해 먼저 `python-multipart`를 설치해야합니다.
+
+예 ) `pip install python-multipart`.
+
+///
## `File` 및 `Form` 업로드
@@ -25,10 +28,13 @@
어떤 파일들은 `bytes`로, 또 어떤 파일들은 `UploadFile`로 선언할 수 있습니다.
-!!! warning "경고"
- 다수의 `File`과 `Form` 매개변수를 한 *경로 작동*에 선언하는 것이 가능하지만, 요청의 본문이 `application/json`가 아닌 `multipart/form-data`로 인코딩 되기 때문에 JSON으로 받아야하는 `Body` 필드를 함께 선언할 수는 없습니다.
+/// warning | "경고"
- 이는 **FastAPI**의 한계가 아니라, HTTP 프로토콜에 의한 것입니다.
+다수의 `File`과 `Form` 매개변수를 한 *경로 작동*에 선언하는 것이 가능하지만, 요청의 본문이 `application/json`가 아닌 `multipart/form-data`로 인코딩 되기 때문에 JSON으로 받아야하는 `Body` 필드를 함께 선언할 수는 없습니다.
+
+이는 **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()`의 `exclude_unset` 매개변수를 사용합니다.
+/// info | "정보"
-!!! info "정보"
- 아래 또한 사용할 수 있습니다:
+FastAPI는 이를 위해 Pydantic 모델의 `.dict()`의 `exclude_unset` 매개변수를 사용합니다.
- * `response_model_exclude_defaults=True`
- * `response_model_exclude_none=True`
+///
- Pydantic 문서에서 `exclude_defaults` 및 `exclude_none`에 대해 설명한 대로 사용할 수 있습니다.
+/// info | "정보"
+
+아래 또한 사용할 수 있습니다:
+
+* `response_model_exclude_defaults=True`
+* `response_model_exclude_none=True`
+
+Pydantic 문서에서 `exclude_defaults` 및 `exclude_none`에 대해 설명한 대로 사용할 수 있습니다.
+
+///
#### 기본값이 있는 필드를 갖는 값의 데이터
@@ -166,10 +181,13 @@ ID가 `baz`인 항목(items)처럼 기본값과 동일한 값을 갖는다면:
따라서 JSON 스키마에 포함됩니다.
-!!! tip "팁"
- `None` 뿐만 아니라 다른 어떤 것도 기본값이 될 수 있습니다.
+/// tip | "팁"
- 리스트(`[]`), `float`인 `10.5` 등이 될 수 있습니다.
+`None` 뿐만 아니라 다른 어떤 것도 기본값이 될 수 있습니다.
+
+리스트(`[]`), `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 | "팁"
- 이는 `set(["name", "description"])`과 동일합니다.
+문법 `{"name", "description"}`은 두 값을 갖는 `set`을 만듭니다.
+
+이는 `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 f92c057be..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 @@
-!!! note "참고"
- 어떤 응답 코드들은 해당 응답에 본문이 없다는 것을 의미하기도 합니다 (다음 항목 참고).
+/// note | "참고"
- 이에 따라 FastAPI는 응답 본문이 없음을 명시하는 OpenAPI를 생성합니다.
+어떤 응답 코드들은 해당 응답에 본문이 없다는 것을 의미하기도 합니다 (다음 항목 참고).
+
+이에 따라 FastAPI는 응답 본문이 없음을 명시하는 OpenAPI를 생성합니다.
+
+///
## HTTP 상태 코드에 대하여
-!!! note "참고"
- 만약 HTTP 상태 코드에 대하여 이미 알고있다면, 다음 항목으로 넘어가십시오.
+/// note | "참고"
+
+만약 HTTP 상태 코드에 대하여 이미 알고있다면, 다음 항목으로 넘어가십시오.
+
+///
HTTP는 세자리의 숫자 상태 코드를 응답의 일부로 전송합니다.
@@ -43,19 +55,22 @@ HTTP는 세자리의 숫자 상태 코드를 응답의 일부로 전송합니다
요약하자면:
-* `**1xx**` 상태 코드는 "정보"용입니다. 이들은 직접적으로는 잘 사용되지는 않습니다. 이 상태 코드를 갖는 응답들은 본문을 가질 수 없습니다.
-* `**2xx**` 상태 코드는 "성공적인" 응답을 위해 사용됩니다. 가장 많이 사용되는 유형입니다.
+* `1xx` 상태 코드는 "정보"용입니다. 이들은 직접적으로는 잘 사용되지는 않습니다. 이 상태 코드를 갖는 응답들은 본문을 가질 수 없습니다.
+* **`2xx`** 상태 코드는 "성공적인" 응답을 위해 사용됩니다. 가장 많이 사용되는 유형입니다.
* `200` 은 디폴트 상태 코드로, 모든 것이 "성공적임"을 의미합니다.
* 다른 예로는 `201` "생성됨"이 있습니다. 일반적으로 데이터베이스에 새로운 레코드를 생성한 후 사용합니다.
* 단, `204` "내용 없음"은 특별한 경우입니다. 이것은 클라이언트에게 반환할 내용이 없는 경우 사용합니다. 따라서 응답은 본문을 가질 수 없습니다.
-* `**3xx**` 상태 코드는 "리다이렉션"용입니다. 본문을 가질 수 없는 `304` "수정되지 않음"을 제외하고, 이 상태 코드를 갖는 응답에는 본문이 있을 수도, 없을 수도 있습니다.
-* `**4xx**` 상태 코드는 "클라이언트 오류" 응답을 위해 사용됩니다. 이것은 아마 가장 많이 사용하게 될 두번째 유형입니다.
+* **`3xx`** 상태 코드는 "리다이렉션"용입니다. 본문을 가질 수 없는 `304` "수정되지 않음"을 제외하고, 이 상태 코드를 갖는 응답에는 본문이 있을 수도, 없을 수도 있습니다.
+* **`4xx`** 상태 코드는 "클라이언트 오류" 응답을 위해 사용됩니다. 이것은 아마 가장 많이 사용하게 될 두번째 유형입니다.
* 일례로 `404` 는 "찾을 수 없음" 응답을 위해 사용합니다.
* 일반적인 클라이언트 오류의 경우 `400` 을 사용할 수 있습니다.
-* `**5xx**` 상태 코드는 서버 오류에 사용됩니다. 이것들을 직접 사용할 일은 거의 없습니다. 응용 프로그램 코드나 서버의 일부에서 문제가 발생하면 자동으로 이들 상태 코드 중 하나를 반환합니다.
+* `5xx` 상태 코드는 서버 오류에 사용됩니다. 이것들을 직접 사용할 일은 거의 없습니다. 응용 프로그램 코드나 서버의 일부에서 문제가 발생하면 자동으로 이들 상태 코드 중 하나를 반환합니다.
-!!! tip "팁"
- 각각의 상태 코드와 이들이 의미하는 내용에 대해 더 알고싶다면 MDN HTTP 상태 코드에 관한 문서 를 확인하십시오.
+/// tip | "팁"
+
+각각의 상태 코드와 이들이 의미하는 내용에 대해 더 알고싶다면 MDN HTTP 상태 코드에 관한 문서 를 확인하십시오.
+
+///
## 이름을 기억하는 쉬운 방법
@@ -79,10 +94,13 @@ HTTP는 세자리의 숫자 상태 코드를 응답의 일부로 전송합니다
-!!! note "기술적 세부사항"
- `from starlette import status` 역시 사용할 수 있습니다.
+/// note | "기술적 세부사항"
- **FastAPI**는 개발자인 당신의 편의를 위해 `fastapi.status` 와 동일한 `starlette.status` 도 제공합니다. 하지만 이것은 Starlette로부터 직접 제공됩니다.
+`from starlette import status` 역시 사용할 수 있습니다.
+
+**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에서 Pydantic 공식 문서: Model Config에 나와 있는 것처럼 `dict`를 받는 `model_config` 어트리뷰트를 사용할 것입니다.
+Pydantic 버전 2에서 Pydantic 공식 문서: Model Config에 나와 있는 것처럼 `dict`를 받는 `model_config` 어트리뷰트를 사용할 것입니다.
- `"json_schema_extra"`를 생성된 JSON 스키마에서 보여주고 싶은 별도의 데이터와 `examples`를 포함하는 `dict`으로 설정할 수 있습니다.
+`"json_schema_extra"`를 생성된 JSON 스키마에서 보여주고 싶은 별도의 데이터와 `examples`를 포함하는 `dict`으로 설정할 수 있습니다.
-=== "Pydantic v1"
+////
- Pydantic v1에서 Pydantic 공식 문서: Schema customization에서 설명하는 것처럼, 내부 클래스인 `Config`와 `schema_extra`를 사용할 것입니다.
+//// tab | Pydantic v1
- `schema_extra`를 생성된 JSON 스키마에서 보여주고 싶은 별도의 데이터와 `examples`를 포함하는 `dict`으로 설정할 수 있습니다.
+Pydantic v1에서 Pydantic 공식 문서: Schema customization에서 설명하는 것처럼, 내부 클래스인 `Config`와 `schema_extra`를 사용할 것입니다.
-!!! tip "팁"
- JSON 스키마를 확장하고 여러분의 별도의 자체 데이터를 추가하기 위해 같은 기술을 사용할 수 있습니다.
+`schema_extra`를 생성된 JSON 스키마에서 보여주고 싶은 별도의 데이터와 `examples`를 포함하는 `dict`으로 설정할 수 있습니다.
- 예를 들면, 프론트엔드 사용자 인터페이스에 메타데이터를 추가하는 등에 사용할 수 있습니다.
+////
-!!! info "정보"
- (FastAPI 0.99.0부터 쓰이기 시작한) OpenAPI 3.1.0은 **JSON 스키마** 표준의 일부인 `examples`에 대한 지원을 추가했습니다.
+/// tip | "팁"
- 그 전에는, 하나의 예제만 가능한 `example` 키워드만 지원했습니다. 이는 아직 OpenAPI 3.1.0에서 지원하지만, 지원이 종료될 것이며 JSON 스키마 표준에 포함되지 않습니다. 그렇기에 `example`을 `examples`으로 이전하는 것을 추천합니다. 🤓
+JSON 스키마를 확장하고 여러분의 별도의 자체 데이터를 추가하기 위해 같은 기술을 사용할 수 있습니다.
- 이 문서 끝에 더 많은 읽을거리가 있습니다.
+예를 들면, 프론트엔드 사용자 인터페이스에 메타데이터를 추가하는 등에 사용할 수 있습니다.
+
+///
+
+/// 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!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="4 10-13"
- {!> ../../../docs_src/schema_extra_example/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+
+```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!}
- ```
+```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!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="23-38"
+{!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!}
+```
- ```Python hl_lines="24-39"
- {!> ../../../docs_src/schema_extra_example/tutorial004_an.py!}
- ```
+////
-=== "Python 3.10+ Annotated가 없는 경우"
+//// tab | Python 3.8+
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+```Python hl_lines="24-39"
+{!> ../../../docs_src/schema_extra_example/tutorial004_an.py!}
+```
- ```Python hl_lines="19-34"
- {!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!}
- ```
+////
-=== "Python 3.8+ Annotated가 없는 경우"
+//// tab | Python 3.10+ Annotated가 없는 경우
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+/// tip | "팁"
- ```Python hl_lines="21-36"
- {!> ../../../docs_src/schema_extra_example/tutorial004.py!}
- ```
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
+
+///
+
+```Python hl_lines="19-34"
+{!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ Annotated가 없는 경우
+
+/// tip | "팁"
+
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
+
+///
+
+```Python hl_lines="21-36"
+{!> ../../../docs_src/schema_extra_example/tutorial004.py!}
+```
+
+////
이와 같이 하면 이 예제는 그 본문 데이터를 위한 내부 **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!}
- ```
+```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!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="23-49"
+{!> ../../../docs_src/schema_extra_example/tutorial005_an_py39.py!}
+```
- ```Python hl_lines="24-50"
- {!> ../../../docs_src/schema_extra_example/tutorial005_an.py!}
- ```
+////
-=== "Python 3.10+ Annotated가 없는 경우"
+//// tab | Python 3.8+
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+```Python hl_lines="24-50"
+{!> ../../../docs_src/schema_extra_example/tutorial005_an.py!}
+```
- ```Python hl_lines="19-45"
- {!> ../../../docs_src/schema_extra_example/tutorial005_py310.py!}
- ```
+////
-=== "Python 3.8+ Annotated가 없는 경우"
+//// tab | Python 3.10+ Annotated가 없는 경우
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+/// tip | "팁"
- ```Python hl_lines="21-47"
- {!> ../../../docs_src/schema_extra_example/tutorial005.py!}
- ```
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
+
+///
+
+```Python hl_lines="19-45"
+{!> ../../../docs_src/schema_extra_example/tutorial005_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ Annotated가 없는 경우
+
+/// tip | "팁"
+
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
+
+///
+
+```Python hl_lines="21-47"
+{!> ../../../docs_src/schema_extra_example/tutorial005.py!}
+```
+
+////
### 문서 UI에서의 OpenAPI 예시
@@ -257,17 +327,23 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를
## 기술적 세부 사항
-!!! tip "팁"
- 이미 **FastAPI**의 **0.99.0 혹은 그 이상** 버전을 사용하고 있다면, 이 세부 사항을 **스킵**해도 상관 없을 것입니다.
+/// tip | "팁"
- 세부 사항은 OpenAPI 3.1.0이 사용가능하기 전, 예전 버전과 더 관련있습니다.
+이미 **FastAPI**의 **0.99.0 혹은 그 이상** 버전을 사용하고 있다면, 이 세부 사항을 **스킵**해도 상관 없을 것입니다.
- 간략한 OpenAPI와 JSON 스키마 **역사 강의**로 생각할 수 있습니다. 🤓
+세부 사항은 OpenAPI 3.1.0이 사용가능하기 전, 예전 버전과 더 관련있습니다.
-!!! warning "경고"
- 표준 **JSON 스키마**와 **OpenAPI**에 대한 아주 기술적인 세부사항입니다.
+간략한 OpenAPI와 JSON 스키마 **역사 강의**로 생각할 수 있습니다. 🤓
- 만약 위의 생각이 작동한다면, 그것으로 충분하며 이 세부 사항은 필요없을 것이니, 마음 편하게 스킵하셔도 됩니다.
+///
+
+/// warning | "경고"
+
+표준 **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 | "정보"
- 이로인해, FastAPI 0.99.0 이전 버전은 아직 OpenAPI 3.1.0 보다 낮은 버전을 사용했습니다.
+더 쉽고 새로운 JSON 스키마와의 통합과 함께 OpenAPI 3.1.0가 배포되었지만, 잠시동안 자동 문서 생성을 제공하는 도구인 Swagger UI는 OpenAPI 3.1.0을 지원하지 않았습니다 (5.0.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 5bc2cee7a..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!}
+```
-=== "파이썬 3.10 이상"
+////
- ```Python hl_lines="3 10-14"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+//// tab | 파이썬 3.10 이상
+
+```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!}
+```
-=== "파이썬 3.10 이상"
+////
- ```Python hl_lines="23"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+//// tab | 파이썬 3.10 이상
+
+```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!}
+```
-=== "파이썬 3.10 이상"
+////
- ```Python hl_lines="17-20 24-25"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+//// tab | 파이썬 3.10 이상
+
+```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!}
+```
-=== "파이썬 3.10 이상"
+////
- ```Python hl_lines="29"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+//// tab | 파이썬 3.10 이상
+
+```Python hl_lines="29"
+{!> ../../../docs_src/security/tutorial002_py310.py!}
+```
+
+////
Pydantic 모델인 `User`로 `current_user`의 타입을 선언하는 것을 알아야 합니다.
이것은 모든 완료 및 타입 검사를 통해 함수 내부에서 우리를 도울 것입니다.
-!!! 팁
- 요청 본문도 Pydantic 모델로 선언된다는 것을 기억할 것입니다.
+/// tip | "팁"
- 여기서 **FastAPI**는 `Depends`를 사용하고 있기 때문에 혼동되지 않습니다.
+요청 본문도 Pydantic 모델로 선언된다는 것을 기억할 것입니다.
-!!! 확인
- 이 의존성 시스템이 설계된 방식은 모두 `User` 모델을 반환하는 다양한 의존성(다른 "의존적인")을 가질 수 있도록 합니다.
+여기서 **FastAPI**는 `Depends`를 사용하고 있기 때문에 혼동되지 않습니다.
- 해당 타입의 데이터를 반환할 수 있는 의존성이 하나만 있는 것으로 제한되지 않습니다.
+///
+
+/// 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!}
+```
-=== "파이썬 3.10 이상"
+////
- ```Python hl_lines="28-30"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+//// tab | 파이썬 3.10 이상
+
+```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
new file mode 100644
index 000000000..9593f96f5
--- /dev/null
+++ b/docs/ko/docs/tutorial/security/simple-oauth2.md
@@ -0,0 +1,359 @@
+# 패스워드와 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`의 의존성으로 사용합니다.
+
+//// tab | 파이썬 3.7 이상
+
+```Python hl_lines="4 76"
+{!> ../../../docs_src/security/tutorial003.py!}
+```
+
+////
+
+//// tab | 파이썬 3.10 이상
+
+```Python hl_lines="2 74"
+{!> ../../../docs_src/security/tutorial003_py310.py!}
+```
+
+////
+
+`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` 예외를 사용합니다:
+
+//// tab | 파이썬 3.7 이상
+
+```Python hl_lines="3 77-79"
+{!> ../../../docs_src/security/tutorial003.py!}
+```
+
+////
+
+//// tab | 파이썬 3.10 이상
+
+```Python hl_lines="1 75-77"
+{!> ../../../docs_src/security/tutorial003_py310.py!}
+```
+
+////
+
+### 패스워드 확인하기
+
+이 시점에서 데이터베이스의 사용자 데이터 형식을 확인했지만 암호를 확인하지 않았습니다.
+
+먼저 데이터를 Pydantic `UserInDB` 모델에 넣겠습니다.
+
+일반 텍스트 암호를 저장하면 안 되니 (가짜) 암호 해싱 시스템을 사용합니다.
+
+두 패스워드가 일치하지 않으면 동일한 오류가 반환됩니다.
+
+#### 패스워드 해싱
+
+"해싱"은 일부 콘텐츠(이 경우 패스워드)를 횡설수설하는 것처럼 보이는 일련의 바이트(문자열)로 변환하는 것을 의미합니다.
+
+정확히 동일한 콘텐츠(정확히 동일한 패스워드)를 전달할 때마다 정확히 동일한 횡설수설이 발생합니다.
+
+그러나 횡설수설에서 암호로 다시 변환할 수는 없습니다.
+
+##### 패스워드 해싱을 사용해야 하는 이유
+
+데이터베이스가 유출된 경우 해커는 사용자의 일반 텍스트 암호가 아니라 해시만 갖게 됩니다.
+
+따라서 해커는 다른 시스템에서 동일한 암호를 사용하려고 시도할 수 없습니다(많은 사용자가 모든 곳에서 동일한 암호를 사용하므로 이는 위험할 수 있습니다).
+
+//// tab | P파이썬 3.7 이상
+
+```Python hl_lines="80-83"
+{!> ../../../docs_src/security/tutorial003.py!}
+```
+
+////
+
+//// tab | 파이썬 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`을 토큰으로 반환합니다.
+
+/// 팁
+
+다음 장에서는 패스워드 해싱 및 JWT 토큰을 사용하여 실제 보안 구현을 볼 수 있습니다.
+
+하지만 지금은 필요한 세부 정보에 집중하겠습니다.
+
+///
+
+//// tab | 파이썬 3.7 이상
+
+```Python hl_lines="85"
+{!> ../../../docs_src/security/tutorial003.py!}
+```
+
+////
+
+//// tab | 파이썬 3.10 이상
+
+```Python hl_lines="83"
+{!> ../../../docs_src/security/tutorial003_py310.py!}
+```
+
+////
+
+/// 팁
+
+사양에 따라 이 예제와 동일하게 `access_token` 및 `token_type`이 포함된 JSON을 반환해야 합니다.
+
+이는 코드에서 직접 수행해야 하며 해당 JSON 키를 사용해야 합니다.
+
+사양을 준수하기 위해 스스로 올바르게 수행하기 위해 거의 유일하게 기억해야 하는 것입니다.
+
+나머지는 **FastAPI**가 처리합니다.
+
+///
+
+## 의존성 업데이트하기
+
+이제 의존성을 업데이트를 할 겁니다.
+
+이 사용자가 활성화되어 있는 *경우에만* `current_user`를 가져올 겁니다.
+
+따라서 `get_current_user`를 의존성으로 사용하는 추가 종속성 `get_current_active_user`를 만듭니다.
+
+이러한 의존성 모두, 사용자가 존재하지 않거나 비활성인 경우 HTTP 오류를 반환합니다.
+
+따라서 엔드포인트에서는 사용자가 존재하고 올바르게 인증되었으며 활성 상태인 경우에만 사용자를 얻습니다:
+
+//// 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!}
+```
+
+////
+
+/// 정보
+
+여기서 반환하는 값이 `Bearer`인 추가 헤더 `WWW-Authenticate`도 사양의 일부입니다.
+
+모든 HTTP(오류) 상태 코드 401 "UNAUTHORIZED"는 `WWW-Authenticate` 헤더도 반환해야 합니다.
+
+베어러 토큰의 경우(지금의 경우) 해당 헤더의 값은 `Bearer`여야 합니다.
+
+실제로 추가 헤더를 건너뛸 수 있으며 여전히 작동합니다.
+
+그러나 여기에서는 사양을 준수하도록 제공됩니다.
+
+또한 이를 예상하고 (현재 또는 미래에) 사용하는 도구가 있을 수 있으며, 현재 또는 미래에 자신 혹은 자신의 유저들에게 유용할 것입니다.
+
+그것이 표준의 이점입니다 ...
+
+///
+
+## 확인하기
+
+대화형 문서 열기: http://127.0.0.1:8000/docs.
+
+### 인증하기
+
+"Authorize" 버튼을 눌러봅시다.
+
+자격 증명을 사용합니다.
+
+유저명: `johndoe`
+
+패스워드: `secret`
+
+
+
+시스템에서 인증하면 다음과 같이 표시됩니다:
+
+
+
+### 자신의 유저 데이터 가져오기
+
+이제 `/users/me` 경로에 `GET` 작업을 진행합시다.
+
+다음과 같은 사용자 데이터를 얻을 수 있습니다:
+
+```JSON
+{
+ "username": "johndoe",
+ "email": "johndoe@example.com",
+ "full_name": "John Doe",
+ "disabled": false,
+ "hashed_password": "fakehashedsecret"
+}
+```
+
+
+
+잠금 아이콘을 클릭하고 로그아웃한 다음 동일한 작업을 다시 시도하면 다음과 같은 HTTP 401 오류가 발생합니다.
+
+```JSON
+{
+ "detail": "Not authenticated"
+}
+```
+
+### 비활성된 유저
+
+이제 비활성된 사용자로 시도하고, 인증해봅시다:
+
+유저명: `alice`
+
+패스워드: `secret2`
+
+그리고 `/users/me` 경로와 함께 `GET` 작업을 사용해 봅시다.
+
+다음과 같은 "Inactive user" 오류가 발생합니다:
+
+```JSON
+{
+ "detail": "Inactive user"
+}
+```
+
+## 요약
+
+이제 API에 대한 `username` 및 `password`를 기반으로 완전한 보안 시스템을 구현할 수 있는 도구가 있습니다.
+
+이러한 도구를 사용하여 보안 시스템을 모든 데이터베이스 및 모든 사용자 또는 데이터 모델과 호환되도록 만들 수 있습니다.
+
+유일한 오점은 아직 실제로 "안전"하지 않다는 것입니다.
+
+다음 장에서는 안전한 패스워드 해싱 라이브러리와 JWT 토큰을 사용하는 방법을 살펴보겠습니다.
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 3d02a8741..4daad5e90 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 📝
@@ -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): https://github.com/tiangolo/fastapi. ⭐️
+Możesz "dodać gwiazdkę" FastAPI na GitHubie (klikając przycisk gwiazdki w prawym górnym rogu): https://github.com/fastapi/fastapi. ⭐️
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): https://github.com/tiangolo/fastapi. 👀
+Możesz "obserwować" FastAPI na GitHubie (klikając przycisk "obserwuj" w prawym górnym rogu): https://github.com/fastapi/fastapi. 👀
Wybierz opcję "Tylko wydania".
@@ -59,7 +59,7 @@ Możesz:
## Napisz tweeta o **FastAPI**
-Napisz tweeta o **FastAPI** i powiedz czemu Ci się podoba. 🎉
+Napisz tweeta o **FastAPI** 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,12 +73,12 @@ 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:
-* Dyskusjach na GitHubie
-* Problemach na GitHubie
+* Dyskusjach na GitHubie
+* Problemach na GitHubie
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. 🤗
@@ -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): https://github.com/tiangolo/fastapi. 👀
+Możesz "obserwować" FastAPI na GitHubie (klikając przycisk "obserwuj" w prawym górnym rogu): https://github.com/fastapi/fastapi. 👀
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 utworzyć nowe pytanie w repozytorium na GitHubie, na przykład aby:
+Możesz utworzyć nowe pytanie w repozytorium na GitHubie, na przykład aby:
* Zadać **pytanie** lub zapytać o **problem**.
* Zaproponować nową **funkcję**.
@@ -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.
@@ -196,7 +199,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, edytując ten plik.
+* Podzielić się artykułem, filmem lub podcastem, który stworzyłeś lub znalazłeś na temat FastAPI, edytując ten plik.
* 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.
@@ -215,8 +218,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,10 +229,13 @@ Jeśli możesz mi w tym pomóc, **pomożesz mi utrzymać FastAPI** i zapewnisz
Dołącz do 👥 serwera czatu na Discordzie 👥 i spędzaj czas z innymi w społeczności FastAPI.
-!!! wskazówka
- Jeśli masz pytania, zadaj je w Dyskusjach na GitHubie, jest dużo większa szansa, że otrzymasz pomoc od [Ekspertów FastAPI](fastapi-people.md#experts){.internal-link target=_blank}.
+/// tip | "Wskazówka"
- Używaj czatu tylko do innych ogólnych rozmów.
+Jeśli masz pytania, zadaj je w Dyskusjach na GitHubie, jest dużo większa szansa, że otrzymasz pomoc od [Ekspertów FastAPI](fastapi-people.md#fastapi-experts){.internal-link target=_blank}.
+
+Używaj czatu tylko do innych ogólnych rozmów.
+
+///
### Nie zadawaj pytań na czacie
@@ -237,7 +243,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..e591e1c9d 100644
--- a/docs/pl/docs/index.md
+++ b/docs/pl/docs/index.md
@@ -1,3 +1,9 @@
+# FastAPI
+
+
+
@@ -5,11 +11,11 @@
FastAPI to szybki, prosty w nauce i gotowy do użycia w produkcji framework
-
-
+
+
-
-
+
+
@@ -20,11 +26,11 @@
**Dokumentacja**: https://fastapi.tiangolo.com
-**Kod żródłowy**: https://github.com/tiangolo/fastapi
+**Kod żródłowy**: https://github.com/fastapi/fastapi
---
-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:
@@ -60,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._"
-
email_validator - dla walidacji adresów email.
+* email-validator - dla walidacji adresów email.
Używane przez Starlette:
@@ -446,12 +450,12 @@ Używane przez Starlette:
* itsdangerous - Wymagany dla wsparcia `SessionMiddleware`.
* pyyaml - Wymagane dla wsparcia `SchemaGenerator` z Starlette (z FastAPI prawdopodobnie tego nie potrzebujesz).
* graphene - Wymagane dla wsparcia `GraphQLApp`.
-* ujson - Wymagane jeżeli chcesz korzystać z `UJSONResponse`.
Używane przez FastAPI / Starlette:
* uvicorn - jako serwer, który ładuje i obsługuje Twoją aplikację.
* orjson - Wymagane jeżeli chcesz używać `ORJSONResponse`.
+* ujson - Wymagane jeżeli chcesz korzystać z `UJSONResponse`.
Możesz zainstalować wszystkie te aplikacje przy pomocy `pip install fastapi[all]`.
diff --git a/docs/pl/docs/tutorial/first-steps.md b/docs/pl/docs/tutorial/first-steps.md
index 9406d703d..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
get
-!!! info "`@decorator` Info"
- Składnia `@something` jest w Pythonie nazywana "dekoratorem".
+/// info | "`@decorator` Info"
- Umieszczasz to na szczycie funkcji. Jak ładną ozdobną czapkę (chyba stąd wzięła się nazwa).
+Składnia `@something` jest w Pythonie nazywana "dekoratorem".
- "Dekorator" przyjmuje funkcję znajdującą się poniżej jego i coś z nią robi.
+Umieszczasz to na szczycie funkcji. Jak ładną ozdobną czapkę (chyba stąd wzięła się nazwa).
- W naszym przypadku dekorator mówi **FastAPI**, że poniższa funkcja odpowiada **ścieżce** `/` z **operacją** `get`.
+"Dekorator" przyjmuje funkcję znajdującą się poniżej jego i coś z nią robi.
- Jest to "**dekorator operacji na ścieżce**".
+W naszym przypadku dekorator mówi **FastAPI**, że poniższa funkcja odpowiada **ścieżce** `/` z **operacją** `get`.
+
+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
- **FastAPI** nie narzuca żadnego konkretnego znaczenia.
+Możesz dowolnie używać każdej operacji (metody HTTP).
- Informacje tutaj są przedstawione jako wskazówka, a nie wymóg.
+**FastAPI** nie narzuca żadnego konkretnego znaczenia.
- Na przykład, używając GraphQL, normalnie wykonujesz wszystkie akcje używając tylko operacji `POST`.
+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`.
+
+///
### 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/#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
+```
- ```
- pip install "uvicorn[standard]"
- ```
+Zainstaluj też `uvicorn`, który będzie służył jako serwer:
- Tak samo możesz zainstalować wszystkie dodatkowe biblioteki, których chcesz użyć.
+```
+pip install "uvicorn[standard]"
+```
+
+Tak samo możesz zainstalować wszystkie dodatkowe biblioteki, których chcesz użyć.
+
+///
## Zaawansowany poradnik
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/advanced/additional-responses.md b/docs/pt/docs/advanced/additional-responses.md
new file mode 100644
index 000000000..c27301b61
--- /dev/null
+++ b/docs/pt/docs/advanced/additional-responses.md
@@ -0,0 +1,255 @@
+# 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:
+
+
+
+## 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:
+
+* Objeto de Retorno OpenAPI, inclui o `Response Object`.
+* Objeto de Retorno OpenAPI, 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`.
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..a0869f342
--- /dev/null
+++ b/docs/pt/docs/advanced/additional-status-codes.md
@@ -0,0 +1,91 @@
+# 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:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="4 25"
+{!> ../../../docs_src/additional_status_codes/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="4 25"
+{!> ../../../docs_src/additional_status_codes/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="4 26"
+{!> ../../../docs_src/additional_status_codes/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip | "Dica"
+
+Faça uso da versão `Annotated` quando possível.
+
+///
+
+```Python hl_lines="2 23"
+{!> ../../../docs_src/additional_status_codes/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "Dica"
+
+Faça uso da versão `Annotated` quando possível.
+
+///
+
+```Python hl_lines="4 25"
+{!> ../../../docs_src/additional_status_codes/tutorial001.py!}
+```
+
+////
+
+/// 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}.
diff --git a/docs/pt/docs/advanced/advanced-dependencies.md b/docs/pt/docs/advanced/advanced-dependencies.md
new file mode 100644
index 000000000..5a7b921b2
--- /dev/null
+++ b/docs/pt/docs/advanced/advanced-dependencies.md
@@ -0,0 +1,177 @@
+# 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__`:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="12"
+{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="11"
+{!> ../../../docs_src/dependencies/tutorial011_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "Dica"
+
+Prefira utilizar a versão `Annotated` se possível.
+
+///
+
+```Python hl_lines="10"
+{!> ../../../docs_src/dependencies/tutorial011.py!}
+```
+
+////
+
+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:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="8"
+{!> ../../../docs_src/dependencies/tutorial011_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "Dica"
+
+Prefira utilizar a versão `Annotated` se possível.
+
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/dependencies/tutorial011.py!}
+```
+
+////
+
+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:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="18"
+{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="17"
+{!> ../../../docs_src/dependencies/tutorial011_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "Dica"
+
+Prefira utilizar a versão `Annotated` se possível.
+
+///
+
+```Python hl_lines="16"
+{!> ../../../docs_src/dependencies/tutorial011.py!}
+```
+
+////
+
+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`:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="22"
+{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="21"
+{!> ../../../docs_src/dependencies/tutorial011_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "Dica"
+
+Prefira utilizar a versão `Annotated` se possível.
+
+///
+
+```Python hl_lines="20"
+{!> ../../../docs_src/dependencies/tutorial011.py!}
+```
+
+////
+
+/// 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.
+
+///
diff --git a/docs/pt/docs/advanced/async-tests.md b/docs/pt/docs/advanced/async-tests.md
new file mode 100644
index 000000000..ab5bfa648
--- /dev/null
+++ b/docs/pt/docs/advanced/async-tests.md
@@ -0,0 +1,107 @@
+# 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 HTTPX, 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:
+
+
+
+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 http://127.0.0.1:9999/api/v1/docs:
+
+
+
+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 http://127.0.0.1:9999/api/v1/docs parecerá:
+
+
+
+/// 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/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 um dos frameworks Python mais rápidos disponíveis, ficando atrás apenas do Starlette e Uvicorn (utilizado internamente pelo FastAPI).
+
+Porém, ao verificar benchmarks e comparações você deve prestar atenção ao seguinte:
+
+## Benchmarks e velocidade
+
+Quando você verifica os benchmarks, é comum ver diversas ferramentas de diferentes tipos comparados como se fossem equivalentes.
+
+Especificamente, para ver o Uvicorn, Starlette e FastAPI comparados entre si (entre diversas outras ferramentas).
+
+Quanto mais simples o problema resolvido pela ferramenta, melhor será a performance. E a maioria das análises não testa funcionalidades adicionais que são oferecidas pela ferramenta.
+
+A hierarquia é:
+
+* **Uvicorn**: um servidor ASGI
+ * **Starlette**: (utiliza Uvicorn) um microframework web
+ * **FastAPI**: (utiliza Starlette) um microframework para APIs com diversas funcionalidades adicionais para a construção de APIs, com validação de dados, etc.
+
+* **Uvicorn**:
+ * Terá a melhor performance, pois não possui muito código além do próprio servidor.
+ * Você não escreveria uma aplicação utilizando o Uvicorn diretamente. Isso significaria que o seu código teria que incluir pelo menos todo o código fornecido pelo Starlette (ou o **FastAPI**). E caso você fizesse isso, a sua aplicação final teria a mesma sobrecarga que teria se utilizasse um framework, minimizando o código e os bugs.
+ * Se você está comparando o Uvicorn, compare com os servidores de aplicação Daphne, Hypercorn, uWSGI, etc.
+* **Starlette**:
+ * Terá o melhor desempenho, depois do Uvicorn. Na verdade, o Starlette utiliza o Uvicorn para rodar. Portanto, ele pode ficar mais "devagar" que o Uvicorn apenas por ter que executar mais código.
+ * Mas ele fornece as ferramentas para construir aplicações web simples, com roteamento baseado em caminhos, etc.
+ * Se você está comparando o Starlette, compare-o com o Sanic, Flask, Django, etc. Frameworks web (ou microframeworks).
+* **FastAPI**:
+ * Da mesma forma que o Starlette utiliza o Uvicorn e não consegue ser mais rápido que ele, o **FastAPI** utiliza o Starlette, portanto, ele não consegue ser mais rápido que ele.
+ * O FastAPI provê mais funcionalidades em cima do Starlette. Funcionalidades que você quase sempre precisará quando estiver construindo APIs, como validação de dados e serialização. E ao utilizá-lo, você obtém documentação automática sem custo nenhum (a documentação automática sequer adiciona sobrecarga nas aplicações rodando, pois ela é gerada na inicialização).
+ * Caso você não utilize o FastAPI e faz uso do Starlette diretamente (ou outra ferramenta, como o Sanic, Flask, Responder, etc) você mesmo teria que implementar toda a validação de dados e serialização. Então, a sua aplicação final ainda teria a mesma sobrecarga caso estivesse usando o FastAPI. E em muitos casos, validação de dados e serialização é a maior parte do código escrito em aplicações.
+ * Então, ao utilizar o FastAPI, você está economizando tempo de programação, evitando bugs, linhas de código, e provavelmente terá a mesma performance (ou até melhor) do que teria caso você não o utilizasse (já que você teria que implementar tudo no seu código).
+ * Se você está comparando o FastAPI, compare-o com frameworks de aplicações web (ou conjunto de ferramentas) que oferecem validação de dados, serialização e documentação, como por exemplo o Flask-apispec, NestJS, Molten, etc. Frameworks que possuem validação integrada de dados, serialização e documentação.
diff --git a/docs/pt/docs/advanced/events.md b/docs/pt/docs/advanced/events.md
index 7f6cb6f5d..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"
- Você provavelmente pode pular essa parte.
+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.
+
+///
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"
-!!! tip "Dica"
- Perceba que nesse caso nós estamos usando a função padrão do Python `open()` que interage com um arquivo.
+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.
- 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`.
+/// tip | "Dica"
- Então, nós declaramos uma função de manipulação de evento com o padrão `def` ao invés de `async def`.
+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.
+
+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,11 +165,14 @@ Só um detalhe técnico para nerds curiosos. 🤓
Por baixo, na especificação técnica ASGI, essa é a parte do Protocolo Lifespan, e define eventos chamados `startup` e `shutdown`.
-!!! info "Informação"
- Você pode ler mais sobre o manipulador `lifespan` do Starlette na Documentação do Lifespan Starlette.
+/// info | "Informação"
- Incluindo como manipular estado do lifespan que pode ser usado em outras áreas do seu código.
+Você pode ler mais sobre o manipulador `lifespan` do Starlette na Documentação do Lifespan Starlette.
+
+Incluindo como manipular estado do lifespan que pode ser usado em outras áreas do seu código.
+
+///
## 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/advanced/index.md b/docs/pt/docs/advanced/index.md
index 7e276f732..2569fc914 100644
--- a/docs/pt/docs/advanced/index.md
+++ b/docs/pt/docs/advanced/index.md
@@ -2,18 +2,21 @@
## 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.
-!!! 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
-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/advanced/openapi-webhooks.md b/docs/pt/docs/advanced/openapi-webhooks.md
new file mode 100644
index 000000000..2ccd0e819
--- /dev/null
+++ b/docs/pt/docs/advanced/openapi-webhooks.md
@@ -0,0 +1,57 @@
+# 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é http://127.0.0.1:8000/docs.
+
+Você verá que a sua documentação possui as *operações de rota* normais e agora também possui alguns **webhooks**:
+
+
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á.
diff --git a/docs/pt/docs/advanced/settings.md b/docs/pt/docs/advanced/settings.md
new file mode 100644
index 000000000..db2b4c9cc
--- /dev/null
+++ b/docs/pt/docs/advanced/settings.md
@@ -0,0 +1,566 @@
+# 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 variável de ambiente (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:
+
+//// tab | Linux, macOS, Windows Bash
+
+
+
+E então, abra a documentação para a sub-aplicação, em http://127.0.0.1:8000/subapi/docs.
+
+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`:
+
+
+
+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}.
diff --git a/docs/pt/docs/advanced/templates.md b/docs/pt/docs/advanced/templates.md
new file mode 100644
index 000000000..6d231b3c2
--- /dev/null
+++ b/docs/pt/docs/advanced/templates.md
@@ -0,0 +1,126 @@
+# 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:
+
+
-
-
+
+
-
-
+
+
@@ -20,11 +26,11 @@
**Documentação**: https://fastapi.tiangolo.com
-**Código fonte**: https://github.com/tiangolo/fastapi
+**Código fonte**: https://github.com/fastapi/fastapi
---
-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:
@@ -60,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**.*"
-
email_validator - para validação de email.
+* email-validator - para validação de email.
Usados por Starlette:
@@ -440,12 +444,12 @@ Usados por Starlette:
* itsdangerous - Necessário para suporte a `SessionMiddleware`.
* pyyaml - Necessário para suporte a `SchemaGenerator` da Starlette (você provavelmente não precisará disso com o FastAPI).
* graphene - Necessário para suporte a `GraphQLApp`.
-* ujson - Necessário se você quer utilizar `UJSONResponse`.
Usados por FastAPI / Starlette:
* uvicorn - para o servidor que carrega e serve sua aplicação.
* orjson - Necessário se você quer utilizar `ORJSONResponse`.
+* ujson - Necessário se você quer utilizar `UJSONResponse`.
Você pode instalar todas essas dependências com `pip install fastapi[all]`.
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/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: **FastAPI** Python:
+* _Backend_ **FastAPI** Python:
* **Rápido**: Alta performance, no nível de **NodeJS** e **Go** (graças ao Starlette e Pydantic).
* **Intuitivo**: Ótimo suporte de editor. _Auto-Complete_ 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/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"
- Nesse caso, `str` é o parâmetro de tipo passado para `List`.
+Esses tipos internos entre colchetes são chamados de "parâmetros de tipo".
+
+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 Pydantic, verifique seus documentos .
+/// info | "Informação"
+
+Para saber mais sobre o Pydantic, verifique seus documentos .
+
+///
**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 "cheat sheet" do `mypy` .
+/// info | "Informação"
+
+Se você já passou por todo o tutorial e voltou para ver mais sobre os tipos, um bom recurso é a "cheat sheet" do `mypy` .
+
+///
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. ✈️
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`.
+
+
+
+## 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.
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"
- E `Field` do Pydantic retorna uma instância de `FieldInfo` também.
+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.
- `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`.
+E `Field` do Pydantic retorna uma instância de `FieldInfo` também.
- Lembre-se que quando você importa `Query`, `Path`, e outros de `fastapi`, esse são na realidade funções que retornam classes especiais.
+`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"
- 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`.
+Lembre-se que quando você importa `Query`, `Path`, e outros de `fastapi`, esse são na realidade funções que retornam classes especiais.
+
+///
+
+/// 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 0eaa9664c..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+"
+////
- ```Python hl_lines="19-21"
- {!> ../../../docs_src/body_multiple_params/tutorial001.py!}
- ```
+//// tab | Python 3.8+
-!!! nota
- Repare que, neste caso, o `item` que seria capturado a partir do corpo é opcional. Visto que ele possui `None` como valor padrão.
+```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.
+
+///
## 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
}
```
-!!! 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!}
- ```
+```Python hl_lines="26"
+{!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004.py!}
- ```
+//// tab | Python 3.8+
-!!! 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.
+```Python hl_lines="27"
+{!> ../../../docs_src/body_multiple_params/tutorial004.py!}
+```
+
+////
+
+/// 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!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="17"
- {!> ../../../docs_src/body_multiple_params/tutorial005.py!}
- ```
+//// tab | Python 3.8+
+
+```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 e039b09b2..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:
}
```
-!!! 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!}
```
-!!! 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!}
```
-!!! Dica
- Leve em condideração que o JSON só suporta `str` como chaves.
+/// tip | "Dica"
- Mas o Pydantic tem conversão automática de dados.
+Leve em condideração que o JSON só suporta `str` como chaves.
- 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.
+Mas o Pydantic tem conversão automática de dados.
- E o `dict` que você recebe como `weights` terá, na verdade, chaves `int` e valores` float`.
+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`.
+
+///
## Recapitulação
diff --git a/docs/pt/docs/tutorial/body.md b/docs/pt/docs/tutorial/body.md
index 5901b8414..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 Pydantic 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
-!!! tip "Dica"
- Se você utiliza o PyCharm como editor, você pode utilizar o Plugin do Pydantic para o PyCharm .
+/// tip | "Dica"
- Melhora o suporte do editor para seus modelos Pydantic com::
+Se você utiliza o PyCharm como editor, você pode utilizar o Plugin do Pydantic para o PyCharm .
- * completação automática
- * verificação de tipos
- * refatoração
- * buscas
- * inspeções
+Melhora o suporte do editor para seus modelos Pydantic com::
+
+* completação automática
+* verificação de tipos
+* refatoração
+* buscas
+* inspeções
+
+///
## Use o modelo
@@ -155,11 +161,14 @@ 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 `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 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.
+
+///
## 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/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
new file mode 100644
index 000000000..e5e2f8c27
--- /dev/null
+++ b/docs/pt/docs/tutorial/cors.md
@@ -0,0 +1,87 @@
+# CORS (Cross-Origin Resource Sharing)
+
+CORS ou "Cross-Origin Resource Sharing" 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 requisições CORS simples.
+* `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 CORS, acesse Mozilla CORS documentation.
+
+/// 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/dependencies/classes-as-dependencies.md b/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md
new file mode 100644
index 000000000..420503b87
--- /dev/null
+++ b/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md
@@ -0,0 +1,638 @@
+# 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"):
+
+//// tab | Python 3.10+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="11"
+{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="12"
+{!> ../../../docs_src/dependencies/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python hl_lines="11"
+{!> ../../../docs_src/dependencies/tutorial001.py!}
+```
+
+////
+
+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`:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="11-15"
+{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="11-15"
+{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="12-16"
+{!> ../../../docs_src/dependencies/tutorial002_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python hl_lines="9-13"
+{!> ../../../docs_src/dependencies/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python hl_lines="11-15"
+{!> ../../../docs_src/dependencies/tutorial002.py!}
+```
+
+////
+
+Observe o método `__init__` usado para criar uma instância da classe:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="12"
+{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="12"
+{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="13"
+{!> ../../../docs_src/dependencies/tutorial002_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python hl_lines="10"
+{!> ../../../docs_src/dependencies/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python hl_lines="12"
+{!> ../../../docs_src/dependencies/tutorial002.py!}
+```
+
+////
+
+...ele possui os mesmos parâmetros que nosso `common_parameters` anterior:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="8"
+{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/dependencies/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python hl_lines="6"
+{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/dependencies/tutorial001.py!}
+```
+
+////
+
+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.
+
+//// tab | Python 3.10+
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="20"
+{!> ../../../docs_src/dependencies/tutorial002_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python hl_lines="17"
+{!> ../../../docs_src/dependencies/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial002.py!}
+```
+
+////
+
+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:
+
+//// tab | Python 3.8+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | 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:
+
+//// tab | Python 3.8+
+
+```Python
+commons: Annotated[CommonQueryParams, ...
+```
+
+////
+
+//// tab | 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:
+
+//// tab | Python 3.8+
+
+```Python
+commons: Annotated[Any, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python
+commons = Depends(CommonQueryParams)
+```
+
+////
+
+...como em:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial003_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial003_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="20"
+{!> ../../../docs_src/dependencies/tutorial003_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python hl_lines="17"
+{!> ../../../docs_src/dependencies/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial003.py!}
+```
+
+////
+
+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`.
+
+
+
+## Pegando um Atalho
+
+Mas você pode ver que temos uma repetição do código neste exemplo, escrevendo `CommonQueryParams` duas vezes:
+
+//// tab | Python 3.8+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | 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:
+
+//// tab | Python 3.8+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
+
+...escreva:
+
+//// tab | Python 3.8+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends()]
+```
+
+////
+
+//// tab | 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:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial004_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial004_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="20"
+{!> ../../../docs_src/dependencies/tutorial004_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python hl_lines="17"
+{!> ../../../docs_src/dependencies/tutorial004_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial004.py!}
+```
+
+////
+
+...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.
+
+///
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..4a7a29390
--- /dev/null
+++ b/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
@@ -0,0 +1,183 @@
+# 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()`:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="18"
+{!> ../../../docs_src/dependencies/tutorial006_an.py!}
+```
+
+////
+
+//// tab | Python 3.8 non-Annotated
+
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível
+
+///
+
+```Python hl_lines="17"
+{!> ../../../docs_src/dependencies/tutorial006.py!}
+```
+
+////
+
+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:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="8 13"
+{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="7 12"
+{!> ../../../docs_src/dependencies/tutorial006_an.py!}
+```
+
+////
+
+//// tab | Python 3.8 non-Annotated
+
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível
+
+///
+
+```Python hl_lines="6 11"
+{!> ../../../docs_src/dependencies/tutorial006.py!}
+```
+
+////
+
+### Levantando exceções
+
+Essas dependências podem levantar exceções, da mesma forma que dependências comuns:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="10 15"
+{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9 14"
+{!> ../../../docs_src/dependencies/tutorial006_an.py!}
+```
+
+////
+
+//// tab | Python 3.8 non-Annotated
+
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível
+
+///
+
+```Python hl_lines="8 13"
+{!> ../../../docs_src/dependencies/tutorial006.py!}
+```
+
+////
+
+### 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:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="11 16"
+{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="10 15"
+{!> ../../../docs_src/dependencies/tutorial006_an.py!}
+```
+
+////
+
+//// tab | Python 3.8 non-Annotated
+
+/// tip | "Dica"
+
+
+
+///
+
+ Utilize a versão com `Annotated` se possível
+
+```Python hl_lines="9 14"
+{!> ../../../docs_src/dependencies/tutorial006.py!}
+```
+
+////
+
+## 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*.
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..16c2cf899
--- /dev/null
+++ b/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md
@@ -0,0 +1,425 @@
+# Dependências com yield
+
+O FastAPI possui suporte para dependências que realizam alguns passos extras ao finalizar.
+
+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:
+
+* `@contextlib.contextmanager` ou
+* `@contextlib.asynccontextmanager`
+
+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`:
+
+//// tab | python 3.9+
+
+```python hl_lines="6 14 22"
+{!> ../../../docs_src/dependencies/tutorial008_an_py39.py!}
+```
+
+////
+
+//// tab | python 3.8+
+
+```python hl_lines="5 13 21"
+{!> ../../../docs_src/dependencies/tutorial008_an.py!}
+```
+
+////
+
+//// tab | python 3.8+ non-annotated
+
+/// tip | "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.
+
+//// tab | python 3.9+
+
+```python hl_lines="18-19 26-27"
+{!> ../../../docs_src/dependencies/tutorial008_an_py39.py!}
+```
+
+////
+
+//// tab | python 3.8+
+
+```python hl_lines="17-18 25-26"
+{!> ../../../docs_src/dependencies/tutorial008_an.py!}
+```
+
+////
+
+//// tab | python 3.8+ non-annotated
+
+/// tip | "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 gerenciadores de contexto 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. 🤓
+
+///
+
+//// 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 | "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:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="15-16"
+{!> ../../../docs_src/dependencies/tutorial008c_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="14-15"
+{!> ../../../docs_src/dependencies/tutorial008c_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-annotated
+
+/// tip | "dica"
+
+utilize a versão com `Annotated` se possível.
+
+///
+
+```Python hl_lines="13-14"
+{!> ../../../docs_src/dependencies/tutorial008c.py!}
+```
+
+////
+
+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`:
+
+//// 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 | "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, você pode utilizar `with` para ler um arquivo:
+
+```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 criar uma classe com dois métodos: `__enter__()` e `__exit__()`.
+
+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:
+
+* `@contextlib.contextmanager` ou
+
+* `@contextlib.asynccontextmanager`
+
+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.
+
+///
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..96dbaee5e
--- /dev/null
+++ b/docs/pt/docs/tutorial/dependencies/global-dependencies.md
@@ -0,0 +1,43 @@
+# 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:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="16"
+{!> ../../../docs_src/dependencies/tutorial012_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="16"
+{!> ../../../docs_src/dependencies/tutorial012_an.py!}
+```
+
+////
+
+//// tab | Python 3.8 non-Annotated
+
+/// tip | "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*.
diff --git a/docs/pt/docs/tutorial/dependencies/index.md b/docs/pt/docs/tutorial/dependencies/index.md
new file mode 100644
index 000000000..f7b32966c
--- /dev/null
+++ b/docs/pt/docs/tutorial/dependencies/index.md
@@ -0,0 +1,422 @@
+# Dependências
+
+O **FastAPI** possui um poderoso, mas intuitivo sistema de **Injeção de Dependência**.
+
+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*:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="8-9"
+{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="8-11"
+{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9-12"
+{!> ../../../docs_src/dependencies/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python hl_lines="6-7"
+{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python hl_lines="8-11"
+{!> ../../../docs_src/dependencies/tutorial001.py!}
+```
+
+////
+
+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`
+
+//// tab | Python 3.10+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/dependencies/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python hl_lines="1"
+{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python hl_lines="3"
+{!> ../../../docs_src/dependencies/tutorial001.py!}
+```
+
+////
+
+### Declarando a dependência, no "dependente"
+
+Da mesma forma que você utiliza `Body`, `Query`, etc. Como parâmetros de sua *função de operação de rota*, utilize `Depends` com um novo parâmetro:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="13 18"
+{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="15 20"
+{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="16 21"
+{!> ../../../docs_src/dependencies/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python hl_lines="11 16"
+{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python hl_lines="15 20"
+{!> ../../../docs_src/dependencies/tutorial001.py!}
+```
+
+////
+
+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:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="12 16 21"
+{!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="14 18 23"
+{!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="15 19 24"
+{!> ../../../docs_src/dependencies/tutorial001_02_an.py!}
+```
+
+////
+
+/// 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:
+
+
+
+## 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.
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..279bf3339
--- /dev/null
+++ b/docs/pt/docs/tutorial/dependencies/sub-dependencies.md
@@ -0,0 +1,255 @@
+# 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:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="8-9"
+{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="8-9"
+{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9-10"
+{!> ../../../docs_src/dependencies/tutorial005_an.py!}
+```
+
+////
+
+//// tab | Python 3.10 non-Annotated
+
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python hl_lines="6-7"
+{!> ../../../docs_src/dependencies/tutorial005_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8 non-Annotated
+
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python hl_lines="8-9"
+{!> ../../../docs_src/dependencies/tutorial005.py!}
+```
+
+////
+
+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):
+
+//// tab | Python 3.10+
+
+```Python hl_lines="13"
+{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="13"
+{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="14"
+{!> ../../../docs_src/dependencies/tutorial005_an.py!}
+```
+
+////
+
+//// tab | Python 3.10 non-Annotated
+
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python hl_lines="11"
+{!> ../../../docs_src/dependencies/tutorial005_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8 non-Annotated
+
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python hl_lines="13"
+{!> ../../../docs_src/dependencies/tutorial005.py!}
+```
+
+////
+
+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:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="23"
+{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="23"
+{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="24"
+{!> ../../../docs_src/dependencies/tutorial005_an.py!}
+```
+
+////
+
+//// tab | Python 3.10 non-Annotated
+
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial005_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8 non-Annotated
+
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python hl_lines="22"
+{!> ../../../docs_src/dependencies/tutorial005.py!}
+```
+
+////
+
+/// 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 "cache" 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`:
+
+//// tab | Python 3.8+
+
+```Python hl_lines="1"
+async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]):
+ return {"fresh_value": fresh_value}
+```
+
+////
+
+//// tab | Python 3.8+ 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.
+
+///
diff --git a/docs/pt/docs/tutorial/encoder.md b/docs/pt/docs/tutorial/encoder.md
index b9bfbf63b..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.
-!!! 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!}
+```
-=== "Python 3.10 and above"
+////
- ```Python hl_lines="7 13-14 17-18 21-22"
- {!> ../../../docs_src/extra_models/tutorial002_py310.py!}
- ```
+//// tab | Python 3.10 and above
+
+```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 `typing.Union`:
-!!! note
- Ao definir um `Union`, 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
-=== "Python 3.8 and above"
+Ao definir um `Union`, 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 hl_lines="1 14-15 18-20 33"
- {!> ../../../docs_src/extra_models/tutorial003.py!}
- ```
+///
-=== "Python 3.10 and above"
+//// tab | Python 3.8 and above
- ```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.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!}
+```
-=== "Python 3.9 and above"
+////
- ```Python hl_lines="6"
- {!> ../../../docs_src/extra_models/tutorial005_py39.py!}
- ```
+//// tab | Python 3.9 and above
+
+```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 9fcdaf91f..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
get
-!!! 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"
- O **FastAPI** não impõe nenhum significado específico.
+Você está livre para usar cada operação (método HTTP) como desejar.
- As informações aqui são apresentadas como uma orientação, não uma exigência.
+O **FastAPI** não impõe nenhum significado específico.
- Por exemplo, ao usar GraphQL, você normalmente executa todas as ações usando apenas operações `POST`.
+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`.
+
+///
### 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!}
```
-!!! 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"
- **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`.
+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`.
+
+///
## 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 `ValidationError` 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"
- **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.
+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.
+
+///
### 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!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="3"
- {!> ../../../docs_src/header_params/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```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!}
- ```
+```Python hl_lines="7"
+{!> ../../../docs_src/header_params/tutorial001_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial001.py!}
- ```
+//// tab | Python 3.8+
-!!! note "Detalhes Técnicos"
- `Header` é uma classe "irmã" de `Path`, `Query` e `Cookie`. Ela também herda da mesma classe em comum `Param`.
+```Python hl_lines="9"
+{!> ../../../docs_src/header_params/tutorial001.py!}
+```
- 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.
+////
-!!! info
- Para declarar headers, você precisa usar `Header`, caso contrário, os parâmetros seriam interpretados como parâmetros de consulta.
+/// note | "Detalhes Técnicos"
+
+`Header` é uma classe "irmã" de `Path`, `Query` e `Cookie`. Ela também herda da mesma classe em comum `Param`.
+
+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.
+
+///
+
+/// 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!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/header_params/tutorial002.py!}
- ```
+//// tab | Python 3.8+
-!!! 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.
+```Python hl_lines="10"
+{!> ../../../docs_src/header_params/tutorial002.py!}
+```
+
+////
+
+/// 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!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial003_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="9"
+{!> ../../../docs_src/header_params/tutorial003_py39.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial003.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```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 5fc0485a0..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.
-!!! 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
+```
- ```
- pip install "uvicorn[standard]"
- ```
+Também instale o `uvicorn` para funcionar como servidor:
- E o mesmo para cada dependência opcional que você quiser usar.
+```
+pip install "uvicorn[standard]"
+```
+
+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
new file mode 100644
index 000000000..1760246ee
--- /dev/null
+++ b/docs/pt/docs/tutorial/middleware.md
@@ -0,0 +1,70 @@
+# 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 usando o prefixo 'X-'.
+
+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 Documentos CORS da Starlette.
+
+///
+
+/// 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 CORS com um middleware na próxima seção.
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!}
+```
-=== "Python 3.9 and above"
+////
- ```Python hl_lines="3 17"
- {!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!}
- ```
+//// tab | Python 3.9 and above
-=== "Python 3.10 and above"
+```Python hl_lines="3 17"
+{!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!}
+```
- ```Python hl_lines="1 15"
- {!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!}
- ```
+////
+
+//// tab | Python 3.10 and above
+
+```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"
- **FastAPI** fornece o mesmo `starlette.status` como `fastapi.status` apenas como uma conveniência para você, o desenvolvedor. Mas vem diretamente do Starlette.
+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.
+
+///
## 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"
+////
- ```Python hl_lines="17 22 27"
- {!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!}
- ```
+//// tab | Python 3.9 and above
-=== "Python 3.10 and above"
+```Python hl_lines="17 22 27"
+{!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!}
+```
- ```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!}
+```
-=== "Python 3.9 and above"
+////
- ```Python hl_lines="20-21"
- {!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!}
- ```
+//// tab | Python 3.9 and above
-=== "Python 3.10 and above"
+```Python hl_lines="20-21"
+{!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!}
+```
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!}
- ```
+////
+
+//// tab | Python 3.10 and above
+
+```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 Markdown 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!}
+```
-=== "Python 3.9 and above"
+////
- ```Python hl_lines="19-27"
- {!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!}
- ```
+//// tab | Python 3.9 and above
-=== "Python 3.10 and above"
+```Python hl_lines="19-27"
+{!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!}
+```
- ```Python hl_lines="17-25"
- {!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!}
- ```
+////
+
+//// tab | Python 3.10 and above
+
+```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!}
- ```
+```Python hl_lines="21"
+{!> ../../../docs_src/path_operation_configuration/tutorial005.py!}
+```
-=== "Python 3.9 and above"
+////
- ```Python hl_lines="21"
- {!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!}
- ```
+//// tab | Python 3.9 and above
-=== "Python 3.10 and above"
+```Python hl_lines="21"
+{!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!}
+```
- ```Python hl_lines="19"
- {!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!}
- ```
+////
-!!! info "Informação"
- Note que `response_description` se refere especificamente à resposta, a `description` se refere à *operação de rota* em geral.
+//// tab | Python 3.10 and above
-!!! check
- OpenAPI especifica que cada *operação de rota* requer uma descrição de resposta.
+```Python hl_lines="19"
+{!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!}
+```
- Então, se você não fornecer uma, o **FastAPI** irá gerar automaticamente uma de "Resposta bem-sucedida".
+////
+
+/// info | "Informação"
+
+Note que `response_description` se refere especificamente à resposta, a `description` se refere à *operação de rota* em geral.
+
+///
+
+/// 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".
+
+///
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+"
+////
- ```Python hl_lines="3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```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+
-!!! note "Nota"
- Um parâmetro de rota é sempre obrigatório, como se fizesse parte da rota.
+```Python hl_lines="10"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
+```
- 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.
+/// 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.
+
+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"
- Todas elas compartilham os mesmos parâmetros para validação adicional e metadados que você viu.
+`Query`, `Path` e outras classes que você verá a frente são subclasses de uma classe comum `Param`.
-!!! note "Detalhes Técnicos"
- Quando você importa `Query`, `Path` e outras de `fastapi`, elas são na verdade funções.
+Todas elas compartilham os mesmos parâmetros para validação adicional e metadados que você viu.
- 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`.
+/// note | "Detalhes Técnicos"
- 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.
+Quando você importa `Query`, `Path` e outras de `fastapi`, elas são na verdade funções.
- Dessa maneira você pode user seu editor e ferramentas de desenvolvimento sem precisar adicionar configurações customizadas para ignorar estes erros.
+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`.
+
+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.
+
+///
diff --git a/docs/pt/docs/tutorial/path-params.md b/docs/pt/docs/tutorial/path-params.md
index be2b7f7a4..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 dados
@@ -35,7 +40,12 @@ Se você rodar esse exemplo e abrir o seu navegador em "parsing" 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: http://127.0.0.1:8000/items/4.2
-!!! 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
-!!! 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 +151,18 @@ Assim, crie atributos de classe com valores fixos, que serão os valores válido
{!../../../docs_src/path_params/tutorial005.py!}
```
-!!! informação
- Enumerations (ou enums) estão disponíveis no Python desde a versão 3.4.
+/// info | "informação"
+
+Enumerations (ou enums) estão disponíveis no Python desde a versão 3.4.
+
+///
+
+/// tip | "Dica"
+
+
+
+///
-!!! dica
Se você está se perguntando, "AlexNet", "ResNet", e "LeNet" são apenas nomes de modelos 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!}
```
-!!! conselho
+/// 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!}
```
-!!! 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)
+```
- O `Union` é apenas para permitir que seu editor de texto lhe dê um melhor suporte.
+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.
+
+///
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 parte do Python e é chamado "Ellipsis".
+/// info | "Informação"
+
+Se você nunca viu os `...` antes: é um valor único especial, faz parte do Python e é chamado "Ellipsis".
+
+///
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"
- 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.
+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.
+
+///
Você pode adicionar um `title`:
diff --git a/docs/pt/docs/tutorial/query-params.md b/docs/pt/docs/tutorial/query-params.md
index 08bb99dbc..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!}
+```
-=== "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!}
+```
+
+////
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!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params/tutorial003.py!}
- ```
+//// tab | Python 3.8+
+
+```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+"
+////
- ```Python hl_lines="8 10"
- {!> ../../../docs_src/query_params/tutorial004.py!}
- ```
+//// tab | Python 3.8+
+
+```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!}
+```
-=== "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!}
+```
+
+////
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#predefined-values){.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 `python-multipart`.
+/// info | "Informação"
- Por exemplo: `pip install python-multipart`.
+Para receber arquivos carregados e/ou dados de formulário, primeiro instale `python-multipart`.
+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"
- Isso não é uma limitação do **FastAPI** , é parte do protocolo HTTP.
+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.
+
+///
## 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 `python-multipart`.
+/// info | "Informação"
- Ex: `pip install python-multipart`.
+Para usar formulários, primeiro instale `python-multipart`.
+
+Ex: `pip install python-multipart`.
+
+///
## Importe `Form`
@@ -29,11 +32,17 @@ A spec exige que os campos sejam exatamente
Com `Form` você pode declarar os mesmos metadados e validação que com `Body` (e `Query`, `Path`, `Cookie`).
-!!! info "Informação"
- `Form` é uma classe que herda diretamente de `Body`.
+/// info | "Informação"
-!!! 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).
+`Form` é uma classe que herda diretamente de `Body`.
+
+///
+
+/// 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).
+
+///
## Sobre "Campos de formulário"
@@ -41,17 +50,23 @@ A forma como os formulários HTML (``) enviam os dados para o servi
O **FastAPI** fará a leitura desses dados no lugar certo em vez de JSON.
-!!! note "Detalhes técnicos"
- Os dados dos formulários são normalmente codificados usando o "tipo de mídia" `application/x-www-form-urlencoded`.
+/// note | "Detalhes técnicos"
- 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.
+Os dados dos formulários são normalmente codificados usando o "tipo de mídia" `application/x-www-form-urlencoded`.
- Se você quiser ler mais sobre essas codificações e campos de formulário, vá para o MDN web docs para POST.
+ 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"
- 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`.
+Se você quiser ler mais sobre essas codificações e campos de formulário, vá para o MDN web docs para POST.
- Esta não é uma limitação do **FastAPI**, é parte do protocolo HTTP.
+///
+
+/// 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.
+
+///
## Recapitulando
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 `python-multipart`.
+
+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 semelhante a arquivos `async`.
+* Ela expõe um objeto python `SpooledTemporaryFile` 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 `SpooledTemporaryFile` (um objeto file-like). 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(``) 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 MDN sobre POST .
+
+///
+
+/// warning | Aviso
+
+Você pode declarar múltiplos parâmetros `File` e `Form` em uma *operação de rota*, mas você não pode declarar campos `Body`que 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.
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 `http.HTTPStatus`.
+/// info | "Informação"
+
+`status_code` também pode receber um `IntEnum`, como o do Python `http.HTTPStatus`.
+
+///
Dessa forma:
@@ -27,15 +33,21 @@ Dessa forma:
-!!! note "Nota"
- Alguns códigos de resposta (consulte a próxima seção) indicam que a resposta não possui um corpo.
+/// note | "Nota"
- O FastAPI sabe disso e produzirá documentos OpenAPI informando que não há corpo de resposta.
+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.
+
+///
## 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 MDN documentação sobre códigos de status HTTP.
+/// tip | "Dica"
+
+Para saber mais sobre cada código de status e qual código serve para quê, verifique o MDN documentação sobre códigos de status HTTP.
+
+///
## 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
-!!! note "Detalhes técnicos"
- Você também pode usar `from starlette import status`.
+/// note | "Detalhes técnicos"
- **FastAPI** fornece o mesmo `starlette.status` como `fastapi.status` apenas como uma conveniência para você, o desenvolvedor. Mas vem diretamente da Starlette.
+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.
+
+///
## 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"
- 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.
+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.
+
+///
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 395621d3b..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
-!!! informação
+/// info | "informação"
+
+
+
+///
+
Primeiro, instale `python-multipart`.
Ex: `pip install python-multipart`.
@@ -52,7 +57,12 @@ Você verá algo deste tipo:
-!!! 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 +71,12 @@ E se você clicar, você terá um pequeno formulário de autorização para digi
-!!! 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`.
-!!! 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!}
```
-!!! 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.
-!!! 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).
-!!! 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/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"
- 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ê.
+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ê.
+
+///
## **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/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: внутреннее устройство, повлиявшие технологии и всё такое прочее. 🤓
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 с пользовательским веб-интерфейсом.
+
+///
### Flask
@@ -56,11 +62,13 @@ Flask часто используется и для приложений, кот
Простота Flask, показалась мне подходящей для создания API.
Но ещё нужно было найти "Django REST Framework" для Flask.
-!!! check "Идеи для **FastAPI**"
- Это будет микрофреймворк. К нему легко будет добавить необходимые инструменты и части.
+/// check | "Идеи для **FastAPI**"
- Должна быть простая и лёгкая в использовании система маршрутизации запросов.
+Это будет микрофреймворк. К нему легко будет добавить необходимые инструменты и части.
+Должна быть простая и лёгкая в использовании система маршрутизации запросов.
+
+///
### Requests
@@ -100,11 +108,13 @@ def read_url():
Глядите, как похоже `requests.get(...)` и `@app.get(...)`.
-!!! check "Идеи для **FastAPI**"
- * Должен быть простой и понятный API.
- * Нужно использовать названия HTTP-методов (операций) для упрощения понимания происходящего.
- * Должны быть разумные настройки по умолчанию и широкие возможности их кастомизации.
+/// check | "Идеи для **FastAPI**"
+* Должен быть простой и понятный API.
+* Нужно использовать названия HTTP-методов (операций) для упрощения понимания происходящего.
+* Должны быть разумные настройки по умолчанию и широкие возможности их кастомизации.
+
+///
### Swagger / OpenAPI
@@ -119,16 +129,19 @@ def read_url():
Вот почему, когда говорят о версии 2.0, обычно говорят "Swagger", а для версии 3+ "OpenAPI".
-!!! check "Идеи для **FastAPI**"
- Использовать открытые стандарты для спецификаций API вместо самодельных схем.
+/// check | "Идеи для **FastAPI**"
- Совместимость с основанными на стандартах пользовательскими интерфейсами:
+Использовать открытые стандарты для спецификаций API вместо самодельных схем.
- * Swagger UI
- * ReDoc
+Совместимость с основанными на стандартах пользовательскими интерфейсами:
- Они были выбраны за популярность и стабильность.
- Но сделав беглый поиск, Вы можете найти десятки альтернативных пользовательских интерфейсов для OpenAPI, которые Вы можете использовать с **FastAPI**.
+* Swagger UI
+* ReDoc
+
+Они были выбраны за популярность и стабильность.
+Но сделав беглый поиск, Вы можете найти десятки альтернативных пользовательских интерфейсов для OpenAPI, которые Вы можете использовать с **FastAPI**.
+
+///
### REST фреймворки для Flask
@@ -152,8 +165,11 @@ def read_url():
Итак, чтобы определить каждую схему,
Вам нужно использовать определенные утилиты и классы, предоставляемые Marshmallow.
-!!! check "Идея для **FastAPI**"
- Использовать код программы для автоматического создания "схем", определяющих типы данных и их проверку.
+/// check | "Идея для **FastAPI**"
+
+Использовать код программы для автоматического создания "схем", определяющих типы данных и их проверку.
+
+///
### Webargs
@@ -165,11 +181,17 @@ Webargs - это инструмент, который был создан для
Это превосходный инструмент и я тоже часто пользовался им до **FastAPI**.
-!!! info "Информация"
- Webargs бы создан разработчиками Marshmallow.
+/// info | "Информация"
-!!! check "Идея для **FastAPI**"
- Должна быть автоматическая проверка входных данных.
+Webargs бы создан разработчиками Marshmallow.
+
+///
+
+/// check | "Идея для **FastAPI**"
+
+Должна быть автоматическая проверка входных данных.
+
+///
### APISpec
@@ -190,11 +212,17 @@ Marshmallow и Webargs осуществляют проверку, анализ
Редактор кода не особо может помочь в такой парадигме.
А изменив какие-то параметры или схемы для Marshmallow можно забыть отредактировать докстринг с YAML и сгенерированная схема становится недействительной.
-!!! info "Информация"
- APISpec тоже был создан авторами Marshmallow.
+/// info | "Информация"
-!!! check "Идея для **FastAPI**"
- Необходима поддержка открытого стандарта для API - OpenAPI.
+APISpec тоже был создан авторами Marshmallow.
+
+///
+
+/// check | "Идея для **FastAPI**"
+
+Необходима поддержка открытого стандарта для API - OpenAPI.
+
+///
### Flask-apispec
@@ -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 должна создаваться автоматически и использовать тот же код, который осуществляет сериализацию и проверку данных.
+
+///
### NestJS (и Angular)
@@ -242,25 +276,34 @@ Marshmallow и Webargs осуществляют проверку, анализ
Кроме того, он не очень хорошо справляется с вложенными моделями.
Если в запросе имеется объект JSON, внутренние поля которого, в свою очередь, являются вложенными объектами JSON, это не может быть должным образом задокументировано и проверено.
-!!! check "Идеи для **FastAPI** "
- Нужно использовать подсказки типов, чтоб воспользоваться поддержкой редактора кода.
+/// check | "Идеи для **FastAPI** "
- Нужна мощная система внедрения зависимостей. Необходим способ для уменьшения повторов кода.
+Нужно использовать подсказки типов, чтоб воспользоваться поддержкой редактора кода.
+
+Нужна мощная система внедрения зависимостей. Необходим способ для уменьшения повторов кода.
+
+///
### Sanic
Sanic был одним из первых чрезвычайно быстрых Python-фреймворков основанных на `asyncio`.
Он был сделан очень похожим на Flask.
-!!! note "Технические детали"
- В нём использован `uvloop` вместо стандартного цикла событий `asyncio`, что и сделало его таким быстрым.
+/// note | "Технические детали"
- Он явно вдохновил создателей Uvicorn и Starlette, которые в настоящее время быстрее Sanic в открытых бенчмарках.
+В нём использован `uvloop` вместо стандартного цикла событий `asyncio`, что и сделало его таким быстрым.
-!!! check "Идеи для **FastAPI**"
- Должна быть сумасшедшая производительность.
+Он явно вдохновил создателей Uvicorn и Starlette, которые в настоящее время быстрее Sanic в открытых бенчмарках.
- Для этого **FastAPI** основан на Starlette, самом быстром из доступных фреймворков (по замерам незаинтересованных лиц).
+///
+
+/// check | "Идеи для **FastAPI**"
+
+Должна быть сумасшедшая производительность.
+
+Для этого **FastAPI** основан на Starlette, самом быстром из доступных фреймворков (по замерам незаинтересованных лиц).
+
+///
### Falcon
@@ -275,12 +318,15 @@ Falcon - ещё один высокопроизводительный Python-ф
Либо эти функции должны быть встроены во фреймворк, сконструированный поверх Falcon, как в Hug.
Такая же особенность присутствует и в других фреймворках, вдохновлённых идеей Falcon, использовать только один объект запроса и один объект ответа.
-!!! check "Идея для **FastAPI**"
- Найдите способы добиться отличной производительности.
+/// check | "Идея для **FastAPI**"
- Объявлять параметры `ответа сервера` в функциях, как в Hug.
+Найдите способы добиться отличной производительности.
- Хотя в FastAPI это необязательно и используется в основном для установки заголовков, куки и альтернативных кодов состояния.
+Объявлять параметры `ответа сервера` в функциях, как в Hug.
+
+Хотя в FastAPI это необязательно и используется в основном для установки заголовков, куки и альтернативных кодов состояния.
+
+///
### Molten
@@ -302,11 +348,14 @@ Molten мне попался на начальной стадии написан
Это больше похоже на Django, чем на Flask и Starlette.
Он разделяет в коде вещи, которые довольно тесно связаны.
-!!! check "Идея для **FastAPI**"
- Определить дополнительные проверки типов данных, используя значения атрибутов модели "по умолчанию".
- Это улучшает помощь редактора и раньше это не было доступно в Pydantic.
+/// check | "Идея для **FastAPI**"
- Фактически это подтолкнуло на обновление Pydantic для поддержки одинакового стиля проверок (теперь этот функционал уже доступен в Pydantic).
+Определить дополнительные проверки типов данных, используя значения атрибутов модели "по умолчанию".
+Это улучшает помощь редактора и раньше это не было доступно в Pydantic.
+
+Фактически это подтолкнуло на обновление Pydantic для поддержки одинакового стиля проверок (теперь этот функционал уже доступен в Pydantic).
+
+///
### Hug
@@ -325,15 +374,21 @@ Hug был одним из первых фреймворков, реализов
Поскольку он основан на WSGI, старом стандарте для синхронных веб-фреймворков, он не может работать с веб-сокетами и другими модными штуками, но всё равно обладает высокой производительностью.
-!!! info "Информация"
- Hug создан Timothy Crosley, автором `isort`, отличного инструмента для автоматической сортировки импортов в Python-файлах.
+/// info | "Информация"
-!!! check "Идеи для **FastAPI**"
- Hug повлиял на создание некоторых частей APIStar и был одним из инструментов, которые я счел наиболее многообещающими, наряду с APIStar.
+Hug создан Timothy Crosley, автором `isort`, отличного инструмента для автоматической сортировки импортов в Python-файлах.
- Hug натолкнул на мысли использовать в **FastAPI** подсказки типов Python для автоматического создания схемы, определяющей API и его параметры.
+///
- Hug вдохновил **FastAPI** объявить параметр `ответа` в функциях для установки заголовков и куки.
+/// check | "Идеи для **FastAPI**"
+
+Hug повлиял на создание некоторых частей APIStar и был одним из инструментов, которые я счел наиболее многообещающими, наряду с APIStar.
+
+Hug натолкнул на мысли использовать в **FastAPI** подсказки типов Python для автоматического создания схемы, определяющей API и его параметры.
+
+Hug вдохновил **FastAPI** объявить параметр `ответа` в функциях для установки заголовков и куки.
+
+///
### APIStar (<= 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"
- Затем **FastAPI** берёт эти схемы JSON и помещает их в схему OpenAPI, не касаясь других вещей, которые он делает.
+Для проверки данных, сериализации данных и автоматической документации моделей (на основе JSON Schema).
+
+Затем **FastAPI** берёт эти схемы JSON и помещает их в схему OpenAPI, не касаясь других вещей, которые он делает.
+
+///
### Starlette
@@ -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.
+
+///
### Uvicorn
@@ -448,12 +518,15 @@ Uvicorn является сервером, а не фреймворком.
Он рекомендуется в качестве сервера для Starlette и **FastAPI**.
-!!! check "**FastAPI** рекомендует его"
- Как основной сервер для запуска приложения **FastAPI**.
+/// check | "**FastAPI** рекомендует его"
- Вы можете объединить его с Gunicorn, чтобы иметь асинхронный многопроцессный сервер.
+Как основной сервер для запуска приложения **FastAPI**.
- Узнать больше деталей можно в разделе [Развёртывание](deployment/index.md){.internal-link target=_blank}.
+Вы можете объединить его с Gunicorn, чтобы иметь асинхронный многопроцессный сервер.
+
+Узнать больше деталей можно в разделе [Развёртывание](deployment/index.md){.internal-link target=_blank}.
+
+///
## Тестовые замеры и скорость
diff --git a/docs/ru/docs/async.md b/docs/ru/docs/async.md
index 4c44fc22d..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**) основаны на
-Но в любом случае велика вероятность, что **FastAPI** [окажется быстрее](/#performance){.internal-link target=_blank}
+Но в любом случае велика вероятность, что **FastAPI** [окажется быстрее](index.md#_11){.internal-link target=_blank}
другого фреймворка (или хотя бы на уровне с ним).
### Зависимости
@@ -502,4 +508,4 @@ Starlette (и **FastAPI**) основаны на Нет времени?.
+В противном случае просто ознакомьтесь с основными принципами в разделе выше: Нет времени?.
diff --git a/docs/ru/docs/contributing.md b/docs/ru/docs/contributing.md
index f9b8912e5..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
-
@@ -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** в ответ на свой запрос, но приложение не сломается и будет продолжать работать с последующими запросами.
@@ -151,12 +151,15 @@
Для случаев, когда ошибки приводят к сбою в запущенном **процессе**, Вам понадобится добавить компонент, который **перезапустит** процесс хотя бы пару раз...
-!!! tip "Заметка"
- ... Если приложение падает сразу же после запуска, вероятно бесполезно его бесконечно перезапускать. Но полагаю, Вы заметите такое поведение во время разработки или, по крайней мере, сразу после развёртывания.
+/// tip | "Заметка"
- Так что давайте сосредоточимся на конкретных случаях, когда приложение может полностью выйти из строя, но всё ещё есть смысл его запустить заново.
+... Если приложение падает сразу же после запуска, вероятно бесполезно его бесконечно перезапускать. Но полагаю, вы заметите такое поведение во время разработки или, по крайней мере, сразу после развёртывания.
-Возможно Вы захотите, чтоб был некий **внешний компонент**, ответственный за перезапуск Вашего приложения даже если уже не работает Uvicorn или Python. То есть ничего из того, что написано в Вашем коде внутри приложения, не может быть выполнено в принципе.
+Так что давайте сосредоточимся на конкретных случаях, когда приложение может полностью выйти из строя, но всё ещё есть смысл его запустить заново.
+
+///
+
+Возможно вы захотите, чтоб был некий **внешний компонент**, ответственный за перезапуск вашего приложения даже если уже не работает Uvicorn или Python. То есть ничего из того, что написано в вашем коде внутри приложения, не может быть выполнено в принципе.
### Примеры инструментов для автоматического перезапуска
@@ -181,13 +184,13 @@
### Множество процессов - Воркеры (Workers)
-Если количество Ваших клиентов больше, чем может обслужить один процесс (допустим, что виртуальная машина не слишком мощная), но при этом Вам доступно **несколько ядер процессора**, то Вы можете запустить **несколько процессов** одного и того же приложения параллельно и распределить запросы между этими процессами.
+Если количество Ваших клиентов больше, чем может обслужить один процесс (допустим, что виртуальная машина не слишком мощная), но при этом Вам доступно **несколько ядер процессора**, то вы можете запустить **несколько процессов** одного и того же приложения параллельно и распределить запросы между этими процессами.
**Несколько запущенных процессов** одной и той же API-программы часто называют **воркерами**.
### Процессы и порты́
-Помните ли Вы, как на странице [Об HTTPS](./https.md){.internal-link target=_blank} мы обсуждали, что на сервере только один процесс может слушать одну комбинацию IP-адреса и порта?
+Помните ли Вы, как на странице [Об HTTPS](https.md){.internal-link target=_blank} мы обсуждали, что на сервере только один процесс может слушать одну комбинацию IP-адреса и порта?
С тех пор ничего не изменилось.
@@ -197,11 +200,11 @@
Работающая программа загружает в память данные, необходимые для её работы, например, переменные содержащие модели машинного обучения или большие файлы. Каждая переменная **потребляет некоторое количество оперативной памяти (RAM)** сервера.
-Обычно процессы **не делятся памятью друг с другом**. Сие означает, что каждый работающий процесс имеет свои данные, переменные и свой кусок памяти. И если для выполнения Вашего кода процессу нужно много памяти, то **каждый такой же процесс** запущенный дополнительно, потребует такого же количества памяти.
+Обычно процессы **не делятся памятью друг с другом**. Сие означает, что каждый работающий процесс имеет свои данные, переменные и свой кусок памяти. И если для выполнения вашего кода процессу нужно много памяти, то **каждый такой же процесс** запущенный дополнительно, потребует такого же количества памяти.
### Память сервера
-Допустим, что Ваш код загружает модель машинного обучения **размером 1 ГБ**. Когда Вы запустите своё API как один процесс, он займёт в оперативной памяти не менее 1 ГБ. А если Вы запустите **4 таких же процесса** (4 воркера), то каждый из них займёт 1 ГБ оперативной памяти. В результате Вашему API потребуется **4 ГБ оперативной памяти (RAM)**.
+Допустим, что Ваш код загружает модель машинного обучения **размером 1 ГБ**. Когда вы запустите своё API как один процесс, он займёт в оперативной памяти не менее 1 ГБ. А если вы запустите **4 таких же процесса** (4 воркера), то каждый из них займёт 1 ГБ оперативной памяти. В результате вашему API потребуется **4 ГБ оперативной памяти (RAM)**.
И если Ваш удалённый сервер или виртуальная машина располагает только 3 ГБ памяти, то попытка загрузить в неё 4 ГБ данных вызовет проблемы. 🚨
@@ -211,15 +214,15 @@
Менеджер процессов будет слушать определённый **сокет** (IP:порт) и передавать данные работающим процессам.
-Каждый из этих процессов будет запускать Ваше приложение для обработки полученного **запроса** и возвращения вычисленного **ответа** и они будут использовать оперативную память.
+Каждый из этих процессов будет запускать ваше приложение для обработки полученного **запроса** и возвращения вычисленного **ответа** и они будут использовать оперативную память.
-
-
+
+
-
-
+
+
@@ -23,11 +29,11 @@
**Документация**: https://fastapi.tiangolo.com
-**Исходный код**: https://github.com/tiangolo/fastapi
+**Исходный код**: https://github.com/fastapi/fastapi
---
-FastAPI — это современный, быстрый (высокопроизводительный) веб-фреймворк для создания API используя Python 3.8+, в основе которого лежит стандартная аннотация типов Python.
+FastAPI — это современный, быстрый (высокопроизводительный) веб-фреймворк для создания API используя Python, в основе которого лежит стандартная аннотация типов Python.
Ключевые особенности:
@@ -63,7 +69,7 @@ FastAPI — это современный, быстрый (высокопрои
"_В последнее время я много где использую **FastAPI**. [...] На самом деле я планирую использовать его для всех **сервисов машинного обучения моей команды в Microsoft**. Некоторые из них интегрируются в основной продукт **Windows**, а некоторые — в продукты **Office**._"
-
email_validator - для проверки электронной почты.
+* email-validator - для проверки электронной почты.
Используется Starlette:
@@ -448,12 +452,12 @@ item: Item
* python-multipart - Обязательно, если вы хотите поддерживать форму "парсинга" с помощью `request.form()`.
* itsdangerous - Обязательно, для поддержки `SessionMiddleware`.
* pyyaml - Обязательно, для поддержки `SchemaGenerator` Starlette (возможно, вам это не нужно с FastAPI).
-* ujson - Обязательно, если вы хотите использовать `UJSONResponse`.
Используется FastAPI / Starlette:
* uvicorn - сервер, который загружает и обслуживает ваше приложение.
* orjson - Обязательно, если вы хотите использовать `ORJSONResponse`.
+* ujson - Обязательно, если вы хотите использовать `UJSONResponse`.
Вы можете установить все это с помощью `pip install "fastapi[all]"`.
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: **FastAPI**:
+* Бэкенд построен на фреймворке **FastAPI**:
* **Быстрый**: Высокопроизводительный, на уровне **NodeJS** и **Go** (благодаря Starlette и Pydantic).
* **Интуитивно понятный**: Отличная поддержка редактора. Автодополнение кода везде. Меньше времени на отладку.
* **Простой**: Разработан так, чтоб быть простым в использовании и изучении. Меньше времени на чтение документации.
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
- Чтобы узнать больше о Pydantic, читайте его документацию.
+/// info
+
+Чтобы узнать больше о Pydantic, читайте его документацию.
+
+///
**FastAPI** целиком основан на Pydantic.
@@ -310,5 +319,8 @@ John Doe
Важно то, что при использовании стандартных типов Python в одном месте (вместо добавления дополнительных классов, декораторов и т.д.) **FastAPI** сделает за вас большую часть работы.
-!!! info
- Если вы уже прошли всё руководство и вернулись, чтобы узнать больше о типах, хорошим ресурсом является «шпаргалка» от `mypy`.
+/// info
+
+Если вы уже прошли всё руководство и вернулись, чтобы узнать больше о типах, хорошим ресурсом является «шпаргалка» от `mypy`.
+
+///
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+"
+////
- ```Python hl_lines="13 15 22 25"
- {!> ../../../docs_src/background_tasks/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+
+```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!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```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 e52ef6f6f..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+"
+////
- ```Python hl_lines="18-20"
- {!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="18-20"
+{!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="19-21"
- {!> ../../../docs_src/body_multiple_params/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! Заметка
- Рекомендуется использовать `Annotated` версию, если это возможно.
+```Python hl_lines="19-21"
+{!> ../../../docs_src/body_multiple_params/tutorial001_an.py!}
+```
- ```Python hl_lines="17-19"
- {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! Заметка
- Рекомендуется использовать версию с `Annotated`, если это возможно.
+/// tip | "Заметка"
- ```Python hl_lines="19-21"
- {!> ../../../docs_src/body_multiple_params/tutorial001.py!}
- ```
+Рекомендуется использовать `Annotated` версию, если это возможно.
-!!! Заметка
- Заметьте, что в данном случае параметр `item`, который будет взят из тела запроса, необязателен. Так как было установлено значение `None` по умолчанию.
+///
+
+```Python hl_lines="17-19"
+{!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "Заметка"
+
+Рекомендуется использовать версию с `Annotated`, если это возможно.
+
+///
+
+```Python hl_lines="19-21"
+{!> ../../../docs_src/body_multiple_params/tutorial001.py!}
+```
+
+////
+
+/// 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 @@
}
```
-!!! Внимание
- Обратите внимание, что хотя параметр `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!}
- ```
+```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!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="23"
+{!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!}
+```
- ```Python hl_lines="24"
- {!> ../../../docs_src/body_multiple_params/tutorial003_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! Заметка
- Рекомендуется использовать `Annotated` версию, если это возможно.
+```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.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! Заметка
- Рекомендуется использовать `Annotated` версию, если это возможно.
+/// tip | "Заметка"
- ```Python hl_lines="22"
- {!> ../../../docs_src/body_multiple_params/tutorial003.py!}
- ```
+Рекомендуется использовать `Annotated` версию, если это возможно.
+
+///
+
+```Python hl_lines="20"
+{!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "Заметка"
+
+Рекомендуется использовать `Annotated` версию, если это возможно.
+
+///
+
+```Python hl_lines="22"
+{!> ../../../docs_src/body_multiple_params/tutorial003.py!}
+```
+
+////
В этом случае, **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!}
- ```
+```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!}
+```
- ```Python hl_lines="28"
- {!> ../../../docs_src/body_multiple_params/tutorial004_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! Заметка
- Рекомендуется использовать `Annotated` версию, если это возможно.
+```Python hl_lines="28"
+{!> ../../../docs_src/body_multiple_params/tutorial004_an.py!}
+```
- ```Python hl_lines="25"
- {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! Заметка
- Рекомендуется использовать `Annotated` версию, если это возможно.
+/// tip | "Заметка"
- ```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004.py!}
- ```
+Рекомендуется использовать `Annotated` версию, если это возможно.
-!!! Информация
- `Body` также имеет все те же дополнительные параметры валидации и метаданных, как у `Query`,`Path` и других, которые вы увидите позже.
+///
+
+```Python hl_lines="25"
+{!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "Заметка"
+
+Рекомендуется использовать `Annotated` версию, если это возможно.
+
+///
+
+```Python hl_lines="27"
+{!> ../../../docs_src/body_multiple_params/tutorial004.py!}
+```
+
+////
+
+/// 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!}
- ```
+```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!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="17"
+{!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!}
+```
- ```Python hl_lines="18"
- {!> ../../../docs_src/body_multiple_params/tutorial005_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! Заметка
- Рекомендуется использовать `Annotated` версию, если это возможно.
+```Python hl_lines="18"
+{!> ../../../docs_src/body_multiple_params/tutorial005_an.py!}
+```
- ```Python hl_lines="15"
- {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! Заметка
- Рекомендуется использовать `Annotated` версию, если это возможно.
+/// tip | "Заметка"
- ```Python hl_lines="17"
- {!> ../../../docs_src/body_multiple_params/tutorial005.py!}
- ```
+Рекомендуется использовать `Annotated` версию, если это возможно.
+
+///
+
+```Python hl_lines="15"
+{!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "Заметка"
+
+Рекомендуется использовать `Annotated` версию, если это возможно.
+
+///
+
+```Python hl_lines="17"
+{!> ../../../docs_src/body_multiple_params/tutorial005.py!}
+```
+
+////
В этом случае **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+"
+////
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```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!}
- ```
+```Python hl_lines="12"
+{!> ../../../docs_src/body_nested_models/tutorial002_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial002_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="14"
+{!> ../../../docs_src/body_nested_models/tutorial002_py39.py!}
+```
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial002.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```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!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial003_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="14"
+{!> ../../../docs_src/body_nested_models/tutorial003_py39.py!}
+```
- ```Python hl_lines="1 14"
- {!> ../../../docs_src/body_nested_models/tutorial003.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```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!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="9-11"
- {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="9-11"
+{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!}
+```
- ```Python hl_lines="9-11"
- {!> ../../../docs_src/body_nested_models/tutorial004.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```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+"
+////
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial006_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="20"
+{!> ../../../docs_src/body_nested_models/tutorial006_py39.py!}
+```
- ```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!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="9 14 20 23 27"
- {!> ../../../docs_src/body_nested_models/tutorial007_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="9 14 20 23 27"
+{!> ../../../docs_src/body_nested_models/tutorial007_py39.py!}
+```
- ```Python hl_lines="9 14 20 23 27"
- {!> ../../../docs_src/body_nested_models/tutorial007.py!}
- ```
+////
-!!! info "Информация"
- Заметьте, что у объекта `Offer` есть список объектов `Item`, которые, в свою очередь, могут содержать необязательный список объектов `Image`
+//// tab | Python 3.8+
+
+```Python hl_lines="9 14 20 23 27"
+{!> ../../../docs_src/body_nested_models/tutorial007.py!}
+```
+
+////
+
+/// 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+"
+////
- ```Python hl_lines="15"
- {!> ../../../docs_src/body_nested_models/tutorial008.py!}
- ```
+//// tab | Python 3.8+
+
+```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!}
- ```
+```Python hl_lines="7"
+{!> ../../../docs_src/body_nested_models/tutorial009_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/body_nested_models/tutorial009.py!}
- ```
+//// tab | Python 3.8+
-!!! tip "Совет"
- Имейте в виду, что JSON поддерживает только ключи типа `str`.
+```Python hl_lines="9"
+{!> ../../../docs_src/body_nested_models/tutorial009.py!}
+```
- Но Pydantic обеспечивает автоматическое преобразование данных.
+////
- Это значит, что даже если пользователи вашего API могут отправлять только строки в качестве ключей, при условии, что эти строки содержат целые числа, Pydantic автоматический преобразует и валидирует эти данные.
+/// tip | "Совет"
- А `dict`, с именем `weights`, который вы получите в качестве ответа Pydantic, действительно будет иметь ключи типа `int` и значения типа `float`.
+Имейте в виду, что JSON поддерживает только ключи типа `str`.
+
+Но Pydantic обеспечивает автоматическое преобразование данных.
+
+Это значит, что даже если пользователи вашего API могут отправлять только строки в качестве ключей, при условии, что эти строки содержат целые числа, Pydantic автоматический преобразует и валидирует эти данные.
+
+А `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!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="30-35"
- {!> ../../../docs_src/body_updates/tutorial001_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.6+"
+```Python hl_lines="30-35"
+{!> ../../../docs_src/body_updates/tutorial001_py39.py!}
+```
- ```Python hl_lines="30-35"
- {!> ../../../docs_src/body_updates/tutorial001.py!}
- ```
+////
+
+//// tab | Python 3.6+
+
+```Python hl_lines="30-35"
+{!> ../../../docs_src/body_updates/tutorial001.py!}
+```
+
+////
`PUT` используется для получения данных, которые должны полностью заменить существующие данные.
@@ -48,14 +54,17 @@
Это означает, что можно передавать только те данные, которые необходимо обновить, оставляя остальные нетронутыми.
-!!! note "Технические детали"
- `PATCH` менее распространен и известен, чем `PUT`.
+/// note | "Технические детали"
- А многие команды используют только `PUT`, даже для частичного обновления.
+`PATCH` менее распространен и известен, чем `PUT`.
- Вы можете **свободно** использовать их как угодно, **FastAPI** не накладывает никаких ограничений.
+А многие команды используют только `PUT`, даже для частичного обновления.
- Но в данном руководстве более или менее понятно, как они должны использоваться.
+Вы можете **свободно** использовать их как угодно, **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+"
+////
- ```Python hl_lines="34"
- {!> ../../../docs_src/body_updates/tutorial002_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.6+"
+```Python hl_lines="34"
+{!> ../../../docs_src/body_updates/tutorial002_py39.py!}
+```
- ```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!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="35"
- {!> ../../../docs_src/body_updates/tutorial002_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.6+"
+```Python hl_lines="35"
+{!> ../../../docs_src/body_updates/tutorial002_py39.py!}
+```
- ```Python hl_lines="35"
- {!> ../../../docs_src/body_updates/tutorial002.py!}
- ```
+////
+
+//// tab | Python 3.6+
+
+```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!}
- ```
+```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!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.6+"
+```Python hl_lines="30-37"
+{!> ../../../docs_src/body_updates/tutorial002_py39.py!}
+```
- ```Python hl_lines="30-37"
- {!> ../../../docs_src/body_updates/tutorial002.py!}
- ```
+////
-!!! tip "Подсказка"
- Эту же технику можно использовать и для операции HTTP `PUT`.
+//// tab | Python 3.6+
- Но в приведенном примере используется `PATCH`, поскольку он был создан именно для таких случаев использования.
+```Python hl_lines="30-37"
+{!> ../../../docs_src/body_updates/tutorial002.py!}
+```
-!!! note "Технические детали"
- Обратите внимание, что входная модель по-прежнему валидируется.
+////
- Таким образом, если вы хотите получать частичные обновления, в которых могут быть опущены все атрибуты, вам необходимо иметь модель, в которой все атрибуты помечены как необязательные (со значениями по умолчанию или `None`).
+/// tip | "Подсказка"
- Чтобы отличить модели со всеми необязательными значениями для **обновления** от моделей с обязательными значениями для **создания**, можно воспользоваться идеями, описанными в [Дополнительные модели](extra-models.md){.internal-link target=_blank}.
+Эту же технику можно использовать и для операции HTTP `PUT`.
+
+Но в приведенном примере используется `PATCH`, поскольку он был создан именно для таких случаев использования.
+
+///
+
+/// note | "Технические детали"
+
+Обратите внимание, что входная модель по-прежнему валидируется.
+
+Таким образом, если вы хотите получать частичные обновления, в которых могут быть опущены все атрибуты, вам необходимо иметь модель, в которой все атрибуты помечены как необязательные (со значениями по умолчанию или `None`).
+
+Чтобы отличить модели со всеми необязательными значениями для **обновления** от моделей с обязательными значениями для **создания**, можно воспользоваться идеями, описанными в [Дополнительные модели](extra-models.md){.internal-link target=_blank}.
+
+///
diff --git a/docs/ru/docs/tutorial/body.md b/docs/ru/docs/tutorial/body.md
index 96f80af06..c3e6326da 100644
--- a/docs/ru/docs/tutorial/body.md
+++ b/docs/ru/docs/tutorial/body.md
@@ -8,12 +8,15 @@
Чтобы объявить тело **запроса**, необходимо использовать модели Pydantic, со всей их мощью и преимуществами.
-!!! 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 @@
-!!! tip "Подсказка"
- Если вы используете PyCharm в качестве редактора, то вам стоит попробовать плагин Pydantic PyCharm Plugin.
+/// tip | "Подсказка"
- Он улучшает поддержку редактором моделей Pydantic в части:
+Если вы используете PyCharm в качестве редактора, то вам стоит попробовать плагин Pydantic PyCharm Plugin.
- * автодополнения,
- * проверки типов,
- * рефакторинга,
- * поиска,
- * инспектирования.
+Он улучшает поддержку редактором моделей Pydantic в части:
+
+* автодополнения,
+* проверки типов,
+* рефакторинга,
+* поиска,
+* инспектирования.
+
+///
## Использование модели
@@ -155,11 +161,14 @@
* Если аннотация типа параметра содержит **примитивный тип** (`int`, `float`, `str`, `bool` и т.п.), он будет интерпретирован как параметр **запроса**.
* Если аннотация типа параметра представляет собой **модель Pydantic**, он будет интерпретирован как параметр **тела запроса**.
-!!! note "Заметка"
- FastAPI понимает, что значение параметра `q` не является обязательным, потому что имеет значение по умолчанию `= None`.
+/// note | "Заметка"
- Аннотация `Optional` в `Optional[str]` не используется FastAPI, но помогает вашему редактору лучше понимать ваш код и обнаруживать ошибки.
+FastAPI понимает, что значение параметра `q` не является обязательным, потому что имеет значение по умолчанию `= None`.
+
+Аннотация `Optional` в `Optional[str]` не используется FastAPI, но помогает вашему редактору лучше понимать ваш код и обнаруживать ошибки.
+
+///
## Без 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/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!}
- ```
+```Python hl_lines="7"
+{!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/cookie_params/tutorial001.py!}
- ```
+//// tab | Python 3.8+
-!!! note "Технические детали"
- `Cookie` - это класс, родственный `Path` и `Query`. Он также наследуется от общего класса `Param`.
+```Python hl_lines="9"
+{!> ../../../docs_src/cookie_params/tutorial001.py!}
+```
- Но помните, что когда вы импортируете `Query`, `Path`, `Cookie` и другое из `fastapi`, это фактически функции, которые возвращают специальные классы.
+////
-!!! info "Дополнительная информация"
- Для объявления cookies, вам нужно использовать `Cookie`, иначе параметры будут интерпретированы как параметры запроса.
+/// note | "Технические детали"
+
+`Cookie` - это класс, родственный `Path` и `Query`. Он также наследуется от общего класса `Param`.
+
+Но помните, что когда вы импортируете `Query`, `Path`, `Cookie` и другое из `fastapi`, это фактически функции, которые возвращают специальные классы.
+
+///
+
+/// 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 @@
Для получения более подробной информации о CORS, обратитесь к Документации CORS от Mozilla.
-!!! 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 38709e56d..685fb7356 100644
--- a/docs/ru/docs/tutorial/debugging.md
+++ b/docs/ru/docs/tutorial/debugging.md
@@ -74,8 +74,11 @@ from myapp import app
не будет выполнена.
-!!! Информация
- Для получения дополнительной информации, ознакомьтесь с официальной документацией Python.
+/// info | "Информация"
+
+Для получения дополнительной информации, ознакомьтесь с официальной документацией Python.
+
+///
## Запуск вашего кода с помощью отладчика
diff --git a/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md
index 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!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="11"
- {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.6+"
+```Python hl_lines="11"
+{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="12"
- {!> ../../../docs_src/dependencies/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.6+
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+```Python hl_lines="12"
+{!> ../../../docs_src/dependencies/tutorial001_an.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.6+ без Annotated"
+//// tab | Python 3.10+ без Annotated
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="11"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.6+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="11"
+{!> ../../../docs_src/dependencies/tutorial001.py!}
+```
+
+////
Но затем мы получаем `словарь` в параметре `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!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.6+
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+```Python hl_lines="12-16"
+{!> ../../../docs_src/dependencies/tutorial002_an.py!}
+```
- ```Python hl_lines="9-13"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
+////
-=== "Python 3.6+ без Annotated"
+//// tab | Python 3.10+ без Annotated
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="11-15"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="9-13"
+{!> ../../../docs_src/dependencies/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.6+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="11-15"
+{!> ../../../docs_src/dependencies/tutorial002.py!}
+```
+
+////
Обратите внимание на метод `__init__`, используемый для создания экземпляра класса:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="12"
- {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!}
- ```
+```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!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.6+"
+```Python hl_lines="12"
+{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!}
+```
- ```Python hl_lines="13"
- {!> ../../../docs_src/dependencies/tutorial002_an.py!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.6+
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+```Python hl_lines="13"
+{!> ../../../docs_src/dependencies/tutorial002_an.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
+////
-=== "Python 3.6+ без Annotated"
+//// tab | Python 3.10+ без Annotated
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="12"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="10"
+{!> ../../../docs_src/dependencies/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.6+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="12"
+{!> ../../../docs_src/dependencies/tutorial002.py!}
+```
+
+////
...имеет те же параметры, что и ранее используемая функция `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+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.6+"
+```Python hl_lines="9"
+{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/dependencies/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.6+
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+```Python hl_lines="10"
+{!> ../../../docs_src/dependencies/tutorial001_an.py!}
+```
- ```Python hl_lines="6"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.6+ без Annotated"
+//// tab | Python 3.10+ без Annotated
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="9"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+Рекомендуется использовать версию с `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!}
+```
+
+////
Эти параметры и будут использоваться **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!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.6+"
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!}
+```
- ```Python hl_lines="20"
- {!> ../../../docs_src/dependencies/tutorial002_an.py!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.6+
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+```Python hl_lines="20"
+{!> ../../../docs_src/dependencies/tutorial002_an.py!}
+```
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
+////
-=== "Python 3.6+ без Annotated"
+//// tab | Python 3.10+ без Annotated
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="17"
+{!> ../../../docs_src/dependencies/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.6+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial002.py!}
+```
+
+////
**FastAPI** вызывает класс `CommonQueryParams`. При этом создается "экземпляр" этого класса, который будет передан в качестве параметра `commons` в вашу функцию.
@@ -269,20 +349,27 @@ fluffy = Cat(name="Mr Fluffy")
Обратите внимание, что в приведенном выше коде мы два раза пишем `CommonQueryParams`:
-=== "Python 3.6+ без Annotated"
+//// tab | Python 3.6+ без Annotated
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python
- commons: CommonQueryParams = Depends(CommonQueryParams)
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
-=== "Python 3.6+"
+///
- ```Python
- commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
- ```
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
+
+//// tab | Python 3.6+
+
+```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, ...
+```
-=== "Python 3.6+ без Annotated"
+////
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+//// tab | Python 3.6+ без Annotated
- ```Python
- commons: CommonQueryParams ...
- ```
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```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"
+////
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+//// tab | Python 3.6+ без Annotated
- ```Python
- commons = Depends(CommonQueryParams)
- ```
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python
+commons = Depends(CommonQueryParams)
+```
+
+////
...как тут:
-=== "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!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial003_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.6+"
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial003_an_py39.py!}
+```
- ```Python hl_lines="20"
- {!> ../../../docs_src/dependencies/tutorial003_an.py!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.6+
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+```Python hl_lines="20"
+{!> ../../../docs_src/dependencies/tutorial003_an.py!}
+```
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial003_py310.py!}
- ```
+////
-=== "Python 3.6+ без Annotated"
+//// tab | Python 3.10+ без Annotated
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial003.py!}
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="17"
+{!> ../../../docs_src/dependencies/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.6+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial003.py!}
+```
+
+////
Но объявление типа приветствуется, так как в этом случае ваш редактор будет знать, что будет передано в качестве параметра `commons`, и тогда он сможет помочь вам с автодополнением, проверкой типов и т.д:
@@ -378,101 +495,141 @@ fluffy = Cat(name="Mr Fluffy")
Но вы видите, что здесь мы имеем некоторое повторение кода, дважды написав `CommonQueryParams`:
-=== "Python 3.6+ без Annotated"
+//// tab | Python 3.6+ без Annotated
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python
- commons: CommonQueryParams = Depends(CommonQueryParams)
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
-=== "Python 3.6+"
+///
- ```Python
- commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
- ```
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
+
+//// tab | Python 3.6+
+
+```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"
+////
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+//// tab | Python 3.6+ без Annotated
- ```Python
- commons: CommonQueryParams = Depends(CommonQueryParams)
- ```
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `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!}
- ```
+```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!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.6+"
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial004_an_py39.py!}
+```
- ```Python hl_lines="20"
- {!> ../../../docs_src/dependencies/tutorial004_an.py!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.6+
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+```Python hl_lines="20"
+{!> ../../../docs_src/dependencies/tutorial004_an.py!}
+```
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial004_py310.py!}
- ```
+////
-=== "Python 3.6+ без Annotated"
+//// tab | Python 3.10+ без Annotated
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial004.py!}
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="17"
+{!> ../../../docs_src/dependencies/tutorial004_py310.py!}
+```
+
+////
+
+//// tab | Python 3.6+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial004.py!}
+```
+
+////
...и **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
new file mode 100644
index 000000000..11df4b474
--- /dev/null
+++ b/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
@@ -0,0 +1,181 @@
+# Зависимости в декораторах операции пути
+
+В некоторых случаях, возвращаемое значение зависимости не используется внутри *функции операции пути*.
+
+Или же зависимость не возвращает никакого значения.
+
+Но вам всё-таки нужно, чтобы она выполнилась.
+
+Для таких ситуаций, вместо объявления *функции операции пути* с параметром `Depends`, вы можете добавить список зависимостей `dependencies` в *декоратор операции пути*.
+
+## Добавление `dependencies` в *декоратор операции пути*
+
+*Декоратор операции пути* получает необязательный аргумент `dependencies`.
+
+Это должен быть `list` состоящий из `Depends()`:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="18"
+{!> ../../../docs_src/dependencies/tutorial006_an.py!}
+```
+
+////
+
+//// tab | Python 3.8 без Annotated
+
+/// подсказка
+
+Рекомендуется использовать версию с Annotated, если возможно.
+
+///
+
+```Python hl_lines="17"
+{!> ../../../docs_src/dependencies/tutorial006.py!}
+```
+
+////
+
+Зависимости из dependencies выполнятся так же, как и обычные зависимости. Но их значения (если они были) не будут переданы в *функцию операции пути*.
+
+/// подсказка
+
+Некоторые редакторы кода определяют неиспользуемые параметры функций и подсвечивают их как ошибку.
+
+Использование `dependencies` в *декораторе операции пути* гарантирует выполнение зависимостей, избегая при этом предупреждений редактора кода и других инструментов.
+
+Это также должно помочь предотвратить путаницу у начинающих разработчиков, которые видят неиспользуемые параметры в коде и могут подумать что в них нет необходимости.
+
+///
+
+/// дополнительная | информация
+
+В этом примере мы используем выдуманные пользовательские заголовки `X-Key` и `X-Token`.
+
+Но в реальных проектах, при внедрении системы безопасности, вы получите больше пользы используя интегрированные [средства защиты (следующая глава)](../security/index.md){.internal-link target=_blank}.
+
+///
+
+## Исключения в dependencies и возвращаемые значения
+
+Вы можете использовать те же *функции* зависимостей, что и обычно.
+
+### Требования к зависимостям
+
+Они могут объявлять требования к запросу (например заголовки) или другие подзависимости:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="8 13"
+{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="7 12"
+{!> ../../../docs_src/dependencies/tutorial006_an.py!}
+```
+
+////
+
+//// tab | Python 3.8 без Annotated
+
+/// подсказка
+
+Рекомендуется использовать версию с Annotated, если возможно.
+
+///
+
+```Python hl_lines="6 11"
+{!> ../../../docs_src/dependencies/tutorial006.py!}
+```
+
+////
+
+### Вызов исключений
+
+Зависимости из dependencies могут вызывать исключения с помощью `raise`, как и обычные зависимости:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="10 15"
+{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9 14"
+{!> ../../../docs_src/dependencies/tutorial006_an.py!}
+```
+
+////
+
+//// tab | Python 3.8 без Annotated
+
+/// подсказка
+
+Рекомендуется использовать версию с Annotated, если возможно.
+
+///
+
+```Python hl_lines="8 13"
+{!> ../../../docs_src/dependencies/tutorial006.py!}
+```
+
+////
+
+### Возвращаемые значения
+
+И они могут возвращать значения или нет, эти значения использоваться не будут.
+
+Таким образом, вы можете переиспользовать обычную зависимость (возвращающую значение), которую вы уже используете где-то в другом месте, и хотя значение не будет использоваться, зависимость будет выполнена:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="11 16"
+{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="10 15"
+{!> ../../../docs_src/dependencies/tutorial006_an.py!}
+```
+
+////
+
+//// tab | Python 3.8 без Annotated
+
+/// подсказка
+
+Рекомендуется использовать версию с Annotated, если возможно.
+
+///
+
+```Python hl_lines="9 14"
+{!> ../../../docs_src/dependencies/tutorial006.py!}
+```
+
+////
+
+## Dependencies для группы *операций путей*
+
+Позже, читая о том как структурировать большие приложения ([Bigger Applications - Multiple Files](../../tutorial/bigger-applications.md){.internal-link target=_blank}), возможно, многофайловые, вы узнаете как объявить единый параметр `dependencies` для всей группы *операций путей*.
+
+## Глобальный Dependencies
+
+Далее мы увидим, как можно добавить dependencies для всего `FastAPI` приложения, так чтобы они применялись к каждой *операции пути*.
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..ece7ef8e3
--- /dev/null
+++ b/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md
@@ -0,0 +1,325 @@
+# Зависимости с yield
+
+FastAPI поддерживает зависимости, которые выполняют некоторые дополнительные действия после завершения работы.
+
+Для этого используйте `yield` вместо `return`, а дополнительный код напишите после него.
+
+/// tip | "Подсказка"
+
+Обязательно используйте `yield` один-единственный раз.
+
+///
+
+/// note | "Технические детали"
+
+Любая функция, с которой может работать:
+
+* `@contextlib.contextmanager` или
+* `@contextlib.asynccontextmanager`
+
+будет корректно использоваться в качестве **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`:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="6 14 22"
+{!> ../../../docs_src/dependencies/tutorial008_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.6+
+
+```Python hl_lines="5 13 21"
+{!> ../../../docs_src/dependencies/tutorial008_an.py!}
+```
+
+////
+
+//// tab | Python 3.6+ без Annotated
+
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="4 12 20"
+{!> ../../../docs_src/dependencies/tutorial008.py!}
+```
+
+////
+
+И все они могут использовать `yield`.
+
+В этом случае `dependency_c` для выполнения своего кода выхода нуждается в том, чтобы значение из `dependency_b` (здесь `dep_b`) было еще доступно.
+
+И, в свою очередь, `dependency_b` нуждается в том, чтобы значение из `dependency_a` (здесь `dep_a`) было доступно для ее завершающего кода.
+
+//// tab | Python 3.9+
+
+```Python hl_lines="18-19 26-27"
+{!> ../../../docs_src/dependencies/tutorial008_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.6+
+
+```Python hl_lines="17-18 25-26"
+{!> ../../../docs_src/dependencies/tutorial008_an.py!}
+```
+
+////
+
+//// tab | Python 3.6+ без Annotated
+
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="16-17 24-25"
+{!> ../../../docs_src/dependencies/tutorial008.py!}
+```
+
+////
+
+Точно так же можно иметь часть зависимостей с `yield`, часть с `return`, и какие-то из них могут зависеть друг от друга.
+
+Либо у вас может быть одна зависимость, которая требует несколько других зависимостей с `yield` и т.д.
+
+Комбинации зависимостей могут быть какими вам угодно.
+
+**FastAPI** проследит за тем, чтобы все выполнялось в правильном порядке.
+
+/// note | "Технические детали"
+
+Это работает благодаря Контекстным менеджерам в 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`.
+
+Например, можно использовать `with` для чтения файла:
+
+```Python
+with open("./somefile.txt") as f:
+ contents = f.read()
+ print(contents)
+```
+
+Под капотом" open("./somefile.txt") создаёт объект называемый "контекстным менеджером".
+
+Когда блок `with` завершается, он обязательно закрывает файл, даже если были исключения.
+
+Когда вы создаете зависимость с помощью `yield`, **FastAPI** внутренне преобразует ее в контекстный менеджер и объединяет с некоторыми другими связанными инструментами.
+
+### Использование менеджеров контекста в зависимостях с помощью `yield`
+
+/// warning | "Внимание"
+
+Это более или менее "продвинутая" идея.
+
+Если вы только начинаете работать с **FastAPI**, то лучше пока пропустить этот пункт.
+
+///
+
+В Python для создания менеджеров контекста можно создать класс с двумя методами: `__enter__()` и `__exit__()`.
+
+Вы также можете использовать их внутри зависимостей **FastAPI** с `yield`, используя операторы
+`with` или `async with` внутри функции зависимости:
+
+```Python hl_lines="1-9 13"
+{!../../../docs_src/dependencies/tutorial010.py!}
+```
+
+/// tip | "Подсказка"
+
+Другой способ создания контекстного менеджера - с помощью:
+
+* `@contextlib.contextmanager` или
+* `@contextlib.asynccontextmanager`
+
+используйте их для оформления функции с одним `yield`.
+
+Это то, что **FastAPI** использует внутри себя для зависимостей с `yield`.
+
+Но использовать декораторы для зависимостей 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 ad6e835e5..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!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="8-11"
- {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "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.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip "Подсказка"
- Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно.
+```Python hl_lines="9-12"
+{!> ../../../docs_src/dependencies/tutorial001_an.py!}
+```
- ```Python hl_lines="6-7"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip "Подсказка"
+/// tip | "Подсказка"
- Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно.
+Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно.
- ```Python hl_lines="8-11"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+///
+
+```Python hl_lines="6-7"
+{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "Подсказка"
+
+Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно.
+
+///
+
+```Python hl_lines="8-11"
+{!> ../../../docs_src/dependencies/tutorial001.py!}
+```
+
+////
**И всё.**
@@ -84,91 +99,125 @@
И в конце она возвращает `dict`, содержащий эти значения.
-!!! Информация
+/// info | "Информация"
- **FastAPI** добавил поддержку для `Annotated` (и начал её рекомендовать) в версии 0.95.0.
+**FastAPI** добавил поддержку для `Annotated` (и начал её рекомендовать) в версии 0.95.0.
- Если у вас более старая версия, будут ошибки при попытке использовать `Annotated`.
+ Если у вас более старая версия, будут ошибки при попытке использовать `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`
-=== "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!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="3"
- {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="3"
+{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="3"
- {!> ../../../docs_src/dependencies/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip "Подсказка"
- Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно.
+```Python hl_lines="3"
+{!> ../../../docs_src/dependencies/tutorial001_an.py!}
+```
- ```Python hl_lines="1"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip "Подсказка"
- Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="3"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно.
+
+///
+
+```Python hl_lines="1"
+{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "Подсказка"
+
+Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно.
+
+///
+
+```Python hl_lines="3"
+{!> ../../../docs_src/dependencies/tutorial001.py!}
+```
+
+////
### Объявите зависимость в "зависимом"
Точно так же, как вы использовали `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!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="15 20"
- {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="15 20"
+{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="16 21"
- {!> ../../../docs_src/dependencies/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip "Подсказка"
- Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно.
+```Python hl_lines="16 21"
+{!> ../../../docs_src/dependencies/tutorial001_an.py!}
+```
- ```Python hl_lines="11 16"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip "Подсказка"
- Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="15 20"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно.
+
+///
+
+```Python hl_lines="11 16"
+{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "Подсказка"
+
+Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно.
+
+///
+
+```Python hl_lines="15 20"
+{!> ../../../docs_src/dependencies/tutorial001.py!}
+```
+
+////
`Depends` работает немного иначе. Вы передаёте в `Depends` одиночный параметр, который будет похож на функцию.
@@ -176,8 +225,11 @@
И потом функция берёт параметры так же, как *функция обработки пути*.
-!!! tip "Подсказка"
- В следующей главе вы увидите, какие другие вещи, помимо функций, можно использовать в качестве зависимостей.
+/// tip | "Подсказка"
+
+В следующей главе вы увидите, какие другие вещи, помимо функций, можно использовать в качестве зависимостей.
+
+///
Каждый раз, когда новый запрос приходит, **FastAPI** позаботится о:
@@ -198,10 +250,13 @@ common_parameters --> read_users
Таким образом, вы пишете общий код один раз, и **FastAPI** позаботится о его вызове для ваших *операций с путями*.
-!!! check "Проверка"
- Обратите внимание, что вы не создаёте специальный класс и не передаёте его куда-то в **FastAPI** для регистрации, или что-то в этом роде.
+/// check | "Проверка"
- Вы просто передаёте это в `Depends`, и **FastAPI** знает, что делать дальше.
+Обратите внимание, что вы не создаёте специальный класс и не передаёте его куда-то в **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
new file mode 100644
index 000000000..332470396
--- /dev/null
+++ b/docs/ru/docs/tutorial/dependencies/sub-dependencies.md
@@ -0,0 +1,255 @@
+# Подзависимости
+
+Вы можете создавать зависимости, которые имеют **подзависимости**.
+
+Их **вложенность** может быть любой глубины.
+
+**FastAPI** сам займётся их управлением.
+
+## Провайдер зависимости
+
+Можно создать первую зависимость следующим образом:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="8-9"
+{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="8-9"
+{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.6+
+
+```Python hl_lines="9-10"
+{!> ../../../docs_src/dependencies/tutorial005_an.py!}
+```
+
+////
+
+//// tab | Python 3.10 без Annotated
+
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="6-7"
+{!> ../../../docs_src/dependencies/tutorial005_py310.py!}
+```
+
+////
+
+//// tab | Python 3.6 без Annotated
+
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="8-9"
+{!> ../../../docs_src/dependencies/tutorial005.py!}
+```
+
+////
+
+Она объявляет необязательный параметр запроса `q` как строку, а затем возвращает его.
+
+Это довольно просто (хотя и не очень полезно), но поможет нам сосредоточиться на том, как работают подзависимости.
+
+## Вторая зависимость
+
+Затем можно создать еще одну функцию зависимости, которая в то же время содержит внутри себя первую зависимость (таким образом, она тоже является "зависимой"):
+
+//// tab | Python 3.10+
+
+```Python hl_lines="13"
+{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="13"
+{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.6+
+
+```Python hl_lines="14"
+{!> ../../../docs_src/dependencies/tutorial005_an.py!}
+```
+
+////
+
+//// tab | Python 3.10 без Annotated
+
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="11"
+{!> ../../../docs_src/dependencies/tutorial005_py310.py!}
+```
+
+////
+
+//// tab | Python 3.6 без Annotated
+
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="13"
+{!> ../../../docs_src/dependencies/tutorial005.py!}
+```
+
+////
+
+Остановимся на объявленных параметрах:
+
+* Несмотря на то, что эта функция сама является зависимостью, она также является зависимой от чего-то другого.
+ * Она зависит от `query_extractor` и присваивает возвращаемое ей значение параметру `q`.
+* Она также объявляет необязательный куки-параметр `last_query` в виде строки.
+ * Если пользователь не указал параметр `q` в запросе, то мы используем последний использованный запрос, который мы ранее сохранили в куки-параметре `last_query`.
+
+## Использование зависимости
+
+Затем мы можем использовать зависимость вместе с:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="23"
+{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="23"
+{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.6+
+
+```Python hl_lines="24"
+{!> ../../../docs_src/dependencies/tutorial005_an.py!}
+```
+
+////
+
+//// tab | Python 3.10 без Annotated
+
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="19"
+{!> ../../../docs_src/dependencies/tutorial005_py310.py!}
+```
+
+////
+
+//// tab | Python 3.6 без Annotated
+
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="22"
+{!> ../../../docs_src/dependencies/tutorial005.py!}
+```
+
+////
+
+/// 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** будет знать, что вызывать эту подзависимость нужно только один раз за запрос.
+
+При этом возвращаемое значение будет сохранено в "кэш" и будет передано всем "зависимым" функциям, которые нуждаются в нем внутри этого конкретного запроса, вместо того, чтобы вызывать зависимость несколько раз для одного и того же запроса.
+
+В расширенном сценарии, когда вы знаете, что вам нужно, чтобы зависимость вызывалась на каждом шаге (возможно, несколько раз) в одном и том же запросе, вместо использования "кэшированного" значения, вы можете установить параметр `use_cache=False` при использовании `Depends`:
+
+//// 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}
+```
+
+////
+
+//// tab | 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 | "Подсказка"
+
+Все это может показаться не столь полезным на этих простых примерах.
+
+Но вы увидите как это пригодится в главах посвященных безопасности.
+
+И вы также увидите, сколько кода это вам сэкономит.
+
+///
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!}
+```
-=== "Python 3.10 и выше"
+////
- ```Python hl_lines="17-18"
- {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
- ```
+//// tab | Python 3.10 и выше
+
+```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!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9 15-16 19-20 23-24"
- {!> ../../../docs_src/extra_models/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="9 15-16 19-20 23-24"
+{!> ../../../docs_src/extra_models/tutorial002.py!}
+```
+
+////
## `Union` или `anyOf`
@@ -178,20 +192,27 @@ UserInDB(
Для этого используйте стандартные аннотации типов в Python `typing.Union`:
-!!! note "Примечание"
- При объявлении `Union`, сначала указывайте наиболее детальные типы, затем менее детальные. В примере ниже более детальный `PlaneItem` стоит перед `CarItem` в `Union[PlaneItem, CarItem]`.
+/// note | "Примечание"
-=== "Python 3.10+"
+При объявлении `Union`, сначала указывайте наиболее детальные типы, затем менее детальные. В примере ниже более детальный `PlaneItem` стоит перед `CarItem` в `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` в 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!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1 8"
- {!> ../../../docs_src/extra_models/tutorial005.py!}
- ```
+//// tab | Python 3.8+
+
+```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 b46f235bc..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
get операцию
-!!! 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 | "Подсказка"
- **FastAPI** не навязывает определенного значения для каждого метода.
+Вы можете использовать каждую операцию (HTTP-метод) по своему усмотрению.
- Информация здесь представлена как рекомендация, а не требование.
+**FastAPI** не навязывает определенного значения для каждого метода.
- Например, при использовании GraphQL обычно все действия выполняются только с помощью POST операций.
+Информация здесь представлена как рекомендация, а не требование.
+
+Например, при использовании GraphQL обычно все действия выполняются только с помощью POST операций.
+
+///
### Шаг 4: определите **функцию операции пути**
@@ -309,8 +324,11 @@ https://example.com/items/foo
{!../../../docs_src/first_steps/tutorial003.py!}
```
-!!! note "Технические детали"
- Если не знаете в чём разница, посмотрите [Конкурентность: *"Нет времени?"*](../async.md#in-a-hurry){.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 | "Технические детали"
- **FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette. То же самое касается и `Request`.
+Также можно использовать `from starlette.requests import Request` и `from starlette.responses import JSONResponse`.
+
+**FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette. То же самое касается и `Request`.
+
+///
## Переопределение стандартных обработчиков исключений
@@ -160,8 +166,11 @@ path -> item_id
#### `RequestValidationError` или `ValidationError`
-!!! warning "Внимание"
- Это технические детали, которые можно пропустить, если они не важны для вас сейчас.
+/// warning | "Внимание"
+
+Это технические детали, которые можно пропустить, если они не важны для вас сейчас.
+
+///
`RequestValidationError` является подклассом Pydantic `ValidationError`.
@@ -183,10 +192,13 @@ path -> item_id
{!../../../docs_src/handling_errors/tutorial004.py!}
```
-!!! note "Технические детали"
- Можно также использовать `from starlette.responses import PlainTextResponse`.
+/// note | "Технические детали"
- **FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette.
+Можно также использовать `from starlette.responses import PlainTextResponse`.
+
+**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+"
+////
- ```Python hl_lines="3"
- {!> ../../../docs_src/header_params/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="3"
+{!> ../../../docs_src/header_params/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="3"
- {!> ../../../docs_src/header_params/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.8+
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+```Python hl_lines="3"
+{!> ../../../docs_src/header_params/tutorial001_an.py!}
+```
- ```Python hl_lines="1"
- {!> ../../../docs_src/header_params/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ без Annotated"
+//// tab | Python 3.10+ без Annotated
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="3"
- {!> ../../../docs_src/header_params/tutorial001.py!}
- ```
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="1"
+{!> ../../../docs_src/header_params/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ без Annotated
+
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="3"
+{!> ../../../docs_src/header_params/tutorial001.py!}
+```
+
+////
## Объявление параметров `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!}
+```
-!!! info "Дополнительная информация"
- Чтобы объявить заголовки, важно использовать `Header`, иначе параметры интерпретируются как query-параметры.
+////
+
+//// tab | Python 3.8+ без Annotated
+
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/header_params/tutorial001.py!}
+```
+
+////
+
+/// 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!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="11"
- {!> ../../../docs_src/header_params/tutorial002_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="11"
+{!> ../../../docs_src/header_params/tutorial002_an_py39.py!}
+```
- ```Python hl_lines="12"
- {!> ../../../docs_src/header_params/tutorial002_an.py!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.8+
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+```Python hl_lines="12"
+{!> ../../../docs_src/header_params/tutorial002_an.py!}
+```
- ```Python hl_lines="8"
- {!> ../../../docs_src/header_params/tutorial002_py310.py!}
- ```
+////
-=== "Python 3.8+ без Annotated"
+//// tab | Python 3.10+ без Annotated
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="10"
- {!> ../../../docs_src/header_params/tutorial002.py!}
- ```
+Предпочтительнее использовать версию с аннотацией, если это возможно.
-!!! warning "Внимание"
- Прежде чем установить для `convert_underscores` значение `False`, имейте в виду, что некоторые HTTP-прокси и серверы запрещают использование заголовков с подчеркиванием.
+///
+
+```Python hl_lines="8"
+{!> ../../../docs_src/header_params/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ без Annotated
+
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="10"
+{!> ../../../docs_src/header_params/tutorial002.py!}
+```
+
+////
+
+/// 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!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/header_params/tutorial003_py310.py!}
- ```
+////
-=== "Python 3.9+ без Annotated"
+//// tab | Python 3.10+ без Annotated
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial003_py39.py!}
- ```
+Предпочтительнее использовать версию с аннотацией, если это возможно.
-=== "Python 3.8+ без Annotated"
+///
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+```Python hl_lines="7"
+{!> ../../../docs_src/header_params/tutorial003_py310.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial003.py!}
- ```
+////
+
+//// tab | Python 3.9+ без Annotated
+
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/header_params/tutorial003_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ без Annotated
+
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/header_params/tutorial003.py!}
+```
+
+////
Если вы взаимодействуете с этой *операцией пути*, отправляя два 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
+```
- ```
- pip install "uvicorn[standard]"
- ```
+Также установите `uvicorn` для работы в качестве сервера:
- И то же самое для каждой из необязательных зависимостей, которые вы хотите использовать.
+```
+pip install "uvicorn[standard]"
+```
+
+И то же самое для каждой из необязательных зависимостей, которые вы хотите использовать.
+
+///
## Продвинутое руководство пользователя
diff --git a/docs/ru/docs/tutorial/metadata.md b/docs/ru/docs/tutorial/metadata.md
index 331c96734..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/#tags){.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!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="3 17"
- {!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="3 17"
+{!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!}
+```
- ```Python hl_lines="3 17"
- {!> ../../../docs_src/path_operation_configuration/tutorial001.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="3 17"
+{!> ../../../docs_src/path_operation_configuration/tutorial001.py!}
+```
+
+////
Этот код состояния будет использован в ответе и будет добавлен в схему OpenAPI.
-!!! note "Технические детали"
- Вы также можете использовать `from starlette import status`.
+/// note | "Технические детали"
- **FastAPI** предоставляет тот же `starlette.status` под псевдонимом `fastapi.status` для удобства разработчика. Но его источник - это непосредственно Starlette.
+Вы также можете использовать `from starlette import status`.
+
+**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+"
+////
- ```Python hl_lines="17 22 27"
- {!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```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.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!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="20-21"
- {!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="20-21"
+{!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!}
+```
- ```Python hl_lines="20-21"
- {!> ../../../docs_src/path_operation_configuration/tutorial003.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="20-21"
+{!> ../../../docs_src/path_operation_configuration/tutorial003.py!}
+```
+
+////
## Описание из строк документации
@@ -104,23 +128,29 @@
Вы можете использовать Markdown в строке документации, и он будет интерпретирован и отображён корректно (с учетом отступа в строке документации).
-=== "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!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="19-27"
- {!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="19-27"
+{!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!}
+```
- ```Python hl_lines="19-27"
- {!> ../../../docs_src/path_operation_configuration/tutorial004.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```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!}
- ```
+```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!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="21"
+{!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!}
+```
- ```Python hl_lines="21"
- {!> ../../../docs_src/path_operation_configuration/tutorial005.py!}
- ```
+////
-!!! info "Дополнительная информация"
- Помните, что `response_description` относится конкретно к ответу, а `description` относится к *операции пути* в целом.
+//// tab | Python 3.8+
-!!! check "Технические детали"
- OpenAPI указывает, что каждой *операции пути* необходимо описание ответа.
+```Python hl_lines="21"
+{!> ../../../docs_src/path_operation_configuration/tutorial005.py!}
+```
- Если вдруг вы не укажете его, то **FastAPI** автоматически сгенерирует это описание с текстом "Successful response".
+////
+
+/// info | "Дополнительная информация"
+
+Помните, что `response_description` относится конкретно к ответу, а `description` относится к *операции пути* в целом.
+
+///
+
+/// check | "Технические детали"
+
+OpenAPI указывает, что каждой *операции пути* необходимо описание ответа.
+
+Если вдруг вы не укажете его, то **FastAPI** автоматически сгенерирует это описание с текстом "Successful response".
+
+///
diff --git a/docs/ru/docs/tutorial/path-params-numeric-validations.md b/docs/ru/docs/tutorial/path-params-numeric-validations.md
index bd2c29d0a..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!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="1 3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="1 3"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="3-4"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.8+
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+```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!}
- ```
+////
-=== "Python 3.8+ без Annotated"
+//// tab | Python 3.10+ без Annotated
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
-!!! info "Информация"
- Поддержка `Annotated` была добавлена в FastAPI начиная с версии 0.95.0 (и с этой версии рекомендуется использовать этот подход).
+///
- Если вы используете более старую версию, вы столкнётесь с ошибками при попытке использовать `Annotated`.
+```Python hl_lines="1"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
+```
- Убедитесь, что вы [обновили версию FastAPI](../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} как минимум до 0.95.1 перед тем, как использовать `Annotated`.
+////
+
+//// tab | Python 3.8+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="3"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
+```
+
+////
+
+/// info | "Информация"
+
+Поддержка `Annotated` была добавлена в FastAPI начиная с версии 0.95.0 (и с этой версии рекомендуется использовать этот подход).
+
+Если вы используете более старую версию, вы столкнётесь с ошибками при попытке использовать `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 "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="7"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!}
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```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+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!}
- ```
+//// tab | Python 3.8+
+
+```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+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!}
- ```
+//// tab | Python 3.8+
+
+```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!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ без Annotated"
+```Python hl_lines="9"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!}
+```
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!}
- ```
+//// tab | Python 3.8+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```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!}
- ```
+```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!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ без Annotated"
+```Python hl_lines="9"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!}
+```
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!}
- ```
+//// tab | Python 3.8+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!}
+```
+
+////
## Валидация числовых данных: числа с плавающей точкой, больше и меньше
@@ -245,26 +320,35 @@ Python не будет ничего делать с `*`, но он будет з
То же самое справедливо и для lt.
-=== "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+ без Annotated"
+```Python hl_lines="12"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!}
+```
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+////
- ```Python hl_lines="11"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!}
- ```
+//// tab | Python 3.8+ без Annotated
+
+/// 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`, на самом деле являются функциями, которые при вызове возвращают экземпляры одноимённых классов.
+Все они используют те же параметры для дополнительной валидации и метаданных, которые вы видели ранее.
- Объект `Query`, который вы импортируете, является функцией. И при вызове она возвращает экземпляр одноимённого класса `Query`.
+///
- Использование функций (вместо использования классов напрямую) нужно для того, чтобы ваш редактор не подсвечивал ошибки, связанные с их типами.
+/// note | "Технические детали"
- Таким образом вы можете использовать привычный вам редактор и инструменты разработки, не добавляя дополнительных конфигураций для игнорирования подобных ошибок.
+`Query`, `Path` и другие "классы", которые вы импортируете из `fastapi`, на самом деле являются функциями, которые при вызове возвращают экземпляры одноимённых классов.
+
+Объект `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 | "Заметка"
+
+Это обеспечит поддержку редактора внутри функции (проверка ошибок, автодополнение и т.п.).
+
+///
## Преобразование данных
@@ -35,10 +38,13 @@
{"item_id":3}
```
-!!! check "Заметка"
- Обратите внимание на значение `3`, которое получила (и вернула) функция. Это целочисленный Python `int`, а не строка `"3"`.
+/// check | "Заметка"
- Используя определения типов, **FastAPI** выполняет автоматический "парсинг" запросов.
+Обратите внимание на значение `3`, которое получила (и вернула) функция. Это целочисленный Python `int`, а не строка `"3"`.
+
+Используя определения типов, **FastAPI** выполняет автоматический "парсинг" запросов.
+
+///
## Проверка данных
@@ -63,12 +69,15 @@
Та же ошибка возникнет, если вместо `int` передать `float` , например: http://127.0.0.1:8000/items/4.2
-!!! check "Заметка"
- **FastAPI** обеспечивает проверку типов, используя всё те же определения типов.
+/// check | "Заметка"
- Обратите внимание, что в тексте ошибки явно указано место не прошедшее проверку.
+**FastAPI** обеспечивает проверку типов, используя всё те же определения типов.
- Это очень полезно при разработке и отладке кода, который взаимодействует с API.
+Обратите внимание, что в тексте ошибки явно указано место не прошедшее проверку.
+
+Это очень полезно при разработке и отладке кода, который взаимодействует с API.
+
+///
## Документация
@@ -76,10 +85,13 @@
-!!! check "Заметка"
- Ещё раз, просто используя определения типов, **FastAPI** обеспечивает автоматическую интерактивную документацию (с интеграцией Swagger UI).
+/// check | "Заметка"
- Обратите внимание, что параметр пути объявлен целочисленным.
+Ещё раз, просто используя определения типов, **FastAPI** обеспечивает автоматическую интерактивную документацию (с интеграцией Swagger UI).
+
+Обратите внимание, что параметр пути объявлен целочисленным.
+
+///
## Преимущества стандартизации, альтернативная документация
@@ -140,11 +152,17 @@
{!../../../docs_src/path_params/tutorial005.py!}
```
-!!! info "Дополнительная информация"
- Перечисления (enum) доступны в Python начиная с версии 3.4.
+/// info | "Дополнительная информация"
-!!! tip "Подсказка"
- Если интересно, то "AlexNet", "ResNet" и "LeNet" - это названия моделей машинного обучения.
+Перечисления (enum) доступны в Python начиная с версии 3.4.
+
+///
+
+/// tip | "Подсказка"
+
+Если интересно, то "AlexNet", "ResNet" и "LeNet" - это названия моделей машинного обучения.
+
+///
### Определение *параметра пути*
@@ -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 | "Подсказка"
- В этом случае URL будет таким: `/files//home/johndoe/myfile.txt`, с двойным слэшем (`//`) между `files` и `home`.
+Возможно, вам понадобится, чтобы параметр содержал `/home/johndoe/myfile.txt` с ведущим слэшем (`/`).
+
+В этом случае 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+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```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 3.9 или выше, `Annotated` является частью стандартной библиотеки, таким образом вы можете импортировать его из `typing`.
- ```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+"
+////
- В версиях Python ниже Python 3.9 `Annotation` импортируется из `typing_extensions`.
+//// tab | Python 3.8+
- Эта библиотека будет установлена вместе с FastAPI.
+В версиях Python ниже Python 3.9 `Annotation` импортируется из `typing_extensions`.
- ```Python hl_lines="3-4"
- {!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!}
- ```
+Эта библиотека будет установлена вместе с FastAPI.
+
+```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
+```
-=== "Python 3.8+"
+////
- ```Python
- q: Annotated[Union[str, None]] = None
- ```
+//// tab | Python 3.8+
+
+```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+"
+////
- ```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!}
+```
+
+////
Обратите внимание, что значение по умолчанию всё ещё `None`, так что параметр остаётся необязательным.
@@ -120,22 +143,29 @@ Query-параметр `q` имеет тип `Union[str, None]` (или `str | N
В предыдущих версиях FastAPI (ниже 0.95.0) необходимо было использовать `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)
- ```
+или:
- так как `None` указан в качестве значения по умолчанию, параметр будет **необязательным**.
+```Python
+= Query(default=None)
+```
- `Union[str, None]` позволит редактору кода оказать вам лучшую поддержку. Но это не то, на что обращает внимание FastAPI для определения необязательности параметра.
+так как `None` указан в качестве значения по умолчанию, параметр будет **необязательным**.
+
+`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!}
- ```
+```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!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial003_an_py39.py!}
+```
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial003_an.py!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.8+
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+```Python hl_lines="11"
+{!> ../../../docs_src/query_params_str_validations/tutorial003_an.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!}
- ```
+////
-=== "Python 3.8+ без Annotated"
+//// tab | Python 3.10+ без Annotated
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial003.py!}
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial003.py!}
+```
+
+////
## Регулярные выражения
Вы можете определить регулярное выражение, которому должен соответствовать параметр:
-=== "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!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.8+
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+```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.8+ без Annotated"
+//// tab | Python 3.10+ без Annotated
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial004.py!}
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="11"
+{!> ../../../docs_src/query_params_str_validations/tutorial004.py!}
+```
+
+////
Данное регулярное выражение проверяет, что полученное значение параметра:
@@ -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!}
- ```
+```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!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ без Annotated"
+```Python hl_lines="8"
+{!> ../../../docs_src/query_params_str_validations/tutorial005_an.py!}
+```
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial005.py!}
- ```
+//// tab | Python 3.8+ без Annotated
-!!! note "Технические детали"
- Наличие значения по умолчанию делает параметр необязательным.
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial005.py!}
+```
+
+////
+
+/// 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
+```
-=== "без Annotated"
+////
- ```Python
- q: Union[str, None] = Query(default=None, min_length=3)
- ```
+//// tab | без Annotated
+
+```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!}
+```
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial006.py!}
- ```
+//// tab | Python 3.8+ без Annotated
- !!! tip "Подсказка"
- Обратите внимание, что даже когда `Query()` используется как значение по умолчанию для параметра функции, мы не передаём `default=None` в `Query()`.
+/// tip | "Подсказка"
- Лучше будет использовать версию с `Annotated`. 😉
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial006.py!}
+```
+
+/// tip | "Подсказка"
+
+Обратите внимание, что даже когда `Query()` используется как значение по умолчанию для параметра функции, мы не передаём `default=None` в `Query()`.
+
+Лучше будет использовать версию с `Annotated`. 😉
+
+///
+
+////
### Обязательный параметр с Ellipsis (`...`)
Альтернативный способ указать обязательность параметра запроса - это указать параметр `default` через многоточие `...`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!}
- ```
+```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!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ без Annotated"
+```Python hl_lines="8"
+{!> ../../../docs_src/query_params_str_validations/tutorial006b_an.py!}
+```
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial006b.py!}
- ```
+//// tab | Python 3.8+ без Annotated
-!!! info "Дополнительная информация"
- Если вы ранее не сталкивались с `...`: это специальное значение, часть языка Python и называется "Ellipsis".
+/// tip | "Подсказка"
- Используется в Pydantic и FastAPI для определения, что значение требуется обязательно.
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial006b.py!}
+```
+
+////
+
+/// info | "Дополнительная информация"
+
+Если вы ранее не сталкивались с `...`: это специальное значение, часть языка Python и называется "Ellipsis".
+
+Используется в 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!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial006c_an.py!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.8+
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial006c_an.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!}
- ```
+////
-=== "Python 3.8+ без Annotated"
+//// tab | Python 3.10+ без 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, раздел Обязательные Опциональные поля.
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial006c.py!}
+```
+
+////
+
+/// tip | "Подсказка"
+
+Pydantic, мощь которого используется в FastAPI для валидации и сериализации, имеет специальное поведение для `Optional` или `Union[Something, None]` без значения по умолчанию. Вы можете узнать об этом больше в документации Pydantic, раздел Обязательные Опциональные поля.
+
+///
### Использование 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!}
- ```
+```Python hl_lines="4 10"
+{!> ../../../docs_src/query_params_str_validations/tutorial006d_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="2 9"
- {!> ../../../docs_src/query_params_str_validations/tutorial006d_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ без Annotated"
+```Python hl_lines="2 9"
+{!> ../../../docs_src/query_params_str_validations/tutorial006d_an.py!}
+```
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+////
- ```Python hl_lines="2 8"
- {!> ../../../docs_src/query_params_str_validations/tutorial006d.py!}
- ```
+//// tab | Python 3.8+ без Annotated
-!!! tip "Подсказка"
- Запомните, когда вам необходимо объявить query-параметр обязательным, вы можете просто не указывать параметр `default`. Таким образом, вам редко придётся использовать `...` или `Required`.
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="2 8"
+{!> ../../../docs_src/query_params_str_validations/tutorial006d.py!}
+```
+
+////
+
+/// 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!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial011_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "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.10+ без Annotated"
+//// tab | Python 3.8+
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial011_an.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial011_py310.py!}
- ```
+////
-=== "Python 3.9+ без Annotated"
+//// tab | Python 3.10+ без Annotated
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!}
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
-=== "Python 3.8+ без Annotated"
+///
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial011_py310.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial011.py!}
- ```
+////
+
+//// tab | Python 3.9+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial011.py!}
+```
+
+////
Затем, получив такой 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!}
- ```
+```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!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ без Annotated"
+```Python hl_lines="8"
+{!> ../../../docs_src/query_params_str_validations/tutorial013_an.py!}
+```
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial013.py!}
- ```
+//// tab | Python 3.8+ без Annotated
-!!! note "Технические детали"
- Запомните, что в таком случае, FastAPI не будет проверять содержимое списка.
+/// tip | "Подсказка"
- Например, для List[int] список будет провалидирован (и задокументирован) на содержание только целочисленных элементов. Но для простого `list` такой проверки не будет.
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial013.py!}
+```
+
+////
+
+/// note | "Технические детали"
+
+Запомните, что в таком случае, FastAPI не будет проверять содержимое списка.
+
+Например, для 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!}
- ```
+```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!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial007_an_py39.py!}
+```
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial007_an.py!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.8+
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+```Python hl_lines="11"
+{!> ../../../docs_src/query_params_str_validations/tutorial007_an.py!}
+```
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!}
- ```
+////
-=== "Python 3.8+ без Annotated"
+//// tab | Python 3.10+ без Annotated
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial007.py!}
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="8"
+{!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial007.py!}
+```
+
+////
Добавить описание, используя параметр `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!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="14"
- {!> ../../../docs_src/query_params_str_validations/tutorial008_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="14"
+{!> ../../../docs_src/query_params_str_validations/tutorial008_an_py39.py!}
+```
- ```Python hl_lines="15"
- {!> ../../../docs_src/query_params_str_validations/tutorial008_an.py!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.8+
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+```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.8+ без Annotated"
+//// tab | Python 3.10+ без Annotated
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="13"
- {!> ../../../docs_src/query_params_str_validations/tutorial008.py!}
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="11"
+{!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="13"
+{!> ../../../docs_src/query_params_str_validations/tutorial008.py!}
+```
+
+////
## Псевдонимы параметров
@@ -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+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial009_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial009_an_py39.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial009_an.py!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.8+
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial009_an.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!}
- ```
+////
-=== "Python 3.8+ без Annotated"
+//// tab | Python 3.10+ без Annotated
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial009.py!}
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params_str_validations/tutorial009.py!}
+```
+
+////
## Устаревшие параметры
@@ -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!}
- ```
+```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!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="19"
+{!> ../../../docs_src/query_params_str_validations/tutorial010_an_py39.py!}
+```
- ```Python hl_lines="20"
- {!> ../../../docs_src/query_params_str_validations/tutorial010_an.py!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.8+
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+```Python hl_lines="20"
+{!> ../../../docs_src/query_params_str_validations/tutorial010_an.py!}
+```
- ```Python hl_lines="16"
- {!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!}
- ```
+////
-=== "Python 3.8+ без Annotated"
+//// tab | Python 3.10+ без Annotated
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="18"
- {!> ../../../docs_src/query_params_str_validations/tutorial010.py!}
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="16"
+{!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="18"
+{!> ../../../docs_src/query_params_str_validations/tutorial010.py!}
+```
+
+////
В документации это будет отображено следующим образом:
@@ -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!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial014_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params_str_validations/tutorial014_an_py39.py!}
+```
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial014_an.py!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.8+
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+```Python hl_lines="11"
+{!> ../../../docs_src/query_params_str_validations/tutorial014_an.py!}
+```
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!}
- ```
+////
-=== "Python 3.8+ без Annotated"
+//// tab | Python 3.10+ без Annotated
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial014.py!}
- ```
+Рекомендуется использовать версию с `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!}
+```
+
+////
## Резюме
diff --git a/docs/ru/docs/tutorial/query-params.md b/docs/ru/docs/tutorial/query-params.md
index 6e885cb65..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!}
+```
-=== "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` по умолчанию.
-!!! Важно
- Также обратите внимание, что **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+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params/tutorial003.py!}
- ```
+//// tab | Python 3.8+
+
+```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!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="8 10"
- {!> ../../../docs_src/query_params/tutorial004.py!}
- ```
+//// tab | Python 3.8+
+
+```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`.
-!!! подсказка
- Вы можете использовать класс `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/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 "Дополнительная информация"
- Чтобы получать загруженные файлы, сначала установите `python-multipart`.
+/// info | "Дополнительная информация"
- Например: `pip install python-multipart`.
+Чтобы получать загруженные файлы, сначала установите `python-multipart`.
- Это связано с тем, что загружаемые файлы передаются как данные формы.
+Например: `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!}
+```
-=== "Python 3.6+"
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/request_files/tutorial001_an.py!}
- ```
+//// tab | Python 3.6+
-=== "Python 3.6+ без Annotated"
+```Python hl_lines="1"
+{!> ../../../docs_src/request_files/tutorial001_an.py!}
+```
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/request_files/tutorial001.py!}
- ```
+//// tab | Python 3.6+ без Annotated
+
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```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!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/request_files/tutorial001_an_py39.py!}
+```
-=== "Python 3.6+"
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/request_files/tutorial001_an.py!}
- ```
+//// tab | Python 3.6+
-=== "Python 3.6+ без Annotated"
+```Python hl_lines="8"
+{!> ../../../docs_src/request_files/tutorial001_an.py!}
+```
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/request_files/tutorial001.py!}
- ```
+//// tab | Python 3.6+ без Annotated
-!!! info "Дополнительная информация"
- `File` - это класс, который наследуется непосредственно от `Form`.
+/// tip | "Подсказка"
- Но помните, что когда вы импортируете `Query`, `Path`, `File` и другие из `fastapi`, на самом деле это функции, которые возвращают специальные классы.
+Предпочтительнее использовать версию с аннотацией, если это возможно.
-!!! tip "Подсказка"
- Для объявления тела файла необходимо использовать `File`, поскольку в противном случае параметры будут интерпретироваться как параметры запроса или параметры тела (JSON).
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/request_files/tutorial001.py!}
+```
+
+////
+
+/// info | "Дополнительная информация"
+
+`File` - это класс, который наследуется непосредственно от `Form`.
+
+Но помните, что когда вы импортируете `Query`, `Path`, `File` и другие из `fastapi`, на самом деле это функции, которые возвращают специальные классы.
+
+///
+
+/// 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!}
+```
-=== "Python 3.6+"
+////
- ```Python hl_lines="13"
- {!> ../../../docs_src/request_files/tutorial001_an.py!}
- ```
+//// tab | Python 3.6+
-=== "Python 3.6+ без Annotated"
+```Python hl_lines="13"
+{!> ../../../docs_src/request_files/tutorial001_an.py!}
+```
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+////
- ```Python hl_lines="12"
- {!> ../../../docs_src/request_files/tutorial001.py!}
- ```
+//// tab | Python 3.6+ без Annotated
+
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```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`"
-!!! note "Технические детали Starlette"
- **FastAPI** наследует `UploadFile` непосредственно из **Starlette**, но добавляет некоторые детали для совместимости с **Pydantic** и другими частями FastAPI.
+При использовании методов `async` **FastAPI** запускает файловые методы в пуле потоков и ожидает их.
+
+///
+
+/// note | "Технические детали Starlette"
+
+**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 | "Технические детали"
- Но когда форма включает файлы, она кодируется как multipart/form-data. Если вы используете `File`, **FastAPI** будет знать, что ему нужно получить файлы из нужной части тела.
+Данные из форм обычно кодируются с использованием "media type" `application/x-www-form-urlencoded` когда он не включает файлы.
- Если вы хотите узнать больше об этих кодировках и полях форм, перейдите по ссылке MDN web docs for POST.
+Но когда форма включает файлы, она кодируется как multipart/form-data. Если вы используете `File`, **FastAPI** будет знать, что ему нужно получить файлы из нужной части тела.
-!!! warning "Внимание"
- В операции *функции операции пути* можно объявить несколько параметров `File` и `Form`, но нельзя также объявлять поля `Body`, которые предполагается получить в виде JSON, поскольку тело запроса будет закодировано с помощью `multipart/form-data`, а не `application/json`.
+Если вы хотите узнать больше об этих кодировках и полях форм, перейдите по ссылке MDN web docs for POST.
- Это не является ограничением **FastAPI**, это часть протокола HTTP.
+///
+
+/// warning | "Внимание"
+
+В операции *функции операции пути* можно объявить несколько параметров `File` и `Form`, но нельзя также объявлять поля `Body`, которые предполагается получить в виде JSON, поскольку тело запроса будет закодировано с помощью `multipart/form-data`, а не `application/json`.
+
+Это не является ограничением **FastAPI**, это часть протокола HTTP.
+
+///
## Необязательная загрузка файлов
Вы можете сделать загрузку файла необязательной, используя стандартные аннотации типов и установив значение по умолчанию `None`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9 17"
- {!> ../../../docs_src/request_files/tutorial001_02_an_py310.py!}
- ```
+```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!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.6+"
+```Python hl_lines="9 17"
+{!> ../../../docs_src/request_files/tutorial001_02_an_py39.py!}
+```
- ```Python hl_lines="10 18"
- {!> ../../../docs_src/request_files/tutorial001_02_an.py!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.6+
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+```Python hl_lines="10 18"
+{!> ../../../docs_src/request_files/tutorial001_02_an.py!}
+```
- ```Python hl_lines="7 15"
- {!> ../../../docs_src/request_files/tutorial001_02_py310.py!}
- ```
+////
-=== "Python 3.6+ без Annotated"
+//// tab | Python 3.10+ без Annotated
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="9 17"
- {!> ../../../docs_src/request_files/tutorial001_02.py!}
- ```
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="7 15"
+{!> ../../../docs_src/request_files/tutorial001_02_py310.py!}
+```
+
+////
+
+//// tab | Python 3.6+ без Annotated
+
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="9 17"
+{!> ../../../docs_src/request_files/tutorial001_02.py!}
+```
+
+////
## `UploadFile` с дополнительными метаданными
Вы также можете использовать `File()` вместе с `UploadFile`, например, для установки дополнительных метаданных:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="9 15"
- {!> ../../../docs_src/request_files/tutorial001_03_an_py39.py!}
- ```
+```Python hl_lines="9 15"
+{!> ../../../docs_src/request_files/tutorial001_03_an_py39.py!}
+```
-=== "Python 3.6+"
+////
- ```Python hl_lines="8 14"
- {!> ../../../docs_src/request_files/tutorial001_03_an.py!}
- ```
+//// tab | Python 3.6+
-=== "Python 3.6+ без Annotated"
+```Python hl_lines="8 14"
+{!> ../../../docs_src/request_files/tutorial001_03_an.py!}
+```
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+////
- ```Python hl_lines="7 13"
- {!> ../../../docs_src/request_files/tutorial001_03.py!}
- ```
+//// tab | Python 3.6+ без Annotated
+
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```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+"
+////
- ```Python hl_lines="11 16"
- {!> ../../../docs_src/request_files/tutorial002_an.py!}
- ```
+//// tab | Python 3.6+
-=== "Python 3.9+ без Annotated"
+```Python hl_lines="11 16"
+{!> ../../../docs_src/request_files/tutorial002_an.py!}
+```
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+////
- ```Python hl_lines="8 13"
- {!> ../../../docs_src/request_files/tutorial002_py39.py!}
- ```
+//// tab | Python 3.9+ без Annotated
-=== "Python 3.6+ без Annotated"
+/// tip | "Подсказка"
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+Предпочтительнее использовать версию с аннотацией, если это возможно.
- ```Python hl_lines="10 15"
- {!> ../../../docs_src/request_files/tutorial002.py!}
- ```
+///
+
+```Python hl_lines="8 13"
+{!> ../../../docs_src/request_files/tutorial002_py39.py!}
+```
+
+////
+
+//// tab | Python 3.6+ без Annotated
+
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="10 15"
+{!> ../../../docs_src/request_files/tutorial002.py!}
+```
+
+////
Вы получите, как и было объявлено, список `list` из `bytes` или `UploadFile`.
-!!! note "Technical Details"
- Можно также использовать `from starlette.responses import HTMLResponse`.
+/// note | "Technical Details"
- **FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette.
+Можно также использовать `from starlette.responses import HTMLResponse`.
+
+**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="11 18"
- {!> ../../../docs_src/request_files/tutorial003.py!}
- ```
+///
+
+```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!}
+```
+
+////
## Резюме
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 "Дополнительная информация"
- Чтобы получать загруженные файлы и/или данные форм, сначала установите `python-multipart`.
+/// info | "Дополнительная информация"
- Например: `pip install python-multipart`.
+Чтобы получать загруженные файлы и/или данные форм, сначала установите `python-multipart`.
+
+Например: `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!}
- ```
+```Python hl_lines="3"
+{!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!}
+```
-=== "Python 3.6+"
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!}
- ```
+//// tab | Python 3.6+
-=== "Python 3.6+ без Annotated"
+```Python hl_lines="1"
+{!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!}
+```
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/request_forms_and_files/tutorial001.py!}
- ```
+//// tab | Python 3.6+ без Annotated
+
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```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 | "Внимание"
- Это не ограничение **Fast API**, это часть протокола HTTP.
+Вы можете объявить несколько параметров `File` и `Form` в операции *path*, но вы не можете также объявить поля `Body`, которые вы ожидаете получить в виде JSON, так как запрос будет иметь тело, закодированное с помощью `multipart/form-data` вместо `application/json`.
+
+Это не ограничение **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 "Дополнительная информация"
- Чтобы использовать формы, сначала установите `python-multipart`.
+/// info | "Дополнительная информация"
- Например, выполните команду `pip install python-multipart`.
+Чтобы использовать формы, сначала установите `python-multipart`.
+
+Например, выполните команду `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!}
- ```
+```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!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ без Annotated"
+```Python hl_lines="1"
+{!> ../../../docs_src/request_forms/tutorial001_an.py!}
+```
- !!! tip "Подсказка"
- Рекомендуется использовать 'Annotated' версию, если это возможно.
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/request_forms/tutorial001.py!}
- ```
+//// tab | Python 3.8+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать 'Annotated' версию, если это возможно.
+
+///
+
+```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!}
- ```
+```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!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ без Annotated"
+```Python hl_lines="8"
+{!> ../../../docs_src/request_forms/tutorial001_an.py!}
+```
- !!! tip "Подсказка"
- Рекомендуется использовать 'Annotated' версию, если это возможно.
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/request_forms/tutorial001.py!}
- ```
+//// tab | Python 3.8+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать 'Annotated' версию, если это возможно.
+
+///
+
+```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 | "Дополнительная информация"
-!!! tip "Подсказка"
- Вам необходимо явно указывать параметр `Form` при объявлении каждого поля, иначе поля будут интерпретироваться как параметры запроса или параметры тела (JSON).
+`Form` - это класс, который наследуется непосредственно от `Body`.
+
+///
+
+/// tip | "Подсказка"
+
+Вам необходимо явно указывать параметр `Form` при объявлении каждого поля, иначе поля будут интерпретироваться как параметры запроса или параметры тела (JSON).
+
+///
## О "полях формы"
@@ -75,17 +102,23 @@
**FastAPI** гарантирует правильное чтение этих данных из соответствующего места, а не из JSON.
-!!! note "Технические детали"
- Данные из форм обычно кодируются с использованием "типа медиа" `application/x-www-form-urlencoded`.
+/// note | "Технические детали"
- Но когда форма содержит файлы, она кодируется как `multipart/form-data`. Вы узнаете о работе с файлами в следующей главе.
+Данные из форм обычно кодируются с использованием "типа медиа" `application/x-www-form-urlencoded`.
- Если вы хотите узнать больше про кодировки и поля формы, ознакомьтесь с документацией MDN для `POST` на веб-сайте.
+Но когда форма содержит файлы, она кодируется как `multipart/form-data`. Вы узнаете о работе с файлами в следующей главе.
-!!! warning "Предупреждение"
- Вы можете объявлять несколько параметров `Form` в *операции пути*, но вы не можете одновременно с этим объявлять поля `Body`, которые вы ожидаете получить в виде JSON, так как запрос будет иметь тело, закодированное с использованием `application/x-www-form-urlencoded`, а не `application/json`.
+Если вы хотите узнать больше про кодировки и поля формы, ознакомьтесь с документацией MDN для `POST` на веб-сайте.
- Это не ограничение **FastAPI**, это часть протокола HTTP.
+///
+
+/// warning | "Предупреждение"
+
+Вы можете объявлять несколько параметров `Form` в *операции пути*, но вы не можете одновременно с этим объявлять поля `Body`, которые вы ожидаете получить в виде JSON, так как запрос будет иметь тело, закодированное с использованием `application/x-www-form-urlencoded`, а не `application/json`.
+
+Это не ограничение **FastAPI**, это часть протокола HTTP.
+
+///
## Резюме
diff --git a/docs/ru/docs/tutorial/response-model.md b/docs/ru/docs/tutorial/response-model.md
index 9b9b60dd5..f8c910fe9 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!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="18 23"
- {!> ../../../docs_src/response_model/tutorial001_01_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="18 23"
+{!> ../../../docs_src/response_model/tutorial001_01_py39.py!}
+```
- ```Python hl_lines="18 23"
- {!> ../../../docs_src/response_model/tutorial001_01.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```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+"
+////
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```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.py!}
- ```
+////
-!!! note "Технические детали"
- Помните, что параметр `response_model` является параметром именно декоратора http-методов (`get`, `post`, и т.п.). Не следует его указывать для *функций операций пути*, как вы бы поступили с другими параметрами или с телом запроса.
+//// tab | Python 3.8+
+
+```Python hl_lines="17 22 24-27"
+{!> ../../../docs_src/response_model/tutorial001.py!}
+```
+
+////
+
+/// note | "Технические детали"
+
+Помните, что параметр `response_model` является параметром именно декоратора http-методов (`get`, `post`, и т.п.). Не следует его указывать для *функций операций пути*, как вы бы поступили с другими параметрами или с телом запроса.
+
+///
`response_model` принимает те же типы, которые можно указать для какого-либо поля в модели Pydantic. Таким образом, это может быть как одиночная модель Pydantic, так и `список (list)` моделей Pydantic. Например, `List[Item]`.
FastAPI будет использовать значение `response_model` для того, чтобы автоматически генерировать документацию, производить валидацию и т.п. А также для **конвертации и фильтрации выходных данных** в объявленный тип.
-!!! tip "Подсказка"
- Если вы используете анализаторы типов со строгой проверкой (например, mypy), можно указать `Any` в качестве типа возвращаемого значения функции.
+/// tip | "Подсказка"
- Таким образом вы информируете ваш редактор кода, что намеренно возвращаете данные неопределенного типа. Но возможности FastAPI, такие как автоматическая генерация документации, валидация, фильтрация и т.д. все так же будут работать, просто используя параметр `response_model`.
+Если вы используете анализаторы типов со строгой проверкой (например, mypy), можно указать `Any` в качестве типа возвращаемого значения функции.
+
+Таким образом вы информируете ваш редактор кода, что намеренно возвращаете данные неопределенного типа. Но возможности 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!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9 11"
- {!> ../../../docs_src/response_model/tutorial002.py!}
- ```
+//// tab | Python 3.8+
-!!! info "Информация"
- Чтобы использовать `EmailStr`, прежде необходимо установить `email_validator`.
- Используйте `pip install email-validator`
- или `pip install pydantic[email]`.
+```Python hl_lines="9 11"
+{!> ../../../docs_src/response_model/tutorial002.py!}
+```
+
+////
+
+/// info | "Информация"
+
+Чтобы использовать `EmailStr`, прежде необходимо установить `email-validator`.
+Используйте `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+"
+////
- ```Python hl_lines="18"
- {!> ../../../docs_src/response_model/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+
+```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!}
+```
-=== "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!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+//// tab | Python 3.8+
+
+```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).
@@ -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!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9-13 15-16 20"
- {!> ../../../docs_src/response_model/tutorial003_01.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="9-13 15-16 20"
+{!> ../../../docs_src/response_model/tutorial003_01.py!}
+```
+
+////
Таким образом, мы получаем поддержку редактора кода и mypy в части типов, сохраняя при этом фильтрацию данных от FastAPI.
@@ -277,17 +325,21 @@ FastAPI совместно с Pydantic выполнит некоторую ма
То же самое произошло бы, если бы у вас было что-то вроде Union различных типов и один или несколько из них не являлись бы допустимыми типами для 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+"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/response_model/tutorial003_04.py!}
- ```
+//// tab | Python 3.8+
+
+```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+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/response_model/tutorial003_05.py!}
- ```
+//// tab | Python 3.8+
+
+```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!}
+```
-=== "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!}
+```
- ```Python hl_lines="11 13-14"
- {!> ../../../docs_src/response_model/tutorial004.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```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 с параметром `exclude_unset`, чтобы достичь такого эффекта.
+/// info | "Информация"
-!!! info "Информация"
- Вы также можете использовать:
+"Под капотом" FastAPI использует метод `.dict()` у объектов моделей Pydantic с параметром `exclude_unset`, чтобы достичь такого эффекта.
- * `response_model_exclude_defaults=True`
- * `response_model_exclude_none=True`
+///
- как описано в документации Pydantic для параметров `exclude_defaults` и `exclude_none`.
+/// info | "Информация"
+
+Вы также можете использовать:
+
+* `response_model_exclude_defaults=True`
+* `response_model_exclude_none=True`
+
+как описано в документации Pydantic для параметров `exclude_defaults` и `exclude_none`.
+
+///
#### Если значение поля отличается от значения по-умолчанию
@@ -420,10 +494,13 @@ FastAPI достаточно умен (на самом деле, это засл
И поэтому, они также будут включены в JSON ответа.
-!!! tip "Подсказка"
- Значением по умолчанию может быть что угодно, не только `None`.
+/// tip | "Подсказка"
- Им может быть и список (`[]`), значение 10.5 типа `float`, и т.п.
+Значением по умолчанию может быть что угодно, не только `None`.
+
+Им может быть и список (`[]`), значение 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` и исключили некоторые атрибуты.
+Но по-прежнему рекомендуется следовать изложенным выше советам и использовать несколько моделей вместо данных параметров.
- То же самое применимо к параметру `response_model_by_alias`.
+Потому как JSON схема OpenAPI, генерируемая вашим приложением (а также документация) все еще будет содержать все поля, даже если вы использовали `response_model_include` или `response_model_exclude` и исключили некоторые атрибуты.
-=== "Python 3.10+"
+То же самое применимо к параметру `response_model_by_alias`.
- ```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 "Подсказка"
- При помощи кода `{"name","description"}` создается объект множества (`set`) с двумя строковыми значениями.
+////
- Того же самого можно достичь используя `set(["name", "description"])`.
+//// tab | Python 3.8+
+
+```Python hl_lines="31 37"
+{!> ../../../docs_src/response_model/tutorial005.py!}
+```
+
+////
+
+/// tip | "Подсказка"
+
+При помощи кода `{"name","description"}` создается объект множества (`set`) с двумя строковыми значениями.
+
+Того же самого можно достичь используя `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+"
+////
- ```Python hl_lines="31 37"
- {!> ../../../docs_src/response_model/tutorial006.py!}
- ```
+//// tab | Python 3.8+
+
+```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`, например, из библиотеки `http.HTTPStatus` в Python.
+/// info | "Информация"
+
+В качестве значения параметра `status_code` также может использоваться `IntEnum`, например, из библиотеки `http.HTTPStatus` в Python.
+
+///
Это позволит:
@@ -27,15 +33,21 @@
-!!! note "Примечание"
- Некоторые коды статуса ответа (см. следующий раздел) указывают на то, что ответ не имеет тела.
+/// note | "Примечание"
- FastAPI знает об этом и создаст документацию OpenAPI, в которой будет указано, что тело ответа отсутствует.
+Некоторые коды статуса ответа (см. следующий раздел) указывают на то, что ответ не имеет тела.
+
+FastAPI знает об этом и создаст документацию OpenAPI, в которой будет указано, что тело ответа отсутствует.
+
+///
## Об HTTP кодах статуса ответа
-!!! note "Примечание"
- Если вы уже знаете, что представляют собой HTTP коды статуса ответа, можете перейти к следующему разделу.
+/// note | "Примечание"
+
+Если вы уже знаете, что представляют собой HTTP коды статуса ответа, можете перейти к следующему разделу.
+
+///
В протоколе HTTP числовой код состояния из 3 цифр отправляется как часть ответа.
@@ -54,8 +66,11 @@
* Для общих ошибок со стороны клиента можно просто использовать код `400`.
* `5XX` – статус-коды, сообщающие о серверной ошибке. Они почти никогда не используются разработчиками напрямую. Когда что-то идет не так в какой-то части кода вашего приложения или на сервере, он автоматически вернёт один из 5XX кодов.
-!!! tip "Подсказка"
- Чтобы узнать больше о HTTP кодах статуса и о том, для чего каждый из них предназначен, ознакомьтесь с документацией MDN об HTTP кодах статуса ответа.
+/// tip | "Подсказка"
+
+Чтобы узнать больше о HTTP кодах статуса и о том, для чего каждый из них предназначен, ознакомьтесь с документацией MDN об HTTP кодах статуса ответа.
+
+///
## Краткие обозначения для запоминания названий кодов
@@ -79,10 +94,13 @@
-!!! note "Технические детали"
- Вы также можете использовать `from starlette import status` вместо `from fastapi import status`.
+/// note | "Технические детали"
- **FastAPI** позволяет использовать как `starlette.status`, так и `fastapi.status` исключительно для удобства разработчиков. Но поставляется fastapi.status непосредственно из Starlette.
+Вы также можете использовать `from starlette import status` вместо `from fastapi import status`.
+
+**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`, как описано в Pydantic документации: Настройка схемы:
-=== "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!}
- ```
+```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!}
- ```
+//// tab | Python 3.8+
-!!! warning Внимание
- Имейте в виду, что эти дополнительные переданные аргументы не добавляют никакой валидации, только дополнительную информацию для документации.
+```Python hl_lines="4 10-13"
+{!> ../../../docs_src/schema_extra_example/tutorial002.py!}
+```
+
+////
+
+/// 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!}
- ```
+```Python hl_lines="22-27"
+{!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="22-27"
- {!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="22-27"
+{!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!}
+```
- ```Python hl_lines="23-28"
- {!> ../../../docs_src/schema_extra_example/tutorial003_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip Заметка
- Рекомендуется использовать версию с `Annotated`, если это возможно.
+```Python hl_lines="23-28"
+{!> ../../../docs_src/schema_extra_example/tutorial003_an.py!}
+```
- ```Python hl_lines="18-23"
- {!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip Заметка
- Рекомендуется использовать версию с `Annotated`, если это возможно.
+/// tip | Заметка
- ```Python hl_lines="20-25"
- {!> ../../../docs_src/schema_extra_example/tutorial003.py!}
- ```
+Рекомендуется использовать версию с `Annotated`, если это возможно.
+
+///
+
+```Python hl_lines="18-23"
+{!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | Заметка
+
+Рекомендуется использовать версию с `Annotated`, если это возможно.
+
+///
+
+```Python hl_lines="20-25"
+{!> ../../../docs_src/schema_extra_example/tutorial003.py!}
+```
+
+////
### Аргумент "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!}
- ```
+```Python hl_lines="23-49"
+{!> ../../../docs_src/schema_extra_example/tutorial004_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="23-49"
- {!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "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.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip Заметка
- Рекомендуется использовать версию с `Annotated`, если это возможно.
+```Python hl_lines="24-50"
+{!> ../../../docs_src/schema_extra_example/tutorial004_an.py!}
+```
- ```Python hl_lines="19-45"
- {!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip Заметка
- Рекомендуется использовать версию с `Annotated`, если это возможно.
+/// tip | Заметка
- ```Python hl_lines="21-47"
- {!> ../../../docs_src/schema_extra_example/tutorial004.py!}
- ```
+Рекомендуется использовать версию с `Annotated`, если это возможно.
+
+///
+
+```Python hl_lines="19-45"
+{!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | Заметка
+
+Рекомендуется использовать версию с `Annotated`, если это возможно.
+
+///
+
+```Python hl_lines="21-47"
+{!> ../../../docs_src/schema_extra_example/tutorial004.py!}
+```
+
+////
### Аргумент "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!}
+```
-=== "Python 3.8+"
+////
- ```Python
- {!> ../../../docs_src/security/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ без Annotated"
+```Python
+{!> ../../../docs_src/security/tutorial001_an.py!}
+```
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+////
- ```Python
- {!> ../../../docs_src/security/tutorial001.py!}
- ```
+//// tab | Python 3.8+ без Annotated
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python
+{!> ../../../docs_src/security/tutorial001.py!}
+```
+
+////
## Запуск
-!!! info "Дополнительная информация"
- Вначале, установите библиотеку `python-multipart`.
+/// info | "Дополнительная информация"
- А именно: `pip install python-multipart`.
+Вначале, установите библиотеку `python-multipart`.
- Это связано с тем, что **OAuth2** использует "данные формы" для передачи `имени пользователя` и `пароля`.
+А именно: `pip install python-multipart`.
+
+Это связано с тем, что **OAuth2** использует "данные формы" для передачи `имени пользователя` и `пароля`.
+
+///
Запустите ваш сервер:
@@ -71,17 +82,23 @@ $ uvicorn main:app --reload
-!!! check "Кнопка авторизации!"
- У вас уже появилась новая кнопка "Authorize".
+/// check | "Кнопка авторизации!"
- А у *операции пути* теперь появился маленький замочек в правом верхнем углу, на который можно нажать.
+У вас уже появилась новая кнопка "Authorize".
+
+А у *операции пути* теперь появился маленький замочек в правом верхнем углу, на который можно нажать.
+
+///
При нажатии на нее появляется небольшая форма авторизации, в которую нужно ввести `имя пользователя` и `пароль` (и другие необязательные поля):
-!!! note "Технические детали"
- Неважно, что вы введете в форму, она пока не будет работать. Но мы к этому еще придем.
+/// note | "Технические детали"
+
+Неважно, что вы введете в форму, она пока не будет работать. Но мы к этому еще придем.
+
+///
Конечно, это не фронтенд для конечных пользователей, но это отличный автоматический инструмент для интерактивного документирования всех ваших API.
@@ -123,51 +140,69 @@ OAuth2 был разработан для того, чтобы бэкэнд ил
В данном примере мы будем использовать **OAuth2**, с аутентификацией по паролю, используя токен **Bearer**. Для этого мы используем класс `OAuth2PasswordBearer`.
-!!! info "Дополнительная информация"
- Токен "bearer" - не единственный вариант, но для нашего случая он является наилучшим.
+/// info | "Дополнительная информация"
- И это может быть лучшим вариантом для большинства случаев использования, если только вы не являетесь экспертом в области OAuth2 и точно знаете, почему вам лучше подходит какой-то другой вариант.
+Токен "bearer" - не единственный вариант, но для нашего случая он является наилучшим.
- В этом случае **FastAPI** также предоставляет инструменты для его реализации.
+И это может быть лучшим вариантом для большинства случаев использования, если только вы не являетесь экспертом в области OAuth2 и точно знаете, почему вам лучше подходит какой-то другой вариант.
+
+В этом случае **FastAPI** также предоставляет инструменты для его реализации.
+
+///
При создании экземпляра класса `OAuth2PasswordBearer` мы передаем в него параметр `tokenUrl`. Этот параметр содержит URL, который клиент (фронтенд, работающий в браузере пользователя) будет использовать для отправки `имени пользователя` и `пароля` с целью получения токена.
-=== "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+ без Annotated"
+```Python hl_lines="7"
+{!> ../../../docs_src/security/tutorial001_an.py!}
+```
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+////
- ```Python hl_lines="6"
- {!> ../../../docs_src/security/tutorial001.py!}
- ```
+//// tab | Python 3.8+ без Annotated
-!!! tip "Подсказка"
- Здесь `tokenUrl="token"` ссылается на относительный URL `token`, который мы еще не создали. Поскольку это относительный URL, он эквивалентен `./token`.
+/// tip | "Подсказка"
- Поскольку мы используем относительный 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}.
+///
+
+```Python hl_lines="6"
+{!> ../../../docs_src/security/tutorial001.py!}
+```
+
+////
+
+/// 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 важно для того, чтобы ваше приложение продолжало работать даже в таких сложных случаях, как оно находится [за прокси-сервером](../../advanced/behind-a-proxy.md){.internal-link target=_blank}.
+
+///
Этот параметр не создает конечную точку / *операцию пути*, а объявляет, что URL `/token` будет таким, который клиент должен использовать для получения токена. Эта информация используется в OpenAPI, а затем в интерактивных системах документации API.
Вскоре мы создадим и саму операцию пути.
-!!! info "Дополнительная информация"
- Если вы очень строгий "питонист", то вам может не понравиться стиль названия параметра `tokenUrl` вместо `token_url`.
+/// info | "Дополнительная информация"
- Это связано с тем, что тут используется то же имя, что и в спецификации OpenAPI. Таким образом, если вам необходимо более подробно изучить какую-либо из этих схем безопасности, вы можете просто использовать копирование/вставку, чтобы найти дополнительную информацию о ней.
+Если вы очень строгий "питонист", то вам может не понравиться стиль названия параметра `tokenUrl` вместо `token_url`.
+
+Это связано с тем, что тут используется то же имя, что и в спецификации 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!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="11"
- {!> ../../../docs_src/security/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ без Annotated"
+```Python hl_lines="11"
+{!> ../../../docs_src/security/tutorial001_an.py!}
+```
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/security/tutorial001.py!}
- ```
+//// tab | Python 3.8+ без Annotated
+
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```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 | "Технические детали"
- Все утилиты безопасности, интегрируемые в OpenAPI (и автоматическая документация по API), наследуются от `SecurityBase`, поэтому **FastAPI** может знать, как интегрировать их в OpenAPI.
+**FastAPI** будет знать, что он может использовать класс `OAuth2PasswordBearer` (объявленный в зависимости) для определения схемы безопасности в OpenAPI, поскольку он наследуется от `fastapi.security.oauth2.OAuth2`, который, в свою очередь, наследуется от `fastapi.security.base.SecurityBase`.
+
+Все утилиты безопасности, интегрируемые в 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 | "Подсказка"
- Самой сложной проблемой является создание такого провайдера аутентификации/авторизации, но **FastAPI** предоставляет вам инструменты, позволяющие легко это сделать, выполняя при этом всю тяжелую работу за вас.
+Интеграция сторонних сервисов для аутентификации/авторизации таких как Google, Facebook, Twitter, GitHub и т.д. осуществляется достаточно легко.
+
+Самой сложной проблемой является создание такого провайдера аутентификации/авторизации, но **FastAPI** предоставляет вам инструменты, позволяющие легко это сделать, выполняя при этом всю тяжелую работу за вас.
+
+///
## Преимущества **FastAPI**
diff --git a/docs/ru/docs/tutorial/static-files.md b/docs/ru/docs/tutorial/static-files.md
index ec09eb5a3..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!}
```
-!!! заметка "Технические детали"
- Вы также можете использовать `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 ca47a6f51..efefbfb01 100644
--- a/docs/ru/docs/tutorial/testing.md
+++ b/docs/ru/docs/tutorial/testing.md
@@ -8,10 +8,13 @@
## Использование класса `TestClient`
-!!! info "Информация"
- Для использования класса `TestClient` необходимо установить библиотеку `httpx`.
+/// info | "Информация"
- Например, так: `pip install httpx`.
+Для использования класса `TestClient` необходимо установить библиотеку `httpx`.
+
+Например, так: `pip install httpx`.
+
+///
Импортируйте `TestClient`.
@@ -27,20 +30,29 @@
{!../../../docs_src/app_testing/tutorial001.py!}
```
-!!! tip "Подсказка"
- Обратите внимание, что тестирующая функция является обычной `def`, а не асинхронной `async def`.
+/// tip | "Подсказка"
- И вызов клиента также осуществляется без `await`.
+Обратите внимание, что тестирующая функция является обычной `def`, а не асинхронной `async def`.
- Это позволяет вам использовать `pytest` без лишних усложнений.
+И вызов клиента также осуществляется без `await`.
-!!! note "Технические детали"
- Также можно написать `from starlette.testclient import TestClient`.
+Это позволяет вам использовать `pytest` без лишних усложнений.
- **FastAPI** предоставляет тот же самый `starlette.testclient` как `fastapi.testclient`. Это всего лишь небольшое удобство для Вас, как разработчика.
+///
-!!! tip "Подсказка"
- Если для тестирования Вам, помимо запросов к приложению FastAPI, необходимо вызывать асинхронные функции (например, для подключения к базе данных с помощью асинхронного драйвера), то ознакомьтесь со страницей [Асинхронное тестирование](../advanced/async-tests.md){.internal-link target=_blank} в расширенном руководстве.
+/// note | "Технические детали"
+
+Также можно написать `from starlette.testclient import TestClient`.
+
+**FastAPI** предоставляет тот же самый `starlette.testclient` как `fastapi.testclient`. Это всего лишь небольшое удобство для Вас, как разработчика.
+
+///
+
+/// tip | "Подсказка"
+
+Если для тестирования Вам, помимо запросов к приложению FastAPI, необходимо вызывать асинхронные функции (например, для подключения к базе данных с помощью асинхронного драйвера), то ознакомьтесь со страницей [Асинхронное тестирование](../advanced/async-tests.md){.internal-link target=_blank} в расширенном руководстве.
+
+///
## Разделение тестов и приложения
@@ -50,7 +62,7 @@
### Файл приложения **FastAPI**
-Допустим, структура файлов Вашего приложения похожа на ту, что описана на странице [Более крупные приложения](./bigger-applications.md){.internal-link target=_blank}:
+Допустим, структура файлов Вашего приложения похожа на ту, что описана на странице [Более крупные приложения](bigger-applications.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+
- !!! tip "Подсказка"
- По возможности используйте версию с `Annotated`.
+```Python
+{!> ../../../docs_src/app_testing/app_b_an/main.py!}
+```
- ```Python
- {!> ../../../docs_src/app_testing/app_b_py310/main.py!}
- ```
+////
-=== "Python 3.8+ без Annotated"
+//// tab | Python 3.10+ без Annotated
- !!! tip "Подсказка"
- По возможности используйте версию с `Annotated`.
+/// tip | "Подсказка"
- ```Python
- {!> ../../../docs_src/app_testing/app_b/main.py!}
- ```
+По возможности используйте версию с `Annotated`.
+
+///
+
+```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` ознакомьтесь с документацией HTTPX.
-!!! info "Информация"
- Обратите внимание, что `TestClient` принимает данные, которые можно конвертировать в JSON, но не модели Pydantic.
+/// info | "Информация"
- Если в Ваших тестах есть модели Pydantic и Вы хотите отправить их в тестируемое приложение, то можете использовать функцию `jsonable_encoder`, описанную на странице [Кодировщик совместимый с JSON](encoder.md){.internal-link target=_blank}.
+Обратите внимание, что `TestClient` принимает данные, которые можно конвертировать в JSON, но не модели Pydantic.
+
+Если в Ваших тестах есть модели 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
new file mode 100644
index 000000000..6c057162e
--- /dev/null
+++ b/docs/tr/docs/advanced/index.md
@@ -0,0 +1,36 @@
+# 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:
+
+* Talk Python Training
+* Test-Driven Development
diff --git a/docs/tr/docs/advanced/security/index.md b/docs/tr/docs/advanced/security/index.md
new file mode 100644
index 000000000..227674bd4
--- /dev/null
+++ b/docs/tr/docs/advanced/security/index.md
@@ -0,0 +1,19 @@
+# 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.
diff --git a/docs/tr/docs/advanced/testing-websockets.md b/docs/tr/docs/advanced/testing-websockets.md
new file mode 100644
index 000000000..59a2499e2
--- /dev/null
+++ b/docs/tr/docs/advanced/testing-websockets.md
@@ -0,0 +1,15 @@
+# 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 Websockets'i Test Etmek dokümantasyonunu inceleyin.
+
+///
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 http://localhost:8000/v1/ adresine giderseniz, Flask'tan gelen yanıtı göreceksiniz:
+
+```txt
+Hello, World from Flask!
+```
+
+Eğer http://localhost:8000/v2/ adresine giderseniz, FastAPI'dan gelen yanıtı göreceksiniz:
+
+```JSON
+{
+ "message": "Hello World"
+}
+```
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ı.
+
+///
### Flask
@@ -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 yönlendirme sistemine 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 yönlendirme sistemine sahip olmalı.
+
+///
### Requests
@@ -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ı.
+
+///
### Swagger / OpenAPI
@@ -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 açık standart benimseyip kullanmalı.
+/// check | "**FastAPI**'a nasıl ilham verdi?"
- Ayrıca standarda bağlı kullanıcı arayüzü araçlarını entegre etmeli:
+API spesifikasyonları için özel bir şema yerine bir açık standart benimseyip kullanmalı.
- * Swagger UI
- * ReDoc
+Ayrıca standarda bağlı kullanıcı arayüzü araçlarını entegre etmeli:
- 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.
+* Swagger UI
+* ReDoc
+
+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 şemayı tanımlamak için Marshmallow'un sunduğu spesifik araçları ve sınıfları kullanmanız gerekiyordu.
-!!! check "**FastAPI**'a nasıl ilham verdi?"
- 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ı.
+
+///
### Webargs
@@ -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"
-!!! check "**FastAPI**'a nasıl ilham verdi?"
- Gelen istek verisi için otomatik veri doğrulamaya sahip olmalı.
+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ı.
+
+///
### APISpec
@@ -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"
-!!! check "**FastAPI**'a nasıl ilham verdi?"
- API'lar için açık standart desteği olmalı (OpenAPI gibi).
+APISpec de aynı Marshmallow geliştiricileri tarafından oluşturuldu.
+
+///
+
+/// check | "**FastAPI**'a nasıl ilham verdi?"
+
+API'lar için açık standart desteği olmalı (OpenAPI gibi).
+
+///
### Flask-apispec
@@ -193,11 +223,17 @@ Bunu kullanmak, bir kaç NestJS (and Angular)
@@ -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üçlü bir bağımlılık enjeksiyon sistemine sahip olmalı. Kod tekrarını minimuma indirecek bir yol bulmalı.
+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ı.
+
+///
### Sanic
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 `uvloop` kullanıldı. Hızının asıl kaynağı buydu.
+/// note | "Teknik detaylar"
- 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.
+İçerisinde standart Python `asyncio` döngüsü yerine `uvloop` kullanıldı. Hızının asıl kaynağı buydu.
-!!! check "**FastAPI**'a nasıl ilham oldu?"
- Uçuk performans sağlayacak bir yol bulmalı.
+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.
- 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)
+///
+
+/// check | "**FastAPI**'a nasıl ilham oldu?"
+
+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)
+
+///
### Falcon
@@ -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?"
- Hug ile birlikte (Hug zaten Falcon'a dayandığından) **FastAPI**'ın fonksiyonlarda `cevap` parametresi belirtmesinde ilham kaynağı oldu.
+Harika bir performans'a sahip olmanın yollarını bulmalı.
- FastAPI'da opsiyonel olmasına rağmen, daha çok header'lar, çerezler ve alternatif durum kodları belirlemede kullanılıyor.
+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.
+
+///
### Molten
@@ -263,10 +311,13 @@ Biraz daha detaylı ayarlamalara gerek duyuyor. Ayrıca Yol'lar fonksiyonun üstünde endpoint'i işleyen dekoratörler yerine farklı yerlerde tanımlanan fonksiyonlarla belirlenir. Bu Flask (ve Starlette) yerine daha çok Django'nun yaklaşımına daha yakın bir metot. Bu, kodda nispeten birbiriyle sıkı ilişkili olan şeyleri ayırmaya sebep oluyor.
-!!! check "**FastAPI**'a nasıl ilham oldu?"
- 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?"
- 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.
+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.
+
+///
### Hug
@@ -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 `isort`'un geliştiricisi Timothy Crosley tarafından geliştirildi.
+/// info | "Bilgi"
-!!! 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, Python dosyalarında bulunan dahil etme satırlarını otomatik olarak sıralayan harika bir araç olan `isort`'un geliştiricisi Timothy Crosley tarafından geliştirildi.
- **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ı.
+/// 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.
+
+**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ı.
+
+///
### APIStar (<= 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"
- * Django REST Framework
- * **FastAPI**'ın da dayandığı Starlette
- * Starlette ve **FastAPI** tarafından da kullanılan Uvicorn
+APIStar, aşağıdaki projeleri de üreten Tom Christie tarafından geliştirildi:
-!!! check "**FastAPI**'a nasıl ilham oldu?"
- Var oldu.
+* Django REST Framework
+* **FastAPI**'ın da dayandığı Starlette
+* Starlette ve **FastAPI** tarafından da kullanılan Uvicorn
- 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.
+///
- Uzunca bir süre boyunca benzer bir framework arayıp pek çok farklı alternatifi denedikten sonra, APIStar en iyi seçenekti.
+/// check | "**FastAPI**'a nasıl ilham oldu?"
- 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ı.
+Var oldu.
- Ben bu önceki araçlardan öğrendiklerime dayanarak **FastAPI**'ın özelliklerini arttırıp geliştiriyor, tip desteği sistemi ve diğer kısımları iyileştiriyorum ancak yine de **FastAPI**'ı APIStar'ın "ruhani varisi" olarak görüyorum.
+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.
+
+Uzunca bir süre boyunca benzer bir framework arayıp pek çok farklı alternatifi denedikten sonra, APIStar en iyi seçenekti.
+
+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, tip desteği 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?"
- **FastAPI** yaptığı her şeyin yanı sıra bu JSON Şema verisini alıp daha sonra OpenAPI'ya yerleştiriyor.
+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.
+
+///
### Starlette
@@ -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"
- 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.
+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.
-!!! check "**FastAPI** nerede kullanı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.
- 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!
+/// check | "**FastAPI** nerede kullanıyor?"
- Yani, Starlette ile yapabileceğiniz her şeyi, Starlette'in bir nevi güçlendirilmiş hali olan **FastAPI** ile doğrudan yapabilirsiniz.
+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!
+
+Yani, Starlette ile yapabileceğiniz her şeyi, Starlette'in bir nevi güçlendirilmiş hali olan **FastAPI** ile doğrudan yapabilirsiniz.
+
+///
### Uvicorn
@@ -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?"
- Gunicorn ile birleştirdiğinizde asenkron ve çoklu işlem destekleyen bir sunucu elde ediyorsunuz!
+**FastAPI** uygulamalarını çalıştırmak için ana web sunucusu Uvicorn!
- Daha fazla detay için [Deployment](deployment/index.md){.internal-link target=_blank} bölümünü inceleyebilirsiniz.
+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.
+
+///
## Karşılaştırma ve Hız
diff --git a/docs/tr/docs/async.md b/docs/tr/docs/async.md
index 2be594343..0d463a2f0 100644
--- a/docs/tr/docs/async.md
+++ b/docs/tr/docs/async.md
@@ -21,8 +21,11 @@ async def read_results():
return results
```
-!!! 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
- Bunlar, **FastAPI**'nin altta nasıl çalıştığına dair çok teknik ayrıntılardır.
+Muhtemelen burayı atlayabilirsiniz.
- 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.
+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.
+
+///
### Path fonksiyonu
@@ -376,7 +382,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* G/Ç 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#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/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:
+
+* Platform.sh
+* Porter
+* Coherence
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. ✨
diff --git a/docs/tr/docs/external-links.md b/docs/tr/docs/external-links.md
deleted file mode 100644
index 78eaf1729..000000000
--- a/docs/tr/docs/external-links.md
+++ /dev/null
@@ -1,33 +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 Pull Request 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 %}
-
-* {{ item.title }} by {{ item.author }}.
-
-{% endfor %}
-{% endfor %}
-{% endfor %}
-
-## Projeler
-
-`fastapi` konulu en son GitHub projeleri:
-
-
-
-
+
+
-
-
+
+
@@ -23,11 +29,11 @@
**Dokümantasyon**: https://fastapi.tiangolo.com
-**Kaynak Kod**: https://github.com/tiangolo/fastapi
+**Kaynak Kod**: https://github.com/fastapi/fastapi
---
-FastAPI, Python 3.8+'nin standart tip belirteçlerine dayalı, modern ve hızlı (yüksek performanslı) API'lar oluşturmak için kullanılabilecek web framework'tür.
+FastAPI, Python 'nin standart tip belirteçlerine dayalı, modern ve hızlı (yüksek performanslı) API'lar oluşturmak için kullanılabilecek web framework'tür.
Temel özellikleri şunlardır:
@@ -63,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._"
-
email_validator - email doğrulaması için.
+* email-validator - email doğrulaması için.
* pydantic-settings - ayar yönetimi için.
* pydantic-extra-types - Pydantic ile birlikte kullanılabilecek ek tipler için.
@@ -456,12 +460,12 @@ Starlette tarafında kullanılan:
* python-multipart - Eğer `request.form()` ile form dönüşümü desteğini kullanacaksanız gereklidir.
* itsdangerous - `SessionMiddleware` desteği için gerekli.
* pyyaml - `SchemaGenerator` desteği için gerekli (Muhtemelen FastAPI kullanırken ihtiyacınız olmaz).
-* ujson - `UJSONResponse` kullanacaksanız gerekli.
Hem FastAPI hem de Starlette tarafından kullanılan:
* uvicorn - oluşturduğumuz uygulamayı servis edecek web sunucusu görevini üstlenir.
* orjson - `ORJSONResponse` kullanacaksanız gereklidir.
+* ujson - `UJSONResponse` kullanacaksanız gerekli.
Bunların hepsini `pip install fastapi[all]` ile yükleyebilirsin.
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
-
-
-
-
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: **FastAPI** backend:
+* Python **FastAPI** backend:
* **Hızlı**: **NodeJS** ve **Go** ile eşit, çok yüksek performans (Starlette ve Pydantic'e teşekkürler).
* **Sezgisel**: Editor desteğı. Otomatik tamamlama. Daha az debugging.
* **Kolay**: Kolay öğrenip kolay kullanmak için tasarlandı. Daha az döküman okuma daha çok iş.
diff --git a/docs/tr/docs/python-types.md b/docs/tr/docs/python-types.md
index a0d32c86e..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.
-!!! 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!}
```
-!!! ipucu
- Köşeli parantez içindeki bu dahili tiplere "tip parametreleri" denir.
+/// tip | "Ipucu"
- Bu durumda `str`, `List`e iletilen tür parametresidir.
+Köşeli parantez içindeki bu dahili tiplere "tip parametreleri" denir.
+
+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 Pydantic'i takip edin.
+/// info
+
+Daha fazla şey öğrenmek için Pydantic'i takip edin.
+
+///
**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: the "cheat sheet" from `mypy`.
+/// info
+
+Tüm öğreticiyi zaten okuduysanız ve türler hakkında daha fazla bilgi için geri döndüyseniz, iyi bir kaynak: the "cheat sheet" from `mypy`.
+
+///
diff --git a/docs/tr/docs/tutorial/cookie-params.md b/docs/tr/docs/tutorial/cookie-params.md
new file mode 100644
index 000000000..807f85e8a
--- /dev/null
+++ b/docs/tr/docs/tutorial/cookie-params.md
@@ -0,0 +1,135 @@
+# Ç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:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/cookie_params/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip | "İpucu"
+
+Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın.
+
+///
+
+```Python hl_lines="1"
+{!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "İpucu"
+
+Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın.
+
+///
+
+```Python hl_lines="3"
+{!> ../../../docs_src/cookie_params/tutorial001.py!}
+```
+
+////
+
+## `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:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/cookie_params/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip | "İpucu"
+
+Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın.
+
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "İpucu"
+
+Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın.
+
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/cookie_params/tutorial001.py!}
+```
+
+////
+
+/// 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.
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
get operasyonu ile
* `/` yoluna gelen istekler
-!!! info "`@decorator` Bilgisi"
- Python'da `@something` sözdizimi "dekoratör" 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 "dekoratör" 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"
- **FastAPI** herhangi bir özel amacı veya anlamı olması konusunda ısrarcı olmaz.
+Her işlemi (HTTP metod) istediğiniz gibi kullanmakta özgürsünüz.
- Buradaki bilgiler bir gereklilik değil, bir kılavuz olarak sunulmaktadır.
+**FastAPI** herhangi bir özel amacı veya anlamı olması konusunda ısrarcı olmaz.
- Mesela GraphQL kullanırkan genelde tüm işlemleri yalnızca `POST` operasyonunu kullanarak gerçekleştirirsiniz.
+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.
+
+///
### 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 Dönüşümü
@@ -35,10 +38,13 @@ Eğer bu örneği çalıştırıp tarayıcınızda "ayrıştırma" özelliği sağlar.
+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 "ayrıştırma" özelliği sağlar.
+
+///
## Veri Doğrulama
@@ -65,12 +71,15 @@ Eğer tarayıcınızda http://127.0.0.1:8000/items/4.2 sayfasında olduğu gibi `int` yerine `float` bir değer verseydik de ortaya çıkardı.
-!!! check "Ek bilgi"
- 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ı
-!!! 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"
- Dikkatinizi çekerim ki, yol parametresi integer olarak tanımlanmıştır.
+Ü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.
+
+///
## 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 enumerationlar (ya da enumlar) Python'da mevcuttur.
+/// info | "Bilgi"
-!!! tip "İpucu"
- Merak ediyorsanız söyleyeyim, "AlexNet", "ResNet" ve "LeNet" isimleri Makine Öğrenmesi modellerini temsil eder.
+3.4 sürümünden beri enumerationlar (ya da enumlar) Python'da mevcuttur.
+
+///
+
+/// tip | "İpucu"
+
+Merak ediyorsanız söyleyeyim, "AlexNet", "ResNet" ve "LeNet" isimleri Makine Öğrenmesi modellerini 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"
- Bu durumda, URL, `files` ile `home` arasında iki eğik çizgiye (`//`) sahip olup `/files//home/johndoe/myfile.txt` gibi gözükecektir.
+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.
+
+///
## Özet
diff --git a/docs/tr/docs/tutorial/query-params.md b/docs/tr/docs/tutorial/query-params.md
index aa3915557..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!}
+```
-=== "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!}
+```
+
+////
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+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params/tutorial003.py!}
- ```
+//// tab | Python 3.8+
+
+```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!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="8 10"
- {!> ../../../docs_src/query_params/tutorial004.py!}
- ```
+//// tab | Python 3.8+
+
+```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#predefined-values){.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
new file mode 100644
index 000000000..8e8ccfba4
--- /dev/null
+++ b/docs/tr/docs/tutorial/request-forms.md
@@ -0,0 +1,125 @@
+# 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 `python-multipart` 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:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="3"
+{!> ../../../docs_src/request_forms/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="1"
+{!> ../../../docs_src/request_forms/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="1"
+{!> ../../../docs_src/request_forms/tutorial001.py!}
+```
+
+////
+
+## `Form` Parametrelerini Tanımlayın
+
+Form parametrelerini `Body` veya `Query` için yaptığınız gibi oluşturun:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/request_forms/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="8"
+{!> ../../../docs_src/request_forms/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/request_forms/tutorial001.py!}
+```
+
+////
+
+Örneğin, OAuth2 spesifikasyonunun kullanılabileceği ("şifre akışı" olarak adlandırılan) yollardan birinde, form alanları olarak "username" ve "password" gönderilmesi gerekir.
+
+Bu spesifikasyon 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 (``) 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 MDN web docs for POST 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.
diff --git a/docs/tr/docs/tutorial/static-files.md b/docs/tr/docs/tutorial/static-files.md
new file mode 100644
index 000000000..b82be611f
--- /dev/null
+++ b/docs/tr/docs/tutorial/static-files.md
@@ -0,0 +1,42 @@
+# 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 Starlette'in Statik Dosyalar hakkındaki dokümantasyonunu incelleyin.
diff --git a/docs/uk/docs/alternatives.md b/docs/uk/docs/alternatives.md
index bdb62513e..eb48d6be7 100644
--- a/docs/uk/docs/alternatives.md
+++ b/docs/uk/docs/alternatives.md
@@ -30,12 +30,17 @@
Це був один із перших прикладів **автоматичної документації API**, і саме це була одна з перших ідей, яка надихнула на «пошук» **FastAPI**.
-!!! Примітка
- Django REST Framework створив Том Крісті. Той самий творець Starlette і Uvicorn, на яких базується **FastAPI**.
+/// note | "Примітка"
+Django REST Framework створив Том Крісті. Той самий творець Starlette і Uvicorn, на яких базується **FastAPI**.
-!!! Перегляньте "Надихнуло **FastAPI** на"
- Мати автоматичний веб-інтерфейс документації API.
+///
+
+/// check | "Надихнуло **FastAPI** на"
+
+Мати автоматичний веб-інтерфейс документації API.
+
+///
### Flask
@@ -51,11 +56,13 @@ Flask — це «мікрофреймворк», він не включає ін
Враховуючи простоту Flask, він здавався хорошим підходом для створення API. Наступним, що знайшов, був «Django REST Framework» для Flask.
-!!! Переглянте "Надихнуло **FastAPI** на"
- Бути мікрофреймоворком. Зробити легким комбінування та поєднання необхідних інструментів та частин.
+/// check | "Надихнуло **FastAPI** на"
- Мати просту та легку у використанні систему маршрутизації.
+Бути мікрофреймоворком. Зробити легким комбінування та поєднання необхідних інструментів та частин.
+ Мати просту та легку у використанні систему маршрутизації.
+
+///
### Requests
@@ -91,11 +98,13 @@ def read_url():
Зверніть увагу на схожість у `requests.get(...)` і `@app.get(...)`.
-!!! Перегляньте "Надихнуло **FastAPI** на"
- * Майте простий та інтуїтивно зрозумілий API.
- * Використовуйте імена (операції) методів HTTP безпосередньо, простим та інтуїтивно зрозумілим способом.
- * Розумні параметри за замовчуванням, але потужні налаштування.
+/// check | "Надихнуло **FastAPI** на"
+* Майте простий та інтуїтивно зрозумілий API.
+ * Використовуйте імена (операції) методів HTTP безпосередньо, простим та інтуїтивно зрозумілим способом.
+ * Розумні параметри за замовчуванням, але потужні налаштування.
+
+///
### Swagger / OpenAPI
@@ -109,15 +118,18 @@ def read_url():
Тому, коли говорять про версію 2.0, прийнято говорити «Swagger», а про версію 3+ «OpenAPI».
-!!! Перегляньте "Надихнуло **FastAPI** на"
- Прийняти і використовувати відкритий стандарт для специфікацій API замість спеціальної схеми.
+/// check | "Надихнуло **FastAPI** на"
- Інтегрувати інструменти інтерфейсу на основі стандартів:
+Прийняти і використовувати відкритий стандарт для специфікацій API замість спеціальної схеми.
- * Інтерфейс Swagger
- * ReDoc
+ Інтегрувати інструменти інтерфейсу на основі стандартів:
- Ці два було обрано через те, що вони досить популярні та стабільні, але, виконавши швидкий пошук, ви можете знайти десятки додаткових альтернативних інтерфейсів для OpenAPI (які можна використовувати з **FastAPI**).
+ * Інтерфейс Swagger
+ * ReDoc
+
+ Ці два було обрано через те, що вони досить популярні та стабільні, але, виконавши швидкий пошук, ви можете знайти десятки додаткових альтернативних інтерфейсів для OpenAPI (які можна використовувати з **FastAPI**).
+
+///
### Фреймворки REST для Flask
@@ -135,8 +147,11 @@ Marshmallow створено для забезпечення цих функці
Але він був створений до того, як існували підказки типу Python. Отже, щоб визначити кожну схему, вам потрібно використовувати спеціальні утиліти та класи, надані Marshmallow.
-!!! Перегляньте "Надихнуло **FastAPI** на"
- Використовувати код для автоматичного визначення "схем", які надають типи даних і перевірку.
+/// check | "Надихнуло **FastAPI** на"
+
+Використовувати код для автоматичного визначення "схем", які надають типи даних і перевірку.
+
+///
### Webargs
@@ -148,11 +163,17 @@ Webargs — це інструмент, створений, щоб забезпе
Це чудовий інструмент, і я також часто використовував його, перш ніж створити **FastAPI**.
-!!! Інформація
- Webargs був створений тими ж розробниками Marshmallow.
+/// info | "Інформація"
-!!! Перегляньте "Надихнуло **FastAPI** на"
- Мати автоматичну перевірку даних вхідного запиту.
+Webargs був створений тими ж розробниками Marshmallow.
+
+///
+
+/// check | "Надихнуло **FastAPI** на"
+
+Мати автоматичну перевірку даних вхідного запиту.
+
+///
### APISpec
@@ -172,12 +193,17 @@ Marshmallow і Webargs забезпечують перевірку, аналіз
Редактор тут нічим не може допомогти. І якщо ми змінимо параметри чи схеми Marshmallow і забудемо також змінити цю строку документа YAML, згенерована схема буде застарілою.
-!!! Інформація
- APISpec був створений тими ж розробниками Marshmallow.
+/// info | "Інформація"
+APISpec був створений тими ж розробниками Marshmallow.
-!!! Перегляньте "Надихнуло **FastAPI** на"
- Підтримувати відкритий стандарт API, OpenAPI.
+///
+
+/// check | "Надихнуло **FastAPI** на"
+
+Підтримувати відкритий стандарт API, OpenAPI.
+
+///
### Flask-apispec
@@ -199,11 +225,17 @@ Marshmallow і Webargs забезпечують перевірку, аналіз
І ці самі генератори повного стеку були основою [**FastAPI** генераторів проектів](project-generation.md){.internal-link target=_blank}.
-!!! Інформація
- Flask-apispec був створений тими ж розробниками Marshmallow.
+/// info | "Інформація"
-!!! Перегляньте "Надихнуло **FastAPI** на"
- Створення схеми OpenAPI автоматично з того самого коду, який визначає серіалізацію та перевірку.
+Flask-apispec був створений тими ж розробниками Marshmallow.
+
+///
+
+/// check | "Надихнуло **FastAPI** на"
+
+Створення схеми OpenAPI автоматично з того самого коду, який визначає серіалізацію та перевірку.
+
+///
### NestJS (та Angular)
@@ -219,24 +251,33 @@ Marshmallow і Webargs забезпечують перевірку, аналіз
Він не дуже добре обробляє вкладені моделі. Отже, якщо тіло JSON у запиті є об’єктом JSON із внутрішніми полями, які, у свою чергу, є вкладеними об’єктами JSON, його неможливо належним чином задокументувати та перевірити.
-!!! Перегляньте "Надихнуло **FastAPI** на"
- Використовувати типи Python, щоб мати чудову підтримку редактора.
+/// check | "Надихнуло **FastAPI** на"
- Мати потужну систему впровадження залежностей. Знайдіть спосіб звести до мінімуму повторення коду.
+Використовувати типи Python, щоб мати чудову підтримку редактора.
+
+ Мати потужну систему впровадження залежностей. Знайдіть спосіб звести до мінімуму повторення коду.
+
+///
### Sanic
Це був один із перших надзвичайно швидких фреймворків Python на основі `asyncio`. Він був дуже схожий на Flask.
-!!! Примітка "Технічні деталі"
- Він використовував `uvloop` замість стандартного циклу Python `asyncio`. Ось що зробило його таким швидким.
+/// note | "Технічні деталі"
- Це явно надихнуло Uvicorn і Starlette, які зараз швидші за Sanic у відкритих тестах.
+Він використовував `uvloop` замість стандартного циклу Python `asyncio`. Ось що зробило його таким швидким.
-!!! Перегляньте "Надихнуло **FastAPI** на"
- Знайти спосіб отримати божевільну продуктивність.
+ Це явно надихнуло Uvicorn і Starlette, які зараз швидші за Sanic у відкритих тестах.
- Ось чому **FastAPI** базується на Starlette, оскільки це найшвидша доступна структура (перевірена тестами сторонніх розробників).
+///
+
+/// check | "Надихнуло **FastAPI** на"
+
+Знайти спосіб отримати божевільну продуктивність.
+
+ Ось чому **FastAPI** базується на Starlette, оскільки це найшвидша доступна структура (перевірена тестами сторонніх розробників).
+
+///
### Falcon
@@ -246,12 +287,15 @@ Falcon — ще один високопродуктивний фреймворк
Таким чином, перевірка даних, серіалізація та документація повинні виконуватися в коді, а не автоматично. Або вони повинні бути реалізовані як фреймворк поверх Falcon, як Hug. Така сама відмінність спостерігається в інших фреймворках, натхненних дизайном Falcon, що мають один об’єкт запиту та один об’єкт відповіді як параметри.
-!!! Перегляньте "Надихнуло **FastAPI** на"
- Знайти способи отримати чудову продуктивність.
+/// check | "Надихнуло **FastAPI** на"
- Разом із Hug (оскільки Hug базується на Falcon) надихнув **FastAPI** оголосити параметр `response` у функціях.
+Знайти способи отримати чудову продуктивність.
- Хоча у FastAPI це необов’язково, і використовується в основному для встановлення заголовків, файлів cookie та альтернативних кодів стану.
+ Разом із Hug (оскільки Hug базується на Falcon) надихнув **FastAPI** оголосити параметр `response` у функціях.
+
+ Хоча у FastAPI це необов’язково, і використовується в основному для встановлення заголовків, файлів cookie та альтернативних кодів стану.
+
+///
### Molten
@@ -269,10 +313,13 @@ Falcon — ще один високопродуктивний фреймворк
Маршрути оголошуються в одному місці з використанням функцій, оголошених в інших місцях (замість використання декораторів, які можна розмістити безпосередньо поверх функції, яка обробляє кінцеву точку). Це ближче до того, як це робить Django, ніж до Flask (і Starlette). Він розділяє в коді речі, які відносно тісно пов’язані.
-!!! Перегляньте "Надихнуло **FastAPI** на"
- Визначити додаткові перевірки для типів даних, використовуючи значення "за замовчуванням" атрибутів моделі. Це покращує підтримку редактора, а раніше вона була недоступна в Pydantic.
+/// check | "Надихнуло **FastAPI** на"
- Це фактично надихнуло оновити частини Pydantic, щоб підтримувати той самий стиль оголошення перевірки (всі ці функції вже доступні в Pydantic).
+Визначити додаткові перевірки для типів даних, використовуючи значення "за замовчуванням" атрибутів моделі. Це покращує підтримку редактора, а раніше вона була недоступна в Pydantic.
+
+ Це фактично надихнуло оновити частини Pydantic, щоб підтримувати той самий стиль оголошення перевірки (всі ці функції вже доступні в Pydantic).
+
+///
### Hug
@@ -288,15 +335,21 @@ Hug був одним із перших фреймворків, який реа
Оскільки він заснований на попередньому стандарті для синхронних веб-фреймворків Python (WSGI), він не може працювати з Websockets та іншими речами, хоча він також має високу продуктивність.
-!!! Інформація
- Hug створив Тімоті Крослі, той самий творець `isort`, чудовий інструмент для автоматичного сортування імпорту у файлах Python.
+/// info | "Інформація"
-!!! Перегляньте "Надихнуло **FastAPI** на"
- Hug надихнув частину APIStar і був одним із найбільш перспективних інструментів, поряд із APIStar.
+Hug створив Тімоті Крослі, той самий творець `isort`, чудовий інструмент для автоматичного сортування імпорту у файлах Python.
- Hug надихнув **FastAPI** на використання підказок типу Python для оголошення параметрів і автоматичного створення схеми, що визначає API.
+///
- Hug надихнув **FastAPI** оголосити параметр `response` у функціях для встановлення заголовків і файлів cookie.
+/// check | "Надихнуло **FastAPI** на"
+
+Hug надихнув частину APIStar і був одним із найбільш перспективних інструментів, поряд із APIStar.
+
+ Hug надихнув **FastAPI** на використання підказок типу Python для оголошення параметрів і автоматичного створення схеми, що визначає API.
+
+ Hug надихнув **FastAPI** оголосити параметр `response` у функціях для встановлення заголовків і файлів cookie.
+
+///
### APIStar (<= 0,5)
@@ -322,21 +375,27 @@ Hug був одним із перших фреймворків, який реа
Тепер APIStar — це набір інструментів для перевірки специфікацій OpenAPI, а не веб-фреймворк.
-!!! Інформація
- APIStar створив Том Крісті. Той самий хлопець, який створив:
+/// info | "Інформація"
- * Django REST Framework
- * Starlette (на якому базується **FastAPI**)
- * Uvicorn (використовується Starlette і **FastAPI**)
+APIStar створив Том Крісті. Той самий хлопець, який створив:
-!!! Перегляньте "Надихнуло **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**
@@ -348,10 +407,13 @@ Pydantic — це бібліотека для визначення переві
Його можна порівняти з Marshmallow. Хоча він швидший за Marshmallow у тестах. Оскільки він базується на тих самих підказках типу Python, підтримка редактора чудова.
-!!! Перегляньте "**FastAPI** використовує його для"
- Виконання перевірки всіх даних, серіалізації даних і автоматичної документацію моделі (на основі схеми JSON).
+/// check | "**FastAPI** використовує його для"
- Потім **FastAPI** бере ці дані схеми JSON і розміщує їх у OpenAPI, окремо від усіх інших речей, які він робить.
+Виконання перевірки всіх даних, серіалізації даних і автоматичної документацію моделі (на основі схеми JSON).
+
+ Потім **FastAPI** бере ці дані схеми JSON і розміщує їх у OpenAPI, окремо від усіх інших речей, які він робить.
+
+///
### Starlette
@@ -380,17 +442,23 @@ Starlette надає всі основні функції веб-мікрофр
Це одна з головних речей, які **FastAPI** додає зверху, все на основі підказок типу Python (з використанням Pydantic). Це, а також система впровадження залежностей, утиліти безпеки, створення схеми OpenAPI тощо.
-!!! Примітка "Технічні деталі"
- ASGI — це новий «стандарт», який розробляється членами основної команди Django. Це ще не «стандарт Python» (PEP), хоча вони в процесі цього.
+/// note | "Технічні деталі"
- Тим не менш, він уже використовується як «стандарт» кількома інструментами. Це значно покращує сумісність, оскільки ви можете переключити Uvicorn на будь-який інший сервер ASGI (наприклад, Daphne або Hypercorn), або ви можете додати інструменти, сумісні з ASGI, як-от `python-socketio`.
+ASGI — це новий «стандарт», який розробляється членами основної команди Django. Це ще не «стандарт Python» (PEP), хоча вони в процесі цього.
-!!! Перегляньте "**FastAPI** використовує його для"
- Керування всіма основними веб-частинами. Додавання функцій зверху.
+ Тим не менш, він уже використовується як «стандарт» кількома інструментами. Це значно покращує сумісність, оскільки ви можете переключити Uvicorn на будь-який інший сервер ASGI (наприклад, Daphne або Hypercorn), або ви можете додати інструменти, сумісні з ASGI, як-от `python-socketio`.
- Сам клас `FastAPI` безпосередньо успадковує клас `Starlette`.
+///
- Отже, усе, що ви можете робити зі Starlette, ви можете робити це безпосередньо за допомогою **FastAPI**, оскільки це, по суті, Starlette на стероїдах.
+/// check | "**FastAPI** використовує його для"
+
+Керування всіма основними веб-частинами. Додавання функцій зверху.
+
+ Сам клас `FastAPI` безпосередньо успадковує клас `Starlette`.
+
+ Отже, усе, що ви можете робити зі Starlette, ви можете робити це безпосередньо за допомогою **FastAPI**, оскільки це, по суті, Starlette на стероїдах.
+
+///
### Uvicorn
@@ -400,12 +468,15 @@ Uvicorn — це блискавичний сервер ASGI, побудован
Це рекомендований сервер для Starlette і **FastAPI**.
-!!! Перегляньте "**FastAPI** рекомендує це як"
- Основний веб-сервер для запуску програм **FastAPI**.
+/// check | "**FastAPI** рекомендує це як"
- Ви можете поєднати його з Gunicorn, щоб мати асинхронний багатопроцесний сервер.
+Основний веб-сервер для запуску програм **FastAPI**.
- Додаткову інформацію див. у розділі [Розгортання](deployment/index.md){.internal-link target=_blank}.
+ Ви можете поєднати його з Gunicorn, щоб мати асинхронний багатопроцесний сервер.
+
+ Додаткову інформацію див. у розділі [Розгортання](deployment/index.md){.internal-link target=_blank}.
+
+///
## Орієнтири та швидкість
diff --git a/docs/uk/docs/fastapi-people.md b/docs/uk/docs/fastapi-people.md
deleted file mode 100644
index f7d0220b5..000000000
--- a/docs/uk/docs/fastapi-people.md
+++ /dev/null
@@ -1,178 +0,0 @@
-# Люди FastAPI
-
-FastAPI має дивовижну спільноту, яка вітає людей різного походження.
-
-## Творець – Супроводжувач
-
-Привіт! 👋
-
-Це я:
-
-{% if people %}
-
-
-
+
+
-
-
+
+
@@ -23,11 +23,11 @@
**Документація**: https://fastapi.tiangolo.com
-**Програмний код**: https://github.com/tiangolo/fastapi
+**Програмний код**: https://github.com/fastapi/fastapi
---
-FastAPI - це сучасний, швидкий (високопродуктивний), вебфреймворк для створення API за допомогою Python 3.8+,в основі якого лежить стандартна анотація типів Python.
+FastAPI - це сучасний, швидкий (високопродуктивний), вебфреймворк для створення API за допомогою Python,в основі якого лежить стандартна анотація типів Python.
Ключові особливості:
@@ -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._"
-
email_validator - для валідації електронної пошти.
+* email-validator - для валідації електронної пошти.
* pydantic-settings - для управління налаштуваннями.
* pydantic-extra-types - для додаткових типів, що можуть бути використані з Pydantic.
@@ -451,12 +449,12 @@ Starlette використовує:
* python-multipart - Необхідно, якщо Ви хочете підтримувати "розбір" форми за допомогою `request.form()`.
* itsdangerous - Необхідно для підтримки `SessionMiddleware`.
* pyyaml - Необхідно для підтримки Starlette `SchemaGenerator` (ймовірно, вам це не потрібно з FastAPI).
-* ujson - Необхідно, якщо Ви хочете використовувати `UJSONResponse`.
FastAPI / Starlette використовують:
* uvicorn - для сервера, який завантажує та обслуговує вашу програму.
* orjson - Необхідно, якщо Ви хочете використовувати `ORJSONResponse`.
+* ujson - Необхідно, якщо Ви хочете використовувати `UJSONResponse`.
Ви можете встановити все це за допомогою `pip install fastapi[all]`.
diff --git a/docs/uk/docs/python-types.md b/docs/uk/docs/python-types.md
index e767db2fb..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`):
+З модуля `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!}
+```
-=== "Python 3.9 і вище"
+////
- Оголосимо змінну з тим самим синтаксисом двокрапки (`:`).
+//// tab | Python 3.9 і вище
- Як тип вкажемо `list`.
+Оголосимо змінну з тим самим синтаксисом двокрапки (`:`).
- Оскільки список є типом, який містить деякі внутрішні типи, ви поміщаєте їх у квадратні дужки:
+Як тип вкажемо `list`.
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial006_py39.py!}
- ```
+Оскільки список є типом, який містить деякі внутрішні типи, ви поміщаєте їх у квадратні дужки:
-!!! info
- Ці внутрішні типи в квадратних дужках називаються "параметрами типу".
+```Python hl_lines="1"
+{!> ../../../docs_src/python_types/tutorial006_py39.py!}
+```
- У цьому випадку, `str` це параметр типу переданий у `List` (або `list` у Python 3.9 і вище).
+////
+
+/// info
+
+Ці внутрішні типи в квадратних дужках називаються "параметрами типу".
+
+У цьому випадку, `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 і вище"
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial007_py39.py!}
- ```
+//// tab | Python 3.9 і вище
+
+```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!}
+```
-=== "Python 3.9 і вище"
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial008_py39.py!}
- ```
+//// tab | Python 3.9 і вище
+
+```Python hl_lines="1"
+{!> ../../../docs_src/python_types/tutorial008_py39.py!}
+```
+
+////
Це означає:
@@ -269,17 +290,21 @@ John Doe
У Python 3.10 також є **альтернативний синтаксис**, у якому ви можете розділити можливі типи за допомогою вертикальної смуги (`|`).
-=== "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!}
+```
-=== "Python 3.10 і вище"
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial008b_py310.py!}
- ```
+//// tab | Python 3.10 і вище
+
+```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!}
+```
-=== "Python 3.8 і вище - альтернатива"
+////
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial009b.py!}
- ```
+//// tab | Python 3.8 і вище - альтернатива
-=== "Python 3.10 і вище"
+```Python hl_lines="1 4"
+{!> ../../../docs_src/python_types/tutorial009b.py!}
+```
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial009_py310.py!}
- ```
+////
+
+//// tab | Python 3.10 і вище
+
+```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`
+* ...та інші.
-=== "Python 3.9 і вище"
+////
- Ви можете використовувати ті самі вбудовані типи, як generic (з квадратними дужками та типами всередині):
+//// tab | Python 3.9 і вище
- * `list`
- * `tuple`
- * `set`
- * `dict`
+Ви можете використовувати ті самі вбудовані типи, як generic (з квадратними дужками та типами всередині):
- І те саме, що й у Python 3.8, із модуля `typing`:
+* `list`
+* `tuple`
+* `set`
+* `dict`
- * `Union`
- * `Optional`
- * ...та інші.
+І те саме, що й у Python 3.8, із модуля `typing`:
-=== "Python 3.10 і вище"
+* `Union`
+* `Optional`
+* ...та інші.
- Ви можете використовувати ті самі вбудовані типи, як generic (з квадратними дужками та типами всередині):
+////
- * `list`
- * `tuple`
- * `set`
- * `dict`
+//// tab | Python 3.10 і вище
- І те саме, що й у Python 3.8, із модуля `typing`:
+Ви можете використовувати ті самі вбудовані типи, як generic (з квадратними дужками та типами всередині):
- * `Union`
- * `Optional` (так само як у Python 3.8)
- * ...та інші.
+* `list`
+* `tuple`
+* `set`
+* `dict`
- У Python 3.10, як альтернатива використанню `Union` та `Optional`, ви можете використовувати вертикальну смугу (`|`) щоб оголосити об'єднання типів.
+І те саме, що й у Python 3.8, із модуля `typing`:
+
+* `Union`
+* `Optional` (так само як у Python 3.8)
+* ...та інші.
+
+У Python 3.10, як альтернатива використанню `Union` та `Optional`, ви можете використовувати вертикальну смугу (`|`) щоб оголосити об'єднання типів.
+
+////
### Класи як типи
@@ -397,26 +434,35 @@ John Doe
Приклад з документації Pydantic:
-=== "Python 3.8 і вище"
+//// tab | Python 3.8 і вище
- ```Python
- {!> ../../../docs_src/python_types/tutorial011.py!}
- ```
+```Python
+{!> ../../../docs_src/python_types/tutorial011.py!}
+```
-=== "Python 3.9 і вище"
+////
- ```Python
- {!> ../../../docs_src/python_types/tutorial011_py39.py!}
- ```
+//// tab | Python 3.9 і вище
-=== "Python 3.10 і вище"
+```Python
+{!> ../../../docs_src/python_types/tutorial011_py39.py!}
+```
- ```Python
- {!> ../../../docs_src/python_types/tutorial011_py310.py!}
- ```
+////
-!!! info
- Щоб дізнатись більше про Pydantic, перегляньте його документацію.
+//// tab | Python 3.10 і вище
+
+```Python
+{!> ../../../docs_src/python_types/tutorial011_py310.py!}
+```
+
+////
+
+/// info
+
+Щоб дізнатись більше про Pydantic, перегляньте його документацію.
+
+///
**FastAPI** повністю базується на Pydantic.
@@ -444,5 +490,8 @@ John Doe
Важливо те, що за допомогою стандартних типів Python в одному місці (замість того, щоб додавати більше класів, декораторів тощо), **FastAPI** зробить багато роботи за вас.
-!!! info
- Якщо ви вже пройшли весь навчальний посібник і повернулися, щоб дізнатися більше про типи, ось хороший ресурс "шпаргалка" від `mypy`.
+/// info
+
+Якщо ви вже пройшли весь навчальний посібник і повернулися, щоб дізнатися більше про типи, ось хороший ресурс "шпаргалка" від `mypy`.
+
+///
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!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="11-14"
+{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="12-15"
- {!> ../../../docs_src/body_fields/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Варто користуватись `Annotated` версією, якщо це можливо..
+```Python hl_lines="12-15"
+{!> ../../../docs_src/body_fields/tutorial001_an.py!}
+```
- ```Python hl_lines="9-12"
- {!> ../../../docs_src/body_fields/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Варто користуватись `Annotated` версією, якщо це можливо..
+/// tip
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001.py!}
- ```
+Варто користуватись `Annotated` версією, якщо це можливо..
+
+///
+
+```Python hl_lines="9-12"
+{!> ../../../docs_src/body_fields/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Варто користуватись `Annotated` версією, якщо це можливо..
+
+///
+
+```Python hl_lines="11-14"
+{!> ../../../docs_src/body_fields/tutorial001.py!}
+```
+
+////
`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 @@
Щоб оголосити тіло **запиту**, ви використовуєте Pydantic моделі з усією їх потужністю та перевагами.
-!!! 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!}
+```
-=== "Python 3.10 і вище"
+////
- ```Python hl_lines="2"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
+//// tab | Python 3.10 і вище
+
+```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 @@
-!!! tip
- Якщо ви використовуєте PyCharm як ваш редактор, ви можете використати Pydantic PyCharm Plugin.
+/// tip
- Він покращує підтримку редакторів для моделей Pydantic за допомогою:
+Якщо ви використовуєте PyCharm як ваш редактор, ви можете використати Pydantic PyCharm Plugin.
- * автозаповнення
- * перевірки типу
- * рефакторингу
- * пошуку
- * інспекції
+Він покращує підтримку редакторів для моделей 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!}
+```
-=== "Python 3.10 і вище"
+////
- ```Python hl_lines="19"
- {!> ../../../docs_src/body/tutorial002_py310.py!}
- ```
+//// tab | Python 3.10 і вище
+
+```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 і вище"
+////
- ```Python hl_lines="15-16"
- {!> ../../../docs_src/body/tutorial003_py310.py!}
- ```
+//// tab | Python 3.10 і вище
+
+```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 і вище"
+////
- ```Python hl_lines="16"
- {!> ../../../docs_src/body/tutorial004_py310.py!}
- ```
+//// tab | Python 3.10 і вище
+
+```Python hl_lines="16"
+{!> ../../../docs_src/body/tutorial004_py310.py!}
+```
+
+////
Параметри функції будуть розпізнаватися наступним чином:
@@ -203,10 +233,13 @@
* Якщо параметр має **сингулярний тип** (наприклад, `int`, `float`, `str`, `bool` тощо), він буде інтерпретуватися як параметр **запиту**.
* Якщо параметр оголошується як тип **Pydantic моделі**, він інтерпретується як **тіло** запиту.
-!!! note
- FastAPI буде знати, що значення "q" не є обов'язковим через значення за замовчуванням "= None".
+/// note
- `Optional` у `Optional[str]` не використовується FastAPI, але дозволить вашому редактору надати вам кращу підтримку та виявляти помилки.
+FastAPI буде знати, що значення "q" не є обов'язковим через значення за замовчуванням "= None".
+
+`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!}
- ```
+```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!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="9"
+{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/cookie_params/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Бажано використовувати `Annotated` версію, якщо це можливо.
+```Python hl_lines="10"
+{!> ../../../docs_src/cookie_params/tutorial001_an.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Бажано використовувати `Annotated` версію, якщо це можливо.
+/// tip
- ```Python hl_lines="9"
- {!> ../../../docs_src/cookie_params/tutorial001.py!}
- ```
+Бажано використовувати `Annotated` версію, якщо це можливо.
-!!! note "Технічні Деталі"
- `Cookie` це "сестра" класів `Path` і `Query`. Вони наслідуються від одного батьківського класу `Param`.
- Але пам'ятайте, що коли ви імпортуєте `Query`, `Path`, `Cookie` та інше з `fastapi`, це фактично функції, що повертають спеціальні класи.
+///
-!!! info
- Для визначення cookies ви маєте використовувати `Cookie`, тому що в іншому випадку параметри будуть інтерпритовані, як параметри запиту.
+```Python hl_lines="7"
+{!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Бажано використовувати `Annotated` версію, якщо це можливо.
+
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/cookie_params/tutorial001.py!}
+```
+
+////
+
+/// note | "Технічні Деталі"
+
+`Cookie` це "сестра" класів `Path` і `Query`. Вони наслідуються від одного батьківського класу `Param`.
+Але пам'ятайте, що коли ви імпортуєте `Query`, `Path`, `Cookie` та інше з `fastapi`, це фактично функції, що повертають спеціальні класи.
+
+///
+
+/// info
+
+Для визначення cookies ви маєте використовувати `Cookie`, тому що в іншому випадку параметри будуть інтерпритовані, як параметри запиту.
+
+///
## Підсумки
diff --git a/docs/uk/docs/tutorial/encoder.md b/docs/uk/docs/tutorial/encoder.md
index b6583341f..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.
-!!! Примітка
- `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!}
- ```
+```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!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="18-19"
+{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="19-20"
- {!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Бажано використовувати `Annotated` версію, якщо це можливо.
+```Python hl_lines="19-20"
+{!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
+```
- ```Python hl_lines="17-18"
- {!> ../../../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="18-19"
- {!> ../../../docs_src/extra_data_types/tutorial001.py!}
- ```
+Бажано використовувати `Annotated` версію, якщо це можливо.
+
+///
+
+```Python hl_lines="17-18"
+{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Бажано використовувати `Annotated` версію, якщо це можливо.
+
+///
+
+```Python hl_lines="18-19"
+{!> ../../../docs_src/extra_data_types/tutorial001.py!}
+```
+
+////
diff --git a/docs/uk/docs/tutorial/first-steps.md b/docs/uk/docs/tutorial/first-steps.md
new file mode 100644
index 000000000..784da65f5
--- /dev/null
+++ b/docs/uk/docs/tutorial/first-steps.md
@@ -0,0 +1,342 @@
+# Перші кроки
+
+Найпростіший файл FastAPI може виглядати так:
+
+```Python
+{!../../../docs_src/first_steps/tutorial001.py!}
+```
+
+Скопіюйте це до файлу `main.py`.
+
+Запустіть сервер:
+
+get операцію
+
+/// 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`.
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
+```
- ```
- pip install "uvicorn[standard]"
- ```
+Також встановіть `uvicorn`, щоб він працював як сервер:
- І те саме для кожної з опціональних залежностей, які ви хочете використовувати.
+```
+pip install "uvicorn[standard]"
+```
+
+І те саме для кожної з опціональних залежностей, які ви хочете використовувати.
+
+///
## Розширений посібник користувача
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 کے تحت چلنے والی ایپلی کیشنز کو ایک تیز رفتار Python فریم ورک میں سے ایک ، صرف Starlette اور Uvicorn کے نیچے ( FASTAPI کے ذریعہ اندرونی طور پر استعمال کیا جاتا ہے ) (*)
لیکن جب بینچ مارک اور موازنہ کی جانچ پڑتال کرتے ہو تو آپ کو مندرجہ ذیل بات ذہن میں رکھنی چاہئے.
@@ -14,39 +13,39 @@
درجہ بندی کی طرح ہے:
-
-
-
+
+
-
-
+
+
@@ -23,15 +29,15 @@
**Tài liệu**: https://fastapi.tiangolo.com
-**Mã nguồn**: https://github.com/tiangolo/fastapi
+**Mã nguồn**: https://github.com/fastapi/fastapi
---
-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ư:
-* **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. Completion mọi nơi. Ít thời gian gỡ lỗi.
@@ -63,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**._"
-
ujson - "Parse" JSON nhanh hơn.
-* email_validator - cho email validation.
+* email-validator - cho email validation.
Sử dụng Starlette:
@@ -458,12 +461,12 @@ Sử dụng Starlette:
* python-multipart - Bắt buộc nếu bạn muốn hỗ trợ "parsing", form với `request.form()`.
* itsdangerous - Bắt buộc để hỗ trợ `SessionMiddleware`.
* pyyaml - Bắt buộc để hỗ trợ `SchemaGenerator` cho Starlette (bạn có thể không cần nó trong FastAPI).
-* ujson - Bắt buộc nếu bạn muốn sử dụng `UJSONResponse`.
Sử dụng bởi FastAPI / Starlette:
* uvicorn - Server để chạy ứng dụng của bạn.
* orjson - Bắt buộc nếu bạn muốn sử dụng `ORJSONResponse`.
+* ujson - 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/vi/docs/python-types.md b/docs/vi/docs/python-types.md
index b2a399aa5..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!}
+```
- Tương tự như kiểu dữ liệu, `List` bạn import từ `typing`.
+Khai báo biến với cùng dấu hai chấm (`:`).
- 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:
+Tương tự như kiểu dữ liệu, `List` bạn import từ `typing`.
- ```Python hl_lines="4"
- {!> ../../../docs_src/python_types/tutorial006.py!}
- ```
+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:
-!!! 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".
+```Python hl_lines="4"
+{!> ../../../docs_src/python_types/tutorial006.py!}
+```
- 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).
+////
+
+/// 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".
+
+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!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial008.py!}
- ```
+//// tab | Python 3.8+
+
+```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 sổ dọc (`|`).
-=== "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!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial008b.py!}
- ```
+//// tab | Python 3.8+
+
+```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!}
+```
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial009b.py!}
- ```
+////
+
+//// tab | Python 3.8+ alternative
+
+```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 sổ dọc ('|') để 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 sổ dọc ('|') để 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+"
+////
- 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):
+//// tab | Python 3.9+
- * `list`
- * `tuple`
- * `set`
- * `dict`
+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):
- Và tương tự với Python 3.6, từ mô đun `typing`:
+* `list`
+* `tuple`
+* `set`
+* `dict`
- * `Union`
- * `Optional`
- * ...and others.
+Và tương tự với Python 3.6, từ mô đun `typing`:
-=== "Python 3.8+"
+* `Union`
+* `Optional`
+* ...and others.
- * `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!}
- ```
+```Python
+{!> ../../../docs_src/python_types/tutorial011_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python
- {!> ../../../docs_src/python_types/tutorial011_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python
+{!> ../../../docs_src/python_types/tutorial011_py39.py!}
+```
- ```Python
- {!> ../../../docs_src/python_types/tutorial011.py!}
- ```
+////
-!!! info
- Để học nhiều hơn về Pydantic, tham khảo tài liệu của nó.
+//// tab | Python 3.8+
+
+```Python
+{!> ../../../docs_src/python_types/tutorial011.py!}
+```
+
+////
+
+/// info
+
+Để học nhiều hơn về Pydantic, tham khảo tài liệu của nó.
+
+///
**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ề Required Optional fields.
+/// 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ề Required Optional fields.
+
+///
## 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`.
+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!}
- ```
+```Python hl_lines="1 4"
+{!> ../../../docs_src/python_types/tutorial013_py39.py!}
+```
-=== "Python 3.8+"
+////
- Ở phiên bản dưới Python 3.9, bạn import `Annotated` từ `typing_extensions`.
+//// tab | Python 3.8+
- Nó đã được cài đặt sẵng cùng với **FastAPI**.
+Ở phiên bản dưới Python 3.9, bạn import `Annotated` từ `typing_extensions`.
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial013.py!}
- ```
+Nó đã được cài đặt sẵng cùng với **FastAPI**.
+
+```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ư "cheat sheet" từ `mypy`.
+/// 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ư "cheat sheet" từ `mypy`.
+
+///
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
get
-!!! 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
- **FastAPI** không bắt buộc bất kì ý nghĩa cụ thể nào.
+Bạn thoải mái sử dụng mỗi toán tử (phương thức HTTP) như bạn mơ ướ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.
+**FastAPI** không bắt buộc bất kì ý nghĩa cụ thể nào.
- 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`.
+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`.
+
+///
### 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
+```
- ```
- pip install "uvicorn[standard]"
- ```
+Cũng cài đặt `uvicorn` để làm việc như một server:
- Và tương tự với từng phụ thuộc tùy chọn mà bạn muốn sử dụng.
+```
+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.
+
+///
## Hướng dẫn nâng cao
diff --git a/docs/yo/docs/index.md b/docs/yo/docs/index.md
index 5684f0a6a..ee7f56220 100644
--- a/docs/yo/docs/index.md
+++ b/docs/yo/docs/index.md
@@ -1,3 +1,9 @@
+# FastAPI
+
+
+
@@ -5,11 +11,11 @@
Ì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
-
-
+
+
-
-
+
+
@@ -23,15 +29,15 @@
**Àkọsílẹ̀**: https://fastapi.tiangolo.com
-**Orisun Kóòdù**: https://github.com/tiangolo/fastapi
+**Orisun Kóòdù**: https://github.com/fastapi/fastapi
---
-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:
-* **Ó 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. Ìparí nibi gbogbo. Àkókò díẹ̀ nipa wíwá ibi tí ìṣòro kóòdù wà.
@@ -63,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**._"
-
email_validator - fún ifọwọsi ímeèlì.
+* email-validator - fún ifọwọsi ímeèlì.
* pydantic-settings - fún ètò ìsàkóso.
* pydantic-extra-types - fún àfikún oríṣi láti lọ pẹ̀lú Pydantic.
@@ -456,12 +460,12 @@ Láti ní òye síi nípa rẹ̀, wo abala àwọn python-multipart - Nílò tí ó bá fẹ́ láti ṣe àtìlẹ́yìn fún "àyẹ̀wò" fọọmu, pẹ̀lú `request.form()`.
* itsdangerous - Nílò fún àtìlẹ́yìn `SessionMiddleware`.
* pyyaml - Nílò fún àtìlẹ́yìn Starlette's `SchemaGenerator` (ó ṣe ṣe kí ó má nílò rẹ̀ fún FastAPI).
-* ujson - Nílò tí ó bá fẹ́ láti lọ `UJSONResponse`.
Èyí tí FastAPI / Starlette ń lò:
* uvicorn - Fún olupin tí yóò sẹ́ àmúyẹ àti tí yóò ṣe ìpèsè fún iṣẹ́ rẹ tàbí ohun èlò rẹ.
* orjson - Nílò tí ó bá fẹ́ láti lọ `ORJSONResponse`.
+* ujson - 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/benchmarks.md b/docs/zh-hant/docs/benchmarks.md
new file mode 100644
index 000000000..c59e8e71c
--- /dev/null
+++ b/docs/zh-hant/docs/benchmarks.md
@@ -0,0 +1,34 @@
+# 基準測試
+
+由第三方機構 TechEmpower 的基準測試表明在 Uvicorn 下運行的 **FastAPI** 應用程式是 最快的 Python 可用框架之一,僅次於 Starlette 和 Uvicorn 本身(於 FastAPI 內部使用)。
+
+但是在查看基準得分和對比時,請注意以下幾點。
+
+## 基準測試和速度
+
+當你查看基準測試時,時常會見到幾個不同類型的工具被同時進行測試。
+
+具體來說,是將 Uvicorn、Starlette 和 FastAPI 同時進行比較(以及許多其他工具)。
+
+該工具解決的問題越簡單,其效能就越好。而且大多數基準測試不會測試該工具提供的附加功能。
+
+層次結構如下:
+
+* **Uvicorn**:ASGI 伺服器
+ * **Starlette**:(使用 Uvicorn)一個網頁微框架
+ * **FastAPI**:(使用 Starlette)一個 API 微框架,具有用於建立 API 的多個附加功能、資料驗證等。
+
+* **Uvicorn**:
+ * 具有最佳效能,因為除了伺服器本身之外,它沒有太多額外的程式碼。
+ * 你不會直接在 Uvicorn 中編寫應用程式。這意味著你的程式碼必須或多或少地包含 Starlette(或 **FastAPI**)提供的所有程式碼。如果你這樣做,你的最終應用程式將具有與使用框架相同的開銷並最大限度地減少應用程式程式碼和錯誤。
+ * 如果你要比較 Uvicorn,請將其與 Daphne、Hypercorn、uWSGI 等應用程式伺服器進行比較。
+* **Starlette**:
+ * 繼 Uvicorn 之後的次佳表現。事實上,Starlette 使用 Uvicorn 來運行。因此它將可能只透過執行更多程式碼而變得比 Uvicorn「慢」。
+ * 但它為你提供了建立簡單網頁應用程式的工具,以及基於路徑的路由等。
+ * 如果你要比較 Starlette,請將其與 Sanic、Flask、Django 等網頁框架(或微框架)進行比較。
+* **FastAPI**:
+ * 就像 Starlette 使用 Uvicorn 並不能比它更快一樣, **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/index.md b/docs/zh-hant/docs/index.md
index 9859d3c51..d260b5b79 100644
--- a/docs/zh-hant/docs/index.md
+++ b/docs/zh-hant/docs/index.md
@@ -5,11 +5,11 @@
FastAPI 框架,高效能,易於學習,快速開發,適用於生產環境
-
-
+
+
-
-
+
+
@@ -23,11 +23,11 @@
**文件**: https://fastapi.tiangolo.com
-**程式碼**: https://github.com/tiangolo/fastapi
+**程式碼**: https://github.com/fastapi/fastapi
---
-FastAPI 是一個現代、快速(高效能)的 web 框架,用於 Python 3.8+ 並採用標準 Python 型別提示。
+FastAPI 是一個現代、快速(高效能)的 web 框架,用於 Python 並採用標準 Python 型別提示。
主要特點包含:
@@ -63,7 +63,7 @@ FastAPI 是一個現代、快速(高效能)的 web 框架,用於 Python 3.
"_[...] 近期大量的使用 **FastAPI**。 [...] 目前正在計畫在**微軟**團隊的**機器學習**服務中導入。其中一些正在整合到核心的 **Windows** 產品和一些 **Office** 產品。_"
-
email_validator - 用於電子郵件驗證。
+- email-validator - 用於電子郵件驗證。
- pydantic-settings - 用於設定管理。
- pydantic-extra-types - 用於與 Pydantic 一起使用的額外型別。
@@ -456,12 +454,12 @@ item: Item
- python-multipart - 需要使用 `request.form()` 對表單進行 "解析" 時安裝。
- itsdangerous - 需要使用 `SessionMiddleware` 支援時安裝。
- pyyaml - 用於支援 Starlette 的 `SchemaGenerator` (如果你使用 FastAPI,可能不需要它)。
-- ujson - 使用 `UJSONResponse` 時必須安裝。
用於 FastAPI / Starlette:
- uvicorn - 用於加載和運行應用程式的服務器。
- orjson - 使用 `ORJSONResponse`時必須安裝。
+- ujson - 使用 `UJSONResponse` 時必須安裝。
你可以使用 `pip install "fastapi[all]"` 來安裝這些所有依賴套件。
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
-!!! Info
- - 除非在 `responses` 参数中明确指定不同的媒体类型,否则**FastAPI**将假定响应与主响应类具有相同的媒体类型(默认为` application/json` )。
- - 但是如果您指定了一个自定义响应类,并将 `None `作为其媒体类型,**FastAPI**将使用 `application/json` 作为具有关联模型的任何其他响应。
+- 请注意,您必须直接使用 `FileResponse` 返回图像。
+
+///
+
+/// 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 738bd7119..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,包含路径前缀:http://127.0.0.1:9999/api/v1/app。
@@ -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`。
+
+///
http://127.0.0.1:9999/api/v1/docs 的 API 文档所示如下:
-!!! tip "提示"
+/// tip | "提示"
- API 文档与所选的服务器进行交互。
+API 文档与所选的服务器进行交互。
+
+///
### 从 `root_path` 禁用自动服务器
@@ -346,6 +360,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/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 | "提示"
- 在这个例子中,HTTP 头的 `Content-Type` 会被设置成 `application/json`。
+参数 `response_class` 也会用来定义响应的「媒体类型」。
- 并且在 OpenAPI 文档中也会这样记录。
+在这个例子中,HTTP 头的 `Content-Type` 会被设置成 `application/json`。
-!!! tip "小贴士"
- `ORJSONResponse` 目前只在 FastAPI 中可用,而在 Starlette 中不可用。
+并且在 OpenAPI 文档中也会这样记录。
+///
+/// tip | "小贴士"
+
+`ORJSONResponse` 目前只在 FastAPI 中可用,而在 Starlette 中不可用。
+
+///
## HTML 响应
@@ -48,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`
@@ -65,11 +75,17 @@
{!../../../docs_src/custom_response/tutorial003.py!}
```
-!!! warning "警告"
- *路径操作函数* 直接返回的 `Response` 不会被 OpenAPI 的文档记录(比如,`Content-Type` 不会被文档记录),并且在自动化交互文档中也是不可见的。
+/// warning | "警告"
-!!! info "提示"
- 当然,实际的 `Content-Type` 头,状态码等等,将来自于你返回的 `Response` 对象。
+*路径操作函数* 直接返回的 `Response` 不会被 OpenAPI 的文档记录(比如,`Content-Type` 不会被文档记录),并且在自动化交互文档中也是不可见的。
+
+///
+
+/// info | "提示"
+
+当然,实际的 `Content-Type` 头,状态码等等,将来自于你返回的 `Response` 对象。
+
+///
### OpenAPI 中的文档和重载 `Response`
@@ -99,10 +115,13 @@
要记得你可以使用 `Response` 来返回任何其他东西,甚至创建一个自定义的子类。
-!!! note "技术细节"
- 你也可以使用 `from starlette.responses import HTMLResponse`。
+/// note | "技术细节"
- **FastAPI** 提供了同 `fastapi.responses` 相同的 `starlette.responses` 只是为了方便开发者。但大多数可用的响应都直接来自 Starlette。
+你也可以使用 `from starlette.responses import HTMLResponse`。
+
+**FastAPI** 提供了同 `fastapi.responses` 相同的 `starlette.responses` 只是为了方便开发者。但大多数可用的响应都直接来自 Starlette。
+
+///
### `Response`
@@ -151,15 +170,21 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它
`UJSONResponse` 是一个使用 `ujson` 的可选 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
new file mode 100644
index 000000000..72567e245
--- /dev/null
+++ b/docs/zh/docs/advanced/dataclasses.md
@@ -0,0 +1,101 @@
+# 使用数据类
+
+FastAPI 基于 **Pydantic** 构建,前文已经介绍过如何使用 Pydantic 模型声明请求与响应。
+
+但 FastAPI 还可以使用数据类(`dataclasses`):
+
+```Python hl_lines="1 7-12 19-20"
+{!../../../docs_src/dataclasses/tutorial001.py!}
+```
+
+这还是借助于 **Pydantic** 及其内置的 `dataclasses`。
+
+因此,即便上述代码没有显式使用 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 文档中也会显示相关概图:
+
+
+
+## 在嵌套数据结构中使用数据类
+
+您还可以把 `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 仍能把数据序列化为 JSON;
+
+7. 这行代码中,`response_model` 的类型注解是 `Author` 数据类列表;
+
+ 再一次,可以把 `dataclasses` 与标准类型注解一起使用;
+
+8. 注意,*路径操作函数*使用的是普通函数,不是异步函数;
+
+ 与往常一样,在 FastAPI 中,可以按需组合普通函数与异步函数;
+
+ 如果不清楚何时使用异步函数或普通函数,请参阅**急不可待?**一节中对 `async` 与 `await` 的说明;
+
+9. *路径操作函数*返回的不是数据类(虽然它可以返回数据类),而是返回内含数据的字典列表;
+
+ FastAPI 使用(包含数据类的) `response_model` 参数转换响应。
+
+把 `dataclasses` 与其它类型注解组合在一起,可以组成不同形式的复杂数据结构。
+
+更多内容详见上述代码内的注释。
+
+## 深入学习
+
+您还可以把 `dataclasses` 与其它 Pydantic 模型组合在一起,继承合并的模型,把它们包含在您自己的模型里。
+
+详见 Pydantic 官档 - 数据类。
+
+## 版本
+
+本章内容自 FastAPI `0.67.0` 版起生效。🔖
diff --git a/docs/zh/docs/advanced/events.md b/docs/zh/docs/advanced/events.md
index 6017b8ef0..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"` 指的是**追加**。因此这行文本会添加在文件已有内容之后,不会覆盖之前的内容。
+`open()` 函数中,`mode="a"` 指的是**追加**。因此这行文本会添加在文件已有内容之后,不会覆盖之前的内容。
-!!! tip "提示"
+///
- 注意,本例使用 Python `open()` 标准函数与文件交互。
+/// tip | "提示"
- 这个函数执行 I/O(输入/输出)操作,需要等待内容写进磁盘。
+注意,本例使用 Python `open()` 标准函数与文件交互。
- 但 `open()` 函数不支持使用 `async` 与 `await`。
+这个函数执行 I/O(输入/输出)操作,需要等待内容写进磁盘。
- 因此,声明事件处理函数要使用 `def`,不能使用 `asnyc def`。
+但 `open()` 函数不支持使用 `async` 与 `await`。
-!!! info "说明"
+因此,声明事件处理函数要使用 `def`,不能使用 `asnyc def`。
- 有关事件处理器的详情,请参阅 Starlette 官档 - 事件。
+///
+
+/// info | "说明"
+
+有关事件处理器的详情,请参阅 Starlette 官档 - 事件。
+
+///
diff --git a/docs/zh/docs/advanced/generate-clients.md b/docs/zh/docs/advanced/generate-clients.md
index e222e479c..56aad3bd2 100644
--- a/docs/zh/docs/advanced/generate-clients.md
+++ b/docs/zh/docs/advanced/generate-clients.md
@@ -10,23 +10,27 @@
一个常见的工具是 OpenAPI Generator。
-如果您正在开发**前端**,一个非常有趣的替代方案是 openapi-typescript-codegen。
+如果您正在开发**前端**,一个非常有趣的替代方案是 openapi-ts。
## 生成一个 TypeScript 前端客户端
让我们从一个简单的 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+"
+////
- ```Python hl_lines="9-11 14-15 18 19 23"
- {!> ../../../docs_src/generate_clients/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="9-11 14-15 18 19 23"
+{!> ../../../docs_src/generate_clients/tutorial001.py!}
+```
+
+////
请注意,*路径操作* 定义了他们所用于请求数据和回应数据的模型,所使用的模型是`Item` 和 `ResponseMessage`。
@@ -46,14 +50,14 @@ OpenAPI中所包含的模型里有相同的信息可以用于 **生成客户端
现在我们有了带有模型的应用,我们可以为前端生成客户端代码。
-#### 安装 `openapi-typescript-codegen`
+#### 安装 `openapi-ts`
-您可以使用以下工具在前端代码中安装 `openapi-typescript-codegen`:
+您可以使用以下工具在前端代码中安装 `openapi-ts`:
-!!! 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!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="23 28 36"
- {!> ../../../docs_src/generate_clients/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+
+```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+"
+////
- ```Python hl_lines="8-9 12"
- {!> ../../../docs_src/generate_clients/tutorial003.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="8-9 12"
+{!> ../../../docs_src/generate_clients/tutorial003.py!}
+```
+
+////
### 使用自定义操作ID生成TypeScript客户端
@@ -234,12 +249,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"
}
}
diff --git a/docs/zh/docs/advanced/index.md b/docs/zh/docs/advanced/index.md
index 824f91f47..6525802fc 100644
--- a/docs/zh/docs/advanced/index.md
+++ b/docs/zh/docs/advanced/index.md
@@ -2,17 +2,20 @@
## 额外特性
-主要的教程 [教程 - 用户指南](../tutorial/){.internal-link target=_blank} 应该足以让你了解 **FastAPI** 的所有主要特性。
+主要的教程 [教程 - 用户指南](../tutorial/index.md){.internal-link target=_blank} 应该足以让你了解 **FastAPI** 的所有主要特性。
你会在接下来的章节中了解到其他的选项、配置以及额外的特性。
-!!! tip
- 接下来的章节**并不一定是**「高级的」。
+/// tip
- 而且对于你的使用场景来说,解决方案很可能就在其中。
+接下来的章节**并不一定是**「高级的」。
+
+而且对于你的使用场景来说,解决方案很可能就在其中。
+
+///
## 先阅读教程
-你可能仍会用到 **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/middleware.md b/docs/zh/docs/advanced/middleware.md
new file mode 100644
index 000000000..926082b94
--- /dev/null
+++ b/docs/zh/docs/advanced/middleware.md
@@ -0,0 +1,101 @@
+# 高级中间件
+
+用户指南介绍了如何为应用添加[自定义中间件](../tutorial/middleware.md){.internal-link target=_blank} 。
+
+以及如何[使用 `CORSMiddleware` 处理 CORS](../tutorial/cors.md){.internal-link target=_blank}。
+
+本章学习如何使用其它中间件。
+
+## 添加 ASGI 中间件
+
+因为 **FastAPI** 基于 Starlette,且执行 ASGI 规范,所以可以使用任意 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 中间件。
+
+例如:
+
+* Uvicorn 的 `ProxyHeadersMiddleware`
+* MessagePack
+
+其它可用中间件详见 Starlette 官档 - 中间件 及 ASGI Awesome 列表。
diff --git a/docs/zh/docs/advanced/openapi-callbacks.md b/docs/zh/docs/advanced/openapi-callbacks.md
new file mode 100644
index 000000000..7c7323cb5
--- /dev/null
+++ b/docs/zh/docs/advanced/openapi-callbacks.md
@@ -0,0 +1,194 @@
+# 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 的 URL 类型。
+
+///
+
+此处唯一比较新的内容是*路径操作装饰器*中的 `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 请求。
+
+实现回调时,要使用 HTTPX 或 Requests。
+
+///
+
+## 编写回调文档代码
+
+应用不执行这部分代码,只是用它来*记录 外部 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` 就可以了
+* *路径*可以包含 OpenAPI 3 表达式(详见下文),可以使用带参数的变量,以及发送至您的 API 的原始请求的部分
+
+### 回调路径表达式
+
+回调*路径*支持包含发送给您的 API 的原始请求的部分的 OpenAPI 3 表达式。
+
+本例中是**字符串**:
+
+```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 启动应用,打开 http://127.0.0.1:8000/docs。
+
+就能看到文档的*路径操作*已经包含了**回调**的内容以及*外部 API*:
+
+
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
-!!! warning
- 如果你这样做,务必确保你的每个 *路径操作函数* 的名字唯一。
+如果你手动调用 `app.openapi()`,你应该在此之前更新 `operationId`。
- 即使它们在不同的模块中(Python 文件)。
+///
+
+/// warning
+
+如果你这样做,务必确保你的每个 *路径操作函数* 的名字唯一。
+
+即使它们在不同的模块中(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 | "技术细节"
- 为了方便开发者,**FastAPI** 封装了相同数据类型,如`starlette.responses` 和 `fastapi.responses`。不过大部分response对象都是直接引用自Starlette。
+你也可以使用`from starlette.responses import Response` 或者 `from starlette.responses import JSONResponse`。
- 因为`Response`对象可以非常便捷的设置headers和cookies,所以 **FastAPI** 同时也封装了`fastapi.Response`。
+为了方便开发者,**FastAPI** 封装了相同数据类型,如`starlette.responses` 和 `fastapi.responses`。不过大部分response对象都是直接引用自Starlette。
+
+因为`Response`对象可以非常便捷的设置headers和cookies,所以 **FastAPI** 同时也封装了`fastapi.Response`。
+
+///
如果你想查看所有可用的参数和选项,可以参考 Starlette帮助文档
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 | "技术细节"
- 出于方便,**FastAPI** 会提供与 `starlette.responses` 相同的 `fastapi.responses` 给开发者。但是大多数可用的响应都直接来自 Starlette。
+你也可以使用 `from starlette.responses import JSONResponse`。
+
+出于方便,**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 85dab15ac..e18d1620d 100644
--- a/docs/zh/docs/advanced/response-headers.md
+++ b/docs/zh/docs/advanced/response-headers.md
@@ -25,12 +25,15 @@
```
-!!! 注意 "技术细节"
- 你也可以使用`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
new file mode 100644
index 000000000..a76353186
--- /dev/null
+++ b/docs/zh/docs/advanced/security/http-basic-auth.md
@@ -0,0 +1,191 @@
+# HTTP 基础授权
+
+最简单的用例是使用 HTTP 基础授权(HTTP Basic Auth)。
+
+在 HTTP 基础授权中,应用需要请求头包含用户名与密码。
+
+如果没有接收到 HTTP 基础授权,就返回 HTTP 401 `"Unauthorized"` 错误。
+
+并返回含 `Basic` 值的请求头 `WWW-Authenticate`以及可选的 `realm` 参数。
+
+HTTP 基础授权让浏览器显示内置的用户名与密码提示。
+
+输入用户名与密码后,浏览器会把它们自动发送至请求头。
+
+## 简单的 HTTP 基础授权
+
+* 导入 `HTTPBasic` 与 `HTTPBasicCredentials`
+* 使用 `HTTPBasic` 创建**安全概图**
+* 在*路径操作*的依赖项中使用 `security`
+* 返回类型为 `HTTPBasicCredentials` 的对象:
+ * 包含发送的 `username` 与 `password`
+
+//// tab | Python 3.9+
+
+```Python hl_lines="4 8 12"
+{!> ../../../docs_src/security/tutorial006_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="2 7 11"
+{!> ../../../docs_src/security/tutorial006_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="2 6 10"
+{!> ../../../docs_src/security/tutorial006.py!}
+```
+
+////
+
+第一次打开 URL(或在 API 文档中点击 **Execute** 按钮)时,浏览器要求输入用户名与密码:
+
+
+
+## 检查用户名
+
+以下是更完整的示例。
+
+使用依赖项检查用户名与密码是否正确。
+
+为此要使用 Python 标准模块 `secrets` 检查用户名与密码。
+
+`secrets.compare_digest()` 需要仅包含 ASCII 字符(英语字符)的 `bytes` 或 `str`,这意味着它不适用于像`á`一样的字符,如 `Sebastián`。
+
+为了解决这个问题,我们首先将 `username` 和 `password` 转换为使用 UTF-8 编码的 `bytes` 。
+
+然后我们可以使用 `secrets.compare_digest()` 来确保 `credentials.username` 是 `"stanleyjobson"`,且 `credentials.password` 是`"swordfish"`。
+
+//// tab | Python 3.9+
+
+```Python hl_lines="1 12-24"
+{!> ../../../docs_src/security/tutorial007_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="1 12-24"
+{!> ../../../docs_src/security/tutorial007_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="1 11-21"
+{!> ../../../docs_src/security/tutorial007.py!}
+```
+
+////
+
+这类似于:
+
+```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`,让浏览器再次显示登录提示:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="26-30"
+{!> ../../../docs_src/security/tutorial007_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="26-30"
+{!> ../../../docs_src/security/tutorial007_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="23-27"
+{!> ../../../docs_src/security/tutorial007.py!}
+```
+
+////
diff --git a/docs/zh/docs/advanced/security/index.md b/docs/zh/docs/advanced/security/index.md
index fdc8075c7..836086ae2 100644
--- a/docs/zh/docs/advanced/security/index.md
+++ b/docs/zh/docs/advanced/security/index.md
@@ -2,15 +2,18 @@
## 附加特性
-除 [教程 - 用户指南: 安全性](../../tutorial/security/){.internal-link target=_blank} 中涵盖的功能之外,还有一些额外的功能来处理安全性.
+除 [教程 - 用户指南: 安全性](../../tutorial/security/index.md){.internal-link target=_blank} 中涵盖的功能之外,还有一些额外的功能来处理安全性.
-!!! tip "小贴士"
- 接下来的章节 **并不一定是 "高级的"**.
+/// tip | "小贴士"
- 而且对于你的使用场景来说,解决方案很可能就在其中。
+接下来的章节 **并不一定是 "高级的"**.
+
+而且对于你的使用场景来说,解决方案很可能就在其中。
+
+///
## 先阅读教程
-接下来的部分假设你已经阅读了主要的 [教程 - 用户指南: 安全性](../../tutorial/security/){.internal-link target=_blank}.
+接下来的部分假设你已经阅读了主要的 [教程 - 用户指南: 安全性](../../tutorial/security/index.md){.internal-link target=_blank}.
它们都基于相同的概念,但支持一些额外的功能.
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..b75ae11a4
--- /dev/null
+++ b/docs/zh/docs/advanced/security/oauth2-scopes.md
@@ -0,0 +1,290 @@
+# 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 登录时的授权机制。
+
+
+
+## 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 文档,进行身份验证,并指定要授权的作用域。
+
+
+
+没有选择任何作用域,也可以进行**身份验证**,但访问 `/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` 一起使用。
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
-
+
+然后查看子应用文档 http://127.0.0.1:8000/subapi/docs。
+
+下图显示的是子应用的 API 文档,也是只包括其自有的*路径操作*,所有这些路径操作都在 `/subapi` 子路径前缀下。
+
+
+
+两个用户界面都可以正常运行,因为浏览器能够与每个指定的应用或子应用会话。
+
+### 技术细节:`root_path`
+
+以上述方式挂载子应用时,FastAPI 使用 ASGI 规范中的 `root_path` 机制处理挂载子应用路径之间的通信。
+
+这样,子应用就可以为自动文档使用路径前缀。
+
+并且子应用还可以再挂载子应用,一切都会正常运行,FastAPI 可以自动处理所有 `root_path`。
+
+关于 `root_path` 及如何显式使用 `root_path` 的内容,详见[使用代理](behind-a-proxy.md){.internal-link target=_blank}一章。
diff --git a/docs/zh/docs/advanced/templates.md b/docs/zh/docs/advanced/templates.md
new file mode 100644
index 000000000..b09644e39
--- /dev/null
+++ b/docs/zh/docs/advanced/templates.md
@@ -0,0 +1,127 @@
+# 模板
+
+**FastAPI** 支持多种模板引擎。
+
+Flask 等工具使用的 Jinja2 是最用的模板引擎。
+
+在 Starlette 的支持下,**FastAPI** 应用可以直接使用工具轻易地配置 Jinja2。
+
+## 安装依赖项
+
+安装 `jinja2`:
+
+
-!!! info
- 漂亮的插画来自 Ketrina Thompson. 🎨
+/// info
+
+漂亮的插画来自 Ketrina Thompson. 🎨
+
+///
---
@@ -199,8 +205,11 @@ Python 的现代版本支持通过一种叫**"协程"**——使用 `async` 和
没有太多的交谈或调情,因为大部分时间 🕙 都在柜台前等待😞。
-!!! info
- 漂亮的插画来自 Ketrina Thompson. 🎨
+/// info
+
+漂亮的插画来自 Ketrina Thompson. 🎨
+
+///
---
@@ -392,12 +401,15 @@ Starlette (和 **FastAPI**) 是基于 I/O 的代码。
-在这两种情况下,与您之前的框架相比,**FastAPI** 可能[仍然很快](/#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/contributing.md b/docs/zh/docs/contributing.md
index 3dfc3db7c..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
-
-
-## 启用公开访问
-
-默认情况下,Deta 使用您的账号 Cookies 处理身份验证。
-
-应用一切就绪之后,使用如下命令让公众也能看到您的应用:
-
-
-
-## 更多内容
-
-如果要持久化保存应用数据,可以使用提供了**免费方案**的 Deta Base。
-
-详见 Deta 官档。
diff --git a/docs/zh/docs/deployment/docker.md b/docs/zh/docs/deployment/docker.md
index 0f8906704..f120ebfb8 100644
--- a/docs/zh/docs/deployment/docker.md
+++ b/docs/zh/docs/deployment/docker.md
@@ -4,9 +4,11 @@
使用 Linux 容器有几个优点,包括**安全性**、**可复制性**、**简单性**等。
-!!! tip
- 赶时间并且已经知道这些东西了? 跳转到下面的 [`Dockerfile` 👇](#为-fastapi-构建-docker-镜像)。
+/// tip
+赶时间并且已经知道这些东西了? 跳转到下面的 [`Dockerfile` 👇](#fastapi-docker_1)。
+
+///
+
+但是你可以通过设置 `syntaxHighlight` 为 `False` 来禁用 Swagger UI 中的语法高亮:
+
+```Python hl_lines="3"
+{!../../../docs_src/configure_swagger_ui/tutorial001.py!}
+```
+
+...在此之后,Swagger UI 将不会高亮代码:
+
+
+
+## 改变主题
+
+同样地,你也可以通过设置键 `"syntaxHighlight.theme"` 来设置语法高亮主题(注意中间有一个点):
+
+```Python hl_lines="3"
+{!../../../docs_src/configure_swagger_ui/tutorial002.py!}
+```
+
+这个配置会改变语法高亮主题:
+
+
+
+## 改变默认 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 参数,请阅读 docs for Swagger UI parameters。
+
+## 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。
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..262dcfaee
--- /dev/null
+++ b/docs/zh/docs/how-to/index.md
@@ -0,0 +1,13 @@
+# 如何操作 - 诀窍
+
+在这里,你将看到关于**多个主题**的不同诀窍或“如何操作”指南。
+
+这些方法多数是**相互独立**的,在大多数情况下,你只需在这些内容适用于**你的项目**时才需要学习它们。
+
+如果某些内容看起来对你的项目有用,请继续查阅,否则请直接跳过它们。
+
+/// 小技巧
+
+如果你想以系统的方式**学习 FastAPI**(推荐),请阅读 [教程 - 用户指南](../tutorial/index.md){.internal-link target=_blank} 的每一章节。
+
+///
diff --git a/docs/zh/docs/index.md b/docs/zh/docs/index.md
index a480d6640..777240ec2 100644
--- a/docs/zh/docs/index.md
+++ b/docs/zh/docs/index.md
@@ -1,3 +1,9 @@
+# FastAPI
+
+
+
@@ -5,26 +11,29 @@
FastAPI 框架,高性能,易于学习,高效编码,生产可用
---
**文档**: https://fastapi.tiangolo.com
-**源码**: https://github.com/tiangolo/fastapi
+**源码**: https://github.com/fastapi/fastapi
---
-FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框架,使用 Python 3.8+ 并基于标准的 Python 类型提示。
+FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框架,使用 Python 并基于标准的 Python 类型提示。
关键特性:
@@ -61,7 +70,7 @@ FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框
「_[...] 最近我一直在使用 **FastAPI**。[...] 实际上我正在计划将其用于我所在的**微软**团队的所有**机器学习服务**。其中一些服务正被集成进核心 **Windows** 产品和一些 **Office** 产品。_」
-email_validator - 用于 email 校验。
+* email-validator - 用于 email 校验。
用于 Starlette:
@@ -447,14 +456,14 @@ item: Item
* itsdangerous - 需要 `SessionMiddleware` 支持时安装。
* pyyaml - 使用 Starlette 提供的 `SchemaGenerator` 时安装(有 FastAPI 你可能并不需要它)。
* graphene - 需要 `GraphQLApp` 支持时安装。
-* ujson - 使用 `UJSONResponse` 时安装。
用于 FastAPI / Starlette:
* uvicorn - 用于加载和运行你的应用程序的服务器。
* orjson - 使用 `ORJSONResponse` 时安装。
+* ujson - 使用 `UJSONResponse` 时安装。
-你可以通过 `pip install fastapi[all]` 命令来安装以上所有依赖。
+你可以通过 `pip install "fastapi[all]"` 命令来安装以上所有依赖。
## 许可协议
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:**FastAPI** 后端:
+* Python **FastAPI** 后端:
* * **速度快**:可与 **NodeJS** 和 **Go** 比肩的极高性能(归功于 Starlette 和 Pydantic)
* **直观**:强大的编辑器支持,处处皆可自动补全,减少调试时间
* **简单**:易学、易用,阅读文档所需时间更短
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
- 想进一步了解 Pydantic,请阅读其文档.
+/// info
+
+想进一步了解 Pydantic,请阅读其文档.
+
+///
整个 **FastAPI** 建立在 Pydantic 的基础之上。
@@ -282,5 +288,8 @@ John Doe
最重要的是,通过使用标准的 Python 类型,只需要在一个地方声明(而不是添加更多的类、装饰器等),**FastAPI** 会为你完成很多的工作。
-!!! info
- 如果你已经阅读了所有教程,回过头来想了解有关类型的更多信息,来自 `mypy` 的"速查表"是不错的资源。
+/// info
+
+如果你已经阅读了所有教程,回过头来想了解有关类型的更多信息,来自 `mypy` 的"速查表"是不错的资源。
+
+///
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!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="13 15 22 25"
- {!> ../../../docs_src/background_tasks/tutorial002_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="13 15 22 25"
+{!> ../../../docs_src/background_tasks/tutorial002_an_py39.py!}
+```
- ```Python hl_lines="14 16 23 26"
- {!> ../../../docs_src/background_tasks/tutorial002_an.py!}
- ```
+////
-=== "Python 3.10+ 没Annotated"
+//// tab | Python 3.8+
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+```Python hl_lines="14 16 23 26"
+{!> ../../../docs_src/background_tasks/tutorial002_an.py!}
+```
- ```Python hl_lines="11 13 20 23"
- {!> ../../../docs_src/background_tasks/tutorial002_py310.py!}
- ```
+////
-=== "Python 3.8+ 没Annotated"
+//// tab | Python 3.10+ 没Annotated
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+/// tip
- ```Python hl_lines="13 15 22 25"
- {!> ../../../docs_src/background_tasks/tutorial002.py!}
- ```
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="11 13 20 23"
+{!> ../../../docs_src/background_tasks/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ 没Annotated
+
+/// tip
+
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```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 138959566..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` 中,你可以有如下一行:
+这就是能将代码从一个文件导入到另一个文件的原因。
- ```
- from app.routers import items
- ```
+例如,在 `app/main.py` 中,你可以有如下一行:
+
+```
+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
-!!! check
- `prefix`、`tags`、`responses` 以及 `dependencies` 参数只是(和其他很多情况一样)**FastAPI** 的一个用于帮助你避免代码重复的功能。
+在 `APIRouter`中具有 `dependencies` 可以用来,例如,对一整组的*路径操作*要求身份认证。即使这些依赖项并没有分别添加到每个路径操作中。
+
+///
+
+/// check
+
+`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
- 并且在文档中也会有两个响应,一个用于 `404`,一个用于 `403`。
+最后的这个路径操作将包含标签的组合:`["items","custom"]`。
+
+并且在文档中也会有两个响应,一个用于 `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 包和模块的更多信息,请查阅关于 Modules 的 Python 官方文档。
+```Python
+from app.routers import items, users
+```
+
+要了解有关 Python 包和模块的更多信息,请查阅关于 Modules 的 Python 官方文档。
+
+///
### 避免名称冲突
@@ -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` 没有被「挂载」,它们与应用程序的其余部分没有隔离。
+---
- 这是因为我们想要在 OpenAPI 模式和用户界面中包含它们的*路径操作*。
+`APIRouter` 没有被「挂载」,它们与应用程序的其余部分没有隔离。
- 由于我们不能仅仅隔离它们并独立于其余部分来「挂载」它们,因此*路径操作*是被「克隆的」(重新创建),而不是直接包含。
+这是因为我们想要在 OpenAPI 模式和用户界面中包含它们的*路径操作*。
+
+由于我们不能仅仅隔离它们并独立于其余部分来「挂载」它们,因此*路径操作*是被「克隆的」(重新创建),而不是直接包含。
+
+///
## 查看自动化的 API 文档
diff --git a/docs/zh/docs/tutorial/body-fields.md b/docs/zh/docs/tutorial/body-fields.md
index fb6c6d9b6..6e4c385dd 100644
--- a/docs/zh/docs/tutorial/body-fields.md
+++ b/docs/zh/docs/tutorial/body-fields.md
@@ -1,112 +1,153 @@
# 请求体 - 字段
-与使用 `Query`、`Path` 和 `Body` 在*路径操作函数*中声明额外的校验和元数据的方式相同,你可以使用 Pydantic 的 `Field` 在 Pydantic 模型内部声明校验和元数据。
+与在*路径操作函数*中使用 `Query`、`Path` 、`Body` 声明校验与元数据的方式一样,可以使用 Pydantic 的 `Field` 在 Pydantic 模型内部声明校验和元数据。
## 导入 `Field`
-首先,你必须导入它:
+首先,从 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
- 注意,`Field` 是直接从 `pydantic` 导入的,而不是像其他的(`Query`,`Path`,`Body` 等)都从 `fastapi` 导入。
+///
+
+```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`:
+然后,使用 `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+"
+////
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="11-14"
+{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="12-15"
- {!> ../../../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="12-15"
+{!> ../../../docs_src/body_fields/tutorial001_an.py!}
+```
- ```Python hl_lines="9-12"
- {!> ../../../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="11-14"
- {!> ../../../docs_src/body_fields/tutorial001.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-`Field` 的工作方式和 `Query`、`Path` 和 `Body` 相同,包括它们的参数等等也完全相同。
+///
-!!! note "技术细节"
- 实际上,`Query`、`Path` 和其他你将在之后看到的类,创建的是由一个共同的 `Params` 类派生的子类的对象,该共同类本身又是 Pydantic 的 `FieldInfo` 类的子类。
+```Python hl_lines="9-12"
+{!> ../../../docs_src/body_fields/tutorial001_py310.py!}
+```
- Pydantic 的 `Field` 也会返回一个 `FieldInfo` 的实例。
+////
- `Body` 也直接返回 `FieldInfo` 的一个子类的对象。还有其他一些你之后会看到的类是 `Body` 类的子类。
+//// tab | Python 3.8+ non-Annotated
- 请记住当你从 `fastapi` 导入 `Query`、`Path` 等对象时,他们实际上是返回特殊类的函数。
+/// tip
-!!! tip
- 注意每个模型属性如何使用类型、默认值和 `Field` 在代码结构上和*路径操作函数*的参数是相同的,区别是用 `Field` 替换`Path`、`Query` 和 `Body`。
+Prefer to use the `Annotated` version if possible.
-## 添加额外信息
+///
-你可以在 `Field`、`Query`、`Body` 中声明额外的信息。这些信息将包含在生成的 JSON Schema 中。
+```Python hl_lines="11-14"
+{!> ../../../docs_src/body_fields/tutorial001.py!}
+```
-你将在文档的后面部分学习声明示例时,了解到更多有关添加额外信息的知识。
+////
-## 总结
+`Field` 的工作方式和 `Query`、`Path`、`Body` 相同,参数也相同。
-你可以使用 Pydantic 的 `Field` 为模型属性声明额外的校验和元数据。
+/// note | "技术细节"
-你还可以使用额外的关键字参数来传递额外的 JSON Schema 元数据。
+实际上,`Query`、`Path` 都是 `Params` 的子类,而 `Params` 类又是 Pydantic 中 `FieldInfo` 的子类。
+
+Pydantic 的 `Field` 返回也是 `FieldInfo` 的类实例。
+
+`Body` 直接返回的也是 `FieldInfo` 的子类的对象。后文还会介绍一些 `Body` 的子类。
+
+注意,从 `fastapi` 导入的 `Query`、`Path` 等对象实际上都是返回特殊类的函数。
+
+///
+
+/// tip | "提示"
+
+注意,模型属性的类型、默认值及 `Field` 的代码结构与*路径操作函数*的参数相同,只不过是用 `Field` 替换了`Path`、`Query`、`Body`。
+
+///
+
+## 添加更多信息
+
+`Field`、`Query`、`Body` 等对象里可以声明更多信息,并且 JSON Schema 中也会集成这些信息。
+
+*声明示例*一章中将详细介绍添加更多信息的知识。
+
+## 小结
+
+Pydantic 的 `Field` 可以为模型属性声明更多校验和元数据。
+
+传递 JSON Schema 元数据还可以使用更多关键字参数。
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!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="18-20"
- {!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="18-20"
+{!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="19-21"
- {!> ../../../docs_src/body_multiple_params/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+```Python hl_lines="19-21"
+{!> ../../../docs_src/body_multiple_params/tutorial001_an.py!}
+```
- ```Python hl_lines="17-19"
- {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+/// tip
- ```Python hl_lines="19-21"
- {!> ../../../docs_src/body_multiple_params/tutorial001.py!}
- ```
+尽可能选择使用 `Annotated` 的版本。
-!!! note
- 请注意,在这种情况下,将从请求体获取的 `item` 是可选的。因为它的默认值为 `None`。
+///
+
+```Python hl_lines="17-19"
+{!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="19-21"
+{!> ../../../docs_src/body_multiple_params/tutorial001.py!}
+```
+
+////
+
+/// 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` 参数也是如此。
@@ -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!}
- ```
+```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!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="23"
+{!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!}
+```
- ```Python hl_lines="24"
- {!> ../../../docs_src/body_multiple_params/tutorial003_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+```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.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+/// tip
- ```Python hl_lines="22"
- {!> ../../../docs_src/body_multiple_params/tutorial003.py!}
- ```
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="20"
+{!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="22"
+{!> ../../../docs_src/body_multiple_params/tutorial003.py!}
+```
+
+////
在这种情况下,**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!}
- ```
+```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!}
+```
- ```Python hl_lines="28"
- {!> ../../../docs_src/body_multiple_params/tutorial004_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+```Python hl_lines="28"
+{!> ../../../docs_src/body_multiple_params/tutorial004_an.py!}
+```
- ```Python hl_lines="25"
- {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+/// tip
- ```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004.py!}
- ```
+尽可能选择使用 `Annotated` 的版本。
-!!! info
- `Body` 同样具有与 `Query`、`Path` 以及其他后面将看到的类完全相同的额外校验和元数据参数。
+///
+```Python hl_lines="25"
+{!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="27"
+{!> ../../../docs_src/body_multiple_params/tutorial004.py!}
+```
+
+////
+
+/// info
+
+`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!}
- ```
+```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!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="17"
+{!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!}
+```
- ```Python hl_lines="18"
- {!> ../../../docs_src/body_multiple_params/tutorial005_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+```Python hl_lines="18"
+{!> ../../../docs_src/body_multiple_params/tutorial005_an.py!}
+```
- ```Python hl_lines="15"
- {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+/// tip
- ```Python hl_lines="17"
- {!> ../../../docs_src/body_multiple_params/tutorial005.py!}
- ```
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="15"
+{!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="17"
+{!> ../../../docs_src/body_multiple_params/tutorial005.py!}
+```
+
+////
在这种情况下,**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+"
+////
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```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!}
- ```
+```Python hl_lines="12"
+{!> ../../../docs_src/body_nested_models/tutorial002_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial002_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="14"
+{!> ../../../docs_src/body_nested_models/tutorial002_py39.py!}
+```
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial002.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```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!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial003_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="14"
+{!> ../../../docs_src/body_nested_models/tutorial003_py39.py!}
+```
- ```Python hl_lines="1 14"
- {!> ../../../docs_src/body_nested_models/tutorial003.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```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!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="9-11"
- {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="9-11"
+{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!}
+```
- ```Python hl_lines="9-11"
- {!> ../../../docs_src/body_nested_models/tutorial004.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```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+"
+////
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial006_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="20"
+{!> ../../../docs_src/body_nested_models/tutorial006_py39.py!}
+```
- ```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!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="9 14 20 23 27"
- {!> ../../../docs_src/body_nested_models/tutorial007_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="9 14 20 23 27"
+{!> ../../../docs_src/body_nested_models/tutorial007_py39.py!}
+```
- ```Python hl_lines="9 14 20 23 27"
- {!> ../../../docs_src/body_nested_models/tutorial007.py!}
- ```
+////
-!!! info
- 请注意 `Offer` 拥有一组 `Item` 而反过来 `Item` 又是一个可选的 `Image` 列表是如何发生的。
+//// tab | Python 3.8+
+
+```Python hl_lines="9 14 20 23 27"
+{!> ../../../docs_src/body_nested_models/tutorial007.py!}
+```
+
+////
+
+/// 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+"
+////
- ```Python hl_lines="15"
- {!> ../../../docs_src/body_nested_models/tutorial008.py!}
- ```
+//// tab | Python 3.8+
+
+```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!}
- ```
+```Python hl_lines="7"
+{!> ../../../docs_src/body_nested_models/tutorial009_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/body_nested_models/tutorial009.py!}
- ```
+//// tab | Python 3.8+
-!!! tip
- 请记住 JSON 仅支持将 `str` 作为键。
+```Python hl_lines="9"
+{!> ../../../docs_src/body_nested_models/tutorial009.py!}
+```
- 但是 Pydantic 具有自动转换数据的功能。
+////
- 这意味着,即使你的 API 客户端只能将字符串作为键发送,只要这些字符串内容仅包含整数,Pydantic 就会对其进行转换并校验。
+/// tip
- 然后你接收的名为 `weights` 的 `dict` 实际上将具有 `int` 类型的键和 `float` 类型的值。
+请记住 JSON 仅支持将 `str` 作为键。
+
+但是 Pydantic 具有自动转换数据的功能。
+
+这意味着,即使你的 API 客户端只能将字符串作为键发送,只要这些字符串内容仅包含整数,Pydantic 就会对其进行转换并校验。
+
+然后你接收的名为 `weights` 的 `dict` 实际上将具有 `int` 类型的键和 `float` 类型的值。
+
+///
## 总结
diff --git a/docs/zh/docs/tutorial/body-updates.md b/docs/zh/docs/tutorial/body-updates.md
index 43f20f8fc..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`)。
+注意,输入模型仍需验证。
- 为了区分用于**更新**所有可选值的模型与用于**创建**包含必选值的模型,请参照[更多模型](extra-models.md){.internal-link target=_blank} 一节中的思路。
+因此,如果希望接收的部分更新数据可以省略其他所有属性,则要把模型中所有的属性标记为可选(使用默认值或 `None`)。
+
+为了区分用于**更新**所有可选值的模型与用于**创建**包含必选值的模型,请参照[更多模型](extra-models.md){.internal-link target=_blank} 一节中的思路。
+
+///
diff --git a/docs/zh/docs/tutorial/body.md b/docs/zh/docs/tutorial/body.md
index 3d615be39..c47abec77 100644
--- a/docs/zh/docs/tutorial/body.md
+++ b/docs/zh/docs/tutorial/body.md
@@ -1,55 +1,68 @@
# 请求体
-当你需要将数据从客户端(例如浏览器)发送给 API 时,你将其作为「请求体」发送。
+FastAPI 使用**请求体**从客户端(例如浏览器)向 API 发送数据。
-**请求**体是客户端发送给 API 的数据。**响应**体是 API 发送给客户端的数据。
+**请求体**是客户端发送给 API 的数据。**响应体**是 API 发送给客户端的数据。
-你的 API 几乎总是要发送**响应**体。但是客户端并不总是需要发送**请求**体。
+API 基本上肯定要发送**响应体**,但是客户端不一定发送**请求体**。
-我们使用 Pydantic 模型来声明**请求**体,并能够获得它们所具有的所有能力和优点。
+使用 Pydantic 模型声明**请求体**,能充分利用它的功能和优点。
-!!! 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+"
+//// 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+"
+////
- ```Python hl_lines="4"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="4"
+{!> ../../../docs_src/body/tutorial001.py!}
+```
+
+////
## 创建数据模型
-然后,将你的数据模型声明为继承自 `BaseModel` 的类。
+把数据模型声明为继承 `BaseModel` 的类。
-使用标准的 Python 类型来声明所有属性:
+使用 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!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="7-11"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
+//// tab | Python 3.8+
-和声明查询参数时一样,当一个模型属性具有默认值时,它不是必需的。否则它是一个必需属性。将默认值设为 `None` 可使其成为可选属性。
+```Python hl_lines="7-11"
+{!> ../../../docs_src/body/tutorial001.py!}
+```
-例如,上面的模型声明了一个这样的 JSON「`object`」(或 Python `dict`):
+////
+
+与声明查询参数一样,包含默认值的模型属性是可选的,否则就是必选的。默认值为 `None` 的模型属性也是可选的。
+
+例如,上述模型声明如下 JSON **对象**(即 Python **字典**):
```JSON
{
@@ -60,7 +73,7 @@
}
```
-...由于 `description` 和 `tax` 是可选的(它们的默认值为 `None`),下面的 JSON「`object`」也将是有效的:
+……由于 `description` 和 `tax` 是可选的(默认值为 `None`),下面的 JSON **对象**也有效:
```JSON
{
@@ -69,127 +82,165 @@
}
```
-## 声明为参数
+## 声明请求体参数
-使用与声明路径和查询参数的相同方式声明请求体,即可将其添加到「路径操作」中:
+使用与声明路径和查询参数相同的方式声明请求体,把请求体添加至*路径操作*:
-=== "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+
-...并且将它的类型声明为你创建的 `Item` 模型。
+```Python hl_lines="18"
+{!> ../../../docs_src/body/tutorial001.py!}
+```
-## 结果
+////
-仅仅使用了 Python 类型声明,**FastAPI** 将会:
+……此处,请求体参数的类型为 `Item` 模型。
-* 将请求体作为 JSON 读取。
-* 转换为相应的类型(在需要时)。
-* 校验数据。
- * 如果数据无效,将返回一条清晰易读的错误信息,指出不正确数据的确切位置和内容。
-* 将接收的数据赋值到参数 `item` 中。
- * 由于你已经在函数中将它声明为 `Item` 类型,你还将获得对于所有属性及其类型的一切编辑器支持(代码补全等)。
-* 为你的模型生成 JSON 模式 定义,你还可以在其他任何对你的项目有意义的地方使用它们。
-* 这些模式将成为生成的 OpenAPI 模式的一部分,并且被自动化文档 UI 所使用。
+## 结论
-## 自动化文档
+仅使用 Python 类型声明,**FastAPI** 就可以:
-你所定义模型的 JSON 模式将成为生成的 OpenAPI 模式的一部分,并且在交互式 API 文档中展示:
+* 以 JSON 形式读取请求体
+* (在必要时)把请求体转换为对应的类型
+* 校验数据:
+ * 数据无效时返回错误信息,并指出错误数据的确切位置和内容
+* 把接收的数据赋值给参数 `item`
+ * 把函数中请求体参数的类型声明为 `Item`,还能获得代码补全等编辑器支持
+* 为模型生成 JSON Schema,在项目中所需的位置使用
+* 这些概图是 OpenAPI 概图的部件,用于 API 文档 UI
-
+## API 文档
-而且还将在每一个需要它们的*路径操作*的 API 文档中使用:
+Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文档中显示:
-
+
+
+而且,还会用于 API 文档中使用了概图的*路径操作*:
+
+
## 编辑器支持
-在你的编辑器中,你会在函数内部的任意地方得到类型提示和代码补全(如果你接收的是一个 `dict` 而不是 Pydantic 模型,则不会发生这种情况):
+在编辑器中,函数内部均可使用类型提示、代码补全(如果接收的不是 Pydantic 模型,而是**字典**,就没有这样的支持):
-
+
-你还会获得对不正确的类型操作的错误检查:
+还支持检查错误的类型操作:
-
+
-这并非偶然,整个框架都是围绕该设计而构建。
+这并非偶然,整个 **FastAPI** 框架都是围绕这种思路精心设计的。
-并且在进行任何实现之前,已经在设计阶段经过了全面测试,以确保它可以在所有的编辑器中生效。
+并且,在 FastAPI 的设计阶段,我们就已经进行了全面测试,以确保 FastAPI 可以获得所有编辑器的支持。
-Pydantic 本身甚至也进行了一些更改以支持此功能。
+我们还改进了 Pydantic,让它也支持这些功能。
-上面的截图取自 Visual Studio Code。
+虽然上面的截图取自 Visual Studio Code。
-但是在 PyCharm 和绝大多数其他 Python 编辑器中你也会获得同样的编辑器支持:
+但 PyCharm 和大多数 Python 编辑器也支持同样的功能:
-
+
+
+/// tip | "提示"
+
+使用 PyCharm 编辑器时,推荐安装 Pydantic PyCharm 插件。
+
+该插件用于完善 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+"
+////
- ```Python hl_lines="21"
- {!> ../../../docs_src/body/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="21"
+{!> ../../../docs_src/body/tutorial002.py!}
+```
+
+////
## 请求体 + 路径参数
-你可以同时声明路径参数和请求体。
+**FastAPI** 支持同时声明路径参数和请求体。
-**FastAPI** 将识别出与路径参数匹配的函数参数应**从路径中获取**,而声明为 Pydantic 模型的函数参数应**从请求体中获取**。
+**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+"
+////
- ```Python hl_lines="17-18"
- {!> ../../../docs_src/body/tutorial003.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="17-18"
+{!> ../../../docs_src/body/tutorial003.py!}
+```
+
+////
## 请求体 + 路径参数 + 查询参数
-你还可以同时声明**请求体**、**路径参数**和**查询参数**。
+**FastAPI** 支持同时声明**请求体**、**路径参数**和**查询参数**。
-**FastAPI** 会识别它们中的每一个,并从正确的位置获取数据。
+**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+"
+////
- ```Python hl_lines="18"
- {!> ../../../docs_src/body/tutorial004.py!}
- ```
+//// tab | Python 3.8+
-函数参数将依次按如下规则进行识别:
+```Python hl_lines="18"
+{!> ../../../docs_src/body/tutorial004.py!}
+```
-* 如果在**路径**中也声明了该参数,它将被用作路径参数。
-* 如果参数属于**单一类型**(比如 `int`、`float`、`str`、`bool` 等)它将被解释为**查询**参数。
-* 如果参数的类型被声明为一个 **Pydantic 模型**,它将被解释为**请求体**。
+////
+
+函数参数按如下规则进行识别:
+
+- **路径**中声明了相同参数的参数,是路径参数
+- 类型是(`int`、`float`、`str`、`bool` 等)**单类型**的参数,是**查询**参数
+- 类型是 **Pydantic 模型**的参数,是**请求体**
+
+/// note | "笔记"
+
+因为默认值是 `None`, FastAPI 会把 `q` 当作可选参数。
+
+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#_2){.internal-link target=\_blank}。
diff --git a/docs/zh/docs/tutorial/cookie-params.md b/docs/zh/docs/tutorial/cookie-params.md
index f115f9677..7ca77696e 100644
--- a/docs/zh/docs/tutorial/cookie-params.md
+++ b/docs/zh/docs/tutorial/cookie-params.md
@@ -1,98 +1,136 @@
# Cookie 参数
-你可以像定义 `Query` 参数和 `Path` 参数一样来定义 `Cookie` 参数。
+ 定义 `Cookie` 参数与定义 `Query` 和 `Path` 参数一样。
## 导入 `Cookie`
-首先,导入 `Cookie`:
+首先,导入 `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` 参数
-声明 `Cookie` 参数的结构与声明 `Query` 参数和 `Path` 参数时相同。
+声明 `Cookie` 参数的方式与声明 `Query` 和 `Path` 参数相同。
-第一个值是参数的默认值,同时也可以传递所有验证参数或注释参数,来校验参数:
+第一个值是默认值,还可以传递所有验证参数或注释参数:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!}
- ```
+```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!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="9"
+{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/cookie_params/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+```Python hl_lines="10"
+{!> ../../../docs_src/cookie_params/tutorial001_an.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+/// tip
- ```Python hl_lines="9"
- {!> ../../../docs_src/cookie_params/tutorial001.py!}
- ```
+尽可能选择使用 `Annotated` 的版本。
-!!! note "技术细节"
- `Cookie` 、`Path` 、`Query`是兄弟类,它们都继承自公共的 `Param` 类
+///
- 但请记住,当你从 `fastapi` 导入的 `Query`、`Path`、`Cookie` 或其他参数声明函数,这些实际上是返回特殊类的函数。
+```Python hl_lines="7"
+{!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
+```
-!!! info
- 你需要使用 `Cookie` 来声明 cookie 参数,否则参数将会被解释为查询参数。
+////
-## 总结
+//// tab | Python 3.8+ non-Annotated
-使用 `Cookie` 声明 cookie 参数,使用方式与 `Query` 和 `Path` 类似。
+/// tip
+
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/cookie_params/tutorial001.py!}
+```
+
+////
+
+/// note | "技术细节"
+
+`Cookie` 、`Path` 、`Query` 是**兄弟类**,都继承自共用的 `Param` 类。
+
+注意,从 `fastapi` 导入的 `Query`、`Path`、`Cookie` 等对象,实际上是返回特殊类的函数。
+
+///
+
+/// info | "说明"
+
+必须使用 `Cookie` 声明 cookie 参数,否则该参数会被解释为查询参数。
+
+///
+
+## 小结
+
+使用 `Cookie` 声明 cookie 参数的方式与 `Query` 和 `Path` 相同。
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 @@
更多关于 CORS 的信息,请查看 Mozilla CORS 文档。
-!!! 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
- 更多信息请检查 Python 官方文档.
+/// info
+
+更多信息请检查 Python 官方文档.
+
+///
## 使用你的调试器运行代码
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+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```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+"
+////
- ```Python hl_lines="11-15"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+
+```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+"
+////
- ```Python hl_lines="12"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
- ```
+//// tab | Python 3.6+
+
+```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!}
+```
-=== "Python 3.6+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+//// tab | Python 3.6+
+
+```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!}
+```
-=== "Python 3.6+"
+////
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
- ```
+//// tab | Python 3.6+
+
+```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+"
+////
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial003.py!}
- ```
+//// tab | Python 3.6+
+
+```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+"
+////
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial004.py!}
- ```
+//// tab | Python 3.6+
+
+```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 e24b9409f..6058f7878 100644
--- a/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md
+++ b/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md
@@ -1,27 +1,31 @@
# 使用yield的依赖项
-FastAPI支持在完成后执行一些额外步骤的依赖项.
+FastAPI支持在完成后执行一些额外步骤的依赖项.
-为此,请使用 `yield` 而不是 `return`,然后再编写额外的步骤(代码)。
+为此,你需要使用 `yield` 而不是 `return`,然后再编写这些额外的步骤(代码)。
-!!! 提示
- 确保只使用一次 `yield` 。
+/// tip | 提示
-!!! 注意 "技术细节"
+确保在每个依赖中只使用一次 `yield`。
- 任何一个可以与以下内容一起使用的函数:
+///
- * `@contextlib.contextmanager` 或者
- * `@contextlib.asynccontextmanager`
+/// note | "技术细节"
- 都可以作为 **FastAPI** 的依赖项。
+任何一个可以与以下内容一起使用的函数:
- 实际上,FastAPI内部就使用了这两个装饰器。
+* `@contextlib.contextmanager` 或者
+* `@contextlib.asynccontextmanager`
+都可以作为 **FastAPI** 的依赖项。
+
+实际上,FastAPI内部就使用了这两个装饰器。
+
+///
## 使用 `yield` 的数据库依赖项
-例如,您可以使用这种方式创建一个数据库会话,并在完成后关闭它。
+例如,你可以使用这种方式创建一个数据库会话,并在完成后关闭它。
在发送响应之前,只会执行 `yield` 语句及之前的代码:
@@ -29,133 +33,252 @@ FastAPI支持在完成后执行一些> 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
- 这个图表展示了`HTTPException`,但你也可以引发任何其他你创建了[自定义异常处理程序](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}的异常。
+在发送了其中一个响应之后,就无法再发送其他响应了。
- 如果你引发任何异常,它将传递给带有`yield`的依赖,包括`HTTPException`,然后**再次**传递给异常处理程序。如果没有针对该异常的异常处理程序,那么它将被默认的内部`ServerErrorMiddleware`处理,返回500 HTTP状态码,告知客户端服务器发生了错误。
+///
+
+/// 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` 之后的退出代码是在响应被发送之后再执行,这个时候异常处理器已经执行过了。
+
+这样设计的目的主要是为了允许在后台任务中使用被依赖项`yield`的对象,因为退出代码会在后台任务结束后再执行。
+
+然而这也意味着在等待响应通过网络传输的同时,非必要的持有一个 `yield` 依赖项中的资源(例如数据库连接),这一行为在FastAPI 0.106.0被改变了。
+
+/// tip | 提示
+
+除此之外,后台任务通常是一组独立的逻辑,应该被单独处理,并且使用它自己的资源(例如它自己的数据库连接)。
+
+这样也会让你的代码更加简洁。
+
+///
+
+如果你之前依赖于这一行为,那么现在你应该在后台任务中创建并使用它自己的资源,不要在内部使用属于 `yield` 依赖项的资源。
+
+例如,你应该在后台任务中创建一个新的数据库会话用于查询数据,而不是使用相同的会话。你应该将对象的ID作为参数传递给后台任务函数,然后在该函数中重新获取该对象,而不是直接将数据库对象作为参数。
## 上下文管理器
-### 什么是“上下文管理器”
+### 什么是"上下文管理器"
-“上下文管理器”是您可以在`with`语句中使用的任何Python对象。
+"上下文管理器"是你可以在 `with` 语句中使用的任何Python对象。
-例如,您可以使用`with`读取文件:
+例如,你可以使用`with`读取文件:
```Python
with open("./somefile.txt") as f:
@@ -221,33 +379,39 @@ 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中,你可以通过创建一个带有`__enter__()`和`__exit__()`方法的类来创建上下文管理器。
-你也可以在**FastAPI**的依赖项中使用带有`yield`的`with`或`async with`语句,通过在依赖函数内部使用它们。
+你也可以在 **FastAPI** 的 `yield` 依赖项中通过 `with` 或者 `async with` 语句来使用它们:
```Python hl_lines="1-9 13"
{!../../../docs_src/dependencies/tutorial010.py!}
```
-!!! tip
- 另一种创建上下文管理器的方法是:
+/// tip | 提示
- * `@contextlib.contextmanager`或者
- * `@contextlib.asynccontextmanager`
+另一种创建上下文管理器的方法是:
- 使用上下文管理器装饰一个只有单个`yield`的函数。这就是**FastAPI**在内部用于带有`yield`的依赖项的方式。
+* `@contextlib.contextmanager`或者
+* `@contextlib.asynccontextmanager`
- 但是你不需要为FastAPI的依赖项使用这些装饰器(而且也不应该)。FastAPI会在内部为你处理这些。
+使用它们装饰一个只有单个 `yield` 的函数。这就是 **FastAPI** 内部对于 `yield` 依赖项的处理方式。
+
+但是你不需要为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 提供了简单易用,但功能强大的** 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!}
- ```
+```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!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="18-19"
+{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="19-20"
- {!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+```Python hl_lines="19-20"
+{!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
+```
- ```Python hl_lines="17-18"
- {!> ../../../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="18-19"
- {!> ../../../docs_src/extra_data_types/tutorial001.py!}
- ```
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="17-18"
+{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="18-19"
+{!> ../../../docs_src/extra_data_types/tutorial001.py!}
+```
+
+////
diff --git a/docs/zh/docs/tutorial/extra-models.md b/docs/zh/docs/tutorial/extra-models.md
index f89d58dd1..b23d4188f 100644
--- a/docs/zh/docs/tutorial/extra-models.md
+++ b/docs/zh/docs/tutorial/extra-models.md
@@ -1,63 +1,70 @@
-# 额外的模型
+# 更多模型
-我们从前面的示例继续,拥有多个相关的模型是很常见的。
+书接上文,多个关联模型这种情况很常见。
-对用户模型来说尤其如此,因为:
+特别是用户模型,因为:
-* **输入模型**需要拥有密码属性。
-* **输出模型**不应该包含密码。
-* **数据库模型**很可能需要保存密码的哈希值。
+* **输入模型**应该含密码
+* **输出模型**不应含密码
+* **数据库模型**需要加密的密码
-!!! 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+
-### 关于 `**user_in.dict()`
+```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41"
+{!> ../../../docs_src/extra_models/tutorial001.py!}
+```
+
+////
+
+### `**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 +77,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 +96,7 @@ UserInDB(
)
```
-或者更确切地,直接使用 `user_dict` 来表示将来可能包含的任何内容:
+或更精准,直接把可能会用到的内容与 `user_dict` 一起使用:
```Python
UserInDB(
@@ -100,34 +107,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,101 +146,124 @@ UserInDB(
)
```
-!!! warning
- 辅助性的额外函数只是为了演示可能的数据流,但它们显然不能提供任何真正的安全性。
+/// warning | "警告"
+
+辅助的附加函数只是为了演示可能的数据流,但它们显然不能提供任何真正的安全机制。
+
+///
## 减少重复
-减少代码重复是 **FastAPI** 的核心思想之一。
+**FastAPI** 的核心思想就是减少代码重复。
-因为代码重复会增加出现 bug、安全性问题、代码失步问题(当你在一个位置更新了代码但没有在其他位置更新)等的可能性。
+代码重复会导致 bug、安全问题、代码失步等问题(更新了某个位置的代码,但没有同步更新其它位置的代码)。
-上面的这些模型都共享了大量数据,并拥有重复的属性名称和类型。
+上面的这些模型共享了大量数据,拥有重复的属性名和类型。
-我们可以做得更好。
+FastAPI 可以做得更好。
-我们可以声明一个 `UserBase` 模型作为其他模型的基类。然后我们可以创建继承该模型属性(类型声明,校验等)的子类。
+声明 `UserBase` 模型作为其它模型的基类。然后,用该类衍生出继承其属性(类型声明、验证等)的子类。
-所有的数据转换、校验、文档生成等仍将正常运行。
+所有数据转换、校验、文档等功能仍将正常运行。
-这样,我们可以仅声明模型之间的差异部分(具有明文的 `password`、具有 `hashed_password` 以及不包括密码)。
+这样,就可以仅声明模型之间的差异部分(具有明文的 `password`、具有 `hashed_password` 以及不包括密码)。
-=== "Python 3.10+"
+通过这种方式,可以只声明模型之间的区别(分别包含明文密码、哈希密码,以及无密码的模型)。
- ```Python hl_lines="7 13-14 17-18 21-22"
- {!> ../../../docs_src/extra_models/tutorial002_py310.py!}
- ```
+//// tab | Python 3.10+
-=== "Python 3.8+"
+```Python hl_lines="7 13-14 17-18 21-22"
+{!> ../../../docs_src/extra_models/tutorial002_py310.py!}
+```
- ```Python hl_lines="9 15-16 19-20 23-24"
- {!> ../../../docs_src/extra_models/tutorial002.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9 15-16 19-20 23-24"
+{!> ../../../docs_src/extra_models/tutorial002.py!}
+```
+
+////
## `Union` 或者 `anyOf`
-你可以将一个响应声明为两种类型的 `Union`,这意味着该响应将是两种类型中的任何一种。
+响应可以声明为两种类型的 `Union` 类型,即该响应可以是两种类型中的任意类型。
-这将在 OpenAPI 中使用 `anyOf` 进行定义。
+在 OpenAPI 中可以使用 `anyOf` 定义。
-为此,请使用标准的 Python 类型提示 `typing.Union`:
+为此,请使用 Python 标准类型提示 `typing.Union`:
+/// note | "笔记"
-!!! note
- 定义一个 `Union` 类型时,首先包括最详细的类型,然后是不太详细的类型。在下面的示例中,更详细的 `PlaneItem` 位于 `Union[PlaneItem,CarItem]` 中的 `CarItem` 之前。
+定义 `Union` 类型时,要把详细的类型写在前面,然后是不太详细的类型。下例中,更详细的 `PlaneItem` 位于 `Union[PlaneItem,CarItem]` 中的 `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!}
+```
+
+////
## 模型列表
-你可以用同样的方式声明由对象列表构成的响应。
+使用同样的方式也可以声明由对象列表构成的响应。
为此,请使用标准的 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+"
+////
- ```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` 构成的响应
-你还可以使用一个任意的普通 `dict` 声明响应,仅声明键和值的类型,而不使用 Pydantic 模型。
+任意的 `dict` 都能用于声明响应,只要声明键和值的类型,无需使用 Pydantic 模型。
-如果你事先不知道有效的字段/属性名称(对于 Pydantic 模型是必需的),这将很有用。
+事先不知道可用的字段 / 属性名时(Pydantic 模型必须知道字段是什么),这种方式特别有用。
-在这种情况下,你可以使用 `typing.Dict`:
+此时,可以使用 `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+"
+////
- ```Python hl_lines="1 8"
- {!> ../../../docs_src/extra_models/tutorial005.py!}
- ```
+//// tab | Python 3.8+
-## 总结
+```Python hl_lines="1 8"
+{!> ../../../docs_src/extra_models/tutorial005.py!}
+```
-使用多个 Pydantic 模型,并针对不同场景自由地继承。
+////
-如果一个实体必须能够具有不同的「状态」,你无需为每个状态的实体定义单独的数据模型。以用户「实体」为例,其状态有包含 `password`、包含 `password_hash` 以及不含密码。
+## 小结
+
+针对不同场景,可以随意使用不同的 Pydantic 模型继承定义的基类。
+
+实体必须具有不同的**状态**时,不必为不同状态的实体单独定义数据模型。例如,用户**实体**就有包含 `password`、包含 `password_hash` 以及不含密码等多种状态。
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
get 操作
-!!! 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
- **FastAPI** 没有强制要求操作有任何特定的含义。
+您可以随意使用任何一个操作(HTTP方法)。
- 此处提供的信息仅作为指导,而不是要求。
+**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 的 `ValidationError` 的子类。
@@ -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 2701167b3..a9064c519 100644
--- a/docs/zh/docs/tutorial/header-params.md
+++ b/docs/zh/docs/tutorial/header-params.md
@@ -1,216 +1,293 @@
# Header 参数
-你可以使用定义 `Query`, `Path` 和 `Cookie` 参数一样的方法定义 Header 参数。
+定义 `Header` 参数的方式与定义 `Query`、`Path`、`Cookie` 参数相同。
## 导入 `Header`
-首先导入 `Header`:
+首先,导入 `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+"
+////
- ```Python hl_lines="3"
- {!> ../../../docs_src/header_params/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="3"
+{!> ../../../docs_src/header_params/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="3"
- {!> ../../../docs_src/header_params/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+```Python hl_lines="3"
+{!> ../../../docs_src/header_params/tutorial001_an.py!}
+```
- ```Python hl_lines="1"
- {!> ../../../docs_src/header_params/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+/// tip
- ```Python hl_lines="3"
- {!> ../../../docs_src/header_params/tutorial001.py!}
- ```
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="1"
+{!> ../../../docs_src/header_params/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="3"
+{!> ../../../docs_src/header_params/tutorial001.py!}
+```
+
+////
## 声明 `Header` 参数
-然后使用和`Path`, `Query` and `Cookie` 一样的结构定义 header 参数
+然后,使用和 `Path`、`Query`、`Cookie` 一样的结构定义 header 参数。
-第一个值是默认值,你可以传递所有的额外验证或注释参数:
+第一个值是默认值,还可以传递所有验证参数或注释参数:
-=== "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!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/header_params/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+/// tip
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial001.py!}
- ```
+尽可能选择使用 `Annotated` 的版本。
-!!! note "技术细节"
- `Header` 是 `Path`, `Query` 和 `Cookie` 的兄弟类型。它也继承自通用的 `Param` 类.
+///
- 但是请记得,当你从`fastapi`导入 `Query`, `Path`, `Header`, 或其他时,实际上导入的是返回特定类型的函数。
+```Python hl_lines="7"
+{!> ../../../docs_src/header_params/tutorial001_py310.py!}
+```
-!!! info
- 为了声明headers, 你需要使用`Header`, 因为否则参数将被解释为查询参数。
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="9"
+{!> ../../../docs_src/header_params/tutorial001.py!}
+```
+
+////
+
+/// note | "技术细节"
+
+`Header` 是 `Path`、`Query`、`Cookie` 的**兄弟类**,都继承自共用的 `Param` 类。
+
+注意,从 `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+"
+//// 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!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="11"
- {!> ../../../docs_src/header_params/tutorial002_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="11"
+{!> ../../../docs_src/header_params/tutorial002_an_py39.py!}
+```
- ```Python hl_lines="12"
- {!> ../../../docs_src/header_params/tutorial002_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+```Python hl_lines="12"
+{!> ../../../docs_src/header_params/tutorial002_an.py!}
+```
- ```Python hl_lines="8"
- {!> ../../../docs_src/header_params/tutorial002_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+/// tip
- ```Python hl_lines="10"
- {!> ../../../docs_src/header_params/tutorial002.py!}
- ```
+尽可能选择使用 `Annotated` 的版本。
-!!! warning
- 在设置 `convert_underscores` 为 `False` 之前,请记住,一些HTTP代理和服务器不允许使用带有下划线的headers。
+///
+```Python hl_lines="8"
+{!> ../../../docs_src/header_params/tutorial002_py310.py!}
+```
-## 重复的 headers
+////
-有可能收到重复的headers。这意味着,相同的header具有多个值。
+//// tab | Python 3.8+ non-Annotated
-您可以在类型声明中使用一个list来定义这些情况。
+/// tip
-你可以通过一个Python `list` 的形式获得重复header的所有值。
+尽可能选择使用 `Annotated` 的版本。
-比如, 为了声明一个 `X-Token` header 可以出现多次,你可以这样写:
+///
-=== "Python 3.10+"
+```Python hl_lines="10"
+{!> ../../../docs_src/header_params/tutorial002.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial003_an_py310.py!}
- ```
+////
-=== "Python 3.9+"
+/// warning | "警告"
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial003_an_py39.py!}
- ```
+注意,使用 `convert_underscores = False` 要慎重,有些 HTTP 代理和服务器不支持使用带有下划线的请求头。
-=== "Python 3.8+"
+///
- ```Python hl_lines="10"
- {!> ../../../docs_src/header_params/tutorial003_an.py!}
- ```
+## 重复的请求头
-=== "Python 3.10+ non-Annotated"
+有时,可能需要接收重复的请求头。即同一个请求头有多个值。
- !!! tip
- Prefer to use the `Annotated` version if possible.
+类型声明中可以使用 `list` 定义多个请求头。
- ```Python hl_lines="7"
- {!> ../../../docs_src/header_params/tutorial003_py310.py!}
- ```
+使用 Python `list` 可以接收重复请求头所有的值。
-=== "Python 3.9+ non-Annotated"
+例如,声明 `X-Token` 多次出现的请求头,可以写成这样:
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+//// tab | Python 3.10+
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial003_py39.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/header_params/tutorial003_an_py310.py!}
+```
-=== "Python 3.8+ non-Annotated"
+////
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+//// tab | Python 3.9+
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial003.py!}
- ```
+```Python hl_lines="9"
+{!> ../../../docs_src/header_params/tutorial003_an_py39.py!}
+```
-如果你与*路径操作*通信时发送两个HTTP headers,就像:
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="10"
+{!> ../../../docs_src/header_params/tutorial003_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="7"
+{!> ../../../docs_src/header_params/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+ non-Annotated
+
+/// tip
+
+尽可能选择使用 `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!}
+```
+
+////
+
+与*路径操作*通信时,以下面的方式发送两个 HTTP 请求头:
```
X-Token: foo
X-Token: bar
```
-响应会是:
+响应结果是:
```JSON
{
@@ -221,8 +298,8 @@ X-Token: bar
}
```
-## 回顾
+## 小结
-使用 `Header` 来声明 header , 使用和 `Query`, `Path` 与 `Cookie` 相同的模式。
+使用 `Header` 声明请求头的方式与 `Query`、`Path` 、`Cookie` 相同。
-不用担心变量中的下划线,**FastAPI** 会负责转换它们。
+不用担心变量中的下划线,**FastAPI** 可以自动转换。
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
+```
- ```
- pip install "uvicorn[standard]"
- ```
+并且安装`uvicorn`来作为服务器:
- 然后对你想使用的每个可选依赖项也执行相同的操作。
+```
+pip install "uvicorn[standard]"
+```
+
+然后对你想使用的每个可选依赖项也执行相同的操作。
+
+///
## 进阶用户指南
diff --git a/docs/zh/docs/tutorial/metadata.md b/docs/zh/docs/tutorial/metadata.md
index 09b106273..3316e2ce4 100644
--- a/docs/zh/docs/tutorial/metadata.md
+++ b/docs/zh/docs/tutorial/metadata.md
@@ -1,100 +1,110 @@
-# 元数据和文档 URL
-你可以在 FastAPI 应用程序中自定义多个元数据配置。
-
-## API 元数据
-
-你可以在设置 OpenAPI 规范和自动 API 文档 UI 中使用的以下字段:
-
-| 参数 | 类型 | 描述 |
-|------------|------|-------------|
-| `title` | `str` | API 的标题。 |
-| `summary` | `str` | API 的简短摘要。 自 OpenAPI 3.1.0、FastAPI 0.99.0 起可用。. |
-| `description` | `str` | API 的简短描述。可以使用Markdown。 |
-| `version` | `string` | API 的版本。这是您自己的应用程序的版本,而不是 OpenAPI 的版本。例如 `2.5.0` 。 |
-| `terms_of_service` | `str` | API 服务条款的 URL。如果提供,则必须是 URL。 |
-| `contact` | `dict` | 公开的 API 的联系信息。它可以包含多个字段。contact 字段| 参数 | Type | 描述 |
|---|---|---|
name | str | 联系人/组织的识别名称。 |
url | str | 指向联系信息的 URL。必须采用 URL 格式。 |
email | str | 联系人/组织的电子邮件地址。必须采用电子邮件地址的格式。 |
license_info 字段| 参数 | 类型 | 描述 |
|---|---|---|
name | str | 必须的 (如果设置了license_info). 用于 API 的许可证名称。 |
identifier | str | 一个API的SPDX许可证表达。 The identifier field is mutually exclusive of the url field. 自 OpenAPI 3.1.0、FastAPI 0.99.0 起可用。 |
url | str | 用于 API 的许可证的 URL。必须采用 URL 格式。 |
-
-## 标签元数据
-
-### 创建标签元数据
-
-让我们在带有标签的示例中为 `users` 和 `items` 试一下。
-
-创建标签元数据并把它传递给 `openapi_tags` 参数:
-
-```Python hl_lines="3-16 18"
-{!../../../docs_src/metadata/tutorial004.py!}
-```
-
-注意你可以在描述内使用 Markdown,例如「login」会显示为粗体(**login**)以及「fancy」会显示为斜体(_fancy_)。
-
-!!! 提示
- 不必为你使用的所有标签都添加元数据。
-
-### 使用你的标签
-
-将 `tags` 参数和*路径操作*(以及 `APIRouter`)一起使用,将其分配给不同的标签:
-
-```Python hl_lines="21 26"
-{!../../../docs_src/metadata/tutorial004.py!}
-```
-
-!!! 信息
- 阅读更多关于标签的信息[路径操作配置](../path-operation-configuration/#tags){.internal-link target=_blank}。
-
-### 查看文档
-
-如果你现在查看文档,它们会显示所有附加的元数据:
-
-
-
-### 标签顺序
-
-每个标签元数据字典的顺序也定义了在文档用户界面显示的顺序。
-
-例如按照字母顺序,即使 `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 的简短摘要。 自 OpenAPI 3.1.0、FastAPI 0.99.0 起可用。. |
+| `description` | `str` | API 的简短描述。可以使用Markdown。 |
+| `version` | `string` | API 的版本。这是您自己的应用程序的版本,而不是 OpenAPI 的版本。例如 `2.5.0` 。 |
+| `terms_of_service` | `str` | API 服务条款的 URL。如果提供,则必须是 URL。 |
+| `contact` | `dict` | 公开的 API 的联系信息。它可以包含多个字段。contact 字段| 参数 | Type | 描述 |
|---|---|---|
name | str | 联系人/组织的识别名称。 |
url | str | 指向联系信息的 URL。必须采用 URL 格式。 |
email | str | 联系人/组织的电子邮件地址。必须采用电子邮件地址的格式。 |
license_info 字段| 参数 | 类型 | 描述 |
|---|---|---|
name | str | 必须的 (如果设置了license_info). 用于 API 的许可证名称。 |
identifier | str | 一个API的SPDX许可证表达。 The identifier field is mutually exclusive of the url field. 自 OpenAPI 3.1.0、FastAPI 0.99.0 起可用。 |
url | str | 用于 API 的许可证的 URL。必须采用 URL 格式。 |
+
+## 标签元数据
+
+### 创建标签元数据
+
+让我们在带有标签的示例中为 `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}。
+
+///
+
+### 查看文档
+
+如果你现在查看文档,它们会显示所有附加的元数据:
+
+
+
+### 标签顺序
+
+每个标签元数据字典的顺序也定义了在文档用户界面显示的顺序。
+
+例如按照字母顺序,即使 `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
- 请记住可以 用'X-' 前缀添加专有自定义请求头.
+/// tip
- 但是如果你想让浏览器中的客户端看到你的自定义请求头, 你需要把它们加到 CORS 配置 ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) 的 `expose_headers` 参数中,在 Starlette's CORS docs文档中.
+请记住可以 用'X-' 前缀添加专有自定义请求头.
-!!! note "技术细节"
- 你也可以使用 `from starlette.requests import Request`.
+但是如果你想让浏览器中的客户端看到你的自定义请求头, 你需要把它们加到 CORS 配置 ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) 的 `expose_headers` 参数中,在 Starlette's CORS docs文档中.
- **FastAPI** 为了开发者方便提供了该对象. 但其实它直接来自于 Starlette.
+///
+
+/// note | "技术细节"
+
+你也可以使用 `from starlette.requests import Request`.
+
+**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 "检查"
+///
- OpenAPI 规定每个*路径操作*都要有响应描述。
+/// check | "检查"
- 如果没有定义响应描述,**FastAPI** 则自动生成内容为 "Successful response" 的响应描述。
+OpenAPI 规定每个*路径操作*都要有响应描述。
+
+如果没有定义响应描述,**FastAPI** 则自动生成内容为 "Successful response" 的响应描述。
+
+///
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!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="1 3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="1 3"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="3-4"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+```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!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+/// tip
- ```Python hl_lines="3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
- ```
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="1"
+{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```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+"
+////
- ```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
- 尽可能选择使用 `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+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+/// tip
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
- ```
+尽可能选择使用 `Annotated` 的版本。
-!!! 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
- ```Python hl_lines="7"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!}
- ```
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```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` 和其他同类对象时,它们实际上是函数。
+而且它们都共享相同的所有你已看到并用于添加额外校验和元数据的参数。
- 当被调用时,它们返回同名类的实例。
+///
- 如此,你导入 `Query` 这个函数。当你调用它时,它将返回一个同样命名为 `Query` 的类的实例。
+/// note | "技术细节"
- 因为使用了这些函数(而不是直接使用类),所以你的编辑器不会标记有关其类型的错误。
+当你从 `fastapi` 导入 `Query`、`Path` 和其他同类对象时,它们实际上是函数。
- 这样,你可以使用常规的编辑器和编码工具,而不必添加自定义配置来忽略这些错误。
+当被调用时,它们返回同名类的实例。
+
+如此,你导入 `Query` 这个函数。当你调用它时,它将返回一个同样命名为 `Query` 的类的实例。
+
+因为使用了这些函数(而不是直接使用类),所以你的编辑器不会标记有关其类型的错误。
+
+这样,你可以使用常规的编辑器和编码工具,而不必添加自定义配置来忽略这些错误。
+
+///
diff --git a/docs/zh/docs/tutorial/path-params.md b/docs/zh/docs/tutorial/path-params.md
index 5bb4eba80..091dcbeb0 100644
--- a/docs/zh/docs/tutorial/path-params.md
+++ b/docs/zh/docs/tutorial/path-params.md
@@ -1,48 +1,54 @@
# 路径参数
-你可以使用与 Python 格式化字符串相同的语法来声明路径"参数"或"变量":
+FastAPI 支持使用 Python 字符串格式化语法声明**路径参数**(**变量**):
```Python hl_lines="6-7"
{!../../../docs_src/path_params/tutorial001.py!}
```
-路径参数 `item_id` 的值将作为参数 `item_id` 传递给你的函数。
+这段代码把路径参数 `item_id` 的值传递给路径函数的参数 `item_id`。
-所以,如果你运行示例并访问 http://127.0.0.1:8000/items/foo,将会看到如下响应:
+运行示例并访问 http://127.0.0.1:8000/items/foo,可获得如下响应:
```JSON
{"item_id":"foo"}
```
-## 有类型的路径参数
+## 声明路径参数的类型
-你可以使用标准的 Python 类型标注为函数中的路径参数声明类型。
+使用 Python 标准类型注解,声明路径操作函数中路径参数的类型。
```Python hl_lines="7"
{!../../../docs_src/path_params/tutorial002.py!}
```
-在这个例子中,`item_id` 被声明为 `int` 类型。
+本例把 `item_id` 的类型声明为 `int`。
-!!! check
- 这将为你的函数提供编辑器支持,包括错误检查、代码补全等等。
+/// check | "检查"
-## 数据转换
+类型声明将为函数提供错误检查、代码补全等编辑器支持。
-如果你运行示例并打开浏览器访问 http://127.0.0.1:8000/items/3,将得到如下响应:
+///
+
+## 数据转换
+
+运行示例并访问 http://127.0.0.1:8000/items/3,返回的响应如下:
```JSON
{"item_id":3}
```
-!!! check
- 注意函数接收(并返回)的值为 3,是一个 Python `int` 值,而不是字符串 `"3"`。
+/// check | "检查"
- 所以,**FastAPI** 通过上面的类型声明提供了对请求的自动"解析"。
+注意,函数接收并返回的值是 `3`( `int`),不是 `"3"`(`str`)。
+
+**FastAPI** 通过类型声明自动**解析**请求中的数据。
+
+///
## 数据校验
-但如果你通过浏览器访问 http://127.0.0.1:8000/items/foo,你会看到一个清晰可读的 HTTP 错误:
+通过浏览器访问 http://127.0.0.1:8000/items/foo,接收如下 HTTP 错误信息:
```JSON
{
@@ -59,86 +65,99 @@
}
```
-因为路径参数 `item_id` 传入的值为 `"foo"`,它不是一个 `int`。
+这是因为路径参数 `item_id` 的值 (`"foo"`)的类型不是 `int`。
-如果你提供的是 `float` 而非整数也会出现同样的错误,比如: http://127.0.0.1:8000/items/4.2
+值的类型不是 `int ` 而是浮点数(`float`)时也会显示同样的错误,比如: http://127.0.0.1:8000/items/4.2。
-!!! check
- 所以,通过同样的 Python 类型声明,**FastAPI** 提供了数据校验功能。
+/// check | "检查"
- 注意上面的错误同样清楚地指出了校验未通过的具体原因。
+**FastAPI** 使用 Python 类型声明实现了数据校验。
- 在开发和调试与你的 API 进行交互的代码时,这非常有用。
+注意,上面的错误清晰地指出了未通过校验的具体原因。
-## 文档
+这在开发调试与 API 交互的代码时非常有用。
-当你打开浏览器访问 http://127.0.0.1:8000/docs,你将看到自动生成的交互式 API 文档:
+///
-
+## 查看文档
-!!! check
- 再一次,还是通过相同的 Python 类型声明,**FastAPI** 为你提供了自动生成的交互式文档(集成 Swagger UI)。
+访问 http://127.0.0.1:8000/docs,查看自动生成的 API 文档:
- 注意这里的路径参数被声明为一个整数。
+
-## 基于标准的好处:可选文档
+/// check | "检查"
-由于生成的 API 模式来自于 OpenAPI 标准,所以有很多工具与其兼容。
+还是使用 Python 类型声明,**FastAPI** 提供了(集成 Swagger UI 的)API 文档。
-正因如此,**FastAPI** 内置了一个可选的 API 文档(使用 Redoc):
+注意,路径参数的类型是整数。
-
+///
-同样的,还有很多其他兼容的工具,包括适用于多种语言的代码生成工具。
+## 基于标准的好处,备选文档
+
+**FastAPI** 使用 OpenAPI 生成概图,所以能兼容很多工具。
+
+因此,**FastAPI** 还内置了 ReDoc 生成的备选 API 文档,可在此查看 http://127.0.0.1:8000/redoc:
+
+
+
+同样,还有很多兼容工具,包括多种语言的代码生成工具。
## Pydantic
-所有的数据校验都由 Pydantic 在幕后完成,所以你可以从它所有的优点中受益。并且你知道它在这方面非常胜任。
+FastAPI 充分地利用了 Pydantic 的优势,用它在后台校验数据。众所周知,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 `Enum` 类型。
+路径操作使用 Python 的 `Enum` 类型接收预设的*路径参数*。
-### 创建一个 `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
- 枚举(或 enums)从 3.4 版本起在 Python 中可用。
+/// info | "说明"
-!!! tip
- 如果你想知道,"AlexNet"、"ResNet" 和 "LeNet" 只是机器学习中的模型名称。
+Python 3.4 及之后版本支持枚举(即 enums)。
+
+///
+
+/// tip | "提示"
+
+**AlexNet**、**ResNet**、**LeNet** 是机器学习模型。
+
+///
### 声明*路径参数*
-然后使用你定义的枚举类(`ModelName`)创建一个带有类型标注的*路径参数*:
+使用 Enum 类(`ModelName`)创建使用类型注解的*路径参数*:
```Python hl_lines="16"
{!../../../docs_src/path_params/tutorial005.py!}
@@ -146,17 +165,17 @@
### 查看文档
-因为已经指定了*路径参数*的可用值,所以交互式文档可以恰当地展示它们:
+ API 文档会显示预定义*路径参数*的可用值:
-
+
-### 使用 Python *枚举类型*
+### 使用 Python _枚举类型_
-*路径参数*的值将是一个*枚举成员*。
+*路径参数*的值是枚举的元素。
-#### 比较*枚举成员*
+#### 比较*枚举元素*
-你可以将它与你创建的枚举类 `ModelName` 中的*枚举成员*进行比较:
+枚举类 `ModelName` 中的*枚举元素*支持比较操作:
```Python hl_lines="17"
{!../../../docs_src/path_params/tutorial005.py!}
@@ -164,71 +183,86 @@
#### 获取*枚举值*
-你可以使用 `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` 中)。
+///
-在返回给客户端之前,它们将被转换为对应的值:
+#### 返回*枚举元素*
-```Python hl_lines="18-21"
+即使嵌套在 JSON 请求体里(例如, `dict`),也可以从*路径操作*返回*枚举元素*。
+
+返回给客户端之前,要把枚举元素转换为对应的值(本例中为字符串):
+
+```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 | "提示"
- 在这种情况下,URL 将会是 `/files//home/johndoe/myfile.txt`,在`files` 和 `home` 之间有一个双斜杠(`//`)。
+注意,包含 `/home/johndoe/myfile.txt` 的路径参数要以斜杠(`/`)开头。
-## 总结
+本例中的 URL 是 `/files//home/johndoe/myfile.txt`。注意,`files` 和 `home` 之间要使用**双斜杠**(`//`)。
-使用 **FastAPI**,通过简短、直观和标准的 Python 类型声明,你将获得:
+///
-* 编辑器支持:错误检查,代码补全等
-* 数据 "解析"
-* 数据校验
-* API 标注和自动生成的文档
+## 小结
-而且你只需要声明一次即可。
+通过简短、直观的 Python 标准类型声明,**FastAPI** 可以获得:
-这可能是 **FastAPI** 与其他框架相比主要的明显优势(除了原始性能以外)。
+- 编辑器支持:错误检查,代码自动补全等
+- 数据**解析**
+- 数据校验
+- API 注解和 API 文档
+
+只需要声明一次即可。
+
+这可能是除了性能以外,**FastAPI** 与其它框架相比的主要优势。
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+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```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
- 如果你之前没见过 `...` 这种用法:它是一个特殊的单独值,它是 Python 的一部分并且被称为「省略号」。
- Pydantic 和 FastAPI 使用它来显式的声明需要一个值。
+/// info
+
+如果你之前没见过 `...` 这种用法:它是一个特殊的单独值,它是 Python 的一部分并且被称为「省略号」。
+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 文档中阅读有关必需可选字段的更多信息。
+/// tip
+
+Pydantic 是 FastAPI 中所有数据验证和序列化的核心,当你在没有设默认值的情况下使用 `Optional` 或 `Union[Something, None]` 时,它具有特殊行为,你可以在 Pydantic 文档中阅读有关必需可选字段的更多信息。
+
+///
### 使用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 a0cc7fea3..6853e3899 100644
--- a/docs/zh/docs/tutorial/query-params.md
+++ b/docs/zh/docs/tutorial/query-params.md
@@ -1,95 +1,122 @@
# 查询参数
-声明不属于路径参数的其他函数参数时,它们将被自动解释为"查询字符串"参数
+声明的参数不是路径参数时,路径操作函数会把该参数自动解释为**查询**参数。
```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`)之后,这些值就会转换为声明的类型,并进行类型校验。
-应用于路径参数的所有相同过程也适用于查询参数:
+所有应用于路径参数的流程也适用于查询参数:
-* (很明显的)编辑器支持
-* 数据"解析"
+* (显而易见的)编辑器支持
+* 数据**解析**
* 数据校验
-* 自动生成文档
+* 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+"
+//// 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
- 还要注意的是,**FastAPI** 足够聪明,能够分辨出参数 `item_id` 是路径参数而 `q` 不是,因此 `q` 是一个查询参数。
+本例中,查询参数 `q` 是可选的,默认值为 `None`。
+
+/// check | "检查"
+
+注意,**FastAPI** 可以识别出 `item_id` 是路径参数,`q` 不是路径参数,而是查询参数。
+
+///
+
+/// note | "笔记"
+
+因为默认值为 `= None`,FastAPI 把 `q` 识别为可选参数。
+
+FastAPI 不使用 `Optional[str]` 中的 `Optional`(只使用 `str`),但 `Optional[str]` 可以帮助编辑器发现代码中的错误。
+
+///
## 查询参数类型转换
-你还可以声明 `bool` 类型,它们将被自动转换:
+参数还可以声明为 `bool` 类型,FastAPI 会自动转换参数类型:
+
+
+//// tab | Python 3.10+
```Python hl_lines="7"
-{!../../../docs_src/query_params/tutorial003.py!}
+{!> ../../../docs_src/query_params/tutorial003_py310.py!}
```
-这个例子中,如果你访问:
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../../docs_src/query_params/tutorial003.py!}
+```
+
+////
+
+本例中,访问:
```
http://127.0.0.1:8000/items/foo?short=1
@@ -119,42 +146,54 @@ 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"
-{!../../../docs_src/query_params/tutorial004.py!}
+//// tab | Python 3.10+
+
+```Python hl_lines="6 8"
+{!> ../../../docs_src/query_params/tutorial004_py310.py!}
```
-## 必需查询参数
+////
-当你为非路径参数声明了默认值时(目前而言,我们所知道的仅有查询参数),则该参数不是必需的。
+//// tab | Python 3.8+
-如果你不想添加一个特定的值,而只是想使该参数成为可选的,则将默认值设置为 `None`。
+```Python hl_lines="8 10"
+{!> ../../../docs_src/query_params/tutorial004.py!}
+```
-但当你想让一个查询参数成为必需的,不声明任何默认值就可以:
+////
+
+## 必选查询参数
+
+为不是路径参数的参数声明默认值(至此,仅有查询参数),该参数就**不是必选**的了。
+
+如果只想把参数设为**可选**,但又不想指定参数的值,则要把默认值设为 `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 +210,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 +225,32 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
}
```
-当然,你也可以定义一些参数为必需的,一些具有默认值,而某些则完全是可选的:
+当然,把一些参数定义为必选,为另一些参数设置默认值,再把其它参数定义为可选,这些操作都是可以的:
-```Python hl_lines="7"
-{!../../../docs_src/query_params/tutorial006.py!}
+//// tab | Python 3.10+
+
+```Python hl_lines="8"
+{!> ../../../docs_src/query_params/tutorial006_py310.py!}
```
-在这个例子中,有3个查询参数:
+////
-* `needy`,一个必需的 `str` 类型参数。
-* `skip`,一个默认值为 `0` 的 `int` 类型参数。
-* `limit`,一个可选的 `int` 类型参数。
+//// tab | Python 3.8+
-!!! tip
- 你还可以像在 [路径参数](path-params.md#predefined-values){.internal-link target=_blank} 中那样使用 `Enum`。
+```Python hl_lines="10"
+{!> ../../../docs_src/query_params/tutorial006.py!}
+```
+
+////
+
+本例中有 3 个查询参数:
+
+* `needy`,必选的 `str` 类型参数
+* `skip`,默认值为 `0` 的 `int` 类型参数
+* `limit`,可选的 `int` 类型参数
+
+/// 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 | "说明"
- 因为上传文件以「表单数据」形式发送。
+因为上传文件以「表单数据」形式发送。
- 所以接收上传文件,要预先安装 `python-multipart`。
+所以接收上传文件,要预先安装 `python-multipart`。
- 例如: `pip install python-multipart`。
+例如: `pip install python-multipart`。
+
+///
## 导入 `File`
@@ -26,15 +28,19 @@
{!../../../docs_src/request_files/tutorial001.py!}
```
-!!! info "说明"
+/// info | "说明"
- `File` 是直接继承自 `Form` 的类。
+`File` 是直接继承自 `Form` 的类。
- 注意,从 `fastapi` 导入的 `Query`、`Path`、`File` 等项,实际上是返回特定类的函数。
+注意,从 `fastapi` 导入的 `Query`、`Path`、`File` 等项,实际上是返回特定类的函数。
-!!! tip "提示"
+///
- 声明文件体必须使用 `File`,否则,FastAPI 会把该参数当作查询参数或请求体(JSON)参数。
+/// tip | "提示"
+
+声明文件体必须使用 `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 技术细节"
+///
- **FastAPI** 的 `UploadFile` 直接继承自 **Starlette** 的 `UploadFile`,但添加了一些必要功能,使之与 **Pydantic** 及 FastAPI 的其它部件兼容。
+/// note | "Starlette 技术细节"
+
+**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** 就知道要从请求体的正确位置获取文件。
- 编码和表单字段详见 MDN Web 文档的 POST 小节。
+编码和表单字段详见 MDN Web 文档的 POST 小节。
-!!! 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!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9 17"
- {!> ../../../docs_src/request_files/tutorial001_02.py!}
- ```
+//// tab | Python 3.8+
+
+```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+"
+////
- ```Python hl_lines="10 15"
- {!> ../../../docs_src/request_files/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+
+```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+"
+////
- ```Python hl_lines="18"
- {!> ../../../docs_src/request_files/tutorial003.py!}
- ```
+//// tab | Python 3.8+
+
+```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 | "说明"
- 接收上传文件或表单数据,要预先安装 `python-multipart`。
+接收上传文件或表单数据,要预先安装 `python-multipart`。
- 例如,`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 | "说明"
- 要使用表单,需预先安装 `python-multipart`。
+要使用表单,需预先安装 `python-multipart`。
- 例如,`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 "提示"
+///
- 声明表单体要显式使用 `Form` ,否则,FastAPI 会把该参数当作查询参数或请求体(JSON)参数。
+/// tip | "提示"
+
+声明表单体要显式使用 `Form` ,否则,FastAPI 会把该参数当作查询参数或请求体(JSON)参数。
+
+///
## 关于 "表单字段"
@@ -44,19 +50,23 @@
**FastAPI** 要确保从正确的位置读取数据,而不是读取 JSON。
-!!! note "技术细节"
+/// note | "技术细节"
- 表单数据的「媒体类型」编码一般为 `application/x-www-form-urlencoded`。
+表单数据的「媒体类型」编码一般为 `application/x-www-form-urlencoded`。
- 但包含文件的表单编码为 `multipart/form-data`。文件处理详见下节。
+但包含文件的表单编码为 `multipart/form-data`。文件处理详见下节。
- 编码和表单字段详见 MDN Web 文档的 POST小节。
+编码和表单字段详见 MDN Web 文档的 POST小节。
-!!! warning "警告"
+///
- 可在一个*路径操作*中声明多个 `Form` 参数,但不能同时声明要接收 JSON 的 `Body` 字段。因为此时请求体的编码是 `application/x-www-form-urlencoded`,不是 `application/json`。
+/// warning | "警告"
- 这不是 **FastAPI** 的问题,而是 HTTP 协议的规定。
+可在一个*路径操作*中声明多个 `Form` 参数,但不能同时声明要接收 JSON 的 `Body` 字段。因为此时请求体的编码是 `application/x-www-form-urlencoded`,不是 `application/json`。
+
+这不是 **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+"
+////
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```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.py!}
- ```
+////
-!!! note
- 注意,`response_model`是「装饰器」方法(`get`,`post` 等)的一个参数。不像之前的所有参数和请求体,它不属于*路径操作函数*。
+//// tab | Python 3.8+
+
+```Python hl_lines="17 22 24-27"
+{!> ../../../docs_src/response_model/tutorial001.py!}
+```
+
+////
+
+/// 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!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+//// tab | Python 3.8+
+
+```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()` 配合 该方法的 `exclude_unset` 参数 来实现此功能。
+/// info
-!!! info
- 你还可以使用:
+FastAPI 通过 Pydantic 模型的 `.dict()` 配合 该方法的 `exclude_unset` 参数 来实现此功能。
- * `response_model_exclude_defaults=True`
- * `response_model_exclude_none=True`
+///
- 参考 Pydantic 文档 中对 `exclude_defaults` 和 `exclude_none` 的描述。
+/// info
+
+你还可以使用:
+
+* `response_model_exclude_defaults=True`
+* `response_model_exclude_none=True`
+
+参考 Pydantic 文档 中对 `exclude_defaults` 和 `exclude_none` 的描述。
+
+///
#### 默认值字段有实际值的数据
@@ -203,10 +236,13 @@ FastAPI 将使用此 `response_model` 来:
因此,它们将包含在 JSON 响应中。
-!!! tip
- 请注意默认值可以是任何值,而不仅是`None`。
+/// tip
- 它们可以是一个列表(`[]`),一个值为 `10.5`的 `float`,等等。
+请注意默认值可以是任何值,而不仅是`None`。
+
+它们可以是一个列表(`[]`),一个值为 `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
- 等同于 `set(["name", "description"])`。
+`{"name", "description"}` 语法创建一个具有这两个值的 `set`。
+
+等同于 `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 357831942..506cd4a43 100644
--- a/docs/zh/docs/tutorial/response-status-code.md
+++ b/docs/zh/docs/tutorial/response-status-code.md
@@ -1,89 +1,107 @@
# 响应状态码
-与指定响应模型的方式相同,你也可以在以下任意的*路径操作*中使用 `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 的 `http.HTTPStatus`。
+///
-它将会:
+`status_code` 参数接收表示 HTTP 状态码的数字。
-* 在响应中返回该状态码。
-* 在 OpenAPI 模式中(以及在用户界面中)将其记录为:
+/// info | "说明"
-
+`status_code` 还能接收 `IntEnum` 类型,比如 Python 的 `http.HTTPStatus`。
-!!! note
- 一些响应状态码(请参阅下一部分)表示响应没有响应体。
+///
- FastAPI 知道这一点,并将生成表明没有响应体的 OpenAPI 文档。
+它可以:
+
+* 在响应中返回状态码
+* 在 OpenAPI 概图(及用户界面)中存档:
+
+
+
+/// note | "笔记"
+
+某些响应状态码表示响应没有响应体(参阅下一章)。
+
+FastAPI 可以进行识别,并生成表明无响应体的 OpenAPI 文档。
+
+///
## 关于 HTTP 状态码
-!!! note
- 如果你已经了解什么是 HTTP 状态码,请跳到下一部分。
+/// note | "笔记"
-在 HTTP 协议中,你将发送 3 位数的数字状态码作为响应的一部分。
+如果已经了解 HTTP 状态码,请跳到下一章。
-这些状态码有一个识别它们的关联名称,但是重要的还是数字。
+///
-简而言之:
+在 HTTP 协议中,发送 3 位数的数字状态码是响应的一部分。
-* `100` 及以上状态码用于「消息」响应。你很少直接使用它们。具有这些状态代码的响应不能带有响应体。
-* **`200`** 及以上状态码用于「成功」响应。这些是你最常使用的。
- * `200` 是默认状态代码,它表示一切「正常」。
- * 另一个例子会是 `201`,「已创建」。它通常在数据库中创建了一条新记录后使用。
- * 一个特殊的例子是 `204`,「无内容」。此响应在没有内容返回给客户端时使用,因此该响应不能包含响应体。
-* **`300`** 及以上状态码用于「重定向」。具有这些状态码的响应可能有或者可能没有响应体,但 `304`「未修改」是个例外,该响应不得含有响应体。
-* **`400`** 及以上状态码用于「客户端错误」响应。这些可能是你第二常使用的类型。
- * 一个例子是 `404`,用于「未找到」响应。
- * 对于来自客户端的一般错误,你可以只使用 `400`。
-* `500` 及以上状态码用于服务器端错误。你几乎永远不会直接使用它们。当你的应用程序代码或服务器中的某些部分出现问题时,它将自动返回这些状态代码之一。
+这些状态码都具有便于识别的关联名称,但是重要的还是数字。
-!!! tip
- 要了解有关每个状态代码以及适用场景的更多信息,请查看 MDN 关于 HTTP 状态码的文档。
+简言之:
-## 记住名称的捷径
+* `100` 及以上的状态码用于返回**信息**。这类状态码很少直接使用。具有这些状态码的响应不能包含响应体
+* **`200`** 及以上的状态码用于表示**成功**。这些状态码是最常用的
+ * `200` 是默认状态代码,表示一切**正常**
+ * `201` 表示**已创建**,通常在数据库中创建新记录后使用
+ * `204` 是一种特殊的例子,表示**无内容**。该响应在没有为客户端返回内容时使用,因此,该响应不能包含响应体
+* **`300`** 及以上的状态码用于**重定向**。具有这些状态码的响应不一定包含响应体,但 `304`**未修改**是个例外,该响应不得包含响应体
+* **`400`** 及以上的状态码用于表示**客户端错误**。这些可能是第二常用的类型
+ * `404`,用于**未找到**响应
+ * 对于来自客户端的一般错误,可以只使用 `400`
+* `500` 及以上的状态码用于表示服务器端错误。几乎永远不会直接使用这些状态码。应用代码或服务器出现问题时,会自动返回这些状态代码
-让我们再次看看之前的例子:
+/// tip | "提示"
+
+状态码及适用场景的详情,请参阅 MDN 的 HTTP 状态码文档。
+
+///
+
+## 状态码名称快捷方式
+
+再看下之前的例子:
```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!}
```
-它们只是一种便捷方式,它们具有同样的数字代码,但是这样使用你就可以使用编辑器的自动补全功能来查找它们:
+这只是一种快捷方式,具有相同的数字代码,但它可以使用编辑器的自动补全功能:
-
+
-!!! note "技术细节"
- 你也可以使用 `from starlette import status`。
+/// note | "技术细节"
- 为了给你(即开发者)提供方便,**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}中,将介绍如何返回与在此声明的默认状态码不同的状态码。
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模型声明一个示例,如Pydantic 文档:定制 Schema 中所述:
-=== "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!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="4 10-13"
- {!> ../../../docs_src/schema_extra_example/tutorial002.py!}
- ```
+//// tab | Python 3.8+
-!!! warning
- 请记住,传递的那些额外参数不会添加任何验证,只会添加注释,用于文档的目的。
+```Python hl_lines="4 10-13"
+{!> ../../../docs_src/schema_extra_example/tutorial002.py!}
+```
+
+////
+
+/// 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!}
- ```
+```Python hl_lines="22-27"
+{!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="22-27"
- {!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="22-27"
+{!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!}
+```
- ```Python hl_lines="23-28"
- {!> ../../../docs_src/schema_extra_example/tutorial003_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+```Python hl_lines="23-28"
+{!> ../../../docs_src/schema_extra_example/tutorial003_an.py!}
+```
- ```Python hl_lines="18-23"
- {!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+/// tip
- ```Python hl_lines="20-25"
- {!> ../../../docs_src/schema_extra_example/tutorial003.py!}
- ```
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="18-23"
+{!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="20-25"
+{!> ../../../docs_src/schema_extra_example/tutorial003.py!}
+```
+
+////
## 文档 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!}
+```
-=== "Python 3.8+"
+////
- ```Python
- {!> ../../../docs_src/security/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python
+{!> ../../../docs_src/security/tutorial001_an.py!}
+```
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+////
- ```Python
- {!> ../../../docs_src/security/tutorial001.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python
+{!> ../../../docs_src/security/tutorial001.py!}
+```
+
+////
## 运行
-!!! info "说明"
+/// info | "说明"
- 先安装 `python-multipart`。
+先安装 `python-multipart`。
- 安装命令: `pip install python-multipart`。
+安装命令: `pip install python-multipart`。
- 这是因为 **OAuth2** 使用**表单数据**发送 `username` 与 `password`。
+这是因为 **OAuth2** 使用**表单数据**发送 `username` 与 `password`。
+
+///
用下面的命令运行该示例:
@@ -71,19 +82,23 @@ $ uvicorn main:app --reload
-!!! check "Authorize 按钮!"
+/// check | "Authorize 按钮!"
- 页面右上角出现了一个「**Authorize**」按钮。
+页面右上角出现了一个「**Authorize**」按钮。
- *路径操作*的右上角也出现了一个可以点击的小锁图标。
+*路径操作*的右上角也出现了一个可以点击的小锁图标。
+
+///
点击 **Authorize** 按钮,弹出授权表单,输入 `username` 与 `password` 及其它可选字段:
-!!! 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 477baec3a..f8094e86a 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,75 @@
## 注入当前用户
-因此现在我们可以在*路径操作*中使用 `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` 模型)。
+
+而且,不局限于只能使用特定的数据模型、类或类型。
+
+不想在模型中使用 `username`,而是使用 `id` 和 `email`?当然可以。这些工具也支持。
+
+只想使用字符串?或字典?甚至是数据库类模型的实例?工作方式都一样。
+
+实际上,就算登录应用的不是用户,而是只拥有访问令牌的机器人、程序或其它系统?工作方式也一样。
+
+尽管使用应用所需的任何模型、类、数据库。**FastAPI** 通过依赖注入系统都能帮您搞定。
-## 其他模型
+## 代码大小
-现在你可以直接在*路径操作函数*中获取当前用户,并使用 `Depends` 在**依赖注入**级别处理安全性机制。
+这个示例看起来有些冗长。毕竟这个文件同时包含了安全、数据模型的工具函数,以及路径操作等代码。
-你可以使用任何模型或数据来满足安全性要求(在这个示例中,使用的是 Pydantic 模型 `User`)。
+但,关键是:
-但是你并未被限制只能使用某些特定的数据模型,类或类型。
+**安全和依赖注入的代码只需要写一次。**
-你想要在模型中使用 `id` 和 `email` 而不使用任何的 `username`?当然可以。你可以同样地使用这些工具。
+就算写得再复杂,也只是在一个位置写一次就够了。所以,要多复杂就可以写多复杂。
-你只想要一个 `str`?或者仅仅一个 `dict`?还是直接一个数据库模型类的实例?它们的工作方式都是一样的。
+但是,就算有数千个端点(*路径操作*),它们都可以使用同一个安全系统。
-实际上你没有用户登录到你的应用程序,而是只拥有访问令牌的机器人,程序或其他系统?再一次,它们的工作方式也是一样的。
+而且,所有端点(或它们的任何部件)都可以利用这些依赖项或任何其它依赖项。
-尽管去使用你的应用程序所需要的任何模型,任何类,任何数据库。**FastAPI** 通过依赖项注入系统都帮你搞定。
-
-
-## 代码体积
-
-这个示例似乎看起来很冗长。考虑到我们在同一文件中混合了安全性,数据模型工具函数和路径操作等代码。
-
-但关键的是。
-
-安全性和依赖项注入内容只需要编写一次。
-
-你可以根据需要使其变得很复杂。而且只需要在一个地方写一次。但仍然具备所有的灵活性。
-
-但是,你可以有无数个使用同一安全系统的端点(*路径操作*)。
-
-所有(或所需的任何部分)的端点,都可以利用对这些或你创建的其他依赖项进行复用所带来的优势。
-
-所有的这无数个*路径操作*甚至可以小到只需 3 行代码:
+所有*路径操作*只需 3 行代码就可以了:
```Python hl_lines="30-32"
{!../../../docs_src/security/tutorial002.py!}
```
-## 总结
+## 小结
-现在你可以直接在*路径操作函数*中获取当前用户。
+现在,我们可以直接在*路径操作函数*中获取当前用户。
-我们已经进行到一半了。
+至此,安全的内容已经讲了一半。
-我们只需要再为用户/客户端添加一个真正发送 `username` 和 `password` 的*路径操作*。
+只要再为用户或客户端的*路径操作*添加真正发送 `username` 和 `password` 的功能就可以了。
-这些内容在下一章节。
+下一章见。
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
- 最复杂的问题是创建一个像这样的身份认证/授权提供程序,但是 **FastAPI** 为你提供了轻松完成任务的工具,同时为你解决了重活。
+集成其他身份认证/授权提供者(例如Google,Facebook,Twitter,GitHub等)也是可能的,而且较为容易。
+
+最复杂的问题是创建一个像这样的身份认证/授权提供程序,但是 **FastAPI** 为你提供了轻松完成任务的工具,同时为你解决了重活。
+
+///
## **FastAPI** 实用工具
diff --git a/docs/zh/docs/tutorial/security/oauth2-jwt.md b/docs/zh/docs/tutorial/security/oauth2-jwt.md
index 33a4d7fc7..690bd1789 100644
--- a/docs/zh/docs/tutorial/security/oauth2-jwt.md
+++ b/docs/zh/docs/tutorial/security/oauth2-jwt.md
@@ -26,29 +26,27 @@ JWT 字符串没有加密,任何人都能用它恢复原始信息。
如需深入了解 JWT 令牌,了解它的工作方式,请参阅 https://jwt.io。
-## 安装 `python-jose`
+## 安装 `PyJWT`
-安装 `python-jose`,在 Python 中生成和校验 JWT 令牌:
+安装 `PyJWT`,在 Python 中生成和校验 JWT 令牌:
@@ -233,9 +383,11 @@ JWT 规范还包括 `sub` 键,值是令牌的主题。
-!!! note "笔记"
+/// note | "笔记"
- 注意,请求中 `Authorization` 响应头的值以 `Bearer` 开头。
+注意,请求中 `Authorization` 响应头的值以 `Bearer` 开头。
+
+///
## `scopes` 高级用法
@@ -261,7 +413,7 @@ OAuth2 支持**`scopes`**(作用域)。
开发者可以灵活选择最适合项目的安全机制。
-还可以直接使用 `passlib` 和 `python-jose` 等维护良好、使用广泛的包,这是因为 **FastAPI** 不需要任何复杂机制,就能集成外部的包。
+还可以直接使用 `passlib` 和 `PyJWT` 等维护良好、使用广泛的包,这是因为 **FastAPI** 不需要任何复杂机制,就能集成外部的包。
而且,**FastAPI** 还提供了一些工具,在不影响灵活、稳定和安全的前提下,尽可能地简化安全机制。
diff --git a/docs/zh/docs/tutorial/security/simple-oauth2.md b/docs/zh/docs/tutorial/security/simple-oauth2.md
index c7f46177f..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#about-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 | "提示"
- 下一章介绍使用哈希密码和 JWT Token 的真正安全机制。
+下一章介绍使用哈希密码和 JWT 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 be0c76593..45ec71f7c 100644
--- a/docs/zh/docs/tutorial/sql-databases.md
+++ b/docs/zh/docs/tutorial/sql-databases.md
@@ -1,12 +1,22 @@
# SQL (关系型) 数据库
+/// info
+
+这些文档即将被更新。🎉
+
+当前版本假设Pydantic v1和SQLAlchemy版本小于2。
+
+新的文档将包括Pydantic v2以及 SQLModel(也是基于SQLAlchemy),一旦SQLModel更新为为使用Pydantic v2。
+
+///
+
**FastAPI**不需要你使用SQL(关系型)数据库。
但是您可以使用任何您想要的关系型数据库。
在这里,让我们看一个使用着[SQLAlchemy](https://www.sqlalchemy.org/)的示例。
-您可以很容易地将SQLAlchemy支持任何数据库,像:
+您可以很容易地将其调整为任何SQLAlchemy支持的数据库,如:
* PostgreSQL
* MySQL
@@ -18,11 +28,17 @@
稍后,对于您的产品级别的应用程序,您可能会要使用像**PostgreSQL**这样的数据库服务器。
-!!! tip
- 这儿有一个**FastAPI**和**PostgreSQL**的官方项目生成器,全部基于**Docker**,包括前端和更多工具:https://github.com/tiangolo/full-stack-fastapi-postgresql
+/// tip
-!!! note
- 请注意,大部分代码是`SQLAlchemy`的标准代码,您可以用于任何框架。FastAPI特定的代码和往常一样少。
+这儿有一个**FastAPI**和**PostgreSQL**的官方项目生成器,全部基于**Docker**,包括前端和更多工具:https://github.com/tiangolo/full-stack-fastapi-postgresql
+
+///
+
+/// note
+
+请注意,大部分代码是`SQLAlchemy`的标准代码,您可以用于任何框架。FastAPI特定的代码和往常一样少。
+
+///
## ORMs(对象关系映射)
@@ -56,8 +72,11 @@ ORM 具有在代码和数据库表(“*关系型”)中的**对象**之间
以类似的方式,您也可以使用任何其他 ORM。
-!!! tip
- 在文档中也有一篇使用 Peewee 的等效的文章。
+/// tip
+
+在文档中也有一篇使用 Peewee 的等效的文章。
+
+///
## 文件结构
@@ -74,13 +93,13 @@ ORM 具有在代码和数据库表(“*关系型”)中的**对象**之间
└── schemas.py
```
-该文件`__init__.py`只是一个空文件,但它告诉 Python 其中`sql_app`的所有模块(Python 文件)都是一个包。
+该文件`__init__.py`只是一个空文件,但它告诉 Python `sql_app` 是一个包。
现在让我们看看每个文件/模块的作用。
## 安装 SQLAlchemy
-先下载`SQLAlchemy`所需要的依赖:
+首先你需要安装`SQLAlchemy`: