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
-
+
@@ -46,23 +46,22 @@ The key features are:
-
+
-
-
-
-
-
-
-
-
+
+
+
+
+
-
+
-
+
+
+
@@ -96,7 +95,7 @@ The key features are:
"_Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted **Hug** to be - it's really inspiring to see someone build that._"
-
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:
@@ -465,33 +472,26 @@ Used by Starlette:
Used by FastAPI / Starlette:
-* uvicorn
- for the server that loads and serves your application.
+* 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.
-When you install `fastapi` it comes these standard dependencies.
+### Without `standard` Dependencies
-Additional optional 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]"`.
-* orjson
- Required if you want to use `ORJSONResponse`.
-* ujson
- Required if you want to use `UJSONResponse`.
+### Additional Optional Dependencies
-## `fastapi-slim`
+There are some additional dependencies you might want to install.
-If you don't want the extra standard optional dependencies, install `fastapi-slim` instead.
+Additional optional Pydantic dependencies:
-When you install with:
-
-```bash
-pip install fastapi
-```
-
-...it includes the same code and dependencies as:
+* pydantic-settings
- for settings management.
+* pydantic-extra-types
- for extra types to be used with Pydantic.
-```bash
-pip install "fastapi-slim[standard]"
-```
+Additional optional FastAPI dependencies:
-The standard extra dependencies are the ones mentioned above.
+* 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 9bb7ad6ea..000000000
--- a/docs/az/docs/fastapi-people.md
+++ /dev/null
@@ -1,185 +0,0 @@
----
-hide:
- - navigation
----
-
-# FastAPI İnsanlar
-
-FastAPI-ın bütün mənşəli insanları qəbul edən heyrətamiz icması var.
-
-
-
-## Yaradıcı - İcraçı
-
-Salam! 👋
-
-Bu mənəm:
-
-{% if people %}
-
-
+
@@ -87,7 +87,7 @@ FastAPI Python ilə API yaratmaq üçün standart Python Timothy Crosley - Hug creator (ref)
+
---
@@ -442,7 +442,7 @@ Müstəqil TechEmpower meyarları göstərir ki, Uvicorn üzərində işləyən
Pydantic tərəfindən istifadə olunanlar:
-*
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/environment-variables.md b/docs/bn/docs/environment-variables.md
new file mode 100644
index 000000000..9122ca5bf
--- /dev/null
+++ b/docs/bn/docs/environment-variables.md
@@ -0,0 +1,298 @@
+# এনভায়রনমেন্ট ভেরিয়েবলস
+
+/// tip
+
+আপনি যদি "এনভায়রনমেন্ট ভেরিয়েবলস" কী এবং সেগুলো কীভাবে ব্যবহার করতে হয় সেটা জানেন, তাহলে এই অংশটি স্কিপ করে যেতে পারেন।
+
+///
+
+এনভায়রনমেন্ট ভেরিয়েবল (সংক্ষেপে "**env var**" নামেও পরিচিত) হলো এমন একটি ভেরিয়েবল যা পাইথন কোডের **বাইরে**, **অপারেটিং সিস্টেমে** থাকে এবং আপনার পাইথন কোড (বা অন্যান্য প্রোগ্রাম) দ্বারা যাকে রিড করা যায়।
+
+এনভায়রনমেন্ট ভেরিয়েবলস অ্যাপ্লিকেশনের **সেটিংস** পরিচালনা করতে, পাইথনের **ইনস্টলেশন** প্রক্রিয়ার অংশ হিসেবে, ইত্যাদি কাজে উপযোগী হতে পারে।
+
+## Env Vars তৈরী এবং ব্যবহার
+
+আপনি **শেল (টার্মিনাল)**-এ, পাইথনের প্রয়োজন ছাড়াই, এনভায়রনমেন্ট ভেরিয়েবলস **তৈরি** এবং ব্যবহার করতে পারবেনঃ
+
+//// tab | লিনাক্স, ম্যাকওএস, উইন্ডোজ Bash
+
+
email_validator
- ইমেল যাচাইকরণের জন্য।
+- email-validator
- ইমেল যাচাইকরণের জন্য।
স্টারলেট দ্বারা ব্যবহৃত:
diff --git a/docs/bn/docs/python-types.md b/docs/bn/docs/python-types.md
index 6923363dd..d98c2ec87 100644
--- a/docs/bn/docs/python-types.md
+++ b/docs/bn/docs/python-types.md
@@ -12,16 +12,18 @@ Python-এ ঐচ্ছিক "টাইপ হিন্ট" (যা "টাই
তবে, আপনি যদি কখনো **FastAPI** ব্যবহার নাও করেন, তবুও এগুলি সম্পর্কে একটু শেখা আপনার উপকারে আসবে।
-!!! Note
- যদি আপনি একজন Python বিশেষজ্ঞ হন, এবং টাইপ হিন্ট সম্পর্কে সবকিছু জানেন, তাহলে পরবর্তী অধ্যায়ে চলে যান।
+/// note
+
+যদি আপনি একজন Python বিশেষজ্ঞ হন, এবং টাইপ হিন্ট সম্পর্কে সবকিছু জানেন, তাহলে পরবর্তী অধ্যায়ে চলে যান।
+
+///
## প্রেরণা
চলুন একটি সাধারণ উদাহরণ দিয়ে শুরু করি:
-```Python
-{!../../../docs_src/python_types/tutorial001.py!}
-```
+{* ../../docs_src/python_types/tutorial001.py *}
+
এই প্রোগ্রামটি কল করলে আউটপুট হয়:
@@ -35,9 +37,8 @@ John Doe
* প্রতিটির প্রথম অক্ষরকে `title()` ব্যবহার করে বড় হাতের অক্ষরে রূপান্তর করে।
* তাদেরকে মাঝখানে একটি স্পেস দিয়ে concatenate করে।
-```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial001.py!}
-```
+{* ../../docs_src/python_types/tutorial001.py hl[2] *}
+
### এটি সম্পাদনা করুন
@@ -79,9 +80,8 @@ John Doe
এগুলিই "টাইপ হিন্ট":
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial002.py!}
-```
+{* ../../docs_src/python_types/tutorial002.py hl[1] *}
+
এটি ডিফল্ট ভ্যালু ঘোষণা করার মত নয় যেমন:
@@ -109,9 +109,8 @@ John Doe
এই ফাংশনটি দেখুন, এটিতে ইতিমধ্যে টাইপ হিন্ট রয়েছে:
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial003.py!}
-```
+{* ../../docs_src/python_types/tutorial003.py hl[1] *}
+
এডিটর ভেরিয়েবলগুলির টাইপ জানার কারণে, আপনি শুধুমাত্র অটোকমপ্লিশনই পান না, আপনি এরর চেকও পান:
@@ -119,9 +118,8 @@ John Doe
এখন আপনি জানেন যে আপনাকে এটি ঠিক করতে হবে, `age`-কে একটি স্ট্রিং হিসেবে রূপান্তর করতে `str(age)` ব্যবহার করতে হবে:
-```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial004.py!}
-```
+{* ../../docs_src/python_types/tutorial004.py hl[2] *}
+
## টাইপ ঘোষণা
@@ -140,9 +138,8 @@ John Doe
* `bool`
* `bytes`
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial005.py!}
-```
+{* ../../docs_src/python_types/tutorial005.py hl[1] *}
+
### টাইপ প্যারামিটার সহ জেনেরিক টাইপ
@@ -170,45 +167,55 @@ Python যত এগিয়ে যাচ্ছে, **নতুন সংস্
উদাহরণস্বরূপ, একটি ভেরিয়েবলকে `str`-এর একটি `list` হিসেবে সংজ্ঞায়িত করা যাক।
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+ভেরিয়েবলটি ঘোষণা করুন, একই কোলন (`:`) সিনট্যাক্স ব্যবহার করে।
+
+টাইপ হিসেবে, `list` ব্যবহার করুন।
+
+যেহেতু লিস্ট এমন একটি টাইপ যা অভ্যন্তরীণ টাইপগুলি ধারণ করে, আপনি তাদের স্কোয়ার ব্রাকেটের ভিতরে ব্যবহার করুন:
+
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial006_py39.py!}
+```
- ভেরিয়েবলটি ঘোষণা করুন, একই কোলন (`:`) সিনট্যাক্স ব্যবহার করে।
+////
- টাইপ হিসেবে, `list` ব্যবহার করুন।
+//// tab | Python 3.8+
- যেহেতু লিস্ট এমন একটি টাইপ যা অভ্যন্তরীণ টাইপগুলি ধারণ করে, আপনি তাদের স্কোয়ার ব্রাকেটের ভিতরে ব্যবহার করুন:
+`typing` থেকে `List` (বড় হাতের `L` দিয়ে) ইমপোর্ট করুন:
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial006_py39.py!}
- ```
+``` Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial006.py!}
+```
-=== "Python 3.8+"
+ভেরিয়েবলটি ঘোষণা করুন, একই কোলন (`:`) সিনট্যাক্স ব্যবহার করে।
- `typing` থেকে `List` (বড় হাতের `L` দিয়ে) ইমপোর্ট করুন:
+টাইপ হিসেবে, `typing` থেকে আপনার ইম্পোর্ট করা `List` ব্যবহার করুন।
- ``` Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial006.py!}
- ```
+যেহেতু লিস্ট এমন একটি টাইপ যা অভ্যন্তরীণ টাইপগুলি ধারণ করে, আপনি তাদের স্কোয়ার ব্রাকেটের ভিতরে করুন:
- ভেরিয়েবলটি ঘোষণা করুন, একই কোলন (`:`) সিনট্যাক্স ব্যবহার করে।
+```Python hl_lines="4"
+{!> ../../docs_src/python_types/tutorial006.py!}
+```
- টাইপ হিসেবে, `typing` থেকে আপনার ইম্পোর্ট করা `List` ব্যবহার করুন।
+////
- যেহেতু লিস্ট এমন একটি টাইপ যা অভ্যন্তরীণ টাইপগুলি ধারণ করে, আপনি তাদের স্কোয়ার ব্রাকেটের ভিতরে করুন:
+/// info
- ```Python hl_lines="4"
- {!> ../../../docs_src/python_types/tutorial006.py!}
- ```
+স্কোয়ার ব্রাকেট এর ভিতরে ব্যবহৃত এইসব অভন্তরীন টাইপগুলোকে "ইন্টারনাল টাইপ" বলে।
-!!! Info
- স্কোয়ার ব্রাকেট এর ভিতরে ব্যবহৃত এইসব অভন্তরীন টাইপগুলোকে "ইন্টারনাল টাইপ" বলে।
+এই উদাহরণে, এটি হচ্ছে `List`(অথবা পাইথন ৩.৯ বা তার উপরের সংস্করণের ক্ষেত্রে `list`) এ পাস করা টাইপ প্যারামিটার।
- এই উদাহরণে, এটি হচ্ছে `List`(অথবা পাইথন ৩.৯ বা তার উপরের সংস্করণের ক্ষেত্রে `list`) এ পাস করা টাইপ প্যারামিটার।
+///
এর অর্থ হচ্ছে: "ভেরিয়েবল `items` একটি `list`, এবং এই লিস্টের প্রতিটি আইটেম একটি `str`।"
-!!! Tip
- যদি আপনি Python 3.9 বা তার উপরে ব্যবহার করেন, আপনার `typing` থেকে `List` আমদানি করতে হবে না, আপনি সাধারণ `list` ওই টাইপের পরিবর্তে ব্যবহার করতে পারেন।
+/// tip
+
+যদি আপনি Python 3.9 বা তার উপরে ব্যবহার করেন, আপনার `typing` থেকে `List` আমদানি করতে হবে না, আপনি সাধারণ `list` ওই টাইপের পরিবর্তে ব্যবহার করতে পারেন।
+
+///
এর মাধ্যমে, আপনার এডিটর লিস্ট থেকে আইটেম প্রসেস করার সময় সাপোর্ট প্রদান করতে পারবে:
@@ -224,17 +231,21 @@ Python যত এগিয়ে যাচ্ছে, **নতুন সংস্
আপনি `tuple` এবং `set` ঘোষণা করার জন্য একই প্রক্রিয়া অনুসরণ করবেন:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial007_py39.py!}
+```
+
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial007_py39.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial007.py!}
+```
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial007.py!}
- ```
+////
এর মানে হল:
@@ -249,18 +260,21 @@ Python যত এগিয়ে যাচ্ছে, **নতুন সংস্
দ্বিতীয় টাইপ প্যারামিটারটি হল `dict`-এর মানগুলির জন্য:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial008_py39.py!}
- ```
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial008_py39.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial008.py!}
- ```
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial008.py!}
+```
+////
এর মানে হল:
@@ -276,17 +290,21 @@ Python 3.6 এবং তার উপরের সংস্করণগুলি
Python 3.10-এ একটি **নতুন সিনট্যাক্স** আছে যেখানে আপনি সম্ভাব্য টাইপগুলিকে একটি ভার্টিকাল বার (`|`) দ্বারা পৃথক করতে পারেন।
-=== "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!}
+```
+
+////
উভয় ক্ষেত্রেই এর মানে হল যে `item` হতে পারে একটি `int` অথবা `str`।
@@ -297,7 +315,7 @@ Python 3.10-এ একটি **নতুন সিনট্যাক্স** আ
Python 3.6 এবং তার উপরের সংস্করণগুলিতে (Python 3.10 অনতর্ভুক্ত) আপনি `typing` মডিউল থেকে `Optional` ইমপোর্ট করে এটি ঘোষণা এবং ব্যবহার করতে পারেন।
```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009.py!}
+{!../../docs_src/python_types/tutorial009.py!}
```
`Optional[str]` ব্যবহার করা মানে হল শুধু `str` নয়, এটি হতে পারে `None`-ও, যা আপনার এডিটরকে সেই ত্রুটিগুলি শনাক্ত করতে সাহায্য করবে যেখানে আপনি ধরে নিচ্ছেন যে একটি মান সবসময় `str` হবে, অথচ এটি `None`-ও হতে পারেও।
@@ -306,23 +324,29 @@ Python 3.6 এবং তার উপরের সংস্করণগুলি
এর মানে হল, Python 3.10-এ, আপনি টাইপগুলির ইউনিয়ন ঘোষণা করতে `Something | None` ব্যবহার করতে পারেন:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial009_py310.py!}
- ```
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial009_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial009.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial009.py!}
- ```
+//// tab | Python 3.8+ বিকল্প
-=== "Python 3.8+ বিকল্প"
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial009b.py!}
+```
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial009b.py!}
- ```
+////
#### `Union` বা `Optional` ব্যবহার
@@ -339,9 +363,8 @@ Python 3.6 এবং তার উপরের সংস্করণগুলি
একটি উদাহরণ হিসেবে, এই ফাংশনটি নিন:
-```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009c.py!}
-```
+{* ../../docs_src/python_types/tutorial009c.py hl[1,4] *}
+
`name` প্যারামিটারটি `Optional[str]` হিসেবে সংজ্ঞায়িত হয়েছে, কিন্তু এটি **অপশনাল নয়**, আপনি প্যারামিটার ছাড়া ফাংশনটি কল করতে পারবেন না:
@@ -357,9 +380,8 @@ say_hi(name=None) # এটি কাজ করে, None বৈধ 🎉
সুখবর হল, একবার আপনি Python 3.10 ব্যবহার করা শুরু করলে, আপনাকে এগুলোর ব্যাপারে আর চিন্তা করতে হবে না, যেহুতু আপনি | ব্যবহার করেই ইউনিয়ন ঘোষণা করতে পারবেন:
-```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009c_py310.py!}
-```
+{* ../../docs_src/python_types/tutorial009c_py310.py hl[1,4] *}
+
এবং তারপর আপনাকে নামগুলি যেমন `Optional` এবং `Union` নিয়ে আর চিন্তা করতে হবে না। 😎
@@ -367,46 +389,53 @@ say_hi(name=None) # এটি কাজ করে, None বৈধ 🎉
স্কোয়ার ব্র্যাকেটে টাইপ প্যারামিটার নেওয়া এই টাইপগুলিকে **জেনেরিক টাইপ** বা **জেনেরিকস** বলা হয়, যেমন:
-=== "Python 3.10+"
- আপনি সেই একই বিল্টইন টাইপ জেনেরিক্স হিসেবে ব্যবহার করতে পারবেন(ভিতরে টাইপ সহ স্কয়ারে ব্রাকেট দিয়ে):
+//// tab | Python 3.10+
+
+আপনি সেই একই বিল্টইন টাইপ জেনেরিক্স হিসেবে ব্যবহার করতে পারবেন(ভিতরে টাইপ সহ স্কয়ারে ব্রাকেট দিয়ে):
+
+* `list`
+* `tuple`
+* `set`
+* `dict`
+
+এবং Python 3.8 এর মতোই, `typing` মডিউল থেকে:
+
+* `Union`
+* `Optional` (Python 3.8 এর মতোই)
+* ...এবং অন্যান্য।
- * `list`
- * `tuple`
- * `set`
- * `dict`
+Python 3.10-এ, `Union` এবং `Optional` জেনেরিকস ব্যবহার করার বিকল্প হিসেবে, আপনি টাইপগুলির ইউনিয়ন ঘোষণা করতে ভার্টিকাল বার (`|`) ব্যবহার করতে পারেন, যা ওদের থেকে অনেক ভালো এবং সহজ।
- এবং Python 3.8 এর মতোই, `typing` মডিউল থেকে:
+////
- * `Union`
- * `Optional` (Python 3.8 এর মতোই)
- * ...এবং অন্যান্য।
+//// tab | Python 3.9+
- Python 3.10-এ, `Union` এবং `Optional` জেনেরিকস ব্যবহার করার বিকল্প হিসেবে, আপনি টাইপগুলির ইউনিয়ন ঘোষণা করতে ভার্টিকাল বার (`|`) ব্যবহার করতে পারেন, যা ওদের থেকে অনেক ভালো এবং সহজ।
+আপনি সেই একই বিল্টইন টাইপ জেনেরিক্স হিসেবে ব্যবহার করতে পারবেন(ভিতরে টাইপ সহ স্কয়ারে ব্রাকেট দিয়ে):
-=== "Python 3.9+"
+* `list`
+* `tuple`
+* `set`
+* `dict`
- আপনি সেই একই বিল্টইন টাইপ জেনেরিক্স হিসেবে ব্যবহার করতে পারবেন(ভিতরে টাইপ সহ স্কয়ারে ব্রাকেট দিয়ে):
+এবং Python 3.8 এর মতোই, `typing` মডিউল থেকে:
- * `list`
- * `tuple`
- * `set`
- * `dict`
+* `Union`
+* `Optional`
+* ...এবং অন্যান্য।
- এবং Python 3.8 এর মতোই, `typing` মডিউল থেকে:
+////
- * `Union`
- * `Optional`
- * ...এবং অন্যান্য।
+//// tab | Python 3.8+
-=== "Python 3.8+"
+* `List`
+* `Tuple`
+* `Set`
+* `Dict`
+* `Union`
+* `Optional`
+* ...এবং অন্যান্য।
- * `List`
- * `Tuple`
- * `Set`
- * `Dict`
- * `Union`
- * `Optional`
- * ...এবং অন্যান্য।
+////
### ক্লাস হিসেবে টাইপস
@@ -414,15 +443,13 @@ say_hi(name=None) # এটি কাজ করে, None বৈধ 🎉
ধরুন আপনার কাছে `Person` নামে একটি ক্লাস আছে, যার একটি নাম আছে:
-```Python hl_lines="1-3"
-{!../../../docs_src/python_types/tutorial010.py!}
-```
+{* ../../docs_src/python_types/tutorial010.py hl[1:3] *}
+
তারপর আপনি একটি ভেরিয়েবলকে `Person` টাইপের হিসেবে ঘোষণা করতে পারেন:
-```Python hl_lines="6"
-{!../../../docs_src/python_types/tutorial010.py!}
-```
+{* ../../docs_src/python_types/tutorial010.py hl[6] *}
+
এবং তারপর, আবার, আপনি এডিটর সাপোর্ট পেয়ে যাবেন:
@@ -446,55 +473,71 @@ say_hi(name=None) # এটি কাজ করে, None বৈধ 🎉
অফিসিয়াল 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+"
+//// tab | Python 3.9+
- ```Python
- {!> ../../../docs_src/python_types/tutorial011_py39.py!}
- ```
+```Python
+{!> ../../docs_src/python_types/tutorial011_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python
- {!> ../../../docs_src/python_types/tutorial011.py!}
- ```
+//// tab | Python 3.8+
-!!! Info
- [Pydantic সম্পর্কে আরও জানতে, এর ডকুমেন্টেশন দেখুন](https://docs.pydantic.dev/)।
+```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) সম্পর্কে আরও পড়তে পারেন।
+/// tip
+
+যখন আপনি `Optional` বা `Union[Something, None]` ব্যবহার করেন এবং কোনো ডিফল্ট মান না থাকে, Pydantic-এর একটি বিশেষ আচরণ রয়েছে, আপনি Pydantic ডকুমেন্টেশনে [Required Optional fields](https://docs.pydantic.dev/latest/concepts/models/#required-optional-fields) সম্পর্কে আরও পড়তে পারেন।
+
+///
## মেটাডাটা অ্যানোটেশন সহ টাইপ হিন্টস
Python-এ এমন একটি ফিচার আছে যা `Annotated` ব্যবহার করে এই টাইপ হিন্টগুলিতে **অতিরিক্ত মেটাডাটা** রাখতে দেয়।
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+Python 3.9-এ, `Annotated` স্ট্যান্ডার্ড লাইব্রেরিতে অন্তর্ভুক্ত, তাই আপনি এটি `typing` থেকে ইমপোর্ট করতে পারেন।
- Python 3.9-এ, `Annotated` স্ট্যান্ডার্ড লাইব্রেরিতে অন্তর্ভুক্ত, তাই আপনি এটি `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+"
+//// tab | Python 3.8+
- Python 3.9-এর নীচের সংস্করণগুলিতে, আপনি `Annotated`-কে `typing_extensions` থেকে ইমপোর্ট করেন।
+Python 3.9-এর নীচের সংস্করণগুলিতে, আপনি `Annotated`-কে `typing_extensions` থেকে ইমপোর্ট করেন।
- এটি **FastAPI** এর সাথে ইতিমদ্ধে ইনস্টল হয়ে থাকবে।
+এটি **FastAPI** এর সাথে ইতিমদ্ধে ইনস্টল হয়ে থাকবে।
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial013.py!}
- ```
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial013.py!}
+```
+
+////
Python নিজে এই `Annotated` দিয়ে কিছুই করে না। এবং এডিটর এবং অন্যান্য টুলগুলির জন্য, টাইপটি এখনও `str`।
@@ -506,10 +549,13 @@ Python নিজে এই `Annotated` দিয়ে কিছুই করে
পরবর্তীতে আপনি দেখবেন এটি কতটা **শক্তিশালী** হতে পারে।
-!!! Tip
- এটি **স্ট্যান্ডার্ড Python** হওয়ার মানে হল আপনি আপনার এডিটরে, আপনি যে টুলগুলি কোড বিশ্লেষণ এবং রিফ্যাক্টর করার জন্য ব্যবহার করেন তাতে **সেরা সম্ভাব্য ডেভেলপার এক্সপেরিয়েন্স** পাবেন। ✨
+/// tip
+
+এটি **স্ট্যান্ডার্ড Python** হওয়ার মানে হল আপনি আপনার এডিটরে, আপনি যে টুলগুলি কোড বিশ্লেষণ এবং রিফ্যাক্টর করার জন্য ব্যবহার করেন তাতে **সেরা সম্ভাব্য ডেভেলপার এক্সপেরিয়েন্স** পাবেন। ✨
+
+এবং এছাড়াও আপনার কোড অন্যান্য অনেক Python টুল এবং লাইব্রেরিগুলির সাথে খুব সামঞ্জস্যপূর্ণ হবে। 🚀
- এবং এছাড়াও আপনার কোড অন্যান্য অনেক Python টুল এবং লাইব্রেরিগুলির সাথে খুব সামঞ্জস্যপূর্ণ হবে। 🚀
+///
## **FastAPI**-এ টাইপ হিন্টস
@@ -533,5 +579,8 @@ Python নিজে এই `Annotated` দিয়ে কিছুই করে
গুরুত্বপূর্ণ বিষয় হল, আপনি যদি স্ট্যান্ডার্ড Python টাইপগুলি ব্যবহার করেন, তবে আরও বেশি ক্লাস, ডেকোরেটর ইত্যাদি যোগ না করেই একই স্থানে **FastAPI** আপনার অনেক কাজ করে দিবে।
-!!! Info
- যদি আপনি টিউটোরিয়ালের সমস্ত বিষয় পড়ে ফেলে থাকেন এবং টাইপ সম্পর্কে আরও জানতে চান, তবে একটি ভালো রিসোর্স হল [mypy এর "cheat sheet"](https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html)। এই "cheat sheet" এ আপনি Python টাইপ হিন্ট সম্পর্কে বেসিক থেকে উন্নত লেভেলের ধারণা পেতে পারেন, যা আপনার কোডে টাইপ সেফটি এবং স্পষ্টতা বাড়াতে সাহায্য করবে।
+/// info
+
+যদি আপনি টিউটোরিয়ালের সমস্ত বিষয় পড়ে ফেলে থাকেন এবং টাইপ সম্পর্কে আরও জানতে চান, তবে একটি ভালো রিসোর্স হল [mypy এর "cheat sheet"](https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html)। এই "cheat sheet" এ আপনি Python টাইপ হিন্ট সম্পর্কে বেসিক থেকে উন্নত লেভেলের ধারণা পেতে পারেন, যা আপনার কোডে টাইপ সেফটি এবং স্পষ্টতা বাড়াতে সাহায্য করবে।
+
+///
diff --git a/docs/de/docs/advanced/additional-responses.md b/docs/de/docs/advanced/additional-responses.md
index 2bfcfab33..bf38d9795 100644
--- a/docs/de/docs/advanced/additional-responses.md
+++ b/docs/de/docs/advanced/additional-responses.md
@@ -1,9 +1,12 @@
# Zusätzliche Responses in OpenAPI
-!!! warning "Achtung"
- Dies ist ein eher fortgeschrittenes Thema.
+/// warning | Achtung
- Wenn Sie mit **FastAPI** beginnen, benötigen Sie dies möglicherweise nicht.
+Dies ist ein eher fortgeschrittenes Thema.
+
+Wenn Sie mit **FastAPI** beginnen, benötigen Sie dies möglicherweise nicht.
+
+///
Sie können zusätzliche Responses mit zusätzlichen Statuscodes, Medientypen, Beschreibungen, usw. deklarieren.
@@ -23,24 +26,28 @@ Jedes dieser Response-`dict`s kann einen Schlüssel `model` haben, welcher ein P
Um beispielsweise eine weitere Response mit dem Statuscode `404` und einem Pydantic-Modell `Message` zu deklarieren, können Sie schreiben:
-```Python hl_lines="18 22"
-{!../../../docs_src/additional_responses/tutorial001.py!}
-```
+{* ../../docs_src/additional_responses/tutorial001.py hl[18,22] *}
+
+/// note | Hinweis
+
+Beachten Sie, dass Sie die `JSONResponse` direkt zurückgeben müssen.
+
+///
+
+/// info
-!!! note "Hinweis"
- Beachten Sie, dass Sie die `JSONResponse` direkt zurückgeben müssen.
+Der `model`-Schlüssel ist nicht Teil von OpenAPI.
-!!! 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.
- **FastAPI** nimmt das Pydantic-Modell von dort, generiert das JSON-Schema und fügt es an der richtigen Stelle ein.
+Die richtige Stelle ist:
- Die richtige Stelle ist:
+* Im Schlüssel `content`, der als Wert ein weiteres JSON-Objekt (`dict`) hat, welches Folgendes enthält:
+ * Ein Schlüssel mit dem Medientyp, z. B. `application/json`, der als Wert ein weiteres JSON-Objekt hat, welches Folgendes enthält:
+ * Ein Schlüssel `schema`, der als Wert das JSON-Schema aus dem Modell hat, hier ist die richtige Stelle.
+ * **FastAPI** fügt hier eine Referenz auf die globalen JSON-Schemas an einer anderen Stelle in Ihrer OpenAPI hinzu, anstatt es direkt einzubinden. Auf diese Weise können andere Anwendungen und Clients diese JSON-Schemas direkt verwenden, bessere Tools zur Codegenerierung bereitstellen, usw.
- * Im Schlüssel `content`, der als Wert ein weiteres JSON-Objekt (`dict`) hat, welches Folgendes enthält:
- * Ein Schlüssel mit dem Medientyp, z. B. `application/json`, der als Wert ein weiteres JSON-Objekt hat, welches Folgendes enthält:
- * Ein Schlüssel `schema`, der als Wert das JSON-Schema aus dem Modell hat, hier ist die richtige Stelle.
- * **FastAPI** fügt hier eine Referenz auf die globalen JSON-Schemas an einer anderen Stelle in Ihrer OpenAPI hinzu, anstatt es direkt einzubinden. Auf diese Weise können andere Anwendungen und Clients diese JSON-Schemas direkt verwenden, bessere Tools zur Codegenerierung bereitstellen, usw.
+///
Die generierten Responses in der OpenAPI für diese *Pfadoperation* lauten:
@@ -168,17 +175,21 @@ Sie können denselben `responses`-Parameter verwenden, um verschiedene Medientyp
Sie können beispielsweise einen zusätzlichen Medientyp `image/png` hinzufügen und damit deklarieren, dass Ihre *Pfadoperation* ein JSON-Objekt (mit dem Medientyp `application/json`) oder ein PNG-Bild zurückgeben kann:
-```Python hl_lines="19-24 28"
-{!../../../docs_src/additional_responses/tutorial002.py!}
-```
+{* ../../docs_src/additional_responses/tutorial002.py hl[19:24,28] *}
+
+/// note | Hinweis
+
+Beachten Sie, dass Sie das Bild direkt mit einer `FileResponse` zurückgeben müssen.
+
+///
-!!! note "Hinweis"
- Beachten Sie, dass Sie das Bild direkt mit einer `FileResponse` zurückgeben müssen.
+/// info
-!!! 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`).
+Sofern Sie in Ihrem Parameter `responses` nicht explizit einen anderen Medientyp angeben, geht FastAPI davon aus, dass die Response denselben Medientyp wie die Haupt-Response-Klasse hat (Standardmäßig `application/json`).
- Wenn Sie jedoch eine benutzerdefinierte Response-Klasse mit `None` als Medientyp angegeben haben, verwendet FastAPI `application/json` für jede zusätzliche Response, die über ein zugehöriges Modell verfügt.
+Wenn Sie jedoch eine benutzerdefinierte Response-Klasse mit `None` als Medientyp angegeben haben, verwendet FastAPI `application/json` für jede zusätzliche Response, die über ein zugehöriges Modell verfügt.
+
+///
## Informationen kombinieren
@@ -192,9 +203,7 @@ Sie können beispielsweise eine Response mit dem Statuscode `404` deklarieren, d
Und eine Response mit dem Statuscode `200`, die Ihr `response_model` verwendet, aber ein benutzerdefiniertes Beispiel (`example`) enthält:
-```Python hl_lines="20-31"
-{!../../../docs_src/additional_responses/tutorial003.py!}
-```
+{* ../../docs_src/additional_responses/tutorial003.py hl[20:31] *}
Es wird alles kombiniert und in Ihre OpenAPI eingebunden und in der API-Dokumentation angezeigt:
@@ -228,9 +237,7 @@ Mit dieser Technik können Sie einige vordefinierte Responses in Ihren *Pfadoper
Zum Beispiel:
-```Python hl_lines="13-17 26"
-{!../../../docs_src/additional_responses/tutorial004.py!}
-```
+{* ../../docs_src/additional_responses/tutorial004.py hl[13:17,26] *}
## Weitere Informationen zu OpenAPI-Responses
diff --git a/docs/de/docs/advanced/additional-status-codes.md b/docs/de/docs/advanced/additional-status-codes.md
index e9de267cf..b07bb90ab 100644
--- a/docs/de/docs/advanced/additional-status-codes.md
+++ b/docs/de/docs/advanced/additional-status-codes.md
@@ -14,53 +14,25 @@ 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+"
+{* ../../docs_src/additional_status_codes/tutorial001_an_py310.py hl[4,25] *}
- ```Python hl_lines="4 25"
- {!> ../../../docs_src/additional_status_codes/tutorial001_an_py310.py!}
- ```
+/// warning | Achtung
-=== "Python 3.9+"
+Wenn Sie eine `Response` direkt zurückgeben, wie im obigen Beispiel, wird sie direkt zurückgegeben.
- ```Python hl_lines="4 25"
- {!> ../../../docs_src/additional_status_codes/tutorial001_an_py39.py!}
- ```
+Sie wird nicht mit einem Modell usw. serialisiert.
-=== "Python 3.8+"
+Stellen Sie sicher, dass sie die gewünschten Daten enthält und dass die Werte gültiges JSON sind (wenn Sie `JSONResponse` verwenden).
- ```Python hl_lines="4 26"
- {!> ../../../docs_src/additional_status_codes/tutorial001_an.py!}
- ```
+///
-=== "Python 3.10+ nicht annotiert"
+/// note | Technische Details
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+Sie können auch `from starlette.responses import JSONResponse` verwenden.
- ```Python hl_lines="2 23"
- {!> ../../../docs_src/additional_status_codes/tutorial001_py310.py!}
- ```
+**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`.
-=== "Python 3.8+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="4 25"
- {!> ../../../docs_src/additional_status_codes/tutorial001.py!}
- ```
-
-!!! warning "Achtung"
- Wenn Sie eine `Response` direkt zurückgeben, wie im obigen Beispiel, wird sie direkt zurückgegeben.
-
- Sie wird nicht mit einem Modell usw. serialisiert.
-
- Stellen Sie sicher, dass sie die gewünschten Daten enthält und dass die Werte gültiges JSON sind (wenn Sie `JSONResponse` verwenden).
-
-!!! note "Technische Details"
- Sie können auch `from starlette.responses import JSONResponse` verwenden.
-
- **FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. Das Gleiche gilt für `status`.
+///
## OpenAPI- und API-Dokumentation
diff --git a/docs/de/docs/advanced/advanced-dependencies.md b/docs/de/docs/advanced/advanced-dependencies.md
index 33b93b332..56eb7d454 100644
--- a/docs/de/docs/advanced/advanced-dependencies.md
+++ b/docs/de/docs/advanced/advanced-dependencies.md
@@ -18,26 +18,7 @@ Nicht die Klasse selbst (die bereits aufrufbar ist), sondern eine Instanz dieser
Dazu deklarieren wir eine Methode `__call__`:
-=== "Python 3.9+"
-
- ```Python hl_lines="12"
- {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="11"
- {!> ../../../docs_src/dependencies/tutorial011_an.py!}
- ```
-
-=== "Python 3.8+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/dependencies/tutorial011.py!}
- ```
+{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[12] *}
In diesem Fall ist dieses `__call__` das, was **FastAPI** verwendet, um nach zusätzlichen Parametern und Unterabhängigkeiten zu suchen, und das ist es auch, was später aufgerufen wird, um einen Wert an den Parameter in Ihrer *Pfadoperation-Funktion* zu übergeben.
@@ -45,26 +26,7 @@ In diesem Fall ist dieses `__call__` das, was **FastAPI** verwendet, um nach zus
Und jetzt können wir `__init__` verwenden, um die Parameter der Instanz zu deklarieren, die wir zum `Parametrisieren` der Abhängigkeit verwenden können:
-=== "Python 3.9+"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="8"
- {!> ../../../docs_src/dependencies/tutorial011_an.py!}
- ```
-
-=== "Python 3.8+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="7"
- {!> ../../../docs_src/dependencies/tutorial011.py!}
- ```
+{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[9] *}
In diesem Fall wird **FastAPI** `__init__` nie berühren oder sich darum kümmern, wir werden es direkt in unserem Code verwenden.
@@ -72,26 +34,7 @@ In diesem Fall wird **FastAPI** `__init__` nie berühren oder sich darum kümmer
Wir könnten eine Instanz dieser Klasse erstellen mit:
-=== "Python 3.9+"
-
- ```Python hl_lines="18"
- {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial011_an.py!}
- ```
-
-=== "Python 3.8+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="16"
- {!> ../../../docs_src/dependencies/tutorial011.py!}
- ```
+{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[18] *}
Und auf diese Weise können wir unsere Abhängigkeit „parametrisieren“, die jetzt `"bar"` enthält, als das Attribut `checker.fixed_content`.
@@ -107,32 +50,16 @@ checker(q="somequery")
... und übergibt, was immer das als Wert dieser Abhängigkeit in unserer *Pfadoperation-Funktion* zurückgibt, als den Parameter `fixed_content_included`:
-=== "Python 3.9+"
-
- ```Python hl_lines="22"
- {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="21"
- {!> ../../../docs_src/dependencies/tutorial011_an.py!}
- ```
-
-=== "Python 3.8+ nicht annotiert"
+{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[22] *}
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | Tipp
- ```Python hl_lines="20"
- {!> ../../../docs_src/dependencies/tutorial011.py!}
- ```
+Das alles mag gekünstelt wirken. Und es ist möglicherweise noch nicht ganz klar, welchen Nutzen das hat.
-!!! tip "Tipp"
- Das alles mag gekünstelt wirken. Und es ist möglicherweise noch nicht ganz klar, welchen Nutzen das hat.
+Diese Beispiele sind bewusst einfach gehalten, zeigen aber, wie alles funktioniert.
- Diese Beispiele sind bewusst einfach gehalten, zeigen aber, wie alles funktioniert.
+In den Kapiteln zum Thema Sicherheit gibt es Hilfsfunktionen, die auf die gleiche Weise implementiert werden.
- In den Kapiteln zum Thema Sicherheit gibt es Hilfsfunktionen, die auf die gleiche Weise implementiert werden.
+Wenn Sie das hier alles verstanden haben, wissen Sie bereits, wie diese Sicherheits-Hilfswerkzeuge unter der Haube funktionieren.
- Wenn Sie das hier alles verstanden haben, wissen Sie bereits, wie diese Sicherheits-Hilfswerkzeuge unter der Haube funktionieren.
+///
diff --git a/docs/de/docs/advanced/async-tests.md b/docs/de/docs/advanced/async-tests.md
index 2e2c22210..b82aadf00 100644
--- a/docs/de/docs/advanced/async-tests.md
+++ b/docs/de/docs/advanced/async-tests.md
@@ -32,15 +32,11 @@ Betrachten wir als einfaches Beispiel eine Dateistruktur ähnlich der in [Größ
Die Datei `main.py` hätte als Inhalt:
-```Python
-{!../../../docs_src/async_tests/main.py!}
-```
+{* ../../docs_src/async_tests/main.py *}
Die Datei `test_main.py` hätte die Tests für `main.py`, das könnte jetzt so aussehen:
-```Python
-{!../../../docs_src/async_tests/test_main.py!}
-```
+{* ../../docs_src/async_tests/test_main.py *}
## Es ausführen
@@ -60,18 +56,17 @@ $ pytest
Der Marker `@pytest.mark.anyio` teilt pytest mit, dass diese Testfunktion asynchron aufgerufen werden soll:
-```Python hl_lines="7"
-{!../../../docs_src/async_tests/test_main.py!}
-```
+{* ../../docs_src/async_tests/test_main.py hl[7] *}
+
+/// tip | Tipp
+
+Beachten Sie, dass die Testfunktion jetzt `async def` ist und nicht nur `def` wie zuvor, wenn Sie den `TestClient` verwenden.
-!!! tip "Tipp"
- Beachten Sie, dass die Testfunktion jetzt `async def` ist und nicht nur `def` wie zuvor, wenn Sie den `TestClient` verwenden.
+///
Dann können wir einen `AsyncClient` mit der App erstellen und mit `await` asynchrone Requests an ihn senden.
-```Python hl_lines="9-10"
-{!../../../docs_src/async_tests/test_main.py!}
-```
+{* ../../docs_src/async_tests/test_main.py hl[9:12] *}
Das ist das Äquivalent zu:
@@ -81,15 +76,24 @@ response = client.get('/')
... welches wir verwendet haben, um unsere Requests mit dem `TestClient` zu machen.
-!!! tip "Tipp"
- Beachten Sie, dass wir async/await mit dem neuen `AsyncClient` verwenden – der Request ist asynchron.
+/// tip | Tipp
+
+Beachten Sie, dass wir async/await mit dem neuen `AsyncClient` verwenden – der Request ist asynchron.
+
+///
+
+/// warning | Achtung
-!!! warning "Achtung"
- Falls Ihre Anwendung auf Lifespan-Events angewiesen ist, der `AsyncClient` löst diese Events nicht aus. Um sicherzustellen, dass sie ausgelöst werden, verwenden Sie `LifespanManager` von florimondmanca/asgi-lifespan.
+Falls Ihre Anwendung auf Lifespan-Events angewiesen ist, der `AsyncClient` löst diese Events nicht aus. Um sicherzustellen, dass sie ausgelöst werden, verwenden Sie `LifespanManager` von florimondmanca/asgi-lifespan.
+
+///
## Andere asynchrone Funktionsaufrufe
Da die Testfunktion jetzt asynchron ist, können Sie in Ihren Tests neben dem Senden von Requests an Ihre FastAPI-Anwendung jetzt auch andere `async`hrone Funktionen aufrufen (und `await`en), genau so, wie Sie diese an anderer Stelle in Ihrem Code aufrufen würden.
-!!! tip "Tipp"
- Wenn Sie einen `RuntimeError: Task attached to a different loop` erhalten, wenn Sie asynchrone Funktionsaufrufe in Ihre Tests integrieren (z. B. bei Verwendung von MongoDBs MotorClient), dann denken Sie daran, Objekte zu instanziieren, die einen Event Loop nur innerhalb asynchroner Funktionen benötigen, z. B. einen `@app.on_event("startup")`-Callback.
+/// tip | Tipp
+
+Wenn Sie einen `RuntimeError: Task attached to a different loop` erhalten, wenn Sie asynchrone Funktionsaufrufe in Ihre Tests integrieren (z. B. bei Verwendung von MongoDBs MotorClient), dann denken Sie daran, Objekte zu instanziieren, die einen Event Loop nur innerhalb asynchroner Funktionen benötigen, z. B. einen `@app.on_event("startup")`-Callback.
+
+///
diff --git a/docs/de/docs/advanced/behind-a-proxy.md b/docs/de/docs/advanced/behind-a-proxy.md
index ad0a92e28..9e2282280 100644
--- a/docs/de/docs/advanced/behind-a-proxy.md
+++ b/docs/de/docs/advanced/behind-a-proxy.md
@@ -18,9 +18,7 @@ In diesem Fall würde der ursprüngliche Pfad `/app` tatsächlich unter `/api/v1
Auch wenn Ihr gesamter Code unter der Annahme geschrieben ist, dass es nur `/app` gibt.
-```Python hl_lines="6"
-{!../../../docs_src/behind_a_proxy/tutorial001.py!}
-```
+{* ../../docs_src/behind_a_proxy/tutorial001.py hl[6] *}
Und der Proxy würde das **Pfadpräfix** on-the-fly **"entfernen**", bevor er die Anfrage an Uvicorn übermittelt, dafür sorgend, dass Ihre Anwendung davon überzeugt ist, dass sie unter `/app` bereitgestellt wird, sodass Sie nicht Ihren gesamten Code dahingehend aktualisieren müssen, das Präfix `/api/v1` zu verwenden.
@@ -43,8 +41,11 @@ browser --> proxy
proxy --> server
```
-!!! tip "Tipp"
- Die IP `0.0.0.0` wird üblicherweise verwendet, um anzudeuten, dass das Programm alle auf diesem Computer/Server verfügbaren IPs abhört.
+/// tip | Tipp
+
+Die IP `0.0.0.0` wird üblicherweise verwendet, um anzudeuten, dass das Programm alle auf diesem Computer/Server verfügbaren IPs abhört.
+
+///
Die Benutzeroberfläche der Dokumentation würde benötigen, dass das OpenAPI-Schema deklariert, dass sich dieser API-`server` unter `/api/v1` (hinter dem Proxy) befindet. Zum Beispiel:
@@ -81,10 +82,13 @@ $ uvicorn main:app --root-path /api/v1
Falls Sie Hypercorn verwenden, das hat auch die Option `--root-path`.
-!!! note "Technische Details"
- Die ASGI-Spezifikation definiert einen `root_path` für diesen Anwendungsfall.
+/// note | Technische Details
+
+Die ASGI-Spezifikation definiert einen `root_path` für diesen Anwendungsfall.
+
+Und die Kommandozeilenoption `--root-path` stellt diesen `root_path` bereit.
- Und die Kommandozeilenoption `--root-path` stellt diesen `root_path` bereit.
+///
### Überprüfen des aktuellen `root_path`
@@ -92,9 +96,7 @@ Sie können den aktuellen `root_path` abrufen, der von Ihrer Anwendung für jede
Hier fügen wir ihn, nur zu Demonstrationszwecken, in die Nachricht ein.
-```Python hl_lines="8"
-{!../../../docs_src/behind_a_proxy/tutorial001.py!}
-```
+{* ../../docs_src/behind_a_proxy/tutorial001.py hl[8] *}
Wenn Sie Uvicorn dann starten mit:
@@ -121,9 +123,7 @@ wäre die Response etwa:
Falls Sie keine Möglichkeit haben, eine Kommandozeilenoption wie `--root-path` oder ähnlich zu übergeben, können Sie als Alternative beim Erstellen Ihrer FastAPI-Anwendung den Parameter `root_path` setzen:
-```Python hl_lines="3"
-{!../../../docs_src/behind_a_proxy/tutorial002.py!}
-```
+{* ../../docs_src/behind_a_proxy/tutorial002.py hl[3] *}
Die Übergabe des `root_path` an `FastAPI` wäre das Äquivalent zur Übergabe der `--root-path`-Kommandozeilenoption an Uvicorn oder Hypercorn.
@@ -172,8 +172,11 @@ Dann erstellen Sie eine Datei `traefik.toml` mit:
Dadurch wird Traefik angewiesen, Port 9999 abzuhören und eine andere Datei `routes.toml` zu verwenden.
-!!! tip "Tipp"
- Wir verwenden Port 9999 anstelle des Standard-HTTP-Ports 80, damit Sie ihn nicht mit Administratorrechten (`sudo`) ausführen müssen.
+/// tip | Tipp
+
+Wir verwenden Port 9999 anstelle des Standard-HTTP-Ports 80, damit Sie ihn nicht mit Administratorrechten (`sudo`) ausführen müssen.
+
+///
Erstellen Sie nun die andere Datei `routes.toml`:
@@ -239,8 +242,11 @@ Wenn Sie nun zur URL mit dem Port für Uvicorn gehen: http://127.0.0.1:9999/api/v1/app.
@@ -283,8 +289,11 @@ Dies liegt daran, dass FastAPI diesen `root_path` verwendet, um den Default-`ser
## Zusätzliche Server
-!!! warning "Achtung"
- Dies ist ein fortgeschrittener Anwendungsfall. Überspringen Sie das gerne.
+/// warning | Achtung
+
+Dies ist ein fortgeschrittener Anwendungsfall. Überspringen Sie das gerne.
+
+///
Standardmäßig erstellt **FastAPI** einen `server` im OpenAPI-Schema mit der URL für den `root_path`.
@@ -294,9 +303,7 @@ Wenn Sie eine benutzerdefinierte Liste von Servern (`servers`) übergeben und es
Zum Beispiel:
-```Python hl_lines="4-7"
-{!../../../docs_src/behind_a_proxy/tutorial003.py!}
-```
+{* ../../docs_src/behind_a_proxy/tutorial003.py hl[4:7] *}
Erzeugt ein OpenAPI-Schema, wie:
@@ -323,23 +330,27 @@ Erzeugt ein OpenAPI-Schema, wie:
}
```
-!!! tip "Tipp"
- Beachten Sie den automatisch generierten Server mit dem `URL`-Wert `/api/v1`, welcher vom `root_path` stammt.
+/// tip | Tipp
+
+Beachten Sie den automatisch generierten Server mit dem `URL`-Wert `/api/v1`, welcher vom `root_path` stammt.
+
+///
In der Dokumentationsoberfläche unter http://127.0.0.1:9999/api/v1/docs würde es so aussehen:
-
+
@@ -94,7 +94,7 @@ Seine Schlüssel-Merkmale sind:
„_Ehrlich, was Du gebaut hast, sieht super solide und poliert aus. In vielerlei Hinsicht ist es so, wie ich **Hug** haben wollte – es ist wirklich inspirierend, jemanden so etwas bauen zu sehen._“
-
+
---
@@ -449,7 +449,7 @@ Um mehr darüber zu erfahren, siehe den Abschnitt
email_validator
- für E-Mail-Validierung.
+* 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.
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/python-types.md b/docs/de/docs/python-types.md
index d11a193dd..81d43bc5b 100644
--- a/docs/de/docs/python-types.md
+++ b/docs/de/docs/python-types.md
@@ -12,16 +12,17 @@ Dies ist lediglich eine **schnelle Anleitung / Auffrischung** über Pythons Typh
Aber selbst wenn Sie **FastAPI** nie verwenden, wird es für Sie nützlich sein, ein wenig darüber zu lernen.
-!!! note "Hinweis"
- Wenn Sie ein Python-Experte sind und bereits alles über Typhinweise wissen, überspringen Sie dieses Kapitel und fahren Sie mit dem nächsten fort.
+/// note | Hinweis
+
+Wenn Sie ein Python-Experte sind und bereits alles über Typhinweise wissen, überspringen Sie dieses Kapitel und fahren Sie mit dem nächsten fort.
+
+///
## Motivation
Fangen wir mit einem einfachen Beispiel an:
-```Python
-{!../../../docs_src/python_types/tutorial001.py!}
-```
+{* ../../docs_src/python_types/tutorial001.py *}
Dieses Programm gibt aus:
@@ -35,9 +36,7 @@ Die Funktion macht Folgendes:
* Schreibt den ersten Buchstaben eines jeden Wortes groß, mithilfe von `title()`.
* Verkettet sie mit einem Leerzeichen in der Mitte.
-```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial001.py!}
-```
+{* ../../docs_src/python_types/tutorial001.py hl[2] *}
### Bearbeiten Sie es
@@ -79,9 +78,7 @@ Das war's.
Das sind die „Typhinweise“:
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial002.py!}
-```
+{* ../../docs_src/python_types/tutorial002.py hl[1] *}
Das ist nicht das gleiche wie das Deklarieren von Defaultwerten, wie es hier der Fall ist:
@@ -109,9 +106,7 @@ Hier können Sie durch die Optionen blättern, bis Sie diejenige finden, bei der
Sehen Sie sich diese Funktion an, sie hat bereits Typhinweise:
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial003.py!}
-```
+{* ../../docs_src/python_types/tutorial003.py hl[1] *}
Da der Editor die Typen der Variablen kennt, erhalten Sie nicht nur Code-Vervollständigung, sondern auch eine Fehlerprüfung:
@@ -119,9 +114,7 @@ Da der Editor die Typen der Variablen kennt, erhalten Sie nicht nur Code-Vervoll
Jetzt, da Sie wissen, dass Sie das reparieren müssen, konvertieren Sie `age` mittels `str(age)` in einen String:
-```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial004.py!}
-```
+{* ../../docs_src/python_types/tutorial004.py hl[2] *}
## Deklarieren von Typen
@@ -140,9 +133,7 @@ Zum Beispiel diese:
* `bool`
* `bytes`
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial005.py!}
-```
+{* ../../docs_src/python_types/tutorial005.py hl[1] *}
### Generische Typen mit Typ-Parametern
@@ -170,45 +161,55 @@ Wenn Sie über die **neueste Version von Python** verfügen, verwenden Sie die B
Definieren wir zum Beispiel eine Variable, die eine `list` von `str` – eine Liste von Strings – sein soll.
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+Deklarieren Sie die Variable mit der gleichen Doppelpunkt-Syntax (`:`).
+
+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!}
+```
- Deklarieren Sie die Variable mit der gleichen Doppelpunkt-Syntax (`:`).
+////
- Als Typ nehmen Sie `list`.
+//// tab | Python 3.8+
- Da die Liste ein Typ ist, welcher innere Typen enthält, werden diese von eckigen Klammern umfasst:
+Von `typing` importieren Sie `List` (mit Großbuchstaben `L`):
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial006_py39.py!}
- ```
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial006.py!}
+```
-=== "Python 3.8+"
+Deklarieren Sie die Variable mit der gleichen Doppelpunkt-Syntax (`:`).
- Von `typing` importieren Sie `List` (mit Großbuchstaben `L`):
+Als Typ nehmen Sie das `List`, das Sie von `typing` importiert haben.
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial006.py!}
- ```
+Da die Liste ein Typ ist, welcher innere Typen enthält, werden diese von eckigen Klammern umfasst:
- Deklarieren Sie die Variable mit der gleichen Doppelpunkt-Syntax (`:`).
+```Python hl_lines="4"
+{!> ../../docs_src/python_types/tutorial006.py!}
+```
- 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:
+/// tip | Tipp
- ```Python hl_lines="4"
- {!> ../../../docs_src/python_types/tutorial006.py!}
- ```
+Die inneren Typen in den eckigen Klammern werden als „Typ-Parameter“ bezeichnet.
-!!! 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).
- In diesem Fall ist `str` der Typ-Parameter, der an `List` übergeben wird (oder `list` in Python 3.9 und darüber).
+///
Das bedeutet: Die Variable `items` ist eine Liste – `list` – und jedes der Elemente in dieser Liste ist ein String – `str`.
-!!! tip "Tipp"
- Wenn Sie Python 3.9 oder höher verwenden, müssen Sie `List` nicht von `typing` importieren, Sie können stattdessen den regulären `list`-Typ verwenden.
+/// tip | Tipp
+
+Wenn Sie Python 3.9 oder höher verwenden, müssen Sie `List` nicht von `typing` importieren, Sie können stattdessen den regulären `list`-Typ verwenden.
+
+///
Auf diese Weise kann Ihr Editor Sie auch bei der Bearbeitung von Einträgen aus der Liste unterstützen:
@@ -224,17 +225,21 @@ Und trotzdem weiß der Editor, dass es sich um ein `str` handelt, und bietet ent
Das Gleiche gilt für die Deklaration eines Tupels – `tuple` – und einer Menge – `set`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial007_py39.py!}
- ```
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial007_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial007.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial007.py!}
+```
+
+////
Das bedeutet:
@@ -249,17 +254,21 @@ Der erste Typ-Parameter ist für die Schlüssel des `dict`.
Der zweite Typ-Parameter ist für die Werte des `dict`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial008_py39.py!}
- ```
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial008_py39.py!}
+```
-=== "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!}
+```
+
+////
Das bedeutet:
@@ -275,17 +284,21 @@ In Python 3.6 und höher (inklusive Python 3.10) können Sie den `Union`-Typ von
In Python 3.10 gibt es zusätzlich eine **neue Syntax**, die es erlaubt, die möglichen Typen getrennt von einem vertikalen Balken (`|`) aufzulisten.
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial008b_py310.py!}
+```
+
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial008b_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial008b.py!}
+```
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial008b.py!}
- ```
+////
In beiden Fällen bedeutet das, dass `item` ein `int` oder ein `str` sein kann.
@@ -295,9 +308,7 @@ Sie können deklarieren, dass ein Wert ein `str`, aber vielleicht auch `None` se
In Python 3.6 und darüber (inklusive Python 3.10) können Sie das deklarieren, indem Sie `Optional` vom `typing` Modul importieren und verwenden.
-```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009.py!}
-```
+{* ../../docs_src/python_types/tutorial009.py hl[1,4] *}
Wenn Sie `Optional[str]` anstelle von nur `str` verwenden, wird Ihr Editor Ihnen dabei helfen, Fehler zu erkennen, bei denen Sie annehmen könnten, dass ein Wert immer eine String (`str`) ist, obwohl er auch `None` sein könnte.
@@ -305,23 +316,29 @@ Wenn Sie `Optional[str]` anstelle von nur `str` verwenden, wird Ihr Editor Ihnen
Das bedeutet auch, dass Sie in Python 3.10 `Something | None` verwenden können:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial009_py310.py!}
+```
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial009_py310.py!}
- ```
+////
-=== "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+ Alternative"
+////
- ```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!}
+```
+
+////
#### `Union` oder `Optional` verwenden?
@@ -338,9 +355,7 @@ Es geht nur um Wörter und Namen. Aber diese Worte können beeinflussen, wie Sie
Nehmen wir zum Beispiel diese Funktion:
-```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009c.py!}
-```
+{* ../../docs_src/python_types/tutorial009c.py hl[1,4] *}
Der Parameter `name` ist definiert als `Optional[str]`, aber er ist **nicht optional**, Sie können die Funktion nicht ohne diesen Parameter aufrufen:
@@ -356,9 +371,7 @@ say_hi(name=None) # Das funktioniert, None is gültig 🎉
Die gute Nachricht ist, dass Sie sich darüber keine Sorgen mehr machen müssen, wenn Sie Python 3.10 verwenden, da Sie einfach `|` verwenden können, um Vereinigungen von Typen zu definieren:
-```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009c_py310.py!}
-```
+{* ../../docs_src/python_types/tutorial009c_py310.py hl[1,4] *}
Und dann müssen Sie sich nicht mehr um Namen wie `Optional` und `Union` kümmern. 😎
@@ -366,47 +379,53 @@ Und dann müssen Sie sich nicht mehr um Namen wie `Optional` und `Union` kümmer
Diese Typen, die Typ-Parameter in eckigen Klammern akzeptieren, werden **generische Typen** oder **Generics** genannt.
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+Sie können die eingebauten Typen als Generics verwenden (mit eckigen Klammern und Typen darin):
+
+* `list`
+* `tuple`
+* `set`
+* `dict`
- Sie können die eingebauten Typen als Generics verwenden (mit eckigen Klammern und Typen darin):
+Verwenden Sie für den Rest, wie unter Python 3.8, das `typing`-Modul:
- * `list`
- * `tuple`
- * `set`
- * `dict`
+* `Union`
+* `Optional` (so wie unter Python 3.8)
+* ... und andere.
- Verwenden Sie für den Rest, wie unter Python 3.8, das `typing`-Modul:
+In Python 3.10 können Sie als Alternative zu den Generics `Union` und `Optional` den vertikalen Balken (`|`) verwenden, um Vereinigungen von Typen zu deklarieren, das ist besser und einfacher.
- * `Union`
- * `Optional` (so wie unter Python 3.8)
- * ... und andere.
+////
- In Python 3.10 können Sie als Alternative zu den Generics `Union` und `Optional` den vertikalen Balken (`|`) verwenden, um Vereinigungen von Typen zu deklarieren, das ist besser und einfacher.
+//// tab | Python 3.9+
-=== "Python 3.9+"
+Sie können die eingebauten Typen als Generics verwenden (mit eckigen Klammern und Typen darin):
- Sie können die eingebauten Typen als Generics verwenden (mit eckigen Klammern und Typen darin):
+* `list`
+* `tuple`
+* `set`
+* `dict`
- * `list`
- * `tuple`
- * `set`
- * `dict`
+Verwenden Sie für den Rest, wie unter Python 3.8, das `typing`-Modul:
- Verwenden Sie für den Rest, wie unter Python 3.8, das `typing`-Modul:
+* `Union`
+* `Optional`
+* ... und andere.
- * `Union`
- * `Optional`
- * ... und andere.
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- * `List`
- * `Tuple`
- * `Set`
- * `Dict`
- * `Union`
- * `Optional`
- * ... und andere.
+* `List`
+* `Tuple`
+* `Set`
+* `Dict`
+* `Union`
+* `Optional`
+* ... und andere.
+
+////
### Klassen als Typen
@@ -414,15 +433,11 @@ Sie können auch eine Klasse als Typ einer Variablen deklarieren.
Nehmen wir an, Sie haben eine Klasse `Person`, mit einem Namen:
-```Python hl_lines="1-3"
-{!../../../docs_src/python_types/tutorial010.py!}
-```
+{* ../../docs_src/python_types/tutorial010.py hl[1:3] *}
Dann können Sie eine Variable vom Typ `Person` deklarieren:
-```Python hl_lines="6"
-{!../../../docs_src/python_types/tutorial010.py!}
-```
+{* ../../docs_src/python_types/tutorial010.py hl[6] *}
Und wiederum bekommen Sie die volle Editor-Unterstützung:
@@ -446,55 +461,71 @@ Und Sie erhalten volle Editor-Unterstützung für dieses Objekt.
Ein Beispiel aus der offiziellen Pydantic Dokumentation:
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python
+{!> ../../docs_src/python_types/tutorial011_py310.py!}
+```
+
+////
- ```Python
- {!> ../../../docs_src/python_types/tutorial011_py310.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.9+"
+```Python
+{!> ../../docs_src/python_types/tutorial011_py39.py!}
+```
- ```Python
- {!> ../../../docs_src/python_types/tutorial011_py39.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python
- {!> ../../../docs_src/python_types/tutorial011.py!}
- ```
+```Python
+{!> ../../docs_src/python_types/tutorial011.py!}
+```
-!!! info
- Um mehr über Pydantic zu erfahren, schauen Sie sich dessen Dokumentation an.
+////
+
+/// 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.
+/// 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`.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- In Python 3.9 ist `Annotated` ein Teil der Standardbibliothek, Sie können es von `typing` importieren.
+In Python 3.9 ist `Annotated` ein Teil der Standardbibliothek, Sie können es von `typing` importieren.
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial013_py39.py!}
- ```
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial013_py39.py!}
+```
+
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- In Versionen niedriger als Python 3.9 importieren Sie `Annotated` von `typing_extensions`.
+In Versionen niedriger als Python 3.9 importieren Sie `Annotated` von `typing_extensions`.
- Es wird bereits mit **FastAPI** installiert sein.
+Es wird bereits mit **FastAPI** installiert sein.
+
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial013.py!}
+```
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial013.py!}
- ```
+////
Python selbst macht nichts mit `Annotated`. Für Editoren und andere Tools ist der Typ immer noch `str`.
@@ -506,10 +537,13 @@ Im Moment müssen Sie nur wissen, dass `Annotated` existiert, und dass es Standa
Später werden Sie sehen, wie **mächtig** es sein kann.
-!!! tip "Tipp"
- Der Umstand, dass es **Standard-Python** ist, bedeutet, dass Sie immer noch die **bestmögliche Entwickler-Erfahrung** in ihrem Editor haben, sowie mit den Tools, die Sie nutzen, um ihren Code zu analysieren, zu refaktorisieren, usw. ✨
+/// tip | Tipp
+
+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. 🚀
- Und ebenfalls, dass Ihr Code sehr kompatibel mit vielen anderen Python-Tools und -Bibliotheken sein wird. 🚀
+///
## Typhinweise in **FastAPI**
@@ -533,5 +567,8 @@ Das mag alles abstrakt klingen. Machen Sie sich keine Sorgen. Sie werden all das
Das Wichtigste ist, dass **FastAPI** durch die Verwendung von Standard-Python-Typen an einer einzigen Stelle (anstatt weitere Klassen, Dekoratoren usw. hinzuzufügen) einen Großteil der Arbeit für Sie erledigt.
-!!! info
- Wenn Sie bereits das ganze Tutorial durchgearbeitet haben und mehr über Typen erfahren wollen, dann ist eine gute Ressource der „Cheat Sheet“ von `mypy`.
+/// 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/apirouter.md b/docs/de/docs/reference/apirouter.md
deleted file mode 100644
index b0728b7df..000000000
--- a/docs/de/docs/reference/apirouter.md
+++ /dev/null
@@ -1,24 +0,0 @@
-# `APIRouter`-Klasse
-
-Hier sind die Referenzinformationen für die Klasse `APIRouter` mit all ihren Parametern, Attributen und Methoden.
-
-Sie können die `APIRouter`-Klasse direkt von `fastapi` importieren:
-
-```python
-from fastapi import APIRouter
-```
-
-::: fastapi.APIRouter
- options:
- members:
- - websocket
- - include_router
- - get
- - put
- - post
- - delete
- - options
- - head
- - patch
- - trace
- - on_event
diff --git a/docs/de/docs/reference/background.md b/docs/de/docs/reference/background.md
deleted file mode 100644
index 0fd389325..000000000
--- a/docs/de/docs/reference/background.md
+++ /dev/null
@@ -1,11 +0,0 @@
-# Hintergrundtasks – `BackgroundTasks`
-
-Sie können einen Parameter in einer *Pfadoperation-Funktion* oder einer Abhängigkeitsfunktion mit dem Typ `BackgroundTasks` deklarieren und diesen danach verwenden, um die Ausführung von Hintergrundtasks nach dem Senden der Response zu definieren.
-
-Sie können `BackgroundTasks` direkt von `fastapi` importieren:
-
-```python
-from fastapi import BackgroundTasks
-```
-
-::: fastapi.BackgroundTasks
diff --git a/docs/de/docs/reference/dependencies.md b/docs/de/docs/reference/dependencies.md
deleted file mode 100644
index 2ed5b5050..000000000
--- a/docs/de/docs/reference/dependencies.md
+++ /dev/null
@@ -1,29 +0,0 @@
-# Abhängigkeiten – `Depends()` und `Security()`
-
-## `Depends()`
-
-Abhängigkeiten werden hauptsächlich mit der speziellen Funktion `Depends()` behandelt, die ein Callable entgegennimmt.
-
-Hier finden Sie deren Referenz und Parameter.
-
-Sie können sie direkt von `fastapi` importieren:
-
-```python
-from fastapi import Depends
-```
-
-::: fastapi.Depends
-
-## `Security()`
-
-In vielen Szenarien können Sie die Sicherheit (Autorisierung, Authentifizierung usw.) mit Abhängigkeiten handhaben, indem Sie `Depends()` verwenden.
-
-Wenn Sie jedoch auch OAuth2-Scopes deklarieren möchten, können Sie `Security()` anstelle von `Depends()` verwenden.
-
-Sie können `Security()` direkt von `fastapi` importieren:
-
-```python
-from fastapi import Security
-```
-
-::: fastapi.Security
diff --git a/docs/de/docs/reference/encoders.md b/docs/de/docs/reference/encoders.md
deleted file mode 100644
index 2489b8c60..000000000
--- a/docs/de/docs/reference/encoders.md
+++ /dev/null
@@ -1,3 +0,0 @@
-# Encoder – `jsonable_encoder`
-
-::: fastapi.encoders.jsonable_encoder
diff --git a/docs/de/docs/reference/exceptions.md b/docs/de/docs/reference/exceptions.md
deleted file mode 100644
index 230f902a9..000000000
--- a/docs/de/docs/reference/exceptions.md
+++ /dev/null
@@ -1,20 +0,0 @@
-# Exceptions – `HTTPException` und `WebSocketException`
-
-Dies sind die Exceptions, die Sie auslösen können, um dem Client Fehler zu berichten.
-
-Wenn Sie eine Exception auslösen, wird, wie es bei normalem Python der Fall wäre, der Rest der Ausführung abgebrochen. Auf diese Weise können Sie diese Exceptions von überall im Code werfen, um einen Request abzubrechen und den Fehler dem Client anzuzeigen.
-
-Sie können Folgendes verwenden:
-
-* `HTTPException`
-* `WebSocketException`
-
-Diese Exceptions können direkt von `fastapi` importiert werden:
-
-```python
-from fastapi import HTTPException, WebSocketException
-```
-
-::: fastapi.HTTPException
-
-::: fastapi.WebSocketException
diff --git a/docs/de/docs/reference/fastapi.md b/docs/de/docs/reference/fastapi.md
deleted file mode 100644
index 4e6a56971..000000000
--- a/docs/de/docs/reference/fastapi.md
+++ /dev/null
@@ -1,31 +0,0 @@
-# `FastAPI`-Klasse
-
-Hier sind die Referenzinformationen für die Klasse `FastAPI` mit all ihren Parametern, Attributen und Methoden.
-
-Sie können die `FastAPI`-Klasse direkt von `fastapi` importieren:
-
-```python
-from fastapi import FastAPI
-```
-
-::: fastapi.FastAPI
- options:
- members:
- - openapi_version
- - webhooks
- - state
- - dependency_overrides
- - openapi
- - websocket
- - include_router
- - get
- - put
- - post
- - delete
- - options
- - head
- - patch
- - trace
- - on_event
- - middleware
- - exception_handler
diff --git a/docs/de/docs/reference/httpconnection.md b/docs/de/docs/reference/httpconnection.md
deleted file mode 100644
index 32a9696fa..000000000
--- a/docs/de/docs/reference/httpconnection.md
+++ /dev/null
@@ -1,11 +0,0 @@
-# `HTTPConnection`-Klasse
-
-Wenn Sie Abhängigkeiten definieren möchten, die sowohl mit HTTP als auch mit WebSockets kompatibel sein sollen, können Sie einen Parameter definieren, der eine `HTTPConnection` anstelle eines `Request` oder eines `WebSocket` akzeptiert.
-
-Sie können diese von `fastapi.requests` importieren:
-
-```python
-from fastapi.requests import HTTPConnection
-```
-
-::: fastapi.requests.HTTPConnection
diff --git a/docs/de/docs/reference/index.md b/docs/de/docs/reference/index.md
deleted file mode 100644
index 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/middleware.md b/docs/de/docs/reference/middleware.md
deleted file mode 100644
index d8d2d50fc..000000000
--- a/docs/de/docs/reference/middleware.md
+++ /dev/null
@@ -1,45 +0,0 @@
-# Middleware
-
-Es gibt mehrere Middlewares, die direkt von Starlette bereitgestellt werden.
-
-Lesen Sie mehr darüber in der [FastAPI-Dokumentation über Middleware](../advanced/middleware.md).
-
-::: fastapi.middleware.cors.CORSMiddleware
-
-Kann von `fastapi` importiert werden:
-
-```python
-from fastapi.middleware.cors import CORSMiddleware
-```
-
-::: fastapi.middleware.gzip.GZipMiddleware
-
-Kann von `fastapi` importiert werden:
-
-```python
-from fastapi.middleware.gzip import GZipMiddleware
-```
-
-::: fastapi.middleware.httpsredirect.HTTPSRedirectMiddleware
-
-Kann von `fastapi` importiert werden:
-
-```python
-from fastapi.middleware.httpsredirect import HTTPSRedirectMiddleware
-```
-
-::: fastapi.middleware.trustedhost.TrustedHostMiddleware
-
-Kann von `fastapi` importiert werden:
-
-```python
-from fastapi.middleware.trustedhost import TrustedHostMiddleware
-```
-
-::: fastapi.middleware.wsgi.WSGIMiddleware
-
-Kann von `fastapi` importiert werden:
-
-```python
-from fastapi.middleware.wsgi import WSGIMiddleware
-```
diff --git a/docs/de/docs/reference/openapi/docs.md b/docs/de/docs/reference/openapi/docs.md
deleted file mode 100644
index 3c19ba917..000000000
--- a/docs/de/docs/reference/openapi/docs.md
+++ /dev/null
@@ -1,11 +0,0 @@
-# OpenAPI `docs`
-
-Werkzeuge zur Verwaltung der automatischen OpenAPI-UI-Dokumentation, einschließlich Swagger UI (standardmäßig unter `/docs`) und ReDoc (standardmäßig unter `/redoc`).
-
-::: fastapi.openapi.docs.get_swagger_ui_html
-
-::: fastapi.openapi.docs.get_redoc_html
-
-::: fastapi.openapi.docs.get_swagger_ui_oauth2_redirect_html
-
-::: fastapi.openapi.docs.swagger_ui_default_parameters
diff --git a/docs/de/docs/reference/openapi/index.md b/docs/de/docs/reference/openapi/index.md
deleted file mode 100644
index 0ae3d67c6..000000000
--- a/docs/de/docs/reference/openapi/index.md
+++ /dev/null
@@ -1,5 +0,0 @@
-# OpenAPI
-
-Es gibt mehrere Werkzeuge zur Handhabung von OpenAPI.
-
-Normalerweise müssen Sie diese nicht verwenden, es sei denn, Sie haben einen bestimmten fortgeschrittenen Anwendungsfall, welcher das erfordert.
diff --git a/docs/de/docs/reference/openapi/models.md b/docs/de/docs/reference/openapi/models.md
deleted file mode 100644
index 64306b15f..000000000
--- a/docs/de/docs/reference/openapi/models.md
+++ /dev/null
@@ -1,5 +0,0 @@
-# OpenAPI-`models`
-
-OpenAPI Pydantic-Modelle, werden zum Generieren und Validieren der generierten OpenAPI verwendet.
-
-::: fastapi.openapi.models
diff --git a/docs/de/docs/reference/parameters.md b/docs/de/docs/reference/parameters.md
deleted file mode 100644
index 2638eaf48..000000000
--- a/docs/de/docs/reference/parameters.md
+++ /dev/null
@@ -1,35 +0,0 @@
-# Request-Parameter
-
-Hier die Referenzinformationen für die Request-Parameter.
-
-Dies sind die Sonderfunktionen, die Sie mittels `Annotated` in *Pfadoperation-Funktion*-Parameter oder Abhängigkeitsfunktionen einfügen können, um Daten aus dem Request abzurufen.
-
-Dies beinhaltet:
-
-* `Query()`
-* `Path()`
-* `Body()`
-* `Cookie()`
-* `Header()`
-* `Form()`
-* `File()`
-
-Sie können diese alle direkt von `fastapi` importieren:
-
-```python
-from fastapi import Body, Cookie, File, Form, Header, Path, Query
-```
-
-::: fastapi.Query
-
-::: fastapi.Path
-
-::: fastapi.Body
-
-::: fastapi.Cookie
-
-::: fastapi.Header
-
-::: fastapi.Form
-
-::: fastapi.File
diff --git a/docs/de/docs/reference/request.md b/docs/de/docs/reference/request.md
deleted file mode 100644
index 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/response.md b/docs/de/docs/reference/response.md
deleted file mode 100644
index 215918931..000000000
--- a/docs/de/docs/reference/response.md
+++ /dev/null
@@ -1,13 +0,0 @@
-# `Response`-Klasse
-
-Sie können einen Parameter in einer *Pfadoperation-Funktion* oder einer Abhängigkeit als `Response` deklarieren und dann Daten für die Response wie Header oder Cookies festlegen.
-
-Diese können Sie auch direkt verwenden, um eine Instanz davon zu erstellen und diese von Ihren *Pfadoperationen* zurückzugeben.
-
-Sie können sie direkt von `fastapi` importieren:
-
-```python
-from fastapi import Response
-```
-
-::: fastapi.Response
diff --git a/docs/de/docs/reference/responses.md b/docs/de/docs/reference/responses.md
deleted file mode 100644
index c0e9f07e7..000000000
--- a/docs/de/docs/reference/responses.md
+++ /dev/null
@@ -1,164 +0,0 @@
-# Benutzerdefinierte Responseklassen – File, HTML, Redirect, Streaming, usw.
-
-Es gibt mehrere benutzerdefinierte Responseklassen, von denen Sie eine Instanz erstellen und diese direkt von Ihren *Pfadoperationen* zurückgeben können.
-
-Lesen Sie mehr darüber in der [FastAPI-Dokumentation zu benutzerdefinierten Responses – HTML, Stream, Datei, andere](../advanced/custom-response.md).
-
-Sie können diese direkt von `fastapi.responses` importieren:
-
-```python
-from fastapi.responses import (
- FileResponse,
- HTMLResponse,
- JSONResponse,
- ORJSONResponse,
- PlainTextResponse,
- RedirectResponse,
- Response,
- StreamingResponse,
- UJSONResponse,
-)
-```
-
-## FastAPI-Responses
-
-Es gibt einige benutzerdefinierte FastAPI-Responseklassen, welche Sie verwenden können, um die JSON-Performanz zu optimieren.
-
-::: fastapi.responses.UJSONResponse
- options:
- members:
- - charset
- - status_code
- - media_type
- - body
- - background
- - raw_headers
- - render
- - init_headers
- - headers
- - set_cookie
- - delete_cookie
-
-::: fastapi.responses.ORJSONResponse
- options:
- members:
- - charset
- - status_code
- - media_type
- - body
- - background
- - raw_headers
- - render
- - init_headers
- - headers
- - set_cookie
- - delete_cookie
-
-## Starlette-Responses
-
-::: fastapi.responses.FileResponse
- options:
- members:
- - chunk_size
- - charset
- - status_code
- - media_type
- - body
- - background
- - raw_headers
- - render
- - init_headers
- - headers
- - set_cookie
- - delete_cookie
-
-::: fastapi.responses.HTMLResponse
- options:
- members:
- - charset
- - status_code
- - media_type
- - body
- - background
- - raw_headers
- - render
- - init_headers
- - headers
- - set_cookie
- - delete_cookie
-
-::: fastapi.responses.JSONResponse
- options:
- members:
- - charset
- - status_code
- - media_type
- - body
- - background
- - raw_headers
- - render
- - init_headers
- - headers
- - set_cookie
- - delete_cookie
-
-::: fastapi.responses.PlainTextResponse
- options:
- members:
- - charset
- - status_code
- - media_type
- - body
- - background
- - raw_headers
- - render
- - init_headers
- - headers
- - set_cookie
- - delete_cookie
-
-::: fastapi.responses.RedirectResponse
- options:
- members:
- - charset
- - status_code
- - media_type
- - body
- - background
- - raw_headers
- - render
- - init_headers
- - headers
- - set_cookie
- - delete_cookie
-
-::: fastapi.responses.Response
- options:
- members:
- - charset
- - status_code
- - media_type
- - body
- - background
- - raw_headers
- - render
- - init_headers
- - headers
- - set_cookie
- - delete_cookie
-
-::: fastapi.responses.StreamingResponse
- options:
- members:
- - body_iterator
- - charset
- - status_code
- - media_type
- - body
- - background
- - raw_headers
- - render
- - init_headers
- - headers
- - set_cookie
- - delete_cookie
diff --git a/docs/de/docs/reference/security/index.md b/docs/de/docs/reference/security/index.md
deleted file mode 100644
index 4c2375f2f..000000000
--- a/docs/de/docs/reference/security/index.md
+++ /dev/null
@@ -1,73 +0,0 @@
-# Sicherheitstools
-
-Wenn Sie Abhängigkeiten mit OAuth2-Scopes deklarieren müssen, verwenden Sie `Security()`.
-
-Aber Sie müssen immer noch definieren, was das Dependable, das Callable ist, welches Sie als Parameter an `Depends()` oder `Security()` übergeben.
-
-Es gibt mehrere Tools, mit denen Sie diese Dependables erstellen können, und sie werden in OpenAPI integriert, sodass sie in der Oberfläche der automatischen Dokumentation angezeigt werden und von automatisch generierten Clients und SDKs, usw., verwendet werden können.
-
-Sie können sie von `fastapi.security` importieren:
-
-```python
-from fastapi.security import (
- APIKeyCookie,
- APIKeyHeader,
- APIKeyQuery,
- HTTPAuthorizationCredentials,
- HTTPBasic,
- HTTPBasicCredentials,
- HTTPBearer,
- HTTPDigest,
- OAuth2,
- OAuth2AuthorizationCodeBearer,
- OAuth2PasswordBearer,
- OAuth2PasswordRequestForm,
- OAuth2PasswordRequestFormStrict,
- OpenIdConnect,
- SecurityScopes,
-)
-```
-
-## API-Schlüssel-Sicherheitsschemas
-
-::: fastapi.security.APIKeyCookie
-
-::: fastapi.security.APIKeyHeader
-
-::: fastapi.security.APIKeyQuery
-
-## HTTP-Authentifizierungsschemas
-
-::: fastapi.security.HTTPBasic
-
-::: fastapi.security.HTTPBearer
-
-::: fastapi.security.HTTPDigest
-
-## HTTP-Anmeldeinformationen
-
-::: fastapi.security.HTTPAuthorizationCredentials
-
-::: fastapi.security.HTTPBasicCredentials
-
-## OAuth2-Authentifizierung
-
-::: fastapi.security.OAuth2
-
-::: fastapi.security.OAuth2AuthorizationCodeBearer
-
-::: fastapi.security.OAuth2PasswordBearer
-
-## OAuth2-Passwortformulare
-
-::: fastapi.security.OAuth2PasswordRequestForm
-
-::: fastapi.security.OAuth2PasswordRequestFormStrict
-
-## OAuth2-Sicherheitsscopes in Abhängigkeiten
-
-::: fastapi.security.SecurityScopes
-
-## OpenID Connect
-
-::: fastapi.security.OpenIdConnect
diff --git a/docs/de/docs/reference/staticfiles.md b/docs/de/docs/reference/staticfiles.md
deleted file mode 100644
index 5629854c6..000000000
--- a/docs/de/docs/reference/staticfiles.md
+++ /dev/null
@@ -1,13 +0,0 @@
-# Statische Dateien – `StaticFiles`
-
-Sie können die `StaticFiles`-Klasse verwenden, um statische Dateien wie JavaScript, CSS, Bilder, usw. bereitzustellen.
-
-Lesen Sie mehr darüber in der [FastAPI-Dokumentation zu statischen Dateien](../tutorial/static-files.md).
-
-Sie können sie direkt von `fastapi.staticfiles` importieren:
-
-```python
-from fastapi.staticfiles import StaticFiles
-```
-
-::: fastapi.staticfiles.StaticFiles
diff --git a/docs/de/docs/reference/status.md b/docs/de/docs/reference/status.md
deleted file mode 100644
index 1d9458ee9..000000000
--- a/docs/de/docs/reference/status.md
+++ /dev/null
@@ -1,36 +0,0 @@
-# Statuscodes
-
-Sie können das Modul `status` von `fastapi` importieren:
-
-```python
-from fastapi import status
-```
-
-`status` wird direkt von Starlette bereitgestellt.
-
-Es enthält eine Gruppe benannter Konstanten (Variablen) mit ganzzahligen Statuscodes.
-
-Zum Beispiel:
-
-* 200: `status.HTTP_200_OK`
-* 403: `status.HTTP_403_FORBIDDEN`
-* usw.
-
-Es kann praktisch sein, schnell auf HTTP- (und WebSocket-)Statuscodes in Ihrer Anwendung zuzugreifen, indem Sie die automatische Vervollständigung für den Namen verwenden, ohne sich die Zahlen für die Statuscodes merken zu müssen.
-
-Lesen Sie mehr darüber in der [FastAPI-Dokumentation zu Response-Statuscodes](../tutorial/response-status-code.md).
-
-## Beispiel
-
-```python
-from fastapi import FastAPI, status
-
-app = FastAPI()
-
-
-@app.get("/items/", status_code=status.HTTP_418_IM_A_TEAPOT)
-def read_items():
- return [{"name": "Plumbus"}, {"name": "Portal Gun"}]
-```
-
-::: fastapi.status
diff --git a/docs/de/docs/reference/templating.md b/docs/de/docs/reference/templating.md
deleted file mode 100644
index c367a0179..000000000
--- a/docs/de/docs/reference/templating.md
+++ /dev/null
@@ -1,13 +0,0 @@
-# Templating – `Jinja2Templates`
-
-Sie können die `Jinja2Templates`-Klasse verwenden, um Jinja-Templates zu rendern.
-
-Lesen Sie mehr darüber in der [FastAPI-Dokumentation zu Templates](../advanced/templates.md).
-
-Sie können die Klasse direkt von `fastapi.templating` importieren:
-
-```python
-from fastapi.templating import Jinja2Templates
-```
-
-::: fastapi.templating.Jinja2Templates
diff --git a/docs/de/docs/reference/testclient.md b/docs/de/docs/reference/testclient.md
deleted file mode 100644
index 5bc089c05..000000000
--- a/docs/de/docs/reference/testclient.md
+++ /dev/null
@@ -1,13 +0,0 @@
-# Testclient – `TestClient`
-
-Sie können die `TestClient`-Klasse verwenden, um FastAPI-Anwendungen zu testen, ohne eine tatsächliche HTTP- und Socket-Verbindung zu erstellen, Sie kommunizieren einfach direkt mit dem FastAPI-Code.
-
-Lesen Sie mehr darüber in der [FastAPI-Dokumentation über Testen](../tutorial/testing.md).
-
-Sie können sie direkt von `fastapi.testclient` importieren:
-
-```python
-from fastapi.testclient import TestClient
-```
-
-::: fastapi.testclient.TestClient
diff --git a/docs/de/docs/reference/uploadfile.md b/docs/de/docs/reference/uploadfile.md
deleted file mode 100644
index 8556edf82..000000000
--- a/docs/de/docs/reference/uploadfile.md
+++ /dev/null
@@ -1,22 +0,0 @@
-# `UploadFile`-Klasse
-
-Sie können *Pfadoperation-Funktionsparameter* als Parameter vom Typ `UploadFile` definieren, um Dateien aus dem Request zu erhalten.
-
-Sie können es direkt von `fastapi` importieren:
-
-```python
-from fastapi import UploadFile
-```
-
-::: fastapi.UploadFile
- options:
- members:
- - file
- - filename
- - size
- - headers
- - content_type
- - read
- - write
- - seek
- - close
diff --git a/docs/de/docs/reference/websockets.md b/docs/de/docs/reference/websockets.md
deleted file mode 100644
index 35657172c..000000000
--- a/docs/de/docs/reference/websockets.md
+++ /dev/null
@@ -1,64 +0,0 @@
-# WebSockets
-
-Bei der Definition von WebSockets deklarieren Sie normalerweise einen Parameter vom Typ `WebSocket` und können damit Daten vom Client lesen und an ihn senden. Er wird direkt von Starlette bereitgestellt, Sie können ihn aber von `fastapi` importieren:
-
-```python
-from fastapi import WebSocket
-```
-
-!!! tip "Tipp"
- Wenn Sie Abhängigkeiten definieren möchten, die sowohl mit HTTP als auch mit WebSockets kompatibel sein sollen, können Sie einen Parameter definieren, der eine `HTTPConnection` anstelle eines `Request` oder eines `WebSocket` akzeptiert.
-
-::: fastapi.WebSocket
- options:
- members:
- - scope
- - app
- - url
- - base_url
- - headers
- - query_params
- - path_params
- - cookies
- - client
- - state
- - url_for
- - client_state
- - application_state
- - receive
- - send
- - accept
- - receive_text
- - receive_bytes
- - receive_json
- - iter_text
- - iter_bytes
- - iter_json
- - send_text
- - send_bytes
- - send_json
- - close
-
-Wenn ein Client die Verbindung trennt, wird eine `WebSocketDisconnect`-Exception ausgelöst, die Sie abfangen können.
-
-Sie können diese direkt von `fastapi` importieren:
-
-```python
-from fastapi import WebSocketDisconnect
-```
-
-::: fastapi.WebSocketDisconnect
-
-## WebSockets – zusätzliche Klassen
-
-Zusätzliche Klassen für die Handhabung von WebSockets.
-
-Werden direkt von Starlette bereitgestellt, Sie können sie jedoch von `fastapi` importieren:
-
-```python
-from fastapi.websockets import WebSocketDisconnect, WebSocketState
-```
-
-::: fastapi.websockets.WebSocketDisconnect
-
-::: fastapi.websockets.WebSocketState
diff --git a/docs/de/docs/tutorial/background-tasks.md b/docs/de/docs/tutorial/background-tasks.md
index a7bfd55a7..05779e12c 100644
--- a/docs/de/docs/tutorial/background-tasks.md
+++ b/docs/de/docs/tutorial/background-tasks.md
@@ -15,9 +15,7 @@ Hierzu zählen beispielsweise:
Importieren Sie zunächst `BackgroundTasks` und definieren Sie einen Parameter in Ihrer *Pfadoperation-Funktion* mit der Typdeklaration `BackgroundTasks`:
-```Python hl_lines="1 13"
-{!../../../docs_src/background_tasks/tutorial001.py!}
-```
+{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *}
**FastAPI** erstellt für Sie das Objekt vom Typ `BackgroundTasks` und übergibt es als diesen Parameter.
@@ -33,17 +31,13 @@ In diesem Fall schreibt die Taskfunktion in eine Datei (den Versand einer E-Mail
Und da der Schreibvorgang nicht `async` und `await` verwendet, definieren wir die Funktion mit normalem `def`:
-```Python hl_lines="6-9"
-{!../../../docs_src/background_tasks/tutorial001.py!}
-```
+{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *}
## Den Hintergrundtask hinzufügen
Übergeben Sie innerhalb Ihrer *Pfadoperation-Funktion* Ihre Taskfunktion mit der Methode `.add_task()` an das *Hintergrundtasks*-Objekt:
-```Python hl_lines="14"
-{!../../../docs_src/background_tasks/tutorial001.py!}
-```
+{* ../../docs_src/background_tasks/tutorial001.py hl[14] *}
`.add_task()` erhält als Argumente:
@@ -57,41 +51,7 @@ Die Verwendung von `BackgroundTasks` funktioniert auch mit dem ../../../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!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="14 16 23 26"
- {!> ../../../docs_src/background_tasks/tutorial002_an.py!}
- ```
-
-=== "Python 3.10+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="11 13 20 23"
- {!> ../../../docs_src/background_tasks/tutorial002_py310.py!}
- ```
-
-=== "Python 3.8+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="13 15 22 25"
- {!> ../../../docs_src/background_tasks/tutorial002.py!}
- ```
+{* ../../docs_src/background_tasks/tutorial002_an_py310.py hl[13,15,22,25] *}
In obigem Beispiel werden die Nachrichten, *nachdem* die Response gesendet wurde, in die Datei `log.txt` geschrieben.
@@ -117,8 +77,6 @@ Wenn Sie umfangreiche Hintergrundberechnungen durchführen müssen und diese nic
Sie erfordern in der Regel komplexere Konfigurationen und einen Nachrichten-/Job-Queue-Manager wie RabbitMQ oder Redis, ermöglichen Ihnen jedoch die Ausführung von Hintergrundtasks in mehreren Prozessen und insbesondere auf mehreren Servern.
-Um ein Beispiel zu sehen, sehen Sie sich die [Projektgeneratoren](../project-generation.md){.internal-link target=_blank} an. Sie alle enthalten Celery, bereits konfiguriert.
-
Wenn Sie jedoch über dieselbe **FastAPI**-Anwendung auf Variablen und Objekte zugreifen oder kleine Hintergrundtasks ausführen müssen (z. B. das Senden einer E-Mail-Benachrichtigung), können Sie einfach `BackgroundTasks` verwenden.
## Zusammenfassung
diff --git a/docs/de/docs/tutorial/bigger-applications.md b/docs/de/docs/tutorial/bigger-applications.md
index 66dee0a9a..514e3fd3a 100644
--- a/docs/de/docs/tutorial/bigger-applications.md
+++ b/docs/de/docs/tutorial/bigger-applications.md
@@ -4,8 +4,11 @@ Wenn Sie eine Anwendung oder eine Web-API erstellen, ist es selten der Fall, das
**FastAPI** bietet ein praktisches Werkzeug zur Strukturierung Ihrer Anwendung bei gleichzeitiger Wahrung der Flexibilität.
-!!! info
- Wenn Sie von Flask kommen, wäre dies das Äquivalent zu Flasks Blueprints.
+/// info
+
+Wenn Sie von Flask kommen, wäre dies das Äquivalent zu Flasks Blueprints.
+
+///
## Eine Beispiel-Dateistruktur
@@ -26,16 +29,19 @@ Nehmen wir an, Sie haben eine Dateistruktur wie diese:
│ └── admin.py
```
-!!! tip "Tipp"
- Es gibt mehrere `__init__.py`-Dateien: eine in jedem Verzeichnis oder Unterverzeichnis.
+/// tip | Tipp
+
+Es gibt mehrere `__init__.py`-Dateien: eine in jedem Verzeichnis oder Unterverzeichnis.
- Das ermöglicht den Import von Code aus einer Datei in eine andere.
+Das ermöglicht den Import von Code aus einer Datei in eine andere.
- In `app/main.py` könnten Sie beispielsweise eine Zeile wie diese haben:
+In `app/main.py` könnten Sie beispielsweise eine Zeile wie diese haben:
+
+```
+from app.routers import items
+```
- ```
- from app.routers import items
- ```
+///
* Das Verzeichnis `app` enthält alles. Und es hat eine leere Datei `app/__init__.py`, es handelt sich also um ein „Python-Package“ (eine Sammlung von „Python-Modulen“): `app`.
* Es enthält eine Datei `app/main.py`. Da sie sich in einem Python-Package (einem Verzeichnis mit einer Datei `__init__.py`) befindet, ist sie ein „Modul“ dieses Packages: `app.main`.
@@ -46,7 +52,7 @@ Nehmen wir an, Sie haben eine Dateistruktur wie diese:
* 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`.
-
+
Die gleiche Dateistruktur mit Kommentaren:
@@ -80,7 +86,7 @@ Sie können die *Pfadoperationen* für dieses Modul mit `APIRouter` erstellen.
Sie importieren ihn und erstellen eine „Instanz“ auf die gleiche Weise wie mit der Klasse `FastAPI`:
```Python hl_lines="1 3" title="app/routers/users.py"
-{!../../../docs_src/bigger_applications/app/routers/users.py!}
+{!../../docs_src/bigger_applications/app/routers/users.py!}
```
### *Pfadoperationen* mit `APIRouter`
@@ -90,7 +96,7 @@ Und dann verwenden Sie ihn, um Ihre *Pfadoperationen* zu deklarieren.
Verwenden Sie ihn auf die gleiche Weise wie die Klasse `FastAPI`:
```Python hl_lines="6 11 16" title="app/routers/users.py"
-{!../../../docs_src/bigger_applications/app/routers/users.py!}
+{!../../docs_src/bigger_applications/app/routers/users.py!}
```
Sie können sich `APIRouter` als eine „Mini-`FastAPI`“-Klasse vorstellen.
@@ -99,8 +105,11 @@ Alle die gleichen Optionen werden unterstützt.
Alle die gleichen `parameters`, `responses`, `dependencies`, `tags`, usw.
-!!! tip "Tipp"
- In diesem Beispiel heißt die Variable `router`, aber Sie können ihr einen beliebigen Namen geben.
+/// tip | Tipp
+
+In diesem Beispiel heißt die Variable `router`, aber Sie können ihr einen beliebigen Namen geben.
+
+///
Wir werden diesen `APIRouter` in die Hauptanwendung `FastAPI` einbinden, aber zuerst kümmern wir uns um die Abhängigkeiten und einen anderen `APIRouter`.
@@ -112,31 +121,43 @@ Also fügen wir sie in ihr eigenes `dependencies`-Modul (`app/dependencies.py`)
Wir werden nun eine einfache Abhängigkeit verwenden, um einen benutzerdefinierten `X-Token`-Header zu lesen:
-=== "Python 3.9+"
+//// tab | Python 3.9+
+
+```Python hl_lines="3 6-8" title="app/dependencies.py"
+{!> ../../docs_src/bigger_applications/app_an_py39/dependencies.py!}
+```
- ```Python hl_lines="3 6-8" title="app/dependencies.py"
- {!> ../../../docs_src/bigger_applications/app_an_py39/dependencies.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="1 5-7" title="app/dependencies.py"
- {!> ../../../docs_src/bigger_applications/app_an/dependencies.py!}
- ```
+```Python hl_lines="1 5-7" title="app/dependencies.py"
+{!> ../../docs_src/bigger_applications/app_an/dependencies.py!}
+```
-=== "Python 3.8+ nicht annotiert"
+////
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+//// tab | Python 3.8+ nicht annotiert
- ```Python hl_lines="1 4-6" title="app/dependencies.py"
- {!> ../../../docs_src/bigger_applications/app/dependencies.py!}
- ```
+/// tip | Tipp
-!!! tip "Tipp"
- Um dieses Beispiel zu vereinfachen, verwenden wir einen erfundenen Header.
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- Aber in der Praxis werden Sie mit den integrierten [Sicherheits-Werkzeugen](security/index.md){.internal-link target=_blank} bessere Ergebnisse erzielen.
+///
+
+```Python hl_lines="1 4-6" title="app/dependencies.py"
+{!> ../../docs_src/bigger_applications/app/dependencies.py!}
+```
+
+////
+
+/// tip | Tipp
+
+Um dieses Beispiel zu vereinfachen, verwenden wir einen erfundenen Header.
+
+Aber in der Praxis werden Sie mit den integrierten [Sicherheits-Werkzeugen](security/index.md){.internal-link target=_blank} bessere Ergebnisse erzielen.
+
+///
## Ein weiteres Modul mit `APIRouter`.
@@ -161,7 +182,7 @@ Wir wissen, dass alle *Pfadoperationen* in diesem Modul folgendes haben:
Anstatt also alles zu jeder *Pfadoperation* hinzuzufügen, können wir es dem `APIRouter` hinzufügen.
```Python hl_lines="5-10 16 21" title="app/routers/items.py"
-{!../../../docs_src/bigger_applications/app/routers/items.py!}
+{!../../docs_src/bigger_applications/app/routers/items.py!}
```
Da der Pfad jeder *Pfadoperation* mit `/` beginnen muss, wie in:
@@ -180,8 +201,11 @@ Wir können auch eine Liste von `tags` und zusätzliche `responses` hinzufügen,
Und wir können eine Liste von `dependencies` hinzufügen, die allen *Pfadoperationen* im Router hinzugefügt und für jeden an sie gerichteten Request ausgeführt/aufgelöst werden.
-!!! tip "Tipp"
- Beachten Sie, dass ähnlich wie bei [Abhängigkeiten in *Pfadoperation-Dekoratoren*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank} kein Wert an Ihre *Pfadoperation-Funktion* übergeben wird.
+/// tip | Tipp
+
+Beachten Sie, dass ähnlich wie bei [Abhängigkeiten in *Pfadoperation-Dekoratoren*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank} kein Wert an Ihre *Pfadoperation-Funktion* übergeben wird.
+
+///
Das Endergebnis ist, dass die Pfade für diese Artikel jetzt wie folgt lauten:
@@ -198,11 +222,17 @@ Das Endergebnis ist, dass die Pfade für diese Artikel jetzt wie folgt lauten:
* Zuerst werden die Router-Abhängigkeiten ausgeführt, dann die [`dependencies` im Dekorator](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank} und dann die normalen Parameterabhängigkeiten.
* Sie können auch [`Security`-Abhängigkeiten mit `scopes`](../advanced/security/oauth2-scopes.md){.internal-link target=_blank} hinzufügen.
-!!! tip "Tipp"
- `dependencies` im `APIRouter` können beispielsweise verwendet werden, um eine Authentifizierung für eine ganze Gruppe von *Pfadoperationen* zu erfordern. Selbst wenn die Abhängigkeiten nicht jeder einzeln hinzugefügt werden.
+/// tip | Tipp
+
+`dependencies` im `APIRouter` können beispielsweise verwendet werden, um eine Authentifizierung für eine ganze Gruppe von *Pfadoperationen* zu erfordern. Selbst wenn die Abhängigkeiten nicht jeder einzeln hinzugefügt werden.
+
+///
+
+/// check
-!!! check
- Die Parameter `prefix`, `tags`, `responses` und `dependencies` sind (wie in vielen anderen Fällen) nur ein Feature von **FastAPI**, um Ihnen dabei zu helfen, Codeverdoppelung zu vermeiden.
+Die Parameter `prefix`, `tags`, `responses` und `dependencies` sind (wie in vielen anderen Fällen) nur ein Feature von **FastAPI**, um Ihnen dabei zu helfen, Codeverdoppelung zu vermeiden.
+
+///
### Die Abhängigkeiten importieren
@@ -213,13 +243,16 @@ Und wir müssen die Abhängigkeitsfunktion aus dem Modul `app.dependencies` impo
Daher verwenden wir einen relativen Import mit `..` für die Abhängigkeiten:
```Python hl_lines="3" title="app/routers/items.py"
-{!../../../docs_src/bigger_applications/app/routers/items.py!}
+{!../../docs_src/bigger_applications/app/routers/items.py!}
```
#### Wie relative Importe funktionieren
-!!! tip "Tipp"
- Wenn Sie genau wissen, wie Importe funktionieren, fahren Sie mit dem nächsten Abschnitt unten fort.
+/// tip | Tipp
+
+Wenn Sie genau wissen, wie Importe funktionieren, fahren Sie mit dem nächsten Abschnitt unten fort.
+
+///
Ein einzelner Punkt `.`, wie in:
@@ -237,7 +270,7 @@ Aber diese Datei existiert nicht, unsere Abhängigkeiten befinden sich in einer
Erinnern Sie sich, wie unsere Anwendungs-/Dateistruktur aussieht:
-
+
---
@@ -283,13 +316,16 @@ Wir fügen weder das Präfix `/items` noch `tags=["items"]` zu jeder *Pfadoperat
Aber wir können immer noch _mehr_ `tags` hinzufügen, die auf eine bestimmte *Pfadoperation* angewendet werden, sowie einige zusätzliche `responses`, die speziell für diese *Pfadoperation* gelten:
```Python hl_lines="30-31" title="app/routers/items.py"
-{!../../../docs_src/bigger_applications/app/routers/items.py!}
+{!../../docs_src/bigger_applications/app/routers/items.py!}
```
-!!! tip "Tipp"
- Diese letzte Pfadoperation wird eine Kombination von Tags haben: `["items", "custom"]`.
+/// tip | Tipp
- Und sie wird auch beide Responses in der Dokumentation haben, eine für `404` und eine für `403`.
+Diese letzte Pfadoperation wird eine Kombination von Tags haben: `["items", "custom"]`.
+
+Und sie wird auch beide Responses in der Dokumentation haben, eine für `404` und eine für `403`.
+
+///
## Das Haupt-`FastAPI`.
@@ -308,7 +344,7 @@ Sie importieren und erstellen wie gewohnt eine `FastAPI`-Klasse.
Und wir können sogar [globale Abhängigkeiten](dependencies/global-dependencies.md){.internal-link target=_blank} deklarieren, die mit den Abhängigkeiten für jeden `APIRouter` kombiniert werden:
```Python hl_lines="1 3 7" title="app/main.py"
-{!../../../docs_src/bigger_applications/app/main.py!}
+{!../../docs_src/bigger_applications/app/main.py!}
```
### Den `APIRouter` importieren
@@ -316,7 +352,7 @@ Und wir können sogar [globale Abhängigkeiten](dependencies/global-dependencies
Jetzt importieren wir die anderen Submodule, die `APIRouter` haben:
```Python hl_lines="4-5" title="app/main.py"
-{!../../../docs_src/bigger_applications/app/main.py!}
+{!../../docs_src/bigger_applications/app/main.py!}
```
Da es sich bei den Dateien `app/routers/users.py` und `app/routers/items.py` um Submodule handelt, die Teil desselben Python-Packages `app` sind, können wir einen einzelnen Punkt `.` verwenden, um sie mit „relativen Imports“ zu importieren.
@@ -345,20 +381,23 @@ Wir könnten sie auch wie folgt importieren:
from app.routers import items, users
```
-!!! info
- Die erste Version ist ein „relativer Import“:
+/// info
- ```Python
- from .routers import items, users
- ```
+Die erste Version ist ein „relativer Import“:
- Die zweite Version ist ein „absoluter Import“:
+```Python
+from .routers import items, users
+```
+
+Die zweite Version ist ein „absoluter Import“:
+
+```Python
+from app.routers import items, users
+```
- ```Python
- from app.routers import items, users
- ```
+Um mehr über Python-Packages und -Module zu erfahren, lesen Sie die offizielle Python-Dokumentation über Module.
- Um mehr über Python-Packages und -Module zu erfahren, lesen Sie die offizielle Python-Dokumentation über Module.
+///
### Namenskollisionen vermeiden
@@ -378,7 +417,7 @@ würde der `router` von `users` den von `items` überschreiben und wir könnten
Um also beide in derselben Datei verwenden zu können, importieren wir die Submodule direkt:
```Python hl_lines="5" title="app/main.py"
-{!../../../docs_src/bigger_applications/app/main.py!}
+{!../../docs_src/bigger_applications/app/main.py!}
```
@@ -387,29 +426,38 @@ Um also beide in derselben Datei verwenden zu können, importieren wir die Submo
Inkludieren wir nun die `router` aus diesen Submodulen `users` und `items`:
```Python hl_lines="10-11" title="app/main.py"
-{!../../../docs_src/bigger_applications/app/main.py!}
+{!../../docs_src/bigger_applications/app/main.py!}
```
-!!! info
- `users.router` enthält den `APIRouter` in der Datei `app/routers/users.py`.
+/// info
+
+`users.router` enthält den `APIRouter` in der Datei `app/routers/users.py`.
- Und `items.router` enthält den `APIRouter` in der Datei `app/routers/items.py`.
+Und `items.router` enthält den `APIRouter` in der Datei `app/routers/items.py`.
+
+///
Mit `app.include_router()` können wir jeden `APIRouter` zur Hauptanwendung `FastAPI` hinzufügen.
Es wird alle Routen von diesem Router als Teil von dieser inkludieren.
-!!! note "Technische Details"
- Tatsächlich wird intern eine *Pfadoperation* für jede *Pfadoperation* erstellt, die im `APIRouter` deklariert wurde.
+/// note | Technische Details
+
+Tatsächlich wird intern eine *Pfadoperation* für jede *Pfadoperation* erstellt, die im `APIRouter` deklariert wurde.
+
+Hinter den Kulissen wird es also tatsächlich so funktionieren, als ob alles dieselbe einzige Anwendung wäre.
- Hinter den Kulissen wird es also tatsächlich so funktionieren, als ob alles dieselbe einzige Anwendung wäre.
+///
-!!! check
- Bei der Einbindung von Routern müssen Sie sich keine Gedanken über die Performanz machen.
+/// check
- Dies dauert Mikrosekunden und geschieht nur beim Start.
+Bei der Einbindung von Routern müssen Sie sich keine Gedanken über die Performanz machen.
- Es hat also keinen Einfluss auf die Leistung. ⚡
+Dies dauert Mikrosekunden und geschieht nur beim Start.
+
+Es hat also keinen Einfluss auf die Leistung. ⚡
+
+///
### Einen `APIRouter` mit benutzerdefinierten `prefix`, `tags`, `responses` und `dependencies` einfügen
@@ -420,7 +468,7 @@ Sie enthält einen `APIRouter` mit einigen administrativen *Pfadoperationen*, di
In diesem Beispiel wird es ganz einfach sein. Nehmen wir jedoch an, dass wir, da sie mit anderen Projekten in der Organisation geteilt wird, sie nicht ändern und kein `prefix`, `dependencies`, `tags`, usw. direkt zum `APIRouter` hinzufügen können:
```Python hl_lines="3" title="app/internal/admin.py"
-{!../../../docs_src/bigger_applications/app/internal/admin.py!}
+{!../../docs_src/bigger_applications/app/internal/admin.py!}
```
Aber wir möchten immer noch ein benutzerdefiniertes `prefix` festlegen, wenn wir den `APIRouter` einbinden, sodass alle seine *Pfadoperationen* mit `/admin` beginnen, wir möchten es mit den `dependencies` sichern, die wir bereits für dieses Projekt haben, und wir möchten `tags` und `responses` hinzufügen.
@@ -428,7 +476,7 @@ Aber wir möchten immer noch ein benutzerdefiniertes `prefix` festlegen, wenn wi
Wir können das alles deklarieren, ohne den ursprünglichen `APIRouter` ändern zu müssen, indem wir diese Parameter an `app.include_router()` übergeben:
```Python hl_lines="14-17" title="app/main.py"
-{!../../../docs_src/bigger_applications/app/main.py!}
+{!../../docs_src/bigger_applications/app/main.py!}
```
Auf diese Weise bleibt der ursprüngliche `APIRouter` unverändert, sodass wir dieselbe `app/internal/admin.py`-Datei weiterhin mit anderen Projekten in der Organisation teilen können.
@@ -451,21 +499,24 @@ Wir können *Pfadoperationen* auch direkt zur `FastAPI`-App hinzufügen.
Hier machen wir es ... nur um zu zeigen, dass wir es können 🤷:
```Python hl_lines="21-23" title="app/main.py"
-{!../../../docs_src/bigger_applications/app/main.py!}
+{!../../docs_src/bigger_applications/app/main.py!}
```
und es wird korrekt funktionieren, zusammen mit allen anderen *Pfadoperationen*, die mit `app.include_router()` hinzugefügt wurden.
-!!! info "Sehr technische Details"
- **Hinweis**: Dies ist ein sehr technisches Detail, das Sie wahrscheinlich **einfach überspringen** können.
+/// info | Sehr technische Details
+
+**Hinweis**: Dies ist ein sehr technisches Detail, das Sie wahrscheinlich **einfach überspringen** können.
+
+---
- ---
+Die `APIRouter` sind nicht „gemountet“, sie sind nicht vom Rest der Anwendung isoliert.
- Die `APIRouter` sind nicht „gemountet“, sie sind nicht vom Rest der Anwendung isoliert.
+Das liegt daran, dass wir deren *Pfadoperationen* in das OpenAPI-Schema und die Benutzeroberflächen einbinden möchten.
- Das liegt daran, dass wir deren *Pfadoperationen* in das OpenAPI-Schema und die Benutzeroberflächen einbinden möchten.
+Da wir sie nicht einfach isolieren und unabhängig vom Rest „mounten“ können, werden die *Pfadoperationen* „geklont“ (neu erstellt) und nicht direkt einbezogen.
- Da wir sie nicht einfach isolieren und unabhängig vom Rest „mounten“ können, werden die *Pfadoperationen* „geklont“ (neu erstellt) und nicht direkt einbezogen.
+///
## Es in der automatischen API-Dokumentation ansehen
diff --git a/docs/de/docs/tutorial/body-fields.md b/docs/de/docs/tutorial/body-fields.md
index 643be7489..9fddfb1f0 100644
--- a/docs/de/docs/tutorial/body-fields.md
+++ b/docs/de/docs/tutorial/body-fields.md
@@ -6,98 +6,39 @@ So wie Sie zusätzliche Validation und Metadaten in Parametern der **Pfadoperati
Importieren Sie es zuerst:
-=== "Python 3.10+"
+{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[4] *}
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!}
- ```
+/// warning | Achtung
-=== "Python 3.9+"
+Beachten Sie, dass `Field` direkt von `pydantic` importiert wird, nicht von `fastapi`, wie die anderen (`Query`, `Path`, `Body`, usw.)
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001_an.py!}
- ```
-
-=== "Python 3.10+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="2"
- {!> ../../../docs_src/body_fields/tutorial001_py310.py!}
- ```
-
-=== "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+"
-
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!}
- ```
+{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[11:14] *}
-=== "Python 3.9+"
-
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="12-15"
- {!> ../../../docs_src/body_fields/tutorial001_an.py!}
- ```
-
-=== "Python 3.10+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="9-12"
- {!> ../../../docs_src/body_fields/tutorial001_py310.py!}
- ```
+`Field` funktioniert genauso wie `Query`, `Path` und `Body`, es hat die gleichen Parameter, usw.
-=== "Python 3.8+ nicht annotiert"
+/// note | Technische Details
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+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.
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001.py!}
- ```
+Und Pydantics `Field` gibt ebenfalls eine Instanz von `FieldInfo` zurück.
-`Field` funktioniert genauso wie `Query`, `Path` und `Body`, es hat die gleichen Parameter, usw.
+`Body` gibt auch Instanzen einer Unterklasse von `FieldInfo` zurück. Und später werden Sie andere sehen, die Unterklassen der `Body`-Klasse sind.
-!!! 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.
+Denken Sie daran, dass `Query`, `Path` und andere von `fastapi` tatsächlich Funktionen sind, die spezielle Klassen zurückgeben.
- Und Pydantics `Field` gibt ebenfalls eine Instanz von `FieldInfo` zurück.
+///
- `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
- Denken Sie daran, dass `Query`, `Path` und andere von `fastapi` tatsächlich Funktionen sind, die spezielle Klassen zurückgeben.
+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`.
-!!! 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 +46,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..8a9978d34 100644
--- a/docs/de/docs/tutorial/body-multiple-params.md
+++ b/docs/de/docs/tutorial/body-multiple-params.md
@@ -8,44 +8,13 @@ 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+"
+{* ../../docs_src/body_multiple_params/tutorial001_an_py310.py hl[18:20] *}
- ```Python hl_lines="18-20"
- {!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!}
- ```
+/// note | Hinweis
-=== "Python 3.9+"
+Beachten Sie, dass in diesem Fall das `item`, welches vom Body genommen wird, optional ist. Da es `None` als Defaultwert hat.
- ```Python hl_lines="18-20"
- {!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="19-21"
- {!> ../../../docs_src/body_multiple_params/tutorial001_an.py!}
- ```
-
-=== "Python 3.10+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="17-19"
- {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!}
- ```
-
-=== "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 +31,7 @@ Im vorherigen Beispiel erwartete die *Pfadoperation* einen JSON-Body mit den Att
Aber Sie können auch mehrere Body-Parameter deklarieren, z. B. `item` und `user`:
-=== "Python 3.10+"
-
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="22"
- {!> ../../../docs_src/body_multiple_params/tutorial002.py!}
- ```
+{* ../../docs_src/body_multiple_params/tutorial002_py310.py hl[20] *}
In diesem Fall wird **FastAPI** bemerken, dass es mehr als einen Body-Parameter in der Funktion gibt (zwei Parameter, die Pydantic-Modelle sind).
@@ -93,8 +52,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 +72,7 @@ Wenn Sie diesen Parameter einfach so hinzufügen, wird **FastAPI** annehmen, das
Aber Sie können **FastAPI** instruieren, ihn als weiteren Body-Schlüssel zu erkennen, indem Sie `Body` verwenden:
-=== "Python 3.10+"
-
- ```Python hl_lines="23"
- {!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="23"
- {!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="24"
- {!> ../../../docs_src/body_multiple_params/tutorial003_an.py!}
- ```
-
-=== "Python 3.10+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!}
- ```
-
-=== "Python 3.8+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="22"
- {!> ../../../docs_src/body_multiple_params/tutorial003.py!}
- ```
+{* ../../docs_src/body_multiple_params/tutorial003_an_py310.py hl[23] *}
In diesem Fall erwartet **FastAPI** einen Body wie:
@@ -184,44 +112,13 @@ q: str | None = None
Zum Beispiel:
-=== "Python 3.10+"
-
- ```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="28"
- {!> ../../../docs_src/body_multiple_params/tutorial004_an.py!}
- ```
-
-=== "Python 3.10+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="25"
- {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!}
- ```
-
-=== "Python 3.8+ nicht annotiert"
+{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[27] *}
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// info
- ```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004.py!}
- ```
+`Body` hat die gleichen zusätzlichen Validierungs- und Metadaten-Parameter wie `Query` und `Path` und andere, die Sie später kennenlernen.
-!!! info
- `Body` hat die gleichen zusätzlichen Validierungs- und Metadaten-Parameter wie `Query` und `Path` und andere, die Sie später kennenlernen.
+///
## Einen einzelnen Body-Parameter einbetten
@@ -237,41 +134,7 @@ item: Item = Body(embed=True)
so wie in:
-=== "Python 3.10+"
-
- ```Python hl_lines="17"
- {!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="17"
- {!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="18"
- {!> ../../../docs_src/body_multiple_params/tutorial005_an.py!}
- ```
-
-=== "Python 3.10+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="15"
- {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!}
- ```
-
-=== "Python 3.8+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="17"
- {!> ../../../docs_src/body_multiple_params/tutorial005.py!}
- ```
+{* ../../docs_src/body_multiple_params/tutorial005_an_py310.py hl[17] *}
In diesem Fall erwartet **FastAPI** einen Body wie:
diff --git a/docs/de/docs/tutorial/body-nested-models.md b/docs/de/docs/tutorial/body-nested-models.md
index a7a15a6c2..6287490c6 100644
--- a/docs/de/docs/tutorial/body-nested-models.md
+++ b/docs/de/docs/tutorial/body-nested-models.md
@@ -6,17 +6,7 @@ Mit **FastAPI** können Sie (dank Pydantic) beliebig tief verschachtelte Modelle
Sie können ein Attribut als Kindtyp definieren, zum Beispiel eine Python-`list`e.
-=== "Python 3.10+"
-
- ```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!}
- ```
+{* ../../docs_src/body_nested_models/tutorial001_py310.py hl[12] *}
Das bewirkt, dass `tags` eine Liste ist, wenngleich es nichts über den Typ der Elemente der Liste aussagt.
@@ -30,9 +20,7 @@ In Python 3.9 oder darüber können Sie einfach `list` verwenden, um diese Typan
In Python-Versionen vor 3.9 (3.6 und darüber), müssen Sie zuerst `List` von Pythons Standardmodul `typing` importieren.
-```Python hl_lines="1"
-{!> ../../../docs_src/body_nested_models/tutorial002.py!}
-```
+{* ../../docs_src/body_nested_models/tutorial002.py hl[1] *}
### Eine `list`e mit einem Typ-Parameter deklarieren
@@ -61,23 +49,7 @@ Verwenden Sie dieselbe Standardsyntax für Modellattribute mit inneren Typen.
In unserem Beispiel können wir also bewirken, dass `tags` spezifisch eine „Liste von Strings“ ist:
-=== "Python 3.10+"
-
- ```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!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial002.py!}
- ```
+{* ../../docs_src/body_nested_models/tutorial002_py310.py hl[12] *}
## Set-Typen
@@ -87,23 +59,7 @@ Python hat einen Datentyp speziell für Mengen eindeutiger Dinge: das ../../../docs_src/body_nested_models/tutorial003_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial003_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="1 14"
- {!> ../../../docs_src/body_nested_models/tutorial003.py!}
- ```
+{* ../../docs_src/body_nested_models/tutorial003_py310.py hl[12] *}
Jetzt, selbst wenn Sie einen Request mit duplizierten Daten erhalten, werden diese zu einem Set eindeutiger Dinge konvertiert.
@@ -125,45 +81,13 @@ Alles das beliebig tief verschachtelt.
Wir können zum Beispiel ein `Image`-Modell definieren.
-=== "Python 3.10+"
-
- ```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!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="9-11"
- {!> ../../../docs_src/body_nested_models/tutorial004.py!}
- ```
+{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[7:9] *}
### Das Kindmodell als Typ verwenden
Und dann können wir es als Typ eines Attributes verwenden.
-=== "Python 3.10+"
-
- ```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!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial004.py!}
- ```
+{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[18] *}
Das würde bedeuten, dass **FastAPI** einen Body erwartet wie:
@@ -196,23 +120,7 @@ Um alle Optionen kennenzulernen, die Sie haben, schauen Sie sich ../../../docs_src/body_nested_models/tutorial005_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="4 10"
- {!> ../../../docs_src/body_nested_models/tutorial005_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="4 10"
- {!> ../../../docs_src/body_nested_models/tutorial005.py!}
- ```
+{* ../../docs_src/body_nested_models/tutorial005_py310.py hl[2,8] *}
Es wird getestet, ob der String eine gültige URL ist, und als solche wird er in JSON Schema / OpenAPI dokumentiert.
@@ -220,23 +128,7 @@ Es wird getestet, ob der String eine gültige URL ist, und als solche wird er in
Sie können Pydantic-Modelle auch als Typen innerhalb von `list`, `set`, usw. verwenden:
-=== "Python 3.10+"
-
- ```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!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial006.py!}
- ```
+{* ../../docs_src/body_nested_models/tutorial006_py310.py hl[18] *}
Das wird einen JSON-Body erwarten (konvertieren, validieren, dokumentieren), wie:
@@ -264,33 +156,23 @@ 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
-## Tief verschachtelte Modelle
+Beachten Sie, dass der `images`-Schlüssel jetzt eine Liste von Bild-Objekten hat.
-Sie können beliebig tief verschachtelte Modelle definieren:
+///
-=== "Python 3.10+"
-
- ```Python hl_lines="7 12 18 21 25"
- {!> ../../../docs_src/body_nested_models/tutorial007_py310.py!}
- ```
+## Tief verschachtelte Modelle
-=== "Python 3.9+"
+Sie können beliebig tief verschachtelte Modelle definieren:
- ```Python hl_lines="9 14 20 23 27"
- {!> ../../../docs_src/body_nested_models/tutorial007_py39.py!}
- ```
+{* ../../docs_src/body_nested_models/tutorial007_py310.py hl[7,12,18,21,25] *}
-=== "Python 3.8+"
+/// info
- ```Python hl_lines="9 14 20 23 27"
- {!> ../../../docs_src/body_nested_models/tutorial007.py!}
- ```
+Beachten Sie, wie `Offer` eine Liste von `Item`s hat, von denen jedes seinerseits eine optionale Liste von `Image`s hat.
-!!! info
- Beachten Sie, wie `Offer` eine Liste von `Item`s hat, von denen jedes seinerseits eine optionale Liste von `Image`s hat.
+///
## Bodys aus reinen Listen
@@ -308,17 +190,7 @@ images: list[Image]
so wie in:
-=== "Python 3.9+"
-
- ```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!}
- ```
+{* ../../docs_src/body_nested_models/tutorial008_py39.py hl[13] *}
## Editor-Unterstützung überall
@@ -348,26 +220,19 @@ 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+"
-
- ```Python hl_lines="7"
- {!> ../../../docs_src/body_nested_models/tutorial009_py39.py!}
- ```
+{* ../../docs_src/body_nested_models/tutorial009_py39.py hl[7] *}
-=== "Python 3.8+"
+/// tip | Tipp
- ```Python hl_lines="9"
- {!> ../../../docs_src/body_nested_models/tutorial009.py!}
- ```
+Bedenken Sie, dass JSON nur `str` als Schlüssel unterstützt.
-!!! tip "Tipp"
- Bedenken Sie, dass JSON nur `str` als Schlüssel unterstützt.
+Aber Pydantic hat automatische Datenkonvertierung.
- Aber Pydantic hat automatische Datenkonvertierung.
+Das bedeutet, dass Ihre API-Clients nur Strings senden können, aber solange diese Strings nur Zahlen enthalten, wird Pydantic sie konvertieren und validieren.
- Das bedeutet, dass Ihre API-Clients nur Strings senden können, aber solange diese Strings nur Zahlen enthalten, wird Pydantic sie konvertieren und validieren.
+Und das `dict` welches Sie als `weights` erhalten, wird `int`-Schlüssel und `float`-Werte haben.
- Und das `dict` welches Sie als `weights` erhalten, wird `int`-Schlüssel und `float`-Werte haben.
+///
## Zusammenfassung
diff --git a/docs/de/docs/tutorial/body-updates.md b/docs/de/docs/tutorial/body-updates.md
index 2b3716d6f..574016c58 100644
--- a/docs/de/docs/tutorial/body-updates.md
+++ b/docs/de/docs/tutorial/body-updates.md
@@ -6,23 +6,7 @@ Um einen Artikel zu aktualisieren, können Sie die ../../../docs_src/body_updates/tutorial001_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="30-35"
- {!> ../../../docs_src/body_updates/tutorial001_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="30-35"
- {!> ../../../docs_src/body_updates/tutorial001.py!}
- ```
+{* ../../docs_src/body_updates/tutorial001_py310.py hl[28:33] *}
`PUT` wird verwendet, um Daten zu empfangen, die die existierenden Daten ersetzen sollen.
@@ -48,14 +32,17 @@ Sie können auch die ../../../docs_src/body_updates/tutorial002_py310.py!}
- ```
+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.
-=== "Python 3.9+"
+///
- ```Python hl_lines="34"
- {!> ../../../docs_src/body_updates/tutorial002_py39.py!}
- ```
+Das wird ein `dict` erstellen, mit nur den Daten, die gesetzt wurden als das `item`-Modell erstellt wurde, Defaultwerte ausgeschlossen.
-=== "Python 3.8+"
+Sie können das verwenden, um ein `dict` zu erstellen, das nur die (im Request) gesendeten Daten enthält, ohne Defaultwerte:
- ```Python hl_lines="34"
- {!> ../../../docs_src/body_updates/tutorial002.py!}
- ```
+{* ../../docs_src/body_updates/tutorial002_py310.py hl[32] *}
### 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.
+/// info
-Wie in `stored_item_model.model_copy(update=update_data)`:
-
-=== "Python 3.10+"
-
- ```Python hl_lines="33"
- {!> ../../../docs_src/body_updates/tutorial002_py310.py!}
- ```
+In Pydantic v1 hieß diese Methode `.copy()`, in Pydantic v2 wurde sie deprecated (aber immer noch unterstützt) und in `.model_copy()` umbenannt.
-=== "Python 3.9+"
+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.
- ```Python hl_lines="35"
- {!> ../../../docs_src/body_updates/tutorial002_py39.py!}
- ```
+///
-=== "Python 3.8+"
+Wie in `stored_item_model.model_copy(update=update_data)`:
- ```Python hl_lines="35"
- {!> ../../../docs_src/body_updates/tutorial002.py!}
- ```
+{* ../../docs_src/body_updates/tutorial002_py310.py hl[33] *}
### Rekapitulation zum teilweisen Ersetzen
@@ -134,32 +95,22 @@ Zusammengefasst, um Teil-Ersetzungen vorzunehmen:
* Speichern Sie die Daten in Ihrer Datenbank.
* Geben Sie das aktualisierte Modell zurück.
-=== "Python 3.10+"
-
- ```Python hl_lines="28-35"
- {!> ../../../docs_src/body_updates/tutorial002_py310.py!}
- ```
+{* ../../docs_src/body_updates/tutorial002_py310.py hl[28:35] *}
-=== "Python 3.9+"
+/// tip | Tipp
- ```Python hl_lines="30-37"
- {!> ../../../docs_src/body_updates/tutorial002_py39.py!}
- ```
+Sie können tatsächlich die gleiche Technik mit einer HTTP `PUT` Operation verwenden.
-=== "Python 3.8+"
+Aber dieses Beispiel verwendet `PATCH`, da dieses für solche Anwendungsfälle geschaffen wurde.
- ```Python hl_lines="30-37"
- {!> ../../../docs_src/body_updates/tutorial002.py!}
- ```
+///
-!!! tip "Tipp"
- Sie können tatsächlich die gleiche Technik mit einer HTTP `PUT` Operation verwenden.
+/// note | Hinweis
- Aber dieses Beispiel verwendet `PATCH`, da dieses für solche Anwendungsfälle geschaffen wurde.
+Beachten Sie, dass das hereinkommende Modell immer noch validiert wird.
-!!! note "Hinweis"
- Beachten Sie, dass das hereinkommende Modell immer noch validiert wird.
+Wenn Sie also Teil-Aktualisierungen empfangen wollen, die alle Attribute auslassen können, müssen Sie ein Modell haben, dessen Attribute alle als optional gekennzeichnet sind (mit Defaultwerten oder `None`).
- Wenn Sie also Teil-Aktualisierungen empfangen wollen, die alle Attribute auslassen können, müssen Sie ein Modell haben, dessen Attribute alle als optional gekennzeichnet sind (mit Defaultwerten oder `None`).
+Um zu unterscheiden zwischen Modellen für **Aktualisierungen**, mit lauter optionalen Werten, und solchen für die **Erzeugung**, mit benötigten Werten, können Sie die Techniken verwenden, die in [Extramodelle](extra-models.md){.internal-link target=_blank} beschrieben wurden.
- Um zu unterscheiden zwischen Modellen für **Aktualisierungen**, mit lauter optionalen Werten, und solchen für die **Erzeugung**, mit benötigten Werten, können Sie die Techniken verwenden, die in [Extramodelle](extra-models.md){.internal-link target=_blank} beschrieben wurden.
+///
diff --git a/docs/de/docs/tutorial/body.md b/docs/de/docs/tutorial/body.md
index 6611cb51a..e25323786 100644
--- a/docs/de/docs/tutorial/body.md
+++ b/docs/de/docs/tutorial/body.md
@@ -8,28 +8,21 @@ 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.
-## Importieren Sie Pydantics `BaseModel`
-
-Zuerst müssen Sie `BaseModel` von `pydantic` importieren:
+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.
-=== "Python 3.10+"
+///
- ```Python hl_lines="2"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
+## Importieren Sie Pydantics `BaseModel`
-=== "Python 3.8+"
+Zuerst müssen Sie `BaseModel` von `pydantic` importieren:
- ```Python hl_lines="4"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
+{* ../../docs_src/body/tutorial001_py310.py hl[2] *}
## Erstellen Sie Ihr Datenmodell
@@ -37,17 +30,7 @@ Dann deklarieren Sie Ihr Datenmodell als eine Klasse, die von `BaseModel` erbt.
Verwenden Sie Standard-Python-Typen für die Klassenattribute:
-=== "Python 3.10+"
-
- ```Python hl_lines="5-9"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="7-11"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
+{* ../../docs_src/body/tutorial001_py310.py hl[5:9] *}
Wie auch bei Query-Parametern gilt, wenn ein Modellattribut einen Defaultwert hat, ist das Attribut nicht erforderlich. Ansonsten ist es erforderlich. Verwenden Sie `None`, um es als optional zu kennzeichnen.
@@ -75,17 +58,7 @@ Da `description` und `tax` optional sind (mit `None` als Defaultwert), wäre fol
Um es zu Ihrer *Pfadoperation* hinzuzufügen, deklarieren Sie es auf die gleiche Weise, wie Sie Pfad- und Query-Parameter deklariert haben:
-=== "Python 3.10+"
-
- ```Python hl_lines="16"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="18"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
+{* ../../docs_src/body/tutorial001_py310.py hl[16] *}
... und deklarieren Sie seinen Typ als das Modell, welches Sie erstellt haben, `Item`.
@@ -134,32 +107,25 @@ 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.
-
- Es verbessert die Editor-Unterstützung für Pydantic-Modelle, mit:
+/// tip | Tipp
- * Code-Vervollständigung
- * Typüberprüfungen
- * Refaktorisierung
- * Suchen
- * Inspektionen
+Wenn Sie PyCharm als Ihren Editor verwenden, probieren Sie das Pydantic PyCharm Plugin aus.
-## Das Modell verwenden
+Es verbessert die Editor-Unterstützung für Pydantic-Modelle, mit:
-Innerhalb der Funktion können Sie alle Attribute des Modells direkt verwenden:
+* Code-Vervollständigung
+* Typüberprüfungen
+* Refaktorisierung
+* Suchen
+* Inspektionen
-=== "Python 3.10+"
+///
- ```Python hl_lines="19"
- {!> ../../../docs_src/body/tutorial002_py310.py!}
- ```
+## Das Modell verwenden
-=== "Python 3.8+"
+Innerhalb der Funktion können Sie alle Attribute des Modells direkt verwenden:
- ```Python hl_lines="21"
- {!> ../../../docs_src/body/tutorial002.py!}
- ```
+{* ../../docs_src/body/tutorial002_py310.py hl[19] *}
## Requestbody- + Pfad-Parameter
@@ -167,17 +133,7 @@ Sie können Pfad- und Requestbody-Parameter gleichzeitig deklarieren.
**FastAPI** erkennt, dass Funktionsparameter, die mit Pfad-Parametern übereinstimmen, **vom Pfad genommen** werden sollen, und dass Funktionsparameter, welche Pydantic-Modelle sind, **vom Requestbody genommen** werden sollen.
-=== "Python 3.10+"
-
- ```Python hl_lines="15-16"
- {!> ../../../docs_src/body/tutorial003_py310.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="17-18"
- {!> ../../../docs_src/body/tutorial003.py!}
- ```
+{* ../../docs_src/body/tutorial003_py310.py hl[15:16] *}
## Requestbody- + Pfad- + Query-Parameter
@@ -185,17 +141,7 @@ Sie können auch zur gleichen Zeit **Body-**, **Pfad-** und **Query-Parameter**
**FastAPI** wird jeden Parameter korrekt erkennen und die Daten vom richtigen Ort holen.
-=== "Python 3.10+"
-
- ```Python hl_lines="16"
- {!> ../../../docs_src/body/tutorial004_py310.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="18"
- {!> ../../../docs_src/body/tutorial004.py!}
- ```
+{* ../../docs_src/body/tutorial004_py310.py hl[16] *}
Die Funktionsparameter werden wie folgt erkannt:
@@ -203,10 +149,13 @@ Die Funktionsparameter werden wie folgt erkannt:
* Wenn der Parameter ein **einfacher Typ** ist (wie `int`, `float`, `str`, `bool`, usw.), wird er als **Query**-Parameter interpretiert.
* Wenn der Parameter vom Typ eines **Pydantic-Modells** ist, wird er als Request**body** interpretiert.
-!!! note "Hinweis"
- FastAPI weiß, dass der Wert von `q` nicht erforderlich ist, wegen des definierten Defaultwertes `= None`
+/// note | Hinweis
+
+FastAPI weiß, dass der Wert von `q` nicht erforderlich ist, wegen des definierten Defaultwertes `= None`
+
+Das `Union` in `Union[str, None]` wird von FastAPI nicht verwendet, aber es erlaubt Ihrem Editor, Sie besser zu unterstützen und Fehler zu erkennen.
- Das `Union` in `Union[str, None]` wird von FastAPI nicht verwendet, aber es erlaubt Ihrem Editor, Sie besser zu unterstützen und Fehler zu erkennen.
+///
## Ohne Pydantic
diff --git a/docs/de/docs/tutorial/cookie-params.md b/docs/de/docs/tutorial/cookie-params.md
index c95e28c7d..711c8c8e9 100644
--- a/docs/de/docs/tutorial/cookie-params.md
+++ b/docs/de/docs/tutorial/cookie-params.md
@@ -6,41 +6,7 @@ So wie `Query`- und `Path`-Parameter können Sie auch ../../../docs_src/dependencies/tutorial001_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="3"
- {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="3"
- {!> ../../../docs_src/dependencies/tutorial001_an.py!}
- ```
+/// info
-=== "Python 3.10+ nicht annotiert"
+FastAPI unterstützt (und empfiehlt die Verwendung von) `Annotated` seit Version 0.95.0.
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+Wenn Sie eine ältere Version haben, werden Sie Fehler angezeigt bekommen, wenn Sie versuchen, `Annotated` zu verwenden.
- ```Python hl_lines="1"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+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.
-=== "Python 3.8+ nicht annotiert"
+///
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+### `Depends` importieren
- ```Python hl_lines="3"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[3] *}
### Deklarieren der Abhängigkeit im „Dependant“
So wie auch `Body`, `Query`, usw., verwenden Sie `Depends` mit den Parametern Ihrer *Pfadoperation-Funktion*:
-=== "Python 3.10+"
-
- ```Python hl_lines="13 18"
- {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="15 20"
- {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="16 21"
- {!> ../../../docs_src/dependencies/tutorial001_an.py!}
- ```
-
-=== "Python 3.10+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="11 16"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
-
-=== "Python 3.8+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="15 20"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[13,18] *}
Obwohl Sie `Depends` in den Parametern Ihrer Funktion genauso verwenden wie `Body`, `Query`, usw., funktioniert `Depends` etwas anders.
@@ -179,8 +80,11 @@ Sie **rufen diese nicht direkt auf** (fügen Sie am Ende keine Klammern hinzu),
Und diese Funktion akzeptiert Parameter auf die gleiche Weise wie *Pfadoperation-Funktionen*.
-!!! tip "Tipp"
- Im nächsten Kapitel erfahren Sie, welche anderen „Dinge“, außer Funktionen, Sie als Abhängigkeiten verwenden können.
+/// tip | Tipp
+
+Im nächsten Kapitel erfahren Sie, welche anderen „Dinge“, außer Funktionen, Sie als Abhängigkeiten verwenden können.
+
+///
Immer wenn ein neuer Request eintrifft, kümmert sich **FastAPI** darum:
@@ -201,10 +105,13 @@ common_parameters --> read_users
Auf diese Weise schreiben Sie gemeinsam genutzten Code nur einmal, und **FastAPI** kümmert sich darum, ihn für Ihre *Pfadoperationen* aufzurufen.
-!!! check
- Beachten Sie, dass Sie keine spezielle Klasse erstellen und diese irgendwo an **FastAPI** übergeben müssen, um sie zu „registrieren“ oder so ähnlich.
+/// check
+
+Beachten Sie, dass Sie keine spezielle Klasse erstellen und diese irgendwo an **FastAPI** übergeben müssen, um sie zu „registrieren“ oder so ähnlich.
+
+Sie übergeben es einfach an `Depends` und **FastAPI** weiß, wie der Rest erledigt wird.
- Sie übergeben es einfach an `Depends` und **FastAPI** weiß, wie der Rest erledigt wird.
+///
## `Annotated`-Abhängigkeiten wiederverwenden
@@ -218,28 +125,15 @@ commons: Annotated[dict, Depends(common_parameters)]
Da wir jedoch `Annotated` verwenden, können wir diesen `Annotated`-Wert in einer Variablen speichern und an mehreren Stellen verwenden:
-=== "Python 3.10+"
+{* ../../docs_src/dependencies/tutorial001_02_an_py310.py hl[12,16,21] *}
- ```Python hl_lines="12 16 21"
- {!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!}
- ```
+/// tip | Tipp
-=== "Python 3.9+"
+Das ist schlicht Standard-Python, es wird als „Typalias“ bezeichnet und ist eigentlich nicht **FastAPI**-spezifisch.
- ```Python hl_lines="14 18 23"
- {!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!}
- ```
+Da **FastAPI** jedoch auf Standard-Python, einschließlich `Annotated`, basiert, können Sie diesen Trick in Ihrem Code verwenden. 😎
-=== "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`.
@@ -255,8 +149,11 @@ Und Sie können Abhängigkeiten mit `async def` innerhalb normaler `def`-*Pfadop
Es spielt keine Rolle. **FastAPI** weiß, was zu tun ist.
-!!! note "Hinweis"
- Wenn Ihnen das nichts sagt, lesen Sie den [Async: *„In Eile?“*](../../async.md#in-eile){.internal-link target=_blank}-Abschnitt über `async` und `await` in der Dokumentation.
+/// note | Hinweis
+
+Wenn Ihnen das nichts sagt, lesen Sie den [Async: *„In Eile?“*](../../async.md#in-eile){.internal-link target=_blank}-Abschnitt über `async` und `await` in der Dokumentation.
+
+///
## Integriert in OpenAPI
diff --git a/docs/de/docs/tutorial/dependencies/sub-dependencies.md b/docs/de/docs/tutorial/dependencies/sub-dependencies.md
index 0fa2af839..66bdc7043 100644
--- a/docs/de/docs/tutorial/dependencies/sub-dependencies.md
+++ b/docs/de/docs/tutorial/dependencies/sub-dependencies.md
@@ -10,41 +10,7 @@ Diese können so **tief** verschachtelt sein, wie nötig.
Sie könnten eine erste Abhängigkeit („Dependable“) wie folgt erstellen:
-=== "Python 3.10+"
-
- ```Python hl_lines="8-9"
- {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="8-9"
- {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="9-10"
- {!> ../../../docs_src/dependencies/tutorial005_an.py!}
- ```
-
-=== "Python 3.10 nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="6-7"
- {!> ../../../docs_src/dependencies/tutorial005_py310.py!}
- ```
-
-=== "Python 3.8 nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="8-9"
- {!> ../../../docs_src/dependencies/tutorial005.py!}
- ```
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[8:9] *}
Diese deklariert einen optionalen Abfrageparameter `q` vom Typ `str` und gibt ihn dann einfach zurück.
@@ -54,41 +20,7 @@ Das ist recht einfach (nicht sehr nützlich), hilft uns aber dabei, uns auf die
Dann können Sie eine weitere Abhängigkeitsfunktion (ein „Dependable“) erstellen, die gleichzeitig eine eigene Abhängigkeit deklariert (also auch ein „Dependant“ ist):
-=== "Python 3.10+"
-
- ```Python hl_lines="13"
- {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="13"
- {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="14"
- {!> ../../../docs_src/dependencies/tutorial005_an.py!}
- ```
-
-=== "Python 3.10 nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="11"
- {!> ../../../docs_src/dependencies/tutorial005_py310.py!}
- ```
-
-=== "Python 3.8 nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="13"
- {!> ../../../docs_src/dependencies/tutorial005.py!}
- ```
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[13] *}
Betrachten wir die deklarierten Parameter:
@@ -101,46 +33,15 @@ Betrachten wir die deklarierten Parameter:
Diese Abhängigkeit verwenden wir nun wie folgt:
-=== "Python 3.10+"
-
- ```Python hl_lines="23"
- {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="23"
- {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="24"
- {!> ../../../docs_src/dependencies/tutorial005_an.py!}
- ```
-
-=== "Python 3.10 nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial005_py310.py!}
- ```
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[23] *}
-=== "Python 3.8 nicht annotiert"
+/// info
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+Beachten Sie, dass wir in der *Pfadoperation-Funktion* nur eine einzige Abhängigkeit deklarieren, den `query_or_cookie_extractor`.
- ```Python hl_lines="22"
- {!> ../../../docs_src/dependencies/tutorial005.py!}
- ```
+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.
-!!! 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
@@ -161,22 +62,29 @@ Und es speichert den zurückgegebenen Wert in einem ../../../docs_src/encoder/tutorial001_py310.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="5 22"
- {!> ../../../docs_src/encoder/tutorial001.py!}
- ```
+{* ../../docs_src/encoder/tutorial001_py310.py hl[4,21] *}
In diesem Beispiel wird das Pydantic-Modell in ein `dict`, und das `datetime`-Objekt in ein `str` konvertiert.
@@ -38,5 +28,8 @@ Das Resultat dieses Aufrufs ist etwas, das mit Pythons Standard- ../../../docs_src/extra_data_types/tutorial001_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="1 3 12-16"
- {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="1 3 13-17"
- {!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
- ```
-
-=== "Python 3.10+ nicht annotiert"
-
- !!! tip
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="1 2 11-15"
- {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
- ```
-
-=== "Python 3.8+ nicht annotiert"
-
- !!! tip
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="1 2 12-16"
- {!> ../../../docs_src/extra_data_types/tutorial001.py!}
- ```
+{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[1,3,12:16] *}
Beachten Sie, dass die Parameter innerhalb der Funktion ihren natürlichen Datentyp haben und Sie beispielsweise normale Datumsmanipulationen durchführen können, wie zum Beispiel:
-=== "Python 3.10+"
-
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="19-20"
- {!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
- ```
-
-=== "Python 3.10+ nicht annotiert"
-
- !!! tip
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="17-18"
- {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
- ```
-
-=== "Python 3.8+ nicht annotiert"
-
- !!! tip
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/extra_data_types/tutorial001.py!}
- ```
+{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[18:19] *}
diff --git a/docs/de/docs/tutorial/extra-models.md b/docs/de/docs/tutorial/extra-models.md
index cdf16c4ba..6aad1c0f4 100644
--- a/docs/de/docs/tutorial/extra-models.md
+++ b/docs/de/docs/tutorial/extra-models.md
@@ -8,31 +8,27 @@ Insbesondere Benutzermodelle, denn:
* 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.
+/// danger | Gefahr
- Falls Ihnen das nichts sagt, in den [Sicherheits-Kapiteln](security/simple-oauth2.md#passwort-hashing){.internal-link target=_blank} werden Sie lernen, was ein „Passwort-Hash“ ist.
+Speichern Sie niemals das Klartext-Passwort eines Benutzers. Speichern Sie immer den „sicheren Hash“, den Sie verifizieren können.
+
+Falls Ihnen das nichts sagt, in den [Sicherheits-Kapiteln](security/simple-oauth2.md#passwort-hashing){.internal-link target=_blank} werden Sie lernen, was ein „Passwort-Hash“ ist.
+
+///
## Mehrere Modelle
Hier der generelle Weg, wie die Modelle mit ihren Passwort-Feldern aussehen könnten, und an welchen Orten sie verwendet werden würden.
-=== "Python 3.10+"
+{* ../../docs_src/extra_models/tutorial001_py310.py hl[7,9,14,20,22,27:28,31:33,38:39] *}
- ```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39"
- {!> ../../../docs_src/extra_models/tutorial001_py310.py!}
- ```
+/// info
-=== "Python 3.8+"
+In Pydantic v1 hieß diese Methode `.dict()`, in Pydantic v2 wurde sie deprecated (aber immer noch unterstützt) und in `.model_dump()` umbenannt.
- ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41"
- {!> ../../../docs_src/extra_models/tutorial001.py!}
- ```
+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
- 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()`
@@ -144,8 +140,11 @@ UserInDB(
)
```
-!!! warning "Achtung"
- Die Hilfsfunktionen `fake_password_hasher` und `fake_save_user` demonstrieren nur den möglichen Fluss der Daten und bieten natürlich keine echte Sicherheit.
+/// warning | Achtung
+
+Die Hilfsfunktionen `fake_password_hasher` und `fake_save_user` demonstrieren nur den möglichen Fluss der Daten und bieten natürlich keine echte Sicherheit.
+
+///
## Verdopplung vermeiden
@@ -163,17 +162,7 @@ Die ganze Datenkonvertierung, -validierung, -dokumentation, usw. wird immer noch
Auf diese Weise beschreiben wir nur noch die Unterschiede zwischen den Modellen (mit Klartext-`password`, mit `hashed_password`, und ohne Passwort):
-=== "Python 3.10+"
-
- ```Python hl_lines="7 13-14 17-18 21-22"
- {!> ../../../docs_src/extra_models/tutorial002_py310.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="9 15-16 19-20 23-24"
- {!> ../../../docs_src/extra_models/tutorial002.py!}
- ```
+{* ../../docs_src/extra_models/tutorial002_py310.py hl[7,13:14,17:18,21:22] *}
## `Union`, oder `anyOf`
@@ -183,20 +172,13 @@ 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`.
+/// note | Hinweis
-=== "Python 3.10+"
+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`.
- ```Python hl_lines="1 14-15 18-20 33"
- {!> ../../../docs_src/extra_models/tutorial003_py310.py!}
- ```
+///
-=== "Python 3.8+"
-
- ```Python hl_lines="1 14-15 18-20 33"
- {!> ../../../docs_src/extra_models/tutorial003.py!}
- ```
+{* ../../docs_src/extra_models/tutorial003_py310.py hl[1,14:15,18:20,33] *}
### `Union` in Python 3.10
@@ -218,17 +200,7 @@ Genauso können Sie eine Response deklarieren, die eine Liste von Objekten ist.
Verwenden Sie dafür Pythons Standard `typing.List` (oder nur `list` in Python 3.9 und darüber):
-=== "Python 3.9+"
-
- ```Python hl_lines="18"
- {!> ../../../docs_src/extra_models/tutorial004_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="1 20"
- {!> ../../../docs_src/extra_models/tutorial004.py!}
- ```
+{* ../../docs_src/extra_models/tutorial004_py39.py hl[18] *}
## Response mit beliebigem `dict`
@@ -238,17 +210,7 @@ Das ist nützlich, wenn Sie die gültigen Feld-/Attribut-Namen von vorneherein n
In diesem Fall können Sie `typing.Dict` verwenden (oder nur `dict` in Python 3.9 und darüber):
-=== "Python 3.9+"
-
- ```Python hl_lines="6"
- {!> ../../../docs_src/extra_models/tutorial005_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="1 8"
- {!> ../../../docs_src/extra_models/tutorial005.py!}
- ```
+{* ../../docs_src/extra_models/tutorial005_py39.py hl[6] *}
## Zusammenfassung
diff --git a/docs/de/docs/tutorial/first-steps.md b/docs/de/docs/tutorial/first-steps.md
index 27ba3ec16..3104c8d61 100644
--- a/docs/de/docs/tutorial/first-steps.md
+++ b/docs/de/docs/tutorial/first-steps.md
@@ -2,9 +2,7 @@
Die einfachste FastAPI-Datei könnte wie folgt aussehen:
-```Python
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py *}
Kopieren Sie dies in eine Datei `main.py`.
@@ -24,12 +22,15 @@ $ uvicorn main:app --reload
-!!! note "Hinweis"
- Der Befehl `uvicorn main:app` bezieht sich auf:
+/// note | Hinweis
+
+Der Befehl `uvicorn main:app` bezieht sich auf:
+
+* `main`: die Datei `main.py` (das sogenannte Python-„Modul“).
+* `app`: das Objekt, welches in der Datei `main.py` mit der Zeile `app = FastAPI()` erzeugt wurde.
+* `--reload`: lässt den Server nach Codeänderungen neu starten. Verwenden Sie das nur während der Entwicklung.
- * `main`: die Datei `main.py` (das sogenannte Python-„Modul“).
- * `app`: das Objekt, welches in der Datei `main.py` mit der Zeile `app = FastAPI()` erzeugt wurde.
- * `--reload`: lässt den Server nach Codeänderungen neu starten. Verwenden Sie das nur während der Entwicklung.
+///
In der Konsolenausgabe sollte es eine Zeile geben, die ungefähr so aussieht:
@@ -130,22 +131,21 @@ Ebenfalls können Sie es verwenden, um automatisch Code für Clients zu generier
### Schritt 1: Importieren von `FastAPI`
-```Python hl_lines="1"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[1] *}
`FastAPI` ist eine Python-Klasse, die die gesamte Funktionalität für Ihre API bereitstellt.
-!!! note "Technische Details"
- `FastAPI` ist eine Klasse, die direkt von `Starlette` erbt.
+/// note | Technische Details
+
+`FastAPI` ist eine Klasse, die direkt von `Starlette` erbt.
- Sie können alle Starlette-Funktionalitäten auch mit `FastAPI` nutzen.
+Sie können alle Starlette-Funktionalitäten auch mit `FastAPI` nutzen.
+
+///
### Schritt 2: Erzeugen einer `FastAPI`-„Instanz“
-```Python hl_lines="3"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[3] *}
In diesem Beispiel ist die Variable `app` eine „Instanz“ der Klasse `FastAPI`.
@@ -165,9 +165,7 @@ $ uvicorn main:app --reload
Wenn Sie Ihre Anwendung wie folgt erstellen:
-```Python hl_lines="3"
-{!../../../docs_src/first_steps/tutorial002.py!}
-```
+{* ../../docs_src/first_steps/tutorial002.py hl[3] *}
Und in eine Datei `main.py` einfügen, dann würden Sie `uvicorn` wie folgt aufrufen:
@@ -199,8 +197,11 @@ https://example.com/items/foo
/items/foo
```
-!!! info
- Ein „Pfad“ wird häufig auch als „Endpunkt“ oder „Route“ bezeichnet.
+/// info
+
+Ein „Pfad“ wird häufig auch als „Endpunkt“ oder „Route“ bezeichnet.
+
+///
Bei der Erstellung einer API ist der „Pfad“ die wichtigste Möglichkeit zur Trennung von „Anliegen“ und „Ressourcen“.
@@ -241,25 +242,26 @@ Wir werden sie auch „**Operationen**“ nennen.
#### Definieren eines *Pfadoperation-Dekorators*
-```Python hl_lines="6"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[6] *}
Das `@app.get("/")` sagt **FastAPI**, dass die Funktion direkt darunter für die Bearbeitung von Anfragen zuständig ist, die an:
* den Pfad `/`
* unter der Verwendung der
get
-Operation gehen
-!!! info "`@decorator` Information"
- Diese `@something`-Syntax wird in Python „Dekorator“ genannt.
+/// info | `@decorator` Information
+
+Diese `@something`-Syntax wird in Python „Dekorator“ genannt.
+
+Sie platzieren ihn über einer Funktion. Wie ein hübscher, dekorativer Hut (daher kommt wohl der Begriff).
- Sie platzieren ihn über einer Funktion. Wie ein hübscher, dekorativer Hut (daher kommt wohl der Begriff).
+Ein „Dekorator“ nimmt die darunter stehende Funktion und macht etwas damit.
- Ein „Dekorator“ nimmt die darunter stehende Funktion und macht etwas damit.
+In unserem Fall teilt dieser Dekorator **FastAPI** mit, dass die folgende Funktion mit dem **Pfad** `/` und der **Operation** `get` zusammenhängt.
- 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**“.
- Dies ist der „**Pfadoperation-Dekorator**“.
+///
Sie können auch die anderen Operationen verwenden:
@@ -274,14 +276,17 @@ Oder die exotischeren:
* `@app.patch()`
* `@app.trace()`
-!!! tip "Tipp"
- Es steht Ihnen frei, jede Operation (HTTP-Methode) so zu verwenden, wie Sie es möchten.
+/// tip | Tipp
+
+Es steht Ihnen frei, jede Operation (HTTP-Methode) so zu verwenden, wie Sie es möchten.
+
+**FastAPI** erzwingt keine bestimmte Bedeutung.
- **FastAPI** erzwingt keine bestimmte Bedeutung.
+Die hier aufgeführten Informationen dienen als Leitfaden und sind nicht verbindlich.
- Die hier aufgeführten Informationen dienen als Leitfaden und sind nicht verbindlich.
+Wenn Sie beispielsweise GraphQL verwenden, führen Sie normalerweise alle Aktionen nur mit „POST“-Operationen durch.
- Wenn Sie beispielsweise GraphQL verwenden, führen Sie normalerweise alle Aktionen nur mit „POST“-Operationen durch.
+///
### Schritt 4: Definieren der **Pfadoperation-Funktion**
@@ -291,9 +296,7 @@ Das ist unsere „**Pfadoperation-Funktion**“:
* **Operation**: ist `get`.
* **Funktion**: ist die Funktion direkt unter dem „Dekorator“ (unter `@app.get("/")`).
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[7] *}
Dies ist eine Python-Funktion.
@@ -305,18 +308,17 @@ In diesem Fall handelt es sich um eine `async`-Funktion.
Sie könnten sie auch als normale Funktion anstelle von `async def` definieren:
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial003.py!}
-```
+{* ../../docs_src/first_steps/tutorial003.py hl[7] *}
+
+/// note | Hinweis
-!!! note "Hinweis"
- Wenn Sie den Unterschied nicht kennen, lesen Sie [Async: *„In Eile?“*](../async.md#in-eile){.internal-link target=_blank}.
+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
-```Python hl_lines="8"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[8] *}
Sie können ein `dict`, eine `list`, einzelne Werte wie `str`, `int`, usw. zurückgeben.
diff --git a/docs/de/docs/tutorial/handling-errors.md b/docs/de/docs/tutorial/handling-errors.md
index af658b971..31bc6d328 100644
--- a/docs/de/docs/tutorial/handling-errors.md
+++ b/docs/de/docs/tutorial/handling-errors.md
@@ -25,9 +25,7 @@ Um HTTP-Responses mit Fehlern zum Client zurückzugeben, verwenden Sie `HTTPExce
### `HTTPException` importieren
-```Python hl_lines="1"
-{!../../../docs_src/handling_errors/tutorial001.py!}
-```
+{* ../../docs_src/handling_errors/tutorial001.py hl[1] *}
### Eine `HTTPException` in Ihrem Code auslösen
@@ -41,9 +39,7 @@ Der Vorteil, eine Exception auszulösen (`raise`), statt sie zurückzugeben (`re
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!}
-```
+{* ../../docs_src/handling_errors/tutorial001.py hl[11] *}
### Die resultierende Response
@@ -63,12 +59,15 @@ Aber wenn der Client `http://example.com/items/bar` anfragt (ein nicht-existiere
}
```
-!!! tip "Tipp"
- Wenn Sie eine `HTTPException` auslösen, können Sie dem Parameter `detail` jeden Wert übergeben, der nach JSON konvertiert werden kann, nicht nur `str`.
+/// tip | Tipp
+
+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.
- Zum Beispiel ein `dict`, eine `list`, usw.
+Das wird automatisch von **FastAPI** gehandhabt und der Wert nach JSON konvertiert.
- Das wird automatisch von **FastAPI** gehandhabt und der Wert nach JSON konvertiert.
+///
## Benutzerdefinierte Header hinzufügen
@@ -78,9 +77,7 @@ 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!}
-```
+{* ../../docs_src/handling_errors/tutorial002.py hl[14] *}
## Benutzerdefinierte Exceptionhandler definieren
@@ -92,9 +89,7 @@ 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!}
-```
+{* ../../docs_src/handling_errors/tutorial003.py hl[5:7,13:18,24] *}
Wenn Sie nun `/unicorns/yolo` anfragen, `raise`d die *Pfadoperation* eine `UnicornException`.
@@ -106,10 +101,13 @@ Sie erhalten also einen sauberen Error mit einem Statuscode `418` und dem JSON-I
{"message": "Oops! yolo did something. There goes a rainbow..."}
```
-!!! note "Technische Details"
- Sie können auch `from starlette.requests import Request` und `from starlette.responses import JSONResponse` verwenden.
+/// note | Technische Details
+
+Sie können auch `from starlette.requests import Request` und `from starlette.responses import JSONResponse` verwenden.
+
+**FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. Das Gleiche gilt für `Request`.
- **FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. Das Gleiche gilt für `Request`.
+///
## Die Default-Exceptionhandler überschreiben
@@ -129,9 +127,7 @@ Um diesen zu überschreiben, importieren Sie den `RequestValidationError` und ve
Der Exceptionhandler wird einen `Request` und die Exception entgegennehmen.
-```Python hl_lines="2 14-16"
-{!../../../docs_src/handling_errors/tutorial004.py!}
-```
+{* ../../docs_src/handling_errors/tutorial004.py hl[2,14:16] *}
Wenn Sie nun `/items/foo` besuchen, erhalten Sie statt des Default-JSON-Errors:
@@ -160,8 +156,11 @@ path -> item_id
#### `RequestValidationError` vs. `ValidationError`
-!!! warning "Achtung"
- Das folgende sind technische Details, die Sie überspringen können, wenn sie für Sie nicht wichtig sind.
+/// warning | Achtung
+
+Das folgende sind technische Details, die Sie überspringen können, wenn sie für Sie nicht wichtig sind.
+
+///
`RequestValidationError` ist eine Unterklasse von Pydantics `ValidationError`.
@@ -179,14 +178,15 @@ 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!}
-```
+{* ../../docs_src/handling_errors/tutorial004.py hl[3:4,9:11,22] *}
-!!! note "Technische Details"
- Sie können auch `from starlette.responses import PlainTextResponse` 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 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
@@ -194,9 +194,7 @@ Der `RequestValidationError` enthält den empfangenen `body` mit den ungültigen
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!}
-```
+{* ../../docs_src/handling_errors/tutorial005.py hl[14] *}
Jetzt versuchen Sie, einen ungültigen Artikel zu senden:
@@ -252,8 +250,6 @@ from starlette.exceptions import HTTPException as StarletteHTTPException
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!}
-```
+{* ../../docs_src/handling_errors/tutorial006.py hl[2:5,15,21] *}
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
index 3c9807f47..8283cc929 100644
--- a/docs/de/docs/tutorial/header-params.md
+++ b/docs/de/docs/tutorial/header-params.md
@@ -6,41 +6,7 @@ So wie `Query`-, `Path`-, und `Cookie`-Parameter können Sie auch .
+
+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.
+
+///
-!!! tip "Tipp"
- Beachten Sie, dass benutzerdefinierte proprietäre Header hinzugefügt werden können. Verwenden Sie dafür das Präfix 'X-'.
+/// note | Technische Details
- Wenn Sie jedoch benutzerdefinierte Header haben, die ein Client in einem Browser sehen soll, müssen Sie sie zu Ihrer CORS-Konfigurationen ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) hinzufügen, indem Sie den Parameter `expose_headers` verwenden, der in der Starlette-CORS-Dokumentation dokumentiert ist.
+Sie könnten auch `from starlette.requests import Request` verwenden.
-!!! note "Technische Details"
- Sie könnten auch `from starlette.requests import Request` verwenden.
+**FastAPI** bietet es als Komfort für Sie, den Entwickler, an. Aber es stammt direkt von Starlette.
- **FastAPI** bietet es als Komfort für Sie, den Entwickler, an. Aber es stammt direkt von Starlette.
+///
### Vor und nach der `response`
@@ -50,9 +57,7 @@ Und auch nachdem die `response` generiert wurde, bevor sie zurückgegeben wird.
Sie könnten beispielsweise einen benutzerdefinierten Header `X-Process-Time` hinzufügen, der die Zeit in Sekunden enthält, die benötigt wurde, um den Request zu verarbeiten und eine Response zu generieren:
-```Python hl_lines="10 12-13"
-{!../../../docs_src/middleware/tutorial001.py!}
-```
+{* ../../docs_src/middleware/tutorial001.py hl[10,12:13] *}
## Andere Middlewares
diff --git a/docs/de/docs/tutorial/path-operation-configuration.md b/docs/de/docs/tutorial/path-operation-configuration.md
index 80a4fadc9..7473e515b 100644
--- a/docs/de/docs/tutorial/path-operation-configuration.md
+++ b/docs/de/docs/tutorial/path-operation-configuration.md
@@ -2,8 +2,11 @@
Es gibt mehrere Konfigurations-Parameter, die Sie Ihrem *Pfadoperation-Dekorator* übergeben können.
-!!! warning "Achtung"
- Beachten Sie, dass diese Parameter direkt dem *Pfadoperation-Dekorator* übergeben werden, nicht der *Pfadoperation-Funktion*.
+/// warning | Achtung
+
+Beachten Sie, dass diese Parameter direkt dem *Pfadoperation-Dekorator* übergeben werden, nicht der *Pfadoperation-Funktion*.
+
+///
## Response-Statuscode
@@ -13,52 +16,23 @@ Sie können direkt den `int`-Code übergeben, etwa `404`.
Aber falls Sie sich nicht mehr erinnern, wofür jede Nummer steht, können Sie die Abkürzungs-Konstanten in `status` verwenden:
-=== "Python 3.10+"
-
- ```Python hl_lines="1 15"
- {!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!}
- ```
+{* ../../docs_src/path_operation_configuration/tutorial001_py310.py hl[1,15] *}
-=== "Python 3.9+"
-
- ```Python hl_lines="3 17"
- {!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!}
- ```
-
-=== "Python 3.8+"
+Dieser Statuscode wird in der Response verwendet und zum OpenAPI-Schema hinzugefügt.
- ```Python hl_lines="3 17"
- {!> ../../../docs_src/path_operation_configuration/tutorial001.py!}
- ```
+/// note | Technische Details
-Dieser Statuscode wird in der Response verwendet und zum OpenAPI-Schema hinzugefügt.
+Sie können auch `from starlette import status` verwenden.
-!!! note "Technische Details"
- Sie können auch `from starlette import status` verwenden.
+**FastAPI** bietet dieselben `starlette.status`-Codes auch via `fastapi.status` an, als Annehmlichkeit für Sie, den Entwickler. Sie kommen aber direkt von Starlette.
- **FastAPI** bietet dieselben `starlette.status`-Codes auch via `fastapi.status` an, als Annehmlichkeit für Sie, den Entwickler. Sie kommen aber direkt von Starlette.
+///
## Tags
Sie können Ihrer *Pfadoperation* Tags hinzufügen, mittels des Parameters `tags`, dem eine `list`e von `str`s übergeben wird (in der Regel nur ein `str`):
-=== "Python 3.10+"
-
- ```Python hl_lines="15 20 25"
- {!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="17 22 27"
- {!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="17 22 27"
- {!> ../../../docs_src/path_operation_configuration/tutorial002.py!}
- ```
+{* ../../docs_src/path_operation_configuration/tutorial002_py310.py hl[15,20,25] *}
Diese werden zum OpenAPI-Schema hinzugefügt und von den automatischen Dokumentations-Benutzeroberflächen verwendet:
@@ -72,31 +46,13 @@ In diesem Fall macht es Sinn, die Tags in einem `Enum` zu speichern.
**FastAPI** unterstützt diese genauso wie einfache Strings:
-```Python hl_lines="1 8-10 13 18"
-{!../../../docs_src/path_operation_configuration/tutorial002b.py!}
-```
+{* ../../docs_src/path_operation_configuration/tutorial002b.py hl[1,8:10,13,18] *}
## Zusammenfassung und Beschreibung
Sie können eine Zusammenfassung (`summary`) und eine Beschreibung (`description`) hinzufügen:
-=== "Python 3.10+"
-
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="20-21"
- {!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="20-21"
- {!> ../../../docs_src/path_operation_configuration/tutorial003.py!}
- ```
+{* ../../docs_src/path_operation_configuration/tutorial003_py310.py hl[18:19] *}
## Beschreibung mittels Docstring
@@ -104,23 +60,7 @@ Da Beschreibungen oft mehrere Zeilen lang sind, können Sie die Beschreibung der
Sie können im Docstring Markdown schreiben, es wird korrekt interpretiert und angezeigt (die Einrückung des Docstring beachtend).
-=== "Python 3.10+"
-
- ```Python hl_lines="17-25"
- {!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="19-27"
- {!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="19-27"
- {!> ../../../docs_src/path_operation_configuration/tutorial004.py!}
- ```
+{* ../../docs_src/path_operation_configuration/tutorial004_py310.py hl[17:25] *}
In der interaktiven Dokumentation sieht das dann so aus:
@@ -130,31 +70,21 @@ In der interaktiven Dokumentation sieht das dann so aus:
Die Response können Sie mit dem Parameter `response_description` beschreiben:
-=== "Python 3.10+"
-
- ```Python hl_lines="19"
- {!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!}
- ```
+{* ../../docs_src/path_operation_configuration/tutorial005_py310.py hl[19] *}
-=== "Python 3.9+"
+/// info
- ```Python hl_lines="21"
- {!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!}
- ```
+beachten Sie, dass sich `response_description` speziell auf die Response bezieht, während `description` sich generell auf die *Pfadoperation* bezieht.
-=== "Python 3.8+"
+///
- ```Python hl_lines="21"
- {!> ../../../docs_src/path_operation_configuration/tutorial005.py!}
- ```
+/// check
-!!! info
- beachten Sie, dass sich `response_description` speziell auf die Response bezieht, während `description` sich generell auf die *Pfadoperation* bezieht.
+OpenAPI verlangt, dass jede *Pfadoperation* über eine Beschreibung der Response verfügt.
-!!! check
- OpenAPI verlangt, dass jede *Pfadoperation* über eine Beschreibung der Response verfügt.
+Daher, wenn Sie keine vergeben, wird **FastAPI** automatisch eine für „Erfolgreiche Response“ erstellen.
- Daher, wenn Sie keine vergeben, wird **FastAPI** automatisch eine für „Erfolgreiche Response“ erstellen.
+///
@@ -162,9 +92,7 @@ Die Response können Sie mit dem Parameter `response_description` beschreiben:
Wenn Sie eine *Pfadoperation* als deprecated kennzeichnen möchten, ohne sie zu entfernen, fügen Sie den Parameter `deprecated` hinzu:
-```Python hl_lines="16"
-{!../../../docs_src/path_operation_configuration/tutorial006.py!}
-```
+{* ../../docs_src/path_operation_configuration/tutorial006.py hl[16] *}
Sie wird in der interaktiven Dokumentation gut sichtbar als deprecated markiert werden:
diff --git a/docs/de/docs/tutorial/path-params-numeric-validations.md b/docs/de/docs/tutorial/path-params-numeric-validations.md
index aa3b59b8b..1acdd5b4e 100644
--- a/docs/de/docs/tutorial/path-params-numeric-validations.md
+++ b/docs/de/docs/tutorial/path-params-numeric-validations.md
@@ -6,48 +6,17 @@ So wie Sie mit `Query` für Query-Parameter zusätzliche Validierungen und Metad
Importieren Sie zuerst `Path` von `fastapi`, und importieren Sie `Annotated`.
-=== "Python 3.10+"
+{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[1,3] *}
- ```Python hl_lines="1 3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
- ```
+/// info
-=== "Python 3.9+"
+FastAPI unterstützt (und empfiehlt die Verwendung von) `Annotated` seit Version 0.95.0.
- ```Python hl_lines="1 3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
- ```
+Wenn Sie eine ältere Version haben, werden Sie Fehler angezeigt bekommen, wenn Sie versuchen, `Annotated` zu verwenden.
-=== "Python 3.8+"
+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.
- ```Python hl_lines="3-4"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
- ```
-
-=== "Python 3.10+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="1"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
- ```
-
-=== "Python 3.8+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
- ```
-
-!!! info
- FastAPI unterstützt (und empfiehlt die Verwendung von) `Annotated` seit Version 0.95.0.
-
- Wenn Sie eine ältere Version haben, werden Sie Fehler angezeigt bekommen, wenn Sie versuchen, `Annotated` zu verwenden.
-
- Bitte [aktualisieren Sie FastAPI](../deployment/versions.md#upgrade-der-fastapi-versionen){.internal-link target=_blank} daher mindestens zu Version 0.95.1, bevor Sie `Annotated` verwenden.
+///
## Metadaten deklarieren
@@ -55,53 +24,25 @@ Sie können die gleichen Parameter deklarieren wie für `Query`.
Um zum Beispiel einen `title`-Metadaten-Wert für den Pfad-Parameter `item_id` zu deklarieren, schreiben Sie:
-=== "Python 3.10+"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
- ```
-
-=== "Python 3.8+"
+{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[10] *}
- ```Python hl_lines="11"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
- ```
+/// note | Hinweis
-=== "Python 3.10+ nicht annotiert"
+Ein Pfad-Parameter ist immer erforderlich, weil er Teil des Pfads sein muss.
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+Sie sollten ihn daher mit `...` deklarieren, um ihn als erforderlich auszuzeichnen.
- ```Python hl_lines="8"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
- ```
+Doch selbst wenn Sie ihn mit `None` deklarieren, oder einen Defaultwert setzen, bewirkt das nichts, er bleibt immer erforderlich.
-=== "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.
+## Sortieren Sie die Parameter, wie Sie möchten
- Sie sollten ihn daher mit `...` deklarieren, um ihn als erforderlich auszuzeichnen.
+/// tip | Tipp
- Doch selbst wenn Sie ihn mit `None` deklarieren, oder einen Defaultwert setzen, bewirkt das nichts, er bleibt immer erforderlich.
+Wenn Sie `Annotated` verwenden, ist das folgende nicht so wichtig / nicht notwendig.
-## 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.
@@ -117,33 +58,31 @@ Für **FastAPI** ist es nicht wichtig. Es erkennt die Parameter anhand ihres Nam
Sie können Ihre Funktion also so deklarieren:
-=== "Python 3.8 nicht annotiert"
+//// tab | Python 3.8 nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | Tipp
- ```Python hl_lines="7"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-Aber bedenken Sie, dass Sie dieses Problem nicht haben, wenn Sie `Annotated` verwenden, da Sie nicht die Funktions-Parameter-Defaultwerte für `Query()` oder `Path()` verwenden.
+///
-=== "Python 3.9+"
+```Python hl_lines="7"
+{!> ../../docs_src/path_params_numeric_validations/tutorial002.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!}
- ```
+////
-=== "Python 3.8+"
+Aber bedenken Sie, dass Sie dieses Problem nicht haben, wenn Sie `Annotated` verwenden, da Sie nicht die Funktions-Parameter-Defaultwerte für `Query()` oder `Path()` verwenden.
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!}
- ```
+{* ../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py hl[10] *}
## Sortieren Sie die Parameter wie Sie möchten: Tricks
-!!! tip "Tipp"
- Wenn Sie `Annotated` verwenden, ist das folgende nicht so wichtig / nicht notwendig.
+/// tip | Tipp
+
+Wenn Sie `Annotated` verwenden, ist das folgende nicht so wichtig / nicht notwendig.
+
+///
Hier ein **kleiner Trick**, der nützlich sein kann, aber Sie werden ihn nicht oft brauchen.
@@ -160,51 +99,20 @@ Wenn Sie eines der folgenden Dinge tun möchten:
Python macht nichts mit diesem `*`, aber es wird wissen, dass alle folgenden Parameter als Keyword-Argumente (Schlüssel-Wert-Paare), auch bekannt als
kwargs
, verwendet werden. Selbst wenn diese keinen Defaultwert haben.
-```Python hl_lines="7"
-{!../../../docs_src/path_params_numeric_validations/tutorial003.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *}
### Besser mit `Annotated`
Bedenken Sie, dass Sie, wenn Sie `Annotated` verwenden, dieses Problem nicht haben, weil Sie keine Defaultwerte für Ihre Funktionsparameter haben. Sie müssen daher wahrscheinlich auch nicht `*` verwenden.
-=== "Python 3.9+"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!}
- ```
+{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py hl[10] *}
## Validierung von Zahlen: Größer oder gleich
Mit `Query` und `Path` (und anderen, die Sie später kennenlernen), können Sie Zahlenbeschränkungen deklarieren.
Hier, mit `ge=1`, wird festgelegt, dass `item_id` eine Ganzzahl benötigt, die größer oder gleich `1` ist (`g`reater than or `e`qual).
-=== "Python 3.9+"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!}
- ```
-
-=== "Python 3.8+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="8"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!}
- ```
+{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py hl[10] *}
## Validierung von Zahlen: Größer und kleiner oder gleich
@@ -213,26 +121,7 @@ Das Gleiche trifft zu auf:
* `gt`: `g`reater `t`han – größer als
* `le`: `l`ess than or `e`qual – kleiner oder gleich
-=== "Python 3.9+"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!}
- ```
-
-=== "Python 3.8+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!}
- ```
+{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py hl[10] *}
## Validierung von Zahlen: Floats, größer und kleiner
@@ -244,26 +133,7 @@ Hier wird es wichtig, in der Lage zu sein, lt
.
-=== "Python 3.9+"
-
- ```Python hl_lines="13"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="12"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!}
- ```
-
-=== "Python 3.8+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="11"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!}
- ```
+{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py hl[13] *}
## Zusammenfassung
@@ -276,18 +146,24 @@ Und Sie können auch Validierungen für Zahlen deklarieren:
* `lt`: `l`ess `t`han – kleiner als
* `le`: `l`ess than or `e`qual – kleiner oder gleich
-!!! info
- `Query`, `Path`, und andere Klassen, die Sie später kennenlernen, sind Unterklassen einer allgemeinen `Param`-Klasse.
+/// info
+
+`Query`, `Path`, und andere Klassen, die Sie später kennenlernen, sind Unterklassen einer allgemeinen `Param`-Klasse.
+
+Sie alle teilen die gleichen Parameter für zusätzliche Validierung und Metadaten, die Sie gesehen haben.
+
+///
+
+/// note | Technische Details
- Sie alle teilen die gleichen Parameter für zusätzliche Validierung und Metadaten, die Sie gesehen haben.
+`Query`, `Path` und andere, die Sie von `fastapi` importieren, sind tatsächlich Funktionen.
-!!! note "Technische Details"
- `Query`, `Path` und andere, die Sie von `fastapi` importieren, sind tatsächlich Funktionen.
+Die, wenn sie aufgerufen werden, Instanzen der Klassen mit demselben Namen zurückgeben.
- Die, wenn sie aufgerufen werden, Instanzen der Klassen mit demselben Namen zurückgeben.
+Sie importieren also `Query`, welches eine Funktion ist. Aber wenn Sie es aufrufen, gibt es eine Instanz der Klasse zurück, die auch `Query` genannt wird.
- Sie importieren also `Query`, welches eine Funktion ist. Aber wenn Sie es aufrufen, gibt es eine Instanz der Klasse zurück, die auch `Query` genannt wird.
+Diese Funktionen existieren (statt die Klassen direkt zu verwenden), damit Ihr Editor keine Fehlermeldungen über ihre Typen ausgibt.
- Diese Funktionen existieren (statt die Klassen direkt zu verwenden), damit Ihr Editor keine Fehlermeldungen über ihre Typen ausgibt.
+Auf diese Weise können Sie Ihren Editor und Ihre Programmier-Tools verwenden, ohne besondere Einstellungen vornehmen zu müssen, um diese Fehlermeldungen stummzuschalten.
- Auf diese Weise können Sie Ihren Editor und Ihre Programmier-Tools verwenden, ohne besondere Einstellungen vornehmen zu müssen, um diese Fehlermeldungen stummzuschalten.
+///
diff --git a/docs/de/docs/tutorial/path-params.md b/docs/de/docs/tutorial/path-params.md
index 8c8f2e008..123990940 100644
--- a/docs/de/docs/tutorial/path-params.md
+++ b/docs/de/docs/tutorial/path-params.md
@@ -2,9 +2,7 @@
Sie können Pfad-„Parameter“ oder -„Variablen“ mit der gleichen Syntax deklarieren, welche in Python-Format-Strings verwendet wird:
-```Python hl_lines="6-7"
-{!../../../docs_src/path_params/tutorial001.py!}
-```
+{* ../../docs_src/path_params/tutorial001.py hl[6:7] *}
Der Wert des Pfad-Parameters `item_id` wird Ihrer Funktion als das Argument `item_id` übergeben.
@@ -18,14 +16,15 @@ Wenn Sie dieses Beispiel ausführen und auf Konversion
@@ -35,10 +34,13 @@ Wenn Sie dieses Beispiel ausführen und Ihren Browser unter „parsen“.
+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
@@ -65,12 +67,15 @@ Der Pfad-Parameter `item_id` hatte den Wert `"foo"`, was kein `int` ist.
Die gleiche Fehlermeldung würde angezeigt werden, wenn Sie ein `float` (also eine Kommazahl) statt eines `int`s übergeben würden, wie etwa in: http://127.0.0.1:8000/items/4.2
-!!! check
- Sprich, mit der gleichen Python-Typdeklaration gibt Ihnen **FastAPI** Datenvalidierung.
+/// 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.
+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.
+Das ist unglaublich hilfreich, wenn Sie Code entwickeln und debuggen, welcher mit ihrer API interagiert.
+
+///
## Dokumentation
@@ -78,10 +83,13 @@ Wenn Sie die Seite
-!!! check
- Wiederum, mit dieser gleichen Python-Typdeklaration gibt Ihnen **FastAPI** eine automatische, interaktive Dokumentation (verwendet die Swagger-Benutzeroberfläche).
+/// check
+
+Wiederum, mit dieser gleichen Python-Typdeklaration gibt Ihnen **FastAPI** eine automatische, interaktive Dokumentation (verwendet die Swagger-Benutzeroberfläche).
+
+Beachten Sie, dass der Pfad-Parameter dort als Ganzzahl deklariert ist.
- Beachten Sie, dass der Pfad-Parameter dort als Ganzzahl deklariert ist.
+///
## Nützliche Standards. Alternative Dokumentation
@@ -111,17 +119,13 @@ Und Sie haben auch einen Pfad `/users/{user_id}`, um Daten über einen spezifisc
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!}
-```
+{* ../../docs_src/path_params/tutorial003.py hl[6,11] *}
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!}
-```
+{* ../../docs_src/path_params/tutorial003b.py hl[6,11] *}
Die erste Definition wird immer verwendet werden, da ihr Pfad zuerst übereinstimmt.
@@ -137,23 +141,25 @@ Indem Sie von `str` erben, weiß die API Dokumentation, dass die Werte des Enums
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!}
-```
+{* ../../docs_src/path_params/tutorial005.py hl[1,6:9] *}
-!!! info
- Enumerationen (oder kurz Enums) gibt es in Python seit Version 3.4.
+/// info
-!!! tip "Tipp"
- Falls Sie sich fragen, was „AlexNet“, „ResNet“ und „LeNet“ ist, das sind Namen von Modellen für maschinelles Lernen.
+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!}
-```
+{* ../../docs_src/path_params/tutorial005.py hl[16] *}
### Testen Sie es in der API-Dokumentation
@@ -169,20 +175,19 @@ Der *Pfad-Parameter* wird ein * ../../../docs_src/query_params_str_validations/tutorial001_py310.py!}
- ```
-
-=== "Python 3.8+"
+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.
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial001.py!}
- ```
+/// note | Hinweis
-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.
+FastAPI weiß nur dank des definierten Defaultwertes `=None`, dass der Wert von `q` nicht erforderlich ist
-!!! 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.
- `Union[str, None]` hingegen erlaubt ihren Editor, Sie besser zu unterstützen und Fehler zu erkennen.
+///
## Zusätzliche Validierung
@@ -34,30 +27,37 @@ Importieren Sie zuerst:
* `Query` von `fastapi`
* `Annotated` von `typing` (oder von `typing_extensions` in Python unter 3.9)
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+In Python 3.9 oder darüber, ist `Annotated` Teil der Standardbibliothek, also können Sie es von `typing` importieren.
+
+```Python hl_lines="1 3"
+{!> ../../docs_src/query_params_str_validations/tutorial002_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
- In Python 3.9 oder darüber, ist `Annotated` Teil der Standardbibliothek, also können Sie es von `typing` importieren.
+In Versionen unter Python 3.9 importieren Sie `Annotated` von `typing_extensions`.
- ```Python hl_lines="1 3"
- {!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!}
- ```
+Es wird bereits mit FastAPI installiert sein.
-=== "Python 3.8+"
+```Python hl_lines="3-4"
+{!> ../../docs_src/query_params_str_validations/tutorial002_an.py!}
+```
- In Versionen unter Python 3.9 importieren Sie `Annotated` von `typing_extensions`.
+////
- Es wird bereits mit FastAPI installiert sein.
+/// info
- ```Python hl_lines="3-4"
- {!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!}
- ```
+FastAPI unterstützt (und empfiehlt die Verwendung von) `Annotated` seit Version 0.95.0.
-!!! info
- FastAPI unterstützt (und empfiehlt die Verwendung von) `Annotated` seit Version 0.95.0.
+Wenn Sie eine ältere Version haben, werden Sie Fehler angezeigt bekommen, wenn Sie versuchen, `Annotated` zu verwenden.
- Wenn Sie eine ältere Version haben, werden Sie Fehler angezeigt bekommen, wenn Sie versuchen, `Annotated` zu verwenden.
+Bitte [aktualisieren Sie FastAPI](../deployment/versions.md#upgrade-der-fastapi-versionen){.internal-link target=_blank} daher mindestens zu Version 0.95.1, bevor Sie `Annotated` verwenden.
- Bitte [aktualisieren Sie FastAPI](../deployment/versions.md#upgrade-der-fastapi-versionen){.internal-link target=_blank} daher mindestens zu Version 0.95.1, bevor Sie `Annotated` verwenden.
+///
## `Annotated` im Typ des `q`-Parameters verwenden
@@ -67,31 +67,39 @@ Jetzt ist es an der Zeit, das mit FastAPI auszuprobieren. 🚀
Wir hatten diese Typannotation:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python
- q: str | None = None
- ```
+```Python
+q: str | None = None
+```
-=== "Python 3.8+"
+////
- ```Python
- q: Union[str, None] = None
- ```
+//// tab | Python 3.8+
+
+```Python
+q: Union[str, None] = None
+```
+
+////
Wir wrappen das nun in `Annotated`, sodass daraus wird:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python
- q: Annotated[str | None] = None
- ```
+```Python
+q: Annotated[str | None] = None
+```
+
+////
+
+//// tab | Python 3.8+
-=== "Python 3.8+"
+```Python
+q: Annotated[Union[str, None]] = None
+```
- ```Python
- q: Annotated[Union[str, None]] = None
- ```
+////
Beide Versionen bedeuten dasselbe: `q` ist ein Parameter, der `str` oder `None` sein kann. Standardmäßig ist er `None`.
@@ -101,17 +109,7 @@ Wenden wir uns jetzt den spannenden Dingen zu. 🎉
Jetzt, da wir `Annotated` für unsere Metadaten deklariert haben, fügen Sie `Query` hinzu, und setzen Sie den Parameter `max_length` auf `50`:
-=== "Python 3.10+"
-
- ```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!}
- ```
+{* ../../docs_src/query_params_str_validations/tutorial002_an_py310.py hl[9] *}
Beachten Sie, dass der Defaultwert immer noch `None` ist, sodass der Parameter immer noch optional ist.
@@ -127,22 +125,15 @@ FastAPI wird nun:
Frühere Versionen von FastAPI (vor 0.95.0) benötigten `Query` als Defaultwert des Parameters, statt es innerhalb von `Annotated` unterzubringen. Die Chance ist groß, dass Sie Quellcode sehen, der das immer noch so macht, darum erkläre ich es Ihnen.
-!!! tip "Tipp"
- Verwenden Sie für neuen Code, und wann immer möglich, `Annotated`, wie oben erklärt. Es gibt mehrere Vorteile (unten erläutert) und keine Nachteile. 🍰
+/// tip | Tipp
-So würden Sie `Query()` als Defaultwert Ihres Funktionsparameters verwenden, den Parameter `max_length` auf 50 gesetzt:
-
-=== "Python 3.10+"
+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. 🍰
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!}
- ```
+///
-=== "Python 3.8+"
+So würden Sie `Query()` als Defaultwert Ihres Funktionsparameters verwenden, den Parameter `max_length` auf 50 gesetzt:
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial002.py!}
- ```
+{* ../../docs_src/query_params_str_validations/tutorial002_py310.py hl[7] *}
Da wir in diesem Fall (ohne die Verwendung von `Annotated`) den Parameter-Defaultwert `None` mit `Query()` ersetzen, müssen wir nun dessen Defaultwert mit dem Parameter `Query(default=None)` deklarieren. Das dient demselben Zweck, `None` als Defaultwert für den Funktionsparameter zu setzen (zumindest für FastAPI).
@@ -172,22 +163,25 @@ q: str | None = None
Nur, dass die `Query`-Versionen den Parameter explizit als Query-Parameter deklarieren.
-!!! info
- Bedenken Sie, dass:
+/// info
- ```Python
- = None
- ```
+Bedenken Sie, dass:
- oder:
+```Python
+= None
+```
+
+oder:
+
+```Python
+= Query(default=None)
+```
- ```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 wichtigste Teil ist, um einen Parameter optional zu machen, da dieses `None` der Defaultwert ist, und das ist es, was diesen Parameter **nicht erforderlich** macht.
+Der Teil mit `Union[str, None]` erlaubt es Ihrem Editor, Sie besser zu unterstützen, aber er sagt FastAPI nicht, dass dieser Parameter optional ist.
- Der Teil mit `Union[str, None]` erlaubt es Ihrem Editor, Sie besser zu unterstützen, aber er sagt FastAPI nicht, dass dieser Parameter optional ist.
+///
Jetzt können wir `Query` weitere Parameter übergeben. Fangen wir mit dem `max_length` Parameter an, der auf Strings angewendet wird:
@@ -239,81 +233,13 @@ Da `Annotated` mehrere Metadaten haben kann, können Sie dieselbe Funktion auch
Sie können auch einen Parameter `min_length` hinzufügen:
-=== "Python 3.10+"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial003_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial003_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial003_an.py!}
- ```
-
-=== "Python 3.10+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!}
- ```
-
-=== "Python 3.8+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial003.py!}
- ```
+{* ../../docs_src/query_params_str_validations/tutorial003_an_py310.py hl[10] *}
## Reguläre Ausdrücke hinzufügen
Sie können einen Regulären Ausdruck `pattern` definieren, mit dem der Parameter übereinstimmen muss:
-=== "Python 3.10+"
-
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial004_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial004_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="12"
- {!> ../../../docs_src/query_params_str_validations/tutorial004_an.py!}
- ```
-
-=== "Python 3.10+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!}
- ```
-
-=== "Python 3.8+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial004.py!}
- ```
+{* ../../docs_src/query_params_str_validations/tutorial004_an_py310.py hl[11] *}
Dieses bestimmte reguläre Suchmuster prüft, ob der erhaltene Parameter-Wert:
@@ -331,11 +257,11 @@ Vor Pydantic Version 2 und vor FastAPI Version 0.100.0, war der Name des Paramet
Sie könnten immer noch Code sehen, der den alten Namen verwendet:
-=== "Python 3.10+ Pydantic v1"
+//// tab | Pydantic v1
+
+{* ../../docs_src/query_params_str_validations/tutorial004_regex_an_py310.py hl[11] *}
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial004_an_py310_regex.py!}
- ```
+////
Beachten Sie aber, dass das deprecated ist, und zum neuen Namen `pattern` geändert werden sollte. 🤓
@@ -345,29 +271,13 @@ Sie können natürlich andere Defaultwerte als `None` verwenden.
Beispielsweise könnten Sie den `q` Query-Parameter so deklarieren, dass er eine `min_length` von `3` hat, und den Defaultwert `"fixedquery"`:
-=== "Python 3.9+"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial005_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial005_an.py!}
- ```
-
-=== "Python 3.8+ nicht annotiert"
+{* ../../docs_src/query_params_str_validations/tutorial005_an_py39.py hl[9] *}
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// note | Hinweis
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial005.py!}
- ```
+Ein Parameter ist optional (nicht erforderlich), wenn er irgendeinen Defaultwert, auch `None`, hat.
-!!! note "Hinweis"
- Ein Parameter ist optional (nicht erforderlich), wenn er irgendeinen Defaultwert, auch `None`, hat.
+///
## Erforderliche Parameter
@@ -385,77 +295,25 @@ q: Union[str, None] = None
Aber jetzt deklarieren wir den Parameter mit `Query`, wie in:
-=== "Annotiert"
-
- ```Python
- q: Annotated[Union[str, None], Query(min_length=3)] = None
- ```
-
-=== "Nicht annotiert"
-
- ```Python
- q: Union[str, None] = Query(default=None, min_length=3)
- ```
-
-Wenn Sie einen Parameter erforderlich machen wollen, während Sie `Query` verwenden, deklarieren Sie ebenfalls einfach keinen Defaultwert:
-
-=== "Python 3.9+"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial006_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial006_an.py!}
- ```
-
-=== "Python 3.8+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial006.py!}
- ```
-
- !!! tip "Tipp"
- Beachten Sie, dass, obwohl in diesem Fall `Query()` der Funktionsparameter-Defaultwert ist, wir nicht `default=None` zu `Query()` hinzufügen.
-
- Verwenden Sie bitte trotzdem die `Annotated`-Version. 😉
-
-### Erforderlich mit Ellipse (`...`)
-
-Es gibt eine Alternative, die explizit deklariert, dass ein Wert erforderlich ist. Sie können als Default das Literal `...` setzen:
+//// tab | Annotiert
-=== "Python 3.9+"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial006b_an.py!}
- ```
+```Python
+q: Annotated[Union[str, None], Query(min_length=3)] = None
+```
-=== "Python 3.8+ nicht annotiert"
+////
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+//// tab | Nicht annotiert
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial006b.py!}
- ```
+```Python
+q: Union[str, None] = Query(default=None, min_length=3)
+```
-!!! 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.
+Wenn Sie einen Parameter erforderlich machen wollen, während Sie `Query` verwenden, deklarieren Sie ebenfalls einfach keinen Defaultwert:
-Dies wird **FastAPI** wissen lassen, dass dieser Parameter erforderlich ist.
+{* ../../docs_src/query_params_str_validations/tutorial006_an_py39.py hl[9] *}
### Erforderlich, kann `None` sein
@@ -463,47 +321,19 @@ Sie können deklarieren, dass ein Parameter `None` akzeptiert, aber dennoch erfo
Um das zu machen, deklarieren Sie, dass `None` ein gültiger Typ ist, aber verwenden Sie dennoch `...` als Default:
-=== "Python 3.10+"
-
- ```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!}
- ```
+{* ../../docs_src/query_params_str_validations/tutorial006c_an_py310.py hl[9] *}
-=== "Python 3.8+"
+/// tip | Tipp
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial006c_an.py!}
- ```
+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.
-=== "Python 3.10+ nicht annotiert"
+///
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | Tipp
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!}
- ```
+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.
-=== "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
@@ -511,50 +341,7 @@ Wenn Sie einen Query-Parameter explizit mit `Query` auszeichnen, können Sie ihn
Um zum Beispiel einen Query-Parameter `q` zu deklarieren, der mehrere Male in der URL vorkommen kann, schreiben Sie:
-=== "Python 3.10+"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial011_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial011_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial011_an.py!}
- ```
-
-=== "Python 3.10+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial011_py310.py!}
- ```
-
-=== "Python 3.9+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!}
- ```
-
-=== "Python 3.8+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial011.py!}
- ```
+{* ../../docs_src/query_params_str_validations/tutorial011_an_py310.py hl[9] *}
Dann, mit einer URL wie:
@@ -575,8 +362,11 @@ Die Response für diese URL wäre also:
}
```
-!!! tip "Tipp"
- Um einen Query-Parameter vom Typ `list` zu deklarieren, wie im Beispiel oben, müssen Sie explizit `Query` verwenden, sonst würde der Parameter als Requestbody interpretiert werden.
+/// tip | Tipp
+
+Um einen Query-Parameter vom Typ `list` zu deklarieren, wie im Beispiel oben, müssen Sie explizit `Query` verwenden, sonst würde der Parameter als Requestbody interpretiert werden.
+
+///
Die interaktive API-Dokumentation wird entsprechend aktualisiert und erlaubt jetzt mehrere Werte.
@@ -586,35 +376,7 @@ Die interaktive API-Dokumentation wird entsprechend aktualisiert und erlaubt jet
Und Sie können auch eine Default-`list`e von Werten definieren, wenn keine übergeben werden:
-=== "Python 3.9+"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial012_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial012_an.py!}
- ```
-
-=== "Python 3.9+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!}
- ```
-
-=== "Python 3.8+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial012.py!}
- ```
+{* ../../docs_src/query_params_str_validations/tutorial012_an_py39.py hl[9] *}
Wenn Sie auf:
@@ -637,31 +399,15 @@ gehen, wird der Default für `q` verwendet: `["foo", "bar"]`, und als Response e
Sie können auch `list` direkt verwenden, anstelle von `List[str]` (oder `list[str]` in Python 3.9+):
-=== "Python 3.9+"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial013_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial013_an.py!}
- ```
-
-=== "Python 3.8+ nicht annotiert"
+{* ../../docs_src/query_params_str_validations/tutorial013_an_py39.py hl[9] *}
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// note | Hinweis
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial013.py!}
- ```
+Beachten Sie, dass FastAPI in diesem Fall den Inhalt der Liste nicht überprüft.
-!!! 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.
- Zum Beispiel würde `List[int]` überprüfen (und dokumentieren) dass die Liste Ganzzahlen enthält. `list` alleine macht das nicht.
+///
## Deklarieren von mehr Metadaten
@@ -669,86 +415,21 @@ Sie können mehr Informationen zum Parameter hinzufügen.
Diese Informationen werden zur generierten OpenAPI hinzugefügt, und von den Dokumentations-Oberflächen und von externen Tools verwendet.
-!!! note "Hinweis"
- Beachten Sie, dass verschiedene Tools OpenAPI möglicherweise unterschiedlich gut unterstützen.
+/// note | Hinweis
- 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.
+Beachten Sie, dass verschiedene Tools OpenAPI möglicherweise unterschiedlich gut unterstützen.
-Sie können einen Titel hinzufügen – `title`:
-
-=== "Python 3.10+"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial007_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial007_an_py39.py!}
- ```
-
-=== "Python 3.8+"
+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.
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial007_an.py!}
- ```
+///
-=== "Python 3.10+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!}
- ```
-
-=== "Python 3.8+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+Sie können einen Titel hinzufügen – `title`:
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial007.py!}
- ```
+{* ../../docs_src/query_params_str_validations/tutorial007_an_py310.py hl[10] *}
Und eine Beschreibung – `description`:
-=== "Python 3.10+"
-
- ```Python hl_lines="14"
- {!> ../../../docs_src/query_params_str_validations/tutorial008_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="14"
- {!> ../../../docs_src/query_params_str_validations/tutorial008_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="15"
- {!> ../../../docs_src/query_params_str_validations/tutorial008_an.py!}
- ```
-
-=== "Python 3.10+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!}
- ```
-
-=== "Python 3.8+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="13"
- {!> ../../../docs_src/query_params_str_validations/tutorial008.py!}
- ```
+{* ../../docs_src/query_params_str_validations/tutorial008_an_py310.py hl[14] *}
## Alias-Parameter
@@ -768,41 +449,7 @@ Aber Sie möchten dennoch exakt `item-query` verwenden.
Dann können Sie einen `alias` deklarieren, und dieser Alias wird verwendet, um den Parameter-Wert zu finden:
-=== "Python 3.10+"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial009_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial009_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial009_an.py!}
- ```
-
-=== "Python 3.10+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!}
- ```
-
-=== "Python 3.8+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial009.py!}
- ```
+{* ../../docs_src/query_params_str_validations/tutorial009_an_py310.py hl[9] *}
## Parameter als deprecated ausweisen
@@ -812,41 +459,7 @@ Sie müssen ihn eine Weile dort belassen, weil Clients ihn benutzen, aber Sie m
In diesem Fall fügen Sie den Parameter `deprecated=True` zu `Query` hinzu.
-=== "Python 3.10+"
-
- ```Python hl_lines="19"
- {!> ../../../docs_src/query_params_str_validations/tutorial010_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="19"
- {!> ../../../docs_src/query_params_str_validations/tutorial010_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="20"
- {!> ../../../docs_src/query_params_str_validations/tutorial010_an.py!}
- ```
-
-=== "Python 3.10+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="16"
- {!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!}
- ```
-
-=== "Python 3.8+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="18"
- {!> ../../../docs_src/query_params_str_validations/tutorial010.py!}
- ```
+{* ../../docs_src/query_params_str_validations/tutorial010_an_py310.py hl[19] *}
Die Dokumentation wird das so anzeigen:
@@ -856,41 +469,7 @@ Die Dokumentation wird das so anzeigen:
Um einen Query-Parameter vom generierten OpenAPI-Schema auszuschließen (und daher von automatischen Dokumentations-Systemen), setzen Sie den Parameter `include_in_schema` in `Query` auf `False`.
-=== "Python 3.10+"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial014_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial014_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial014_an.py!}
- ```
-
-=== "Python 3.10+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!}
- ```
-
-=== "Python 3.8+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial014.py!}
- ```
+{* ../../docs_src/query_params_str_validations/tutorial014_an_py310.py hl[10] *}
## Zusammenfassung
diff --git a/docs/de/docs/tutorial/query-params.md b/docs/de/docs/tutorial/query-params.md
index 1b9b56bea..0b0f473e2 100644
--- a/docs/de/docs/tutorial/query-params.md
+++ b/docs/de/docs/tutorial/query-params.md
@@ -2,9 +2,7 @@
Wenn Sie in ihrer Funktion Parameter deklarieren, die nicht Teil der Pfad-Parameter sind, dann werden diese automatisch als „Query“-Parameter interpretiert.
-```Python hl_lines="9"
-{!../../../docs_src/query_params/tutorial001.py!}
-```
+{* ../../docs_src/query_params/tutorial001.py hl[9] *}
Query-Parameter (Deutsch: Abfrage-Parameter) sind die Schlüssel-Wert-Paare, die nach dem `?` in einer URL aufgelistet sind, getrennt durch `&`-Zeichen.
@@ -63,38 +61,21 @@ 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+"
-
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params/tutorial002_py310.py!}
- ```
+{* ../../docs_src/query_params/tutorial002_py310.py hl[7] *}
-=== "Python 3.8+"
+In diesem Fall wird der Funktionsparameter `q` optional, und standardmäßig `None` sein.
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params/tutorial002.py!}
- ```
+/// check
-In diesem Fall wird der Funktionsparameter `q` optional, und standardmäßig `None` sein.
+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+"
-
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params/tutorial003_py310.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params/tutorial003.py!}
- ```
+{* ../../docs_src/query_params/tutorial003_py310.py hl[7] *}
Wenn Sie nun zu:
@@ -136,17 +117,7 @@ Und Sie müssen sie auch nicht in einer spezifischen Reihenfolge deklarieren.
Parameter werden anhand ihres Namens erkannt:
-=== "Python 3.10+"
-
- ```Python hl_lines="6 8"
- {!> ../../../docs_src/query_params/tutorial004_py310.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="8 10"
- {!> ../../../docs_src/query_params/tutorial004.py!}
- ```
+{* ../../docs_src/query_params/tutorial004_py310.py hl[6,8] *}
## Erforderliche Query-Parameter
@@ -156,9 +127,7 @@ Wenn Sie keinen spezifischen Wert haben wollen, sondern der Parameter einfach op
Aber wenn Sie wollen, dass ein Query-Parameter erforderlich ist, vergeben Sie einfach keinen Defaultwert:
-```Python hl_lines="6-7"
-{!../../../docs_src/query_params/tutorial005.py!}
-```
+{* ../../docs_src/query_params/tutorial005.py hl[6:7] *}
Hier ist `needy` ein erforderlicher Query-Parameter vom Typ `str`.
@@ -204,17 +173,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
Und natürlich können Sie einige Parameter als erforderlich, einige mit Defaultwert, und einige als vollständig optional definieren:
-=== "Python 3.10+"
-
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params/tutorial006_py310.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params/tutorial006.py!}
- ```
+{* ../../docs_src/query_params/tutorial006_py310.py hl[8] *}
In diesem Fall gibt es drei Query-Parameter:
@@ -222,5 +181,8 @@ In diesem Fall gibt es drei Query-Parameter:
* `skip`, ein `int` mit einem Defaultwert `0`.
* `limit`, ein optionales `int`.
-!!! tip "Tipp"
- Sie können auch `Enum`s verwenden, auf die gleiche Weise wie mit [Pfad-Parametern](path-params.md#vordefinierte-parameterwerte){.internal-link target=_blank}.
+/// tip | Tipp
+
+Sie können auch `Enum`s verwenden, auf die gleiche Weise wie mit [Pfad-Parametern](path-params.md#vordefinierte-parameterwerte){.internal-link target=_blank}.
+
+///
diff --git a/docs/de/docs/tutorial/request-files.md b/docs/de/docs/tutorial/request-files.md
index 67b5e3a87..1f01b0d1e 100644
--- a/docs/de/docs/tutorial/request-files.md
+++ b/docs/de/docs/tutorial/request-files.md
@@ -2,70 +2,41 @@
Mit `File` können sie vom Client hochzuladende Dateien definieren.
-!!! info
- Um hochgeladene Dateien zu empfangen, installieren Sie zuerst `python-multipart`.
+/// info
- Z. B. `pip install python-multipart`.
+Um hochgeladene Dateien zu empfangen, installieren Sie zuerst `python-multipart`.
- Das, weil hochgeladene Dateien als „Formulardaten“ gesendet werden.
+Z. B. `pip install python-multipart`.
-## `File` importieren
-
-Importieren Sie `File` und `UploadFile` von `fastapi`:
-
-=== "Python 3.9+"
+Das, weil hochgeladene Dateien als „Formulardaten“ gesendet werden.
- ```Python hl_lines="3"
- {!> ../../../docs_src/request_files/tutorial001_an_py39.py!}
- ```
+///
-=== "Python 3.8+"
-
- ```Python hl_lines="1"
- {!> ../../../docs_src/request_files/tutorial001_an.py!}
- ```
-
-=== "Python 3.8+ nicht annotiert"
+## `File` importieren
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+Importieren Sie `File` und `UploadFile` von `fastapi`:
- ```Python hl_lines="1"
- {!> ../../../docs_src/request_files/tutorial001.py!}
- ```
+{* ../../docs_src/request_files/tutorial001_an_py39.py hl[3] *}
## `File`-Parameter definieren
Erstellen Sie Datei-Parameter, so wie Sie es auch mit `Body` und `Form` machen würden:
-=== "Python 3.9+"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/request_files/tutorial001_an_py39.py!}
- ```
+{* ../../docs_src/request_files/tutorial001_an_py39.py hl[9] *}
-=== "Python 3.8+"
+/// info
- ```Python hl_lines="8"
- {!> ../../../docs_src/request_files/tutorial001_an.py!}
- ```
+`File` ist eine Klasse, die direkt von `Form` erbt.
-=== "Python 3.8+ nicht annotiert"
+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"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+///
- ```Python hl_lines="7"
- {!> ../../../docs_src/request_files/tutorial001.py!}
- ```
+/// tip | Tipp
-!!! info
- `File` ist eine Klasse, die direkt von `Form` erbt.
+Um Dateibodys zu deklarieren, müssen Sie `File` verwenden, da diese Parameter sonst als Query-Parameter oder Body(-JSON)-Parameter interpretiert werden würden.
- 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.
@@ -79,26 +50,7 @@ Aber es gibt viele Fälle, in denen Sie davon profitieren, `UploadFile` zu verwe
Definieren Sie einen Datei-Parameter mit dem Typ `UploadFile`:
-=== "Python 3.9+"
-
- ```Python hl_lines="14"
- {!> ../../../docs_src/request_files/tutorial001_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="13"
- {!> ../../../docs_src/request_files/tutorial001_an.py!}
- ```
-
-=== "Python 3.8+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="12"
- {!> ../../../docs_src/request_files/tutorial001.py!}
- ```
+{* ../../docs_src/request_files/tutorial001_an_py39.py hl[14] *}
`UploadFile` zu verwenden, hat mehrere Vorzüge gegenüber `bytes`:
@@ -141,94 +93,53 @@ Wenn Sie sich innerhalb einer normalen `def`-*Pfadoperation-Funktion* befinden,
contents = myfile.file.read()
```
-!!! note "Technische Details zu `async`"
- Wenn Sie die `async`-Methoden verwenden, führt **FastAPI** die Datei-Methoden in einem Threadpool aus und erwartet sie.
+/// note | Technische Details zu `async`
-!!! 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“
+Wenn Sie die `async`-Methoden verwenden, führt **FastAPI** die Datei-Methoden in einem Threadpool aus und erwartet sie.
-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.
+/// note | Technische Details zu Starlette
- 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.
+**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.
- 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.
+## Was sind „Formulardaten“
-## Optionaler Datei-Upload
+HTML-Formulare (``) senden die Daten in einer „speziellen“ Kodierung zum Server, welche sich von JSON unterscheidet.
-Sie können eine Datei optional machen, indem Sie Standard-Typannotationen verwenden und den Defaultwert auf `None` setzen:
+**FastAPI** stellt sicher, dass diese Daten korrekt ausgelesen werden, statt JSON zu erwarten.
-=== "Python 3.10+"
+/// note | Technische Details
- ```Python hl_lines="9 17"
- {!> ../../../docs_src/request_files/tutorial001_02_an_py310.py!}
- ```
+Daten aus Formularen werden, wenn es keine Dateien sind, normalerweise mit dem „media type“ `application/x-www-form-urlencoded` kodiert.
-=== "Python 3.9+"
+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.
- ```Python hl_lines="9 17"
- {!> ../../../docs_src/request_files/tutorial001_02_an_py39.py!}
- ```
+Wenn Sie mehr über Formularfelder und ihre Kodierungen lesen möchten, besuchen Sie die MDN-Webdokumentation für POST
.
-=== "Python 3.8+"
+///
- ```Python hl_lines="10 18"
- {!> ../../../docs_src/request_files/tutorial001_02_an.py!}
- ```
+/// warning | Achtung
-=== "Python 3.10+ nicht annotiert"
+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.
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+Das ist keine Limitation von **FastAPI**, sondern Teil des HTTP-Protokolls.
- ```Python hl_lines="7 15"
- {!> ../../../docs_src/request_files/tutorial001_02_py310.py!}
- ```
+///
-=== "Python 3.8+ nicht annotiert"
+## Optionaler Datei-Upload
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+Sie können eine Datei optional machen, indem Sie Standard-Typannotationen verwenden und den Defaultwert auf `None` setzen:
- ```Python hl_lines="9 17"
- {!> ../../../docs_src/request_files/tutorial001_02.py!}
- ```
+{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *}
## `UploadFile` mit zusätzlichen Metadaten
Sie können auch `File()` zusammen mit `UploadFile` verwenden, um zum Beispiel zusätzliche Metadaten zu setzen:
-=== "Python 3.9+"
-
- ```Python hl_lines="9 15"
- {!> ../../../docs_src/request_files/tutorial001_03_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="8 14"
- {!> ../../../docs_src/request_files/tutorial001_03_an.py!}
- ```
-
-=== "Python 3.8+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="7 13"
- {!> ../../../docs_src/request_files/tutorial001_03.py!}
- ```
+{* ../../docs_src/request_files/tutorial001_03_an_py39.py hl[9,15] *}
## Mehrere Datei-Uploads
@@ -238,76 +149,23 @@ Diese werden demselben Formularfeld zugeordnet, welches mit den Formulardaten ge
Um das zu machen, deklarieren Sie eine Liste von `bytes` oder `UploadFile`s:
-=== "Python 3.9+"
-
- ```Python hl_lines="10 15"
- {!> ../../../docs_src/request_files/tutorial002_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="11 16"
- {!> ../../../docs_src/request_files/tutorial002_an.py!}
- ```
-
-=== "Python 3.9+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+{* ../../docs_src/request_files/tutorial002_an_py39.py hl[10,15] *}
- ```Python hl_lines="8 13"
- {!> ../../../docs_src/request_files/tutorial002_py39.py!}
- ```
-
-=== "Python 3.8+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+Sie erhalten, wie deklariert, eine `list`e von `bytes` oder `UploadFile`s.
- ```Python hl_lines="10 15"
- {!> ../../../docs_src/request_files/tutorial002.py!}
- ```
+/// note | Technische Details
-Sie erhalten, wie deklariert, eine `list`e von `bytes` oder `UploadFile`s.
+Sie können auch `from starlette.responses import HTMLResponse` verwenden.
-!!! note "Technische Details"
- Sie können auch `from starlette.responses import HTMLResponse` verwenden.
+**FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette.
- **FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette.
+///
### Mehrere Datei-Uploads mit zusätzlichen Metadaten
Und so wie zuvor können Sie `File()` verwenden, um zusätzliche Parameter zu setzen, sogar für `UploadFile`:
-=== "Python 3.9+"
-
- ```Python hl_lines="11 18-20"
- {!> ../../../docs_src/request_files/tutorial003_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="12 19-21"
- {!> ../../../docs_src/request_files/tutorial003_an.py!}
- ```
-
-=== "Python 3.9+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="9 16"
- {!> ../../../docs_src/request_files/tutorial003_py39.py!}
- ```
-
-=== "Python 3.8+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="11 18"
- {!> ../../../docs_src/request_files/tutorial003.py!}
- ```
+{* ../../docs_src/request_files/tutorial003_an_py39.py hl[11,18:20] *}
## Zusammenfassung
diff --git a/docs/de/docs/tutorial/request-forms-and-files.md b/docs/de/docs/tutorial/request-forms-and-files.md
index 86b1406e6..3c5e11adf 100644
--- a/docs/de/docs/tutorial/request-forms-and-files.md
+++ b/docs/de/docs/tutorial/request-forms-and-files.md
@@ -2,67 +2,35 @@
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`.
+/// info
- Z. B. `pip install python-multipart`.
+Um hochgeladene Dateien und/oder Formulardaten zu empfangen, installieren Sie zuerst `python-multipart`.
-## `File` und `Form` importieren
-
-=== "Python 3.9+"
-
- ```Python hl_lines="3"
- {!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!}
- ```
-
-=== "Python 3.8+"
+Z. B. `pip install python-multipart`.
- ```Python hl_lines="1"
- {!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!}
- ```
+///
-=== "Python 3.8+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+## `File` und `Form` importieren
- ```Python hl_lines="1"
- {!> ../../../docs_src/request_forms_and_files/tutorial001.py!}
- ```
+{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[3] *}
## `File` und `Form`-Parameter definieren
Erstellen Sie Datei- und Formularparameter, so wie Sie es auch mit `Body` und `Query` machen würden:
-=== "Python 3.9+"
-
- ```Python hl_lines="10-12"
- {!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="9-11"
- {!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!}
- ```
-
-=== "Python 3.8+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="8"
- {!> ../../../docs_src/request_forms_and_files/tutorial001.py!}
- ```
+{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[10:12] *}
Die Datei- und Formularfelder werden als Formulardaten hochgeladen, und Sie erhalten diese Dateien und Formularfelder.
Und Sie können einige der Dateien als `bytes` und einige als `UploadFile` deklarieren.
-!!! warning "Achtung"
- Sie können mehrere `File`- und `Form`-Parameter in einer *Pfadoperation* deklarieren, aber Sie können nicht gleichzeitig auch `Body`-Felder deklarieren, welche Sie als JSON erwarten, da der Request den Body mittels `multipart/form-data` statt `application/json` kodiert.
+/// warning | Achtung
+
+Sie können mehrere `File`- und `Form`-Parameter in einer *Pfadoperation* deklarieren, aber Sie können nicht gleichzeitig auch `Body`-Felder deklarieren, welche Sie als JSON erwarten, da der Request den Body mittels `multipart/form-data` statt `application/json` kodiert.
+
+Das ist keine Limitation von **FastAPI**, sondern Teil des HTTP-Protokolls.
- Das ist keine Limitation von **FastAPI**, sondern Teil des HTTP-Protokolls.
+///
## Zusammenfassung
diff --git a/docs/de/docs/tutorial/request-forms.md b/docs/de/docs/tutorial/request-forms.md
index 6c029b5fe..2f88caaba 100644
--- a/docs/de/docs/tutorial/request-forms.md
+++ b/docs/de/docs/tutorial/request-forms.md
@@ -2,72 +2,43 @@
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`.
+/// info
- Z. B. `pip install python-multipart`.
+Um Formulare zu verwenden, installieren Sie zuerst `python-multipart`.
-## `Form` importieren
-
-Importieren Sie `Form` von `fastapi`:
-
-=== "Python 3.9+"
-
- ```Python hl_lines="3"
- {!> ../../../docs_src/request_forms/tutorial001_an_py39.py!}
- ```
+Z. B. `pip install python-multipart`.
-=== "Python 3.8+"
+///
- ```Python hl_lines="1"
- {!> ../../../docs_src/request_forms/tutorial001_an.py!}
- ```
-
-=== "Python 3.8+ nicht annotiert"
+## `Form` importieren
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+Importieren Sie `Form` von `fastapi`:
- ```Python hl_lines="1"
- {!> ../../../docs_src/request_forms/tutorial001.py!}
- ```
+{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[3] *}
## `Form`-Parameter definieren
Erstellen Sie Formular-Parameter, so wie Sie es auch mit `Body` und `Query` machen würden:
-=== "Python 3.9+"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/request_forms/tutorial001_an_py39.py!}
- ```
-
-=== "Python 3.8+"
+{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[9] *}
- ```Python hl_lines="8"
- {!> ../../../docs_src/request_forms/tutorial001_an.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.
-=== "Python 3.8+ nicht annotiert"
+Die Spec erfordert, dass die Felder exakt `username` und `password` genannt werden und als Formularfelder, nicht JSON, gesendet werden.
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+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.
- ```Python hl_lines="7"
- {!> ../../../docs_src/request_forms/tutorial001.py!}
- ```
+/// info
-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.
+`Form` ist eine Klasse, die direkt von `Body` erbt.
-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.
+/// tip | Tipp
-!!! info
- `Form` ist eine Klasse, die direkt von `Body` erbt.
+Um Formularbodys zu deklarieren, verwenden Sie explizit `Form`, da diese Parameter sonst als Query-Parameter oder Body(-JSON)-Parameter interpretiert werden würden.
-!!! 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“
@@ -75,17 +46,23 @@ HTML-Formulare (``) senden die Daten in einer „speziellen“ Kodi
**FastAPI** stellt sicher, dass diese Daten korrekt ausgelesen werden, statt JSON zu erwarten.
-!!! note "Technische Details"
- Daten aus Formularen werden normalerweise mit dem „media type“ `application/x-www-form-urlencoded` kodiert.
+/// 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
.
+
+///
- Wenn das Formular stattdessen Dateien enthält, werden diese mit `multipart/form-data` kodiert. Im nächsten Kapitel erfahren Sie mehr über die Handhabung von Dateien.
+/// warning | Achtung
- Wenn Sie mehr über Formularfelder und ihre Kodierungen lesen möchten, besuchen Sie die MDN-Webdokumentation für POST
.
+Sie können mehrere `Form`-Parameter in einer *Pfadoperation* deklarieren, aber Sie können nicht gleichzeitig auch `Body`-Felder deklarieren, welche Sie als JSON erwarten, da der Request den Body mittels `application/x-www-form-urlencoded` statt `application/json` kodiert.
-!!! warning "Achtung"
- Sie können mehrere `Form`-Parameter in einer *Pfadoperation* deklarieren, aber Sie können nicht gleichzeitig auch `Body`-Felder deklarieren, welche Sie als JSON erwarten, da der Request den Body mittels `application/x-www-form-urlencoded` statt `application/json` kodiert.
+Das ist keine Limitation von **FastAPI**, sondern Teil des HTTP-Protokolls.
- Das ist keine Limitation von **FastAPI**, sondern Teil des HTTP-Protokolls.
+///
## Zusammenfassung
diff --git a/docs/de/docs/tutorial/response-model.md b/docs/de/docs/tutorial/response-model.md
index d5b92e0f9..faf9be516 100644
--- a/docs/de/docs/tutorial/response-model.md
+++ b/docs/de/docs/tutorial/response-model.md
@@ -4,23 +4,7 @@ Sie können den Typ der ../../../docs_src/response_model/tutorial001_01_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="18 23"
- {!> ../../../docs_src/response_model/tutorial001_01_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="18 23"
- {!> ../../../docs_src/response_model/tutorial001_01.py!}
- ```
+{* ../../docs_src/response_model/tutorial001_01_py310.py hl[16,21] *}
FastAPI wird diesen Rückgabetyp verwenden, um:
@@ -53,35 +37,25 @@ Sie können `response_model` in jeder möglichen *Pfadoperation* verwenden:
* `@app.delete()`
* usw.
-=== "Python 3.10+"
-
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001_py39.py!}
- ```
+{* ../../docs_src/response_model/tutorial001_py310.py hl[17,22,24:27] *}
-=== "Python 3.8+"
+/// note | Hinweis
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001.py!}
- ```
+Beachten Sie, dass `response_model` ein Parameter der „Dekorator“-Methode ist (`get`, `post`, usw.). Nicht der *Pfadoperation-Funktion*, so wie die anderen Parameter.
-!!! note "Hinweis"
- Beachten Sie, dass `response_model` ein Parameter der „Dekorator“-Methode ist (`get`, `post`, usw.). Nicht der *Pfadoperation-Funktion*, so wie die anderen Parameter.
+///
`response_model` nimmt denselben Typ entgegen, den Sie auch für ein Pydantic-Modellfeld deklarieren würden, also etwa ein Pydantic-Modell, aber es kann auch z. B. eine `list`e von Pydantic-Modellen sein, wie etwa `List[Item]`.
FastAPI wird dieses `response_model` nehmen, um die Daten zu dokumentieren, validieren, usw. und auch, um **die Ausgabedaten** entsprechend der Typdeklaration **zu konvertieren und filtern**.
-!!! tip "Tipp"
- Wenn Sie in Ihrem Editor strikte Typchecks haben, mypy, usw., können Sie den Funktions-Rückgabetyp als `Any` deklarieren.
+/// tip | Tipp
- 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`.
+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
@@ -95,37 +69,20 @@ Sie können auch `response_model=None` verwenden, um das Erstellen eines Respons
Im Folgenden deklarieren wir ein `UserIn`-Modell; es enthält ein Klartext-Passwort:
-=== "Python 3.10+"
+{* ../../docs_src/response_model/tutorial002_py310.py hl[7,9] *}
- ```Python hl_lines="7 9"
- {!> ../../../docs_src/response_model/tutorial002_py310.py!}
- ```
+/// info
-=== "Python 3.8+"
+Um `EmailStr` zu verwenden, installieren Sie zuerst `email-validator`.
- ```Python hl_lines="9 11"
- {!> ../../../docs_src/response_model/tutorial002.py!}
- ```
+Z. B. `pip install email-validator`
+oder `pip install pydantic[email]`.
-!!! 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:
-=== "Python 3.10+"
-
- ```Python hl_lines="16"
- {!> ../../../docs_src/response_model/tutorial002_py310.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="18"
- {!> ../../../docs_src/response_model/tutorial002.py!}
- ```
+{* ../../docs_src/response_model/tutorial002_py310.py hl[16] *}
Immer wenn jetzt ein Browser einen Benutzer mit Passwort erzeugt, gibt die API dasselbe Passwort in der Response zurück.
@@ -133,52 +90,25 @@ Hier ist das möglicherweise kein Problem, da es derselbe Benutzer ist, der das
Aber wenn wir dasselbe Modell für eine andere *Pfadoperation* verwenden, könnten wir das Passwort dieses Benutzers zu jedem Client schicken.
-!!! danger "Gefahr"
- Speichern Sie niemals das Klartext-Passwort eines Benutzers, oder versenden Sie es in einer Response wie dieser, wenn Sie sich nicht der resultierenden Gefahren bewusst sind und nicht wissen, was Sie tun.
+/// danger | Gefahr
-## Ausgabemodell hinzufügen
+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.
-Wir können stattdessen ein Eingabemodell mit dem Klartext-Passwort, und ein Ausgabemodell ohne das Passwort erstellen:
-
-=== "Python 3.10+"
+///
- ```Python hl_lines="9 11 16"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
+## Ausgabemodell hinzufügen
-=== "Python 3.8+"
+Wir können stattdessen ein Eingabemodell mit dem Klartext-Passwort, und ein Ausgabemodell ohne das Passwort erstellen:
- ```Python hl_lines="9 11 16"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+{* ../../docs_src/response_model/tutorial003_py310.py hl[9,11,16] *}
Obwohl unsere *Pfadoperation-Funktion* hier denselben `user` von der Eingabe zurückgibt, der das Passwort enthält:
-=== "Python 3.10+"
-
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+{* ../../docs_src/response_model/tutorial003_py310.py hl[24] *}
... haben wir deklariert, dass `response_model` das Modell `UserOut` ist, welches das Passwort nicht enthält:
-=== "Python 3.10+"
-
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+{* ../../docs_src/response_model/tutorial003_py310.py hl[22] *}
Darum wird **FastAPI** sich darum kümmern, dass alle Daten, die nicht im Ausgabemodell deklariert sind, herausgefiltert werden (mittels Pydantic).
@@ -202,17 +132,7 @@ Aber in den meisten Fällen, wenn wir so etwas machen, wollen wir nur, dass das
Und in solchen Fällen können wir Klassen und Vererbung verwenden, um Vorteil aus den Typannotationen in der Funktion zu ziehen, was vom Editor und von Tools besser unterstützt wird, während wir gleichzeitig FastAPIs **Datenfilterung** behalten.
-=== "Python 3.10+"
-
- ```Python hl_lines="7-10 13-14 18"
- {!> ../../../docs_src/response_model/tutorial003_01_py310.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="9-13 15-16 20"
- {!> ../../../docs_src/response_model/tutorial003_01.py!}
- ```
+{* ../../docs_src/response_model/tutorial003_01_py310.py hl[7:10,13:14,18] *}
Damit erhalten wir Tool-Unterstützung, vom Editor und mypy, da dieser Code hinsichtlich der Typen korrekt ist, aber wir erhalten auch die Datenfilterung von FastAPI.
@@ -254,9 +174,7 @@ Es kann Fälle geben, bei denen Sie etwas zurückgeben, das kein gültiges Pydan
Der häufigste Anwendungsfall ist, wenn Sie [eine Response direkt zurückgeben, wie es später im Handbuch für fortgeschrittene Benutzer erläutert wird](../advanced/response-directly.md){.internal-link target=_blank}.
-```Python hl_lines="8 10-11"
-{!> ../../../docs_src/response_model/tutorial003_02.py!}
-```
+{* ../../docs_src/response_model/tutorial003_02.py hl[8,10:11] *}
Dieser einfache Anwendungsfall wird automatisch von FastAPI gehandhabt, weil die Annotation des Rückgabetyps die Klasse (oder eine Unterklasse von) `Response` ist.
@@ -266,9 +184,7 @@ Und Tools werden auch glücklich sein, weil sowohl `RedirectResponse` als auch `
Sie können auch eine Unterklasse von `Response` in der Typannotation verwenden.
-```Python hl_lines="8-9"
-{!> ../../../docs_src/response_model/tutorial003_03.py!}
-```
+{* ../../docs_src/response_model/tutorial003_03.py hl[8:9] *}
Das wird ebenfalls funktionieren, weil `RedirectResponse` eine Unterklasse von `Response` ist, und FastAPI sich um diesen einfachen Anwendungsfall automatisch kümmert.
@@ -278,17 +194,7 @@ Aber wenn Sie ein beliebiges anderes Objekt zurückgeben, das kein gültiger Pyd
Das gleiche wird passieren, wenn Sie eine Union mehrerer Typen haben, und einer oder mehrere sind nicht gültige Pydantic-Typen. Zum Beispiel funktioniert folgendes nicht 💥:
-=== "Python 3.10+"
-
- ```Python hl_lines="8"
- {!> ../../../docs_src/response_model/tutorial003_04_py310.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/response_model/tutorial003_04.py!}
- ```
+{* ../../docs_src/response_model/tutorial003_04_py310.py hl[8] *}
... das scheitert, da die Typannotation kein Pydantic-Typ ist, und auch keine einzelne `Response`-Klasse, oder -Unterklasse, es ist eine Union (eines von beiden) von `Response` und `dict`.
@@ -300,17 +206,7 @@ Aber Sie möchten dennoch den Rückgabetyp in der Funktion annotieren, um Unters
In diesem Fall können Sie die Generierung des Responsemodells abschalten, indem Sie `response_model=None` setzen:
-=== "Python 3.10+"
-
- ```Python hl_lines="7"
- {!> ../../../docs_src/response_model/tutorial003_05_py310.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/response_model/tutorial003_05.py!}
- ```
+{* ../../docs_src/response_model/tutorial003_05_py310.py hl[7] *}
Das bewirkt, dass FastAPI die Generierung des Responsemodells unterlässt, und damit können Sie jede gewünschte Rückgabetyp-Annotation haben, ohne dass es Ihre FastAPI-Anwendung beeinflusst. 🤓
@@ -318,23 +214,7 @@ Das bewirkt, dass FastAPI die Generierung des Responsemodells unterlässt, und d
Ihr Responsemodell könnte Defaultwerte haben, wie:
-=== "Python 3.10+"
-
- ```Python hl_lines="9 11-12"
- {!> ../../../docs_src/response_model/tutorial004_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="11 13-14"
- {!> ../../../docs_src/response_model/tutorial004_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="11 13-14"
- {!> ../../../docs_src/response_model/tutorial004.py!}
- ```
+{* ../../docs_src/response_model/tutorial004_py310.py hl[9,11:12] *}
* `description: Union[str, None] = None` (oder `str | None = None` in Python 3.10) hat einen Defaultwert `None`.
* `tax: float = 10.5` hat einen Defaultwert `10.5`.
@@ -348,23 +228,7 @@ Wenn Sie zum Beispiel Modelle mit vielen optionalen Attributen in einer NoSQL-Da
Sie können den *Pfadoperation-Dekorator*-Parameter `response_model_exclude_unset=True` setzen:
-=== "Python 3.10+"
-
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial004_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial004_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial004.py!}
- ```
+{* ../../docs_src/response_model/tutorial004_py310.py hl[22] *}
Die Defaultwerte werden dann nicht in der Response enthalten sein, sondern nur die tatsächlich gesetzten Werte.
@@ -377,21 +241,30 @@ Wenn Sie also den Artikel mit der ID `foo` bei der *Pfadoperation* anfragen, wir
}
```
-!!! info
- In Pydantic v1 hieß diese Methode `.dict()`, in Pydantic v2 wurde sie deprecated (aber immer noch unterstützt) und in `.model_dump()` umbenannt.
+/// info
+
+In Pydantic v1 hieß diese Methode `.dict()`, in Pydantic v2 wurde sie deprecated (aber immer noch unterstützt) und in `.model_dump()` umbenannt.
+
+Die Beispiele hier verwenden `.dict()` für die Kompatibilität mit Pydantic v1, Sie sollten jedoch stattdessen `.model_dump()` verwenden, wenn Sie Pydantic v2 verwenden können.
+
+///
+
+/// info
+
+FastAPI verwendet `.dict()` von Pydantic Modellen, mit dessen `exclude_unset`-Parameter, um das zu erreichen.
- Die Beispiele hier verwenden `.dict()` für die Kompatibilität mit Pydantic v1, Sie sollten jedoch stattdessen `.model_dump()` verwenden, wenn Sie Pydantic v2 verwenden können.
+///
-!!! info
- FastAPI verwendet `.dict()` von Pydantic Modellen, mit dessen `exclude_unset`-Parameter, um das zu erreichen.
+/// info
-!!! info
- Sie können auch:
+Sie können auch:
- * `response_model_exclude_defaults=True`
- * `response_model_exclude_none=True`
+* `response_model_exclude_defaults=True`
+* `response_model_exclude_none=True`
- verwenden, wie in der Pydantic Dokumentation für `exclude_defaults` und `exclude_none` beschrieben.
+verwenden, wie in der Pydantic Dokumentation für `exclude_defaults` und `exclude_none` beschrieben.
+
+///
#### Daten mit Werten für Felder mit Defaultwerten
@@ -426,10 +299,13 @@ dann ist FastAPI klug genug (tatsächlich ist Pydantic klug genug) zu erkennen,
Diese Felder werden also in der JSON-Response enthalten sein.
-!!! tip "Tipp"
- Beachten Sie, dass Defaultwerte alles Mögliche sein können, nicht nur `None`.
+/// tip | Tipp
+
+Beachten Sie, dass Defaultwerte alles Mögliche sein können, nicht nur `None`.
- Sie können eine Liste (`[]`), ein `float` `10.5`, usw. sein.
+Sie können eine Liste (`[]`), ein `float` `10.5`, usw. sein.
+
+///
### `response_model_include` und `response_model_exclude`
@@ -439,45 +315,31 @@ Diese nehmen ein `set` von `str`s entgegen, welches Namen von Attributen sind, d
Das kann als schnelle Abkürzung verwendet werden, wenn Sie nur ein Pydantic-Modell haben und ein paar Daten von der Ausgabe ausschließen wollen.
-!!! tip "Tipp"
- Es wird dennoch empfohlen, dass Sie die Ideen von oben verwenden, also mehrere Klassen statt dieser Parameter.
+/// tip | Tipp
+
+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.
+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.
+Das trifft auch auf `response_model_by_alias` zu, welches ähnlich funktioniert.
-=== "Python 3.10+"
+///
- ```Python hl_lines="29 35"
- {!> ../../../docs_src/response_model/tutorial005_py310.py!}
- ```
+{* ../../docs_src/response_model/tutorial005_py310.py hl[29,35] *}
-=== "Python 3.8+"
+/// tip | Tipp
- ```Python hl_lines="31 37"
- {!> ../../../docs_src/response_model/tutorial005.py!}
- ```
+Die Syntax `{"name", "description"}` erzeugt ein `set` mit diesen zwei Werten.
-!!! tip "Tipp"
- Die Syntax `{"name", "description"}` erzeugt ein `set` mit diesen zwei Werten.
+Äquivalent zu `set(["name", "description"])`.
- Äquivalent zu `set(["name", "description"])`.
+///
#### `list`en statt `set`s verwenden
Wenn Sie vergessen, ein `set` zu verwenden, und stattdessen eine `list`e oder ein `tuple` übergeben, wird FastAPI die dennoch in ein `set` konvertieren, und es wird korrekt funktionieren:
-=== "Python 3.10+"
-
- ```Python hl_lines="29 35"
- {!> ../../../docs_src/response_model/tutorial006_py310.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="31 37"
- {!> ../../../docs_src/response_model/tutorial006.py!}
- ```
+{* ../../docs_src/response_model/tutorial006_py310.py hl[29,35] *}
## Zusammenfassung
diff --git a/docs/de/docs/tutorial/response-status-code.md b/docs/de/docs/tutorial/response-status-code.md
index a9cc238f8..a1b388a0a 100644
--- a/docs/de/docs/tutorial/response-status-code.md
+++ b/docs/de/docs/tutorial/response-status-code.md
@@ -8,17 +8,21 @@ So wie ein Responsemodell, können Sie auch einen HTTP-Statuscode für die Respo
* `@app.delete()`
* usw.
-```Python hl_lines="6"
-{!../../../docs_src/response_status_code/tutorial001.py!}
-```
+{* ../../docs_src/response_status_code/tutorial001.py hl[6] *}
-!!! note "Hinweis"
- Beachten Sie, dass `status_code` ein Parameter der „Dekorator“-Methode ist (`get`, `post`, usw.). Nicht der *Pfadoperation-Funktion*, so wie die anderen Parameter und der Body.
+/// note | Hinweis
+
+Beachten Sie, dass `status_code` ein Parameter der „Dekorator“-Methode ist (`get`, `post`, usw.). Nicht der *Pfadoperation-Funktion*, so wie die anderen Parameter und der Body.
+
+///
Dem `status_code`-Parameter wird eine Zahl mit dem HTTP-Statuscode übergeben.
-!!! info
- Alternativ kann `status_code` auch ein `IntEnum` erhalten, so wie Pythons `http.HTTPStatus`.
+/// info
+
+Alternativ kann `status_code` auch ein `IntEnum` erhalten, so wie Pythons `http.HTTPStatus`.
+
+///
Das wird:
@@ -27,15 +31,21 @@ Das wird:
-!!! note "Hinweis"
- Einige Responsecodes (siehe nächster Abschnitt) kennzeichnen, dass die Response keinen Body hat.
+/// note | Hinweis
+
+Einige Responsecodes (siehe nächster Abschnitt) kennzeichnen, dass die Response keinen Body hat.
+
+FastAPI versteht das und wird in der OpenAPI-Dokumentation anzeigen, dass es keinen Responsebody gibt.
- FastAPI versteht das und wird in der OpenAPI-Dokumentation anzeigen, dass es keinen Responsebody gibt.
+///
## Über HTTP-Statuscodes
-!!! note "Hinweis"
- Wenn Sie bereits wissen, was HTTP-Statuscodes sind, überspringen Sie dieses Kapitel und fahren Sie mit dem nächsten fort.
+/// note | Hinweis
+
+Wenn Sie bereits wissen, was HTTP-Statuscodes sind, überspringen Sie dieses Kapitel und fahren Sie mit dem nächsten fort.
+
+///
In HTTP senden Sie als Teil der Response einen aus drei Ziffern bestehenden numerischen Statuscode.
@@ -54,16 +64,17 @@ Kurz:
* Für allgemeine Fehler beim Client können Sie einfach `400` verwenden.
* `500` und darüber stehen für Server-Fehler. Diese verwenden Sie fast nie direkt. Wenn etwas an irgendeiner Stelle in Ihrem Anwendungscode oder im Server schiefläuft, wird automatisch einer dieser Fehler-Statuscodes zurückgegeben.
-!!! tip "Tipp"
- Um mehr über Statuscodes zu lernen, und welcher wofür verwendet wird, lesen Sie die MDN Dokumentation über HTTP-Statuscodes.
+/// 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!}
-```
+{* ../../docs_src/response_status_code/tutorial001.py hl[6] *}
`201` ist der Statuscode für „Created“ („Erzeugt“).
@@ -71,18 +82,19 @@ Aber Sie müssen sich nicht daran erinnern, welcher dieser Codes was bedeutet.
Sie können die Hilfsvariablen von `fastapi.status` verwenden.
-```Python hl_lines="1 6"
-{!../../../docs_src/response_status_code/tutorial002.py!}
-```
+{* ../../docs_src/response_status_code/tutorial002.py hl[1,6] *}
Diese sind nur eine Annehmlichkeit und enthalten dieselbe Nummer, aber auf diese Weise können Sie die Autovervollständigung Ihres Editors verwenden, um sie zu finden:
-!!! note "Technische Details"
- Sie können auch `from starlette import status` verwenden.
+/// note | Technische Details
+
+Sie können auch `from starlette import status` verwenden.
+
+**FastAPI** bietet dieselben `starlette.status`-Codes auch via `fastapi.status` an, als Annehmlichkeit für Sie, den Entwickler. Sie kommen aber direkt von Starlette.
- **FastAPI** bietet dieselben `starlette.status`-Codes auch via `fastapi.status` an, als Annehmlichkeit für Sie, den Entwickler. Sie kommen aber direkt von Starlette.
+///
## Den Defaultwert ändern
diff --git a/docs/de/docs/tutorial/schema-extra-example.md b/docs/de/docs/tutorial/schema-extra-example.md
index e8bfc9876..f065ad4ca 100644
--- a/docs/de/docs/tutorial/schema-extra-example.md
+++ b/docs/de/docs/tutorial/schema-extra-example.md
@@ -8,71 +8,59 @@ Hier sind mehrere Möglichkeiten, das zu tun.
Sie können `examples` („Beispiele“) für ein Pydantic-Modell deklarieren, welche dem generierten JSON-Schema hinzugefügt werden.
-=== "Python 3.10+ Pydantic v2"
+//// tab | Pydantic v2
- ```Python hl_lines="13-24"
- {!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!}
- ```
+{* ../../docs_src/schema_extra_example/tutorial001_py310.py hl[13:24] *}
-=== "Python 3.10+ Pydantic v1"
+////
- ```Python hl_lines="13-23"
- {!> ../../../docs_src/schema_extra_example/tutorial001_py310_pv1.py!}
- ```
+//// tab | Pydantic v1
-=== "Python 3.8+ Pydantic v2"
+{* ../../docs_src/schema_extra_example/tutorial001_pv1_py310.py hl[13:23] *}
- ```Python hl_lines="15-26"
- {!> ../../../docs_src/schema_extra_example/tutorial001.py!}
- ```
+////
-=== "Python 3.8+ Pydantic v1"
+Diese zusätzlichen Informationen werden unverändert zum für dieses Modell ausgegebenen **JSON-Schema** hinzugefügt und in der API-Dokumentation verwendet.
- ```Python hl_lines="15-25"
- {!> ../../../docs_src/schema_extra_example/tutorial001_pv1.py!}
- ```
+//// tab | Pydantic v2
-Diese zusätzlichen Informationen werden unverändert zum für dieses Modell ausgegebenen **JSON-Schema** hinzugefügt und in der API-Dokumentation verwendet.
+In Pydantic Version 2 würden Sie das Attribut `model_config` verwenden, das ein `dict` akzeptiert, wie beschrieben in Pydantic-Dokumentation: Configuration.
-=== "Pydantic v2"
+Sie können `json_schema_extra` setzen, mit einem `dict`, das alle zusätzlichen Daten enthält, die im generierten JSON-Schema angezeigt werden sollen, einschließlich `examples`.
- In Pydantic Version 2 würden Sie das Attribut `model_config` verwenden, das ein `dict` akzeptiert, wie beschrieben in 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
-=== "Pydantic v1"
+In Pydantic Version 1 würden Sie eine interne Klasse `Config` und `schema_extra` verwenden, wie beschrieben in Pydantic-Dokumentation: Schema customization.
- 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`.
- Sie können `schema_extra` setzen, mit einem `dict`, das alle zusätzlichen Daten enthält, die im generierten JSON-Schema angezeigt werden sollen, einschließlich `examples`.
+////
-!!! tip "Tipp"
- Mit derselben Technik können Sie das JSON-Schema erweitern und Ihre eigenen benutzerdefinierten Zusatzinformationen hinzufügen.
+/// tip | Tipp
- Sie könnten das beispielsweise verwenden, um Metadaten für eine Frontend-Benutzeroberfläche usw. hinzuzufügen.
+Mit derselben Technik können Sie das JSON-Schema erweitern und Ihre eigenen benutzerdefinierten Zusatzinformationen hinzufügen.
-!!! info
- OpenAPI 3.1.0 (verwendet seit FastAPI 0.99.0) hat Unterstützung für `examples` hinzugefügt, was Teil des **JSON Schema** Standards ist.
+Sie könnten das beispielsweise verwenden, um Metadaten für eine Frontend-Benutzeroberfläche usw. hinzuzufügen.
- Zuvor unterstützte es nur das Schlüsselwort `example` mit einem einzigen Beispiel. Dieses wird weiterhin von OpenAPI 3.1.0 unterstützt, ist jedoch 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.
+/// info
-## Zusätzliche Argumente für `Field`
+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.
-Wenn Sie `Field()` mit Pydantic-Modellen verwenden, können Sie ebenfalls zusätzliche `examples` deklarieren:
+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.
-=== "Python 3.10+"
+///
- ```Python hl_lines="2 8-11"
- {!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!}
- ```
+## Zusätzliche Argumente für `Field`
-=== "Python 3.8+"
+Wenn Sie `Field()` mit Pydantic-Modellen verwenden, können Sie ebenfalls zusätzliche `examples` deklarieren:
- ```Python hl_lines="4 10-13"
- {!> ../../../docs_src/schema_extra_example/tutorial002.py!}
- ```
+{* ../../docs_src/schema_extra_example/tutorial002_py310.py hl[2,8:11] *}
## `examples` im JSON-Schema – OpenAPI
@@ -92,41 +80,7 @@ können Sie auch eine Gruppe von `examples` mit zusätzlichen Informationen dekl
Hier übergeben wir `examples`, welches ein einzelnes Beispiel für die in `Body()` erwarteten Daten enthält:
-=== "Python 3.10+"
-
- ```Python hl_lines="22-29"
- {!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="22-29"
- {!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="23-30"
- {!> ../../../docs_src/schema_extra_example/tutorial003_an.py!}
- ```
-
-=== "Python 3.10+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="18-25"
- {!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!}
- ```
-
-=== "Python 3.8+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="20-27"
- {!> ../../../docs_src/schema_extra_example/tutorial003.py!}
- ```
+{* ../../docs_src/schema_extra_example/tutorial003_an_py310.py hl[22:29] *}
### Beispiel in der Dokumentations-Benutzeroberfläche
@@ -138,41 +92,7 @@ Mit jeder der oben genannten Methoden würde es in `/docs` so aussehen:
Sie können natürlich auch mehrere `examples` übergeben:
-=== "Python 3.10+"
-
- ```Python hl_lines="23-38"
- {!> ../../../docs_src/schema_extra_example/tutorial004_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="23-38"
- {!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="24-39"
- {!> ../../../docs_src/schema_extra_example/tutorial004_an.py!}
- ```
-
-=== "Python 3.10+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="19-34"
- {!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!}
- ```
-
-=== "Python 3.8+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="21-36"
- {!> ../../../docs_src/schema_extra_example/tutorial004.py!}
- ```
+{* ../../docs_src/schema_extra_example/tutorial004_an_py310.py hl[23:38] *}
Wenn Sie das tun, werden die Beispiele Teil des internen **JSON-Schemas** für diese Body-Daten.
@@ -213,41 +133,7 @@ Jedes spezifische Beispiel-`dict` in den `examples` kann Folgendes enthalten:
Sie können es so verwenden:
-=== "Python 3.10+"
-
- ```Python hl_lines="23-49"
- {!> ../../../docs_src/schema_extra_example/tutorial005_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="23-49"
- {!> ../../../docs_src/schema_extra_example/tutorial005_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="24-50"
- {!> ../../../docs_src/schema_extra_example/tutorial005_an.py!}
- ```
-
-=== "Python 3.10+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="19-45"
- {!> ../../../docs_src/schema_extra_example/tutorial005_py310.py!}
- ```
-
-=== "Python 3.8+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="21-47"
- {!> ../../../docs_src/schema_extra_example/tutorial005.py!}
- ```
+{* ../../docs_src/schema_extra_example/tutorial005_an_py310.py hl[23:49] *}
### OpenAPI-Beispiele in der Dokumentations-Benutzeroberfläche
@@ -257,17 +143,23 @@ Wenn `openapi_examples` zu `Body()` hinzugefügt wird, würde `/docs` so aussehe
## Technische Details
-!!! tip "Tipp"
- Wenn Sie bereits **FastAPI** Version **0.99.0 oder höher** verwenden, können Sie diese Details wahrscheinlich **überspringen**.
+/// tip | Tipp
+
+Wenn Sie bereits **FastAPI** Version **0.99.0 oder höher** verwenden, können Sie diese Details wahrscheinlich **überspringen**.
+
+Sie sind für ältere Versionen relevanter, bevor OpenAPI 3.1.0 verfügbar war.
- Sie sind für ältere Versionen relevanter, bevor OpenAPI 3.1.0 verfügbar war.
+Sie können dies als eine kurze **Geschichtsstunde** zu OpenAPI und JSON Schema betrachten. 🤓
- Sie 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**.
+/// warning | Achtung
- 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.
+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**.
@@ -285,8 +177,11 @@ OpenAPI fügte auch die Felder `example` und `examples` zu anderen Teilen der Sp
* `File()`
* `Form()`
-!!! info
- Dieser alte, OpenAPI-spezifische `examples`-Parameter heißt seit FastAPI `0.103.0` jetzt `openapi_examples`.
+/// info
+
+Dieser alte, OpenAPI-spezifische `examples`-Parameter heißt seit FastAPI `0.103.0` jetzt `openapi_examples`.
+
+///
### JSON Schemas Feld `examples`
@@ -298,10 +193,13 @@ Und jetzt hat dieses neue `examples`-Feld Vorrang vor dem alten (und benutzerdef
Dieses neue `examples`-Feld in JSON Schema ist **nur eine `list`e** von Beispielen, kein Dict mit zusätzlichen Metadaten wie an den anderen Stellen in OpenAPI (oben beschrieben).
-!!! info
- Selbst, nachdem OpenAPI 3.1.0 veröffentlicht wurde, mit dieser neuen, einfacheren Integration mit JSON Schema, unterstützte Swagger UI, das Tool, das die automatische Dokumentation bereitstellt, eine Zeit lang OpenAPI 3.1.0 nicht (das tut es seit Version 5.0.0 🎉).
+/// info
+
+Selbst, nachdem OpenAPI 3.1.0 veröffentlicht wurde, mit dieser neuen, einfacheren Integration mit JSON Schema, unterstützte Swagger UI, das Tool, das die automatische Dokumentation bereitstellt, eine Zeit lang OpenAPI 3.1.0 nicht (das tut es seit Version 5.0.0 🎉).
+
+Aus diesem Grund verwendeten Versionen von FastAPI vor 0.99.0 immer noch Versionen von OpenAPI vor 3.1.0.
- Aus diesem Grund verwendeten Versionen von FastAPI vor 0.99.0 immer noch Versionen von OpenAPI vor 3.1.0.
+///
### Pydantic- und FastAPI-`examples`
diff --git a/docs/de/docs/tutorial/security/first-steps.md b/docs/de/docs/tutorial/security/first-steps.md
index 1e75fa8d9..8fa33db7e 100644
--- a/docs/de/docs/tutorial/security/first-steps.md
+++ b/docs/de/docs/tutorial/security/first-steps.md
@@ -20,35 +20,19 @@ Lassen Sie uns zunächst einfach den Code verwenden und sehen, wie er funktionie
Kopieren Sie das Beispiel in eine Datei `main.py`:
-=== "Python 3.9+"
+{* ../../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!}
- ```
-
-=== "Python 3.8+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+## Ausführen
- ```Python
- {!> ../../../docs_src/security/tutorial001.py!}
- ```
+/// info
-## Ausführen
+Um hochgeladene Dateien zu empfangen, installieren Sie zuerst `python-multipart`.
-!!! info
- Um hochgeladene Dateien zu empfangen, installieren Sie zuerst `python-multipart`.
+Z. B. `pip install python-multipart`.
- Z. B. `pip install python-multipart`.
+Das, weil **OAuth2** „Formulardaten“ zum Senden von `username` und `password` verwendet.
- Das, weil **OAuth2** „Formulardaten“ zum Senden von `username` und `password` verwendet.
+///
Führen Sie das Beispiel aus mit:
@@ -70,17 +54,23 @@ Sie werden etwa Folgendes sehen:
-!!! check "Authorize-Button!"
- Sie haben bereits einen glänzenden, neuen „Authorize“-Button.
+/// check | Authorize-Button!
- Und Ihre *Pfadoperation* hat in der oberen rechten Ecke ein kleines Schloss, auf das Sie klicken können.
+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.
+/// note | Hinweis
+
+Es spielt keine Rolle, was Sie in das Formular eingeben, es wird noch nicht funktionieren. Wir kommen dahin.
+
+///
Dies ist natürlich nicht das Frontend für die Endbenutzer, aber es ist ein großartiges automatisches Tool, um Ihre gesamte API interaktiv zu dokumentieren.
@@ -122,53 +112,43 @@ Betrachten wir es also aus dieser vereinfachten Sicht:
In diesem Beispiel verwenden wir **OAuth2** mit dem **Password**-Flow und einem **Bearer**-Token. Wir machen das mit der Klasse `OAuth2PasswordBearer`.
-!!! info
- Ein „Bearer“-Token ist nicht die einzige Option.
-
- 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.
+/// info
- In dem Fall gibt Ihnen **FastAPI** ebenfalls die Tools, die Sie zum Erstellen brauchen.
+Ein „Bearer“-Token ist nicht die einzige Option.
-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.
+Aber es ist die beste für unseren Anwendungsfall.
-=== "Python 3.9+"
+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.
- ```Python hl_lines="8"
- {!> ../../../docs_src/security/tutorial001_an_py39.py!}
- ```
+In dem Fall gibt Ihnen **FastAPI** ebenfalls die Tools, die Sie zum Erstellen brauchen.
-=== "Python 3.8+"
+///
- ```Python hl_lines="7"
- {!> ../../../docs_src/security/tutorial001_an.py!}
- ```
+Wenn wir eine Instanz der Klasse `OAuth2PasswordBearer` erstellen, übergeben wir den Parameter `tokenUrl`. Dieser Parameter enthält die URL, die der Client (das Frontend, das im Browser des Benutzers ausgeführt wird) verwendet, wenn er den `username` und das `password` sendet, um einen Token zu erhalten.
-=== "Python 3.8+ nicht annotiert"
+{* ../../docs_src/security/tutorial001_an_py39.py hl[8] *}
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | Tipp
- ```Python hl_lines="6"
- {!> ../../../docs_src/security/tutorial001.py!}
- ```
+Hier bezieht sich `tokenUrl="token"` auf eine relative URL `token`, die wir noch nicht erstellt haben. Da es sich um eine relative URL handelt, entspricht sie `./token`.
-!!! tip "Tipp"
- 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.
- 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.
- Die Verwendung einer relativen URL ist wichtig, um sicherzustellen, dass Ihre Anwendung auch in einem fortgeschrittenen Anwendungsfall, wie [hinter einem Proxy](../../advanced/behind-a-proxy.md){.internal-link target=_blank}, weiterhin funktioniert.
+///
Dieser Parameter erstellt nicht diesen Endpunkt / diese *Pfadoperation*, sondern deklariert, dass die URL `/token` diejenige sein wird, die der Client verwenden soll, um den Token abzurufen. Diese Information wird in OpenAPI und dann in den interaktiven API-Dokumentationssystemen verwendet.
Wir werden demnächst auch die eigentliche Pfadoperation erstellen.
-!!! info
- Wenn Sie ein sehr strenger „Pythonista“ sind, missfällt Ihnen möglicherweise die Schreibweise des Parameternamens `tokenUrl` anstelle von `token_url`.
+/// info
+
+Wenn Sie ein sehr strenger „Pythonista“ sind, missfällt Ihnen möglicherweise die Schreibweise des Parameternamens `tokenUrl` anstelle von `token_url`.
- Das liegt daran, dass FastAPI denselben Namen wie in der OpenAPI-Spezifikation verwendet. Sodass Sie, wenn Sie mehr über eines dieser Sicherheitsschemas herausfinden möchten, den Namen einfach kopieren und einfügen können, um weitere Informationen darüber zu erhalten.
+Das liegt daran, dass FastAPI denselben Namen wie in der OpenAPI-Spezifikation verwendet. Sodass Sie, wenn Sie mehr über eines dieser Sicherheitsschemas herausfinden möchten, den Namen einfach kopieren und einfügen können, um weitere Informationen darüber zu erhalten.
+
+///
Die Variable `oauth2_scheme` ist eine Instanz von `OAuth2PasswordBearer`, aber auch ein „Callable“.
@@ -184,35 +164,19 @@ Es kann also mit `Depends` verwendet werden.
Jetzt können Sie dieses `oauth2_scheme` als Abhängigkeit `Depends` übergeben.
-=== "Python 3.9+"
-
- ```Python hl_lines="12"
- {!> ../../../docs_src/security/tutorial001_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="11"
- {!> ../../../docs_src/security/tutorial001_an.py!}
- ```
-
-=== "Python 3.8+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/security/tutorial001.py!}
- ```
+{* ../../docs_src/security/tutorial001_an_py39.py hl[12] *}
Diese Abhängigkeit stellt einen `str` bereit, der dem Parameter `token` der *Pfadoperation-Funktion* zugewiesen wird.
**FastAPI** weiß, dass es diese Abhängigkeit verwenden kann, um ein „Sicherheitsschema“ im OpenAPI-Schema (und der automatischen API-Dokumentation) zu definieren.
-!!! info "Technische Details"
- **FastAPI** weiß, dass es die Klasse `OAuth2PasswordBearer` (deklariert in einer Abhängigkeit) verwenden kann, um das Sicherheitsschema in OpenAPI zu definieren, da es von `fastapi.security.oauth2.OAuth2` erbt, das wiederum von `fastapi.security.base.SecurityBase` erbt.
+/// info | Technische Details
+
+**FastAPI** weiß, dass es die Klasse `OAuth2PasswordBearer` (deklariert in einer Abhängigkeit) verwenden kann, um das Sicherheitsschema in OpenAPI zu definieren, da es von `fastapi.security.oauth2.OAuth2` erbt, das wiederum von `fastapi.security.base.SecurityBase` erbt.
+
+Alle Sicherheits-Werkzeuge, die in OpenAPI integriert sind (und die automatische API-Dokumentation), erben von `SecurityBase`, so weiß **FastAPI**, wie es sie in OpenAPI integrieren muss.
- Alle Sicherheits-Werkzeuge, die in OpenAPI integriert sind (und die automatische API-Dokumentation), erben von `SecurityBase`, so weiß **FastAPI**, wie es sie in OpenAPI integrieren muss.
+///
## Was es macht
diff --git a/docs/de/docs/tutorial/security/get-current-user.md b/docs/de/docs/tutorial/security/get-current-user.md
index 09b55a20e..38f7ffcbf 100644
--- a/docs/de/docs/tutorial/security/get-current-user.md
+++ b/docs/de/docs/tutorial/security/get-current-user.md
@@ -2,26 +2,7 @@
Im vorherigen Kapitel hat das Sicherheitssystem (das auf dem Dependency Injection System basiert) der *Pfadoperation-Funktion* einen `token` vom Typ `str` überreicht:
-=== "Python 3.9+"
-
- ```Python hl_lines="12"
- {!> ../../../docs_src/security/tutorial001_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="11"
- {!> ../../../docs_src/security/tutorial001_an.py!}
- ```
-
-=== "Python 3.8+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/security/tutorial001.py!}
- ```
+{* ../../docs_src/security/tutorial001_an_py39.py hl[12] *}
Aber das ist immer noch nicht so nützlich.
@@ -33,41 +14,7 @@ Erstellen wir zunächst ein Pydantic-Benutzermodell.
So wie wir Pydantic zum Deklarieren von Bodys verwenden, können wir es auch überall sonst verwenden:
-=== "Python 3.10+"
-
- ```Python hl_lines="5 12-16"
- {!> ../../../docs_src/security/tutorial002_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="5 12-16"
- {!> ../../../docs_src/security/tutorial002_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="5 13-17"
- {!> ../../../docs_src/security/tutorial002_an.py!}
- ```
-
-=== "Python 3.10+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="3 10-14"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
-
-=== "Python 3.8+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="5 12-16"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+{* ../../docs_src/security/tutorial002_an_py310.py hl[5,12:16] *}
## Eine `get_current_user`-Abhängigkeit erstellen
@@ -79,135 +26,39 @@ Erinnern Sie sich, dass Abhängigkeiten Unterabhängigkeiten haben können?
So wie wir es zuvor in der *Pfadoperation* direkt gemacht haben, erhält unsere neue Abhängigkeit `get_current_user` von der Unterabhängigkeit `oauth2_scheme` einen `token` vom Typ `str`:
-=== "Python 3.10+"
-
- ```Python hl_lines="25"
- {!> ../../../docs_src/security/tutorial002_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="25"
- {!> ../../../docs_src/security/tutorial002_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="26"
- {!> ../../../docs_src/security/tutorial002_an.py!}
- ```
-
-=== "Python 3.10+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="23"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
-
-=== "Python 3.8+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="25"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+{* ../../docs_src/security/tutorial002_an_py310.py hl[25] *}
## Den Benutzer holen
`get_current_user` wird eine von uns erstellte (gefakte) Hilfsfunktion verwenden, welche einen Token vom Typ `str` entgegennimmt und unser Pydantic-`User`-Modell zurückgibt:
-=== "Python 3.10+"
-
- ```Python hl_lines="19-22 26-27"
- {!> ../../../docs_src/security/tutorial002_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="19-22 26-27"
- {!> ../../../docs_src/security/tutorial002_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="20-23 27-28"
- {!> ../../../docs_src/security/tutorial002_an.py!}
- ```
-
-=== "Python 3.10+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="17-20 24-25"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
-
-=== "Python 3.8+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="19-22 26-27"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+{* ../../docs_src/security/tutorial002_an_py310.py hl[19:22,26:27] *}
## Den aktuellen Benutzer einfügen
Und jetzt können wir wiederum `Depends` mit unserem `get_current_user` in der *Pfadoperation* verwenden:
-=== "Python 3.10+"
-
- ```Python hl_lines="31"
- {!> ../../../docs_src/security/tutorial002_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="31"
- {!> ../../../docs_src/security/tutorial002_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="32"
- {!> ../../../docs_src/security/tutorial002_an.py!}
- ```
-
-=== "Python 3.10+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+{* ../../docs_src/security/tutorial002_an_py310.py hl[31] *}
- ```Python hl_lines="29"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+Beachten Sie, dass wir als Typ von `current_user` das Pydantic-Modell `User` deklarieren.
-=== "Python 3.8+ nicht annotiert"
+Das wird uns innerhalb der Funktion bei Codevervollständigung und Typprüfungen helfen.
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | Tipp
- ```Python hl_lines="31"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+Sie erinnern sich vielleicht, dass Requestbodys ebenfalls mit Pydantic-Modellen deklariert werden.
-Beachten Sie, dass wir als Typ von `current_user` das Pydantic-Modell `User` deklarieren.
+Weil Sie `Depends` verwenden, wird **FastAPI** hier aber nicht verwirrt.
-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.
+/// check
- Weil Sie `Depends` verwenden, wird **FastAPI** hier aber nicht verwirrt.
+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.
-!!! 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.
- Wir sind nicht darauf beschränkt, nur eine Abhängigkeit zu haben, die diesen Typ von Daten zurückgeben kann.
+///
## Andere Modelle
@@ -241,41 +92,7 @@ Und alle (oder beliebige Teile davon) können Vorteil ziehen aus der Wiederverwe
Und alle diese Tausenden von *Pfadoperationen* können nur drei Zeilen lang sein:
-=== "Python 3.10+"
-
- ```Python hl_lines="30-32"
- {!> ../../../docs_src/security/tutorial002_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="30-32"
- {!> ../../../docs_src/security/tutorial002_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="31-33"
- {!> ../../../docs_src/security/tutorial002_an.py!}
- ```
-
-=== "Python 3.10+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="28-30"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
-
-=== "Python 3.8+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="30-32"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+{* ../../docs_src/security/tutorial002_an_py310.py hl[30:32] *}
## Zusammenfassung
diff --git a/docs/de/docs/tutorial/security/index.md b/docs/de/docs/tutorial/security/index.md
index 7a11e704d..b01243901 100644
--- a/docs/de/docs/tutorial/security/index.md
+++ b/docs/de/docs/tutorial/security/index.md
@@ -32,9 +32,11 @@ Heutzutage ist es nicht sehr populär und wird kaum verwendet.
OAuth2 spezifiziert nicht, wie die Kommunikation verschlüsselt werden soll, sondern erwartet, dass Ihre Anwendung mit HTTPS bereitgestellt wird.
-!!! tip "Tipp"
- Im Abschnitt über **Deployment** erfahren Sie, wie Sie HTTPS mithilfe von Traefik und Let's Encrypt kostenlos einrichten.
+/// tip | Tipp
+Im Abschnitt über **Deployment** erfahren Sie, wie Sie HTTPS mithilfe von Traefik und Let's Encrypt kostenlos einrichten.
+
+///
## OpenID Connect
@@ -87,10 +89,13 @@ OpenAPI definiert die folgenden Sicherheitsschemas:
* Diese automatische Erkennung ist es, die in der OpenID Connect Spezifikation definiert ist.
-!!! tip "Tipp"
- Auch die Integration anderer Authentifizierungs-/Autorisierungsanbieter wie Google, Facebook, Twitter, GitHub, usw. ist möglich und relativ einfach.
+/// tip | Tipp
+
+Auch die Integration anderer Authentifizierungs-/Autorisierungsanbieter wie Google, Facebook, Twitter, GitHub, usw. ist möglich und relativ einfach.
+
+Das komplexeste Problem besteht darin, einen Authentifizierungs-/Autorisierungsanbieter wie solche aufzubauen, aber **FastAPI** reicht Ihnen die Tools, das einfach zu erledigen, während Ihnen die schwere Arbeit abgenommen wird.
- Das komplexeste Problem besteht darin, einen Authentifizierungs-/Autorisierungsanbieter wie solche aufzubauen, aber **FastAPI** reicht Ihnen die Tools, das einfach zu erledigen, während Ihnen die schwere Arbeit abgenommen wird.
+///
## **FastAPI** Tools
diff --git a/docs/de/docs/tutorial/security/oauth2-jwt.md b/docs/de/docs/tutorial/security/oauth2-jwt.md
index 9f43cccc9..178a95d81 100644
--- a/docs/de/docs/tutorial/security/oauth2-jwt.md
+++ b/docs/de/docs/tutorial/security/oauth2-jwt.md
@@ -44,10 +44,13 @@ $ pip install "python-jose[cryptography]"
Hier verwenden wir das empfohlene: pyca/cryptography.
-!!! tip "Tipp"
- Dieses Tutorial verwendete zuvor PyJWT.
+/// tip | Tipp
- Es wurde jedoch aktualisiert, stattdessen python-jose zu verwenden, da dieses alle Funktionen von PyJWT sowie einige Extras bietet, die Sie später möglicherweise benötigen, wenn Sie Integrationen mit anderen Tools erstellen.
+Dieses Tutorial verwendete zuvor PyJWT.
+
+Es wurde jedoch aktualisiert, stattdessen python-jose zu verwenden, da dieses alle Funktionen von PyJWT sowie einige Extras bietet, die Sie später möglicherweise benötigen, wenn Sie Integrationen mit anderen Tools erstellen.
+
+///
## Passwort-Hashing
@@ -83,12 +86,15 @@ $ pip install "passlib[bcrypt]"
-!!! tip "Tipp"
- Mit `passlib` können Sie sogar konfigurieren, Passwörter zu lesen, die von **Django**, einem **Flask**-Sicherheit-Plugin, oder vielen anderen erstellt wurden.
+/// tip | Tipp
+
+Mit `passlib` können Sie sogar konfigurieren, Passwörter zu lesen, die von **Django**, einem **Flask**-Sicherheit-Plugin, oder vielen anderen erstellt wurden.
+
+So könnten Sie beispielsweise die gleichen Daten aus einer Django-Anwendung in einer Datenbank mit einer FastAPI-Anwendung teilen. Oder schrittweise eine Django-Anwendung migrieren, während Sie dieselbe Datenbank verwenden.
- So könnten Sie beispielsweise die gleichen Daten aus einer Django-Anwendung in einer Datenbank mit einer FastAPI-Anwendung teilen. Oder schrittweise eine Django-Anwendung migrieren, während Sie dieselbe Datenbank verwenden.
+Und Ihre Benutzer könnten sich gleichzeitig über Ihre Django-Anwendung oder Ihre **FastAPI**-Anwendung anmelden.
- Und Ihre Benutzer könnten sich gleichzeitig über Ihre Django-Anwendung oder Ihre **FastAPI**-Anwendung anmelden.
+///
## Die Passwörter hashen und überprüfen
@@ -96,12 +102,15 @@ Importieren Sie die benötigten Tools aus `passlib`.
Erstellen Sie einen PassLib-„Kontext“. Der wird für das Hashen und Verifizieren von Passwörtern verwendet.
-!!! tip "Tipp"
- Der PassLib-Kontext kann auch andere Hashing-Algorithmen verwenden, einschließlich deprecateter Alter, um etwa nur eine Verifizierung usw. zu ermöglichen.
+/// tip | Tipp
- Sie könnten ihn beispielsweise verwenden, um von einem anderen System (wie Django) generierte Passwörter zu lesen und zu verifizieren, aber alle neuen Passwörter mit einem anderen Algorithmus wie Bcrypt zu hashen.
+Der PassLib-Kontext kann auch andere Hashing-Algorithmen verwenden, einschließlich deprecateter Alter, um etwa nur eine Verifizierung usw. zu ermöglichen.
- Und mit allen gleichzeitig kompatibel sein.
+Sie könnten ihn beispielsweise verwenden, um von einem anderen System (wie Django) generierte Passwörter zu lesen und zu verifizieren, aber alle neuen Passwörter mit einem anderen Algorithmus wie Bcrypt zu hashen.
+
+Und mit allen gleichzeitig kompatibel sein.
+
+///
Erstellen Sie eine Hilfsfunktion, um ein vom Benutzer stammendes Passwort zu hashen.
@@ -109,44 +118,13 @@ Und eine weitere, um zu überprüfen, ob ein empfangenes Passwort mit dem gespei
Und noch eine, um einen Benutzer zu authentifizieren und zurückzugeben.
-=== "Python 3.10+"
-
- ```Python hl_lines="7 48 55-56 59-60 69-75"
- {!> ../../../docs_src/security/tutorial004_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="7 48 55-56 59-60 69-75"
- {!> ../../../docs_src/security/tutorial004_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="7 49 56-57 60-61 70-76"
- {!> ../../../docs_src/security/tutorial004_an.py!}
- ```
-
-=== "Python 3.10+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+{* ../../docs_src/security/tutorial004_an_py310.py hl[7,48,55:56,59:60,69:75] *}
- ```Python hl_lines="6 47 54-55 58-59 68-74"
- {!> ../../../docs_src/security/tutorial004_py310.py!}
- ```
+/// note | Hinweis
-=== "Python 3.8+ nicht annotiert"
+Wenn Sie sich die neue (gefakte) Datenbank `fake_users_db` anschauen, sehen Sie, wie das gehashte Passwort jetzt aussieht: `"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`.
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="7 48 55-56 59-60 69-75"
- {!> ../../../docs_src/security/tutorial004.py!}
- ```
-
-!!! note "Hinweis"
- Wenn Sie sich die neue (gefakte) Datenbank `fake_users_db` anschauen, sehen Sie, wie das gehashte Passwort jetzt aussieht: `"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`.
+///
## JWT-Token verarbeiten
@@ -176,41 +154,7 @@ Definieren Sie ein Pydantic-Modell, das im Token-Endpunkt für die Response verw
Erstellen Sie eine Hilfsfunktion, um einen neuen Zugriffstoken zu generieren.
-=== "Python 3.10+"
-
- ```Python hl_lines="6 12-14 28-30 78-86"
- {!> ../../../docs_src/security/tutorial004_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="6 12-14 28-30 78-86"
- {!> ../../../docs_src/security/tutorial004_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="6 13-15 29-31 79-87"
- {!> ../../../docs_src/security/tutorial004_an.py!}
- ```
-
-=== "Python 3.10+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="5 11-13 27-29 77-85"
- {!> ../../../docs_src/security/tutorial004_py310.py!}
- ```
-
-=== "Python 3.8+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="6 12-14 28-30 78-86"
- {!> ../../../docs_src/security/tutorial004.py!}
- ```
+{* ../../docs_src/security/tutorial004_an_py310.py hl[6,12:14,28:30,78:86] *}
## Die Abhängigkeiten aktualisieren
@@ -220,41 +164,7 @@ Dekodieren Sie den empfangenen Token, validieren Sie ihn und geben Sie den aktue
Wenn der Token ungültig ist, geben Sie sofort einen HTTP-Fehler zurück.
-=== "Python 3.10+"
-
- ```Python hl_lines="89-106"
- {!> ../../../docs_src/security/tutorial004_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="89-106"
- {!> ../../../docs_src/security/tutorial004_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="90-107"
- {!> ../../../docs_src/security/tutorial004_an.py!}
- ```
-
-=== "Python 3.10+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="88-105"
- {!> ../../../docs_src/security/tutorial004_py310.py!}
- ```
-
-=== "Python 3.8+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="89-106"
- {!> ../../../docs_src/security/tutorial004.py!}
- ```
+{* ../../docs_src/security/tutorial004_an_py310.py hl[89:106] *}
## Die *Pfadoperation* `/token` aktualisieren
@@ -262,41 +172,7 @@ Erstellen Sie ein `timedelta` mit der Ablaufz
Erstellen Sie einen echten JWT-Zugriffstoken und geben Sie ihn zurück.
-=== "Python 3.10+"
-
- ```Python hl_lines="117-132"
- {!> ../../../docs_src/security/tutorial004_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="117-132"
- {!> ../../../docs_src/security/tutorial004_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="118-133"
- {!> ../../../docs_src/security/tutorial004_an.py!}
- ```
-
-=== "Python 3.10+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="114-129"
- {!> ../../../docs_src/security/tutorial004_py310.py!}
- ```
-
-=== "Python 3.8+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="115-130"
- {!> ../../../docs_src/security/tutorial004.py!}
- ```
+{* ../../docs_src/security/tutorial004_an_py310.py hl[117:132] *}
### Technische Details zum JWT-„Subjekt“ `sub`
@@ -335,8 +211,11 @@ Verwenden Sie die Anmeldeinformationen:
Benutzername: `johndoe`
Passwort: `secret`.
-!!! check
- Beachten Sie, dass im Code nirgendwo das Klartext-Passwort "`secret`" steht, wir haben nur die gehashte Version.
+/// check
+
+Beachten Sie, dass im Code nirgendwo das Klartext-Passwort "`secret`" steht, wir haben nur die gehashte Version.
+
+///
@@ -357,8 +236,11 @@ Wenn Sie die Developer Tools öffnen, können Sie sehen, dass die gesendeten Dat
-!!! note "Hinweis"
- Beachten Sie den Header `Authorization` mit einem Wert, der mit `Bearer` beginnt.
+/// note | Hinweis
+
+Beachten Sie den Header `Authorization` mit einem Wert, der mit `Bearer` beginnt.
+
+///
## Fortgeschrittene Verwendung mit `scopes`
diff --git a/docs/de/docs/tutorial/security/simple-oauth2.md b/docs/de/docs/tutorial/security/simple-oauth2.md
index ed280d486..c0c93cd26 100644
--- a/docs/de/docs/tutorial/security/simple-oauth2.md
+++ b/docs/de/docs/tutorial/security/simple-oauth2.md
@@ -32,14 +32,17 @@ Diese werden normalerweise verwendet, um bestimmte Sicherheitsberechtigungen zu
* `instagram_basic` wird von Facebook / Instagram verwendet.
* `https://www.googleapis.com/auth/drive` wird von Google verwendet.
-!!! info
- In OAuth2 ist ein „Scope“ nur ein String, der eine bestimmte erforderliche Berechtigung deklariert.
+/// info
- Es spielt keine Rolle, ob er andere Zeichen wie `:` enthält oder ob es eine URL ist.
+In OAuth2 ist ein „Scope“ nur ein String, der eine bestimmte erforderliche Berechtigung deklariert.
- Diese Details sind implementierungsspezifisch.
+Es spielt keine Rolle, ob er andere Zeichen wie `:` enthält oder ob es eine URL ist.
- Für OAuth2 sind es einfach nur Strings.
+Diese Details sind implementierungsspezifisch.
+
+Für OAuth2 sind es einfach nur Strings.
+
+///
## Code, um `username` und `password` entgegenzunehmen.
@@ -49,41 +52,7 @@ Lassen Sie uns nun die von **FastAPI** bereitgestellten Werkzeuge verwenden, um
Importieren Sie zunächst `OAuth2PasswordRequestForm` und verwenden Sie es als Abhängigkeit mit `Depends` in der *Pfadoperation* für `/token`:
-=== "Python 3.10+"
-
- ```Python hl_lines="4 78"
- {!> ../../../docs_src/security/tutorial003_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="4 78"
- {!> ../../../docs_src/security/tutorial003_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="4 79"
- {!> ../../../docs_src/security/tutorial003_an.py!}
- ```
-
-=== "Python 3.10+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="2 74"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
-
-=== "Python 3.8+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="4 76"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+{* ../../docs_src/security/tutorial003_an_py310.py hl[4,78] *}
`OAuth2PasswordRequestForm` ist eine Klassenabhängigkeit, die einen Formularbody deklariert mit:
@@ -92,71 +61,46 @@ Importieren Sie zunächst `OAuth2PasswordRequestForm` und verwenden Sie es als A
* Einem optionalen `scope`-Feld als langem String, bestehend aus durch Leerzeichen getrennten Strings.
* Einem optionalen `grant_type` („Art der Anmeldung“).
-!!! tip "Tipp"
- Die OAuth2-Spezifikation *erfordert* tatsächlich ein Feld `grant_type` mit dem festen Wert `password`, aber `OAuth2PasswordRequestForm` erzwingt dies nicht.
-
- 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).
+/// tip | Tipp
-!!! info
- `OAuth2PasswordRequestForm` ist keine spezielle Klasse für **FastAPI**, so wie `OAuth2PasswordBearer`.
+Die OAuth2-Spezifikation *erfordert* tatsächlich ein Feld `grant_type` mit dem festen Wert `password`, aber `OAuth2PasswordRequestForm` erzwingt dies nicht.
- `OAuth2PasswordBearer` lässt **FastAPI** wissen, dass es sich um ein Sicherheitsschema handelt. Daher wird es auf diese Weise zu OpenAPI hinzugefügt.
+Wenn Sie es erzwingen müssen, verwenden Sie `OAuth2PasswordRequestFormStrict` anstelle von `OAuth2PasswordRequestForm`.
- 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.
+* Eine optionale `client_id` (benötigen wir für unser Beispiel nicht).
+* Ein optionales `client_secret` (benötigen wir für unser Beispiel nicht).
-### Die Formulardaten verwenden
+/// info
-!!! 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.
+`OAuth2PasswordRequestForm` ist keine spezielle Klasse für **FastAPI**, so wie `OAuth2PasswordBearer`.
- In diesem Beispiel verwenden wir keine `scopes`, aber die Funktionalität ist vorhanden, wenn Sie sie benötigen.
+`OAuth2PasswordBearer` lässt **FastAPI** wissen, dass es sich um ein Sicherheitsschema handelt. Daher wird es auf diese Weise zu OpenAPI hinzugefügt.
-Rufen Sie nun die Benutzerdaten aus der (gefakten) Datenbank ab, für diesen `username` aus dem Formularfeld.
+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.
-Wenn es keinen solchen Benutzer gibt, geben wir die Fehlermeldung „Incorrect username or password“ zurück.
+Da es sich jedoch um einen häufigen Anwendungsfall handelt, wird er zur Vereinfachung direkt von **FastAPI** bereitgestellt.
-Für den Fehler verwenden wir die Exception `HTTPException`:
+///
-=== "Python 3.10+"
-
- ```Python hl_lines="3 79-81"
- {!> ../../../docs_src/security/tutorial003_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="3 79-81"
- {!> ../../../docs_src/security/tutorial003_an_py39.py!}
- ```
+### Die Formulardaten verwenden
-=== "Python 3.8+"
+/// tip | Tipp
- ```Python hl_lines="3 80-82"
- {!> ../../../docs_src/security/tutorial003_an.py!}
- ```
+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.
-=== "Python 3.10+ nicht annotiert"
+In diesem Beispiel verwenden wir keine `scopes`, aber die Funktionalität ist vorhanden, wenn Sie sie benötigen.
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+///
- ```Python hl_lines="1 75-77"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+Rufen Sie nun die Benutzerdaten aus der (gefakten) Datenbank ab, für diesen `username` aus dem Formularfeld.
-=== "Python 3.8+ nicht annotiert"
+Wenn es keinen solchen Benutzer gibt, geben wir die Fehlermeldung „Incorrect username or password“ zurück.
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+Für den Fehler verwenden wir die Exception `HTTPException`:
- ```Python hl_lines="3 77-79"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+{* ../../docs_src/security/tutorial003_an_py310.py hl[3,79:81] *}
### Das Passwort überprüfen
@@ -182,41 +126,7 @@ Wenn Ihre Datenbank gestohlen wird, hat der Dieb nicht die Klartext-Passwörter
Der Dieb kann also nicht versuchen, die gleichen Passwörter in einem anderen System zu verwenden (da viele Benutzer überall das gleiche Passwort verwenden, wäre dies gefährlich).
-=== "Python 3.10+"
-
- ```Python hl_lines="82-85"
- {!> ../../../docs_src/security/tutorial003_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="82-85"
- {!> ../../../docs_src/security/tutorial003_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="83-86"
- {!> ../../../docs_src/security/tutorial003_an.py!}
- ```
-
-=== "Python 3.10+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="78-81"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
-
-=== "Python 3.8+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="80-83"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+{* ../../docs_src/security/tutorial003_an_py310.py hl[82:85] *}
#### Über `**user_dict`
@@ -234,8 +144,11 @@ UserInDB(
)
```
-!!! info
- Eine ausführlichere Erklärung von `**user_dict` finden Sie in [der Dokumentation für **Extra Modelle**](../extra-models.md#uber-user_indict){.internal-link target=_blank}.
+/// info
+
+Eine ausführlichere Erklärung von `**user_dict` finden Sie in [der Dokumentation für **Extra Modelle**](../extra-models.md#uber-user_indict){.internal-link target=_blank}.
+
+///
## Den Token zurückgeben
@@ -247,55 +160,27 @@ Und es sollte einen `access_token` haben, mit einem String, der unseren Zugriffs
In diesem einfachen Beispiel gehen wir einfach völlig unsicher vor und geben denselben `username` wie der Token zurück.
-!!! tip "Tipp"
- Im nächsten Kapitel sehen Sie eine wirklich sichere Implementierung mit Passwort-Hashing und JWT-Tokens.
-
- Aber konzentrieren wir uns zunächst auf die spezifischen Details, die wir benötigen.
-
-=== "Python 3.10+"
+/// tip | Tipp
- ```Python hl_lines="87"
- {!> ../../../docs_src/security/tutorial003_an_py310.py!}
- ```
+Im nächsten Kapitel sehen Sie eine wirklich sichere Implementierung mit Passwort-Hashing und JWT-Tokens.
-=== "Python 3.9+"
+Aber konzentrieren wir uns zunächst auf die spezifischen Details, die wir benötigen.
- ```Python hl_lines="87"
- {!> ../../../docs_src/security/tutorial003_an_py39.py!}
- ```
+///
-=== "Python 3.8+"
+{* ../../docs_src/security/tutorial003_an_py310.py hl[87] *}
- ```Python hl_lines="88"
- {!> ../../../docs_src/security/tutorial003_an.py!}
- ```
+/// tip | Tipp
-=== "Python 3.10+ nicht annotiert"
+Gemäß der Spezifikation sollten Sie ein JSON mit einem `access_token` und einem `token_type` zurückgeben, genau wie in diesem Beispiel.
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+Das müssen Sie selbst in Ihrem Code tun und sicherstellen, dass Sie diese JSON-Schlüssel verwenden.
- ```Python hl_lines="83"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+Es ist fast das Einzige, woran Sie denken müssen, es selbst richtigzumachen und die Spezifikationen einzuhalten.
-=== "Python 3.8+ nicht annotiert"
+Den Rest erledigt **FastAPI** für Sie.
- !!! 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
@@ -309,56 +194,25 @@ Beide Abhängigkeiten geben nur dann einen HTTP-Error zurück, wenn der Benutzer
In unserem Endpunkt erhalten wir also nur dann einen Benutzer, wenn der Benutzer existiert, korrekt authentifiziert wurde und aktiv ist:
-=== "Python 3.10+"
-
- ```Python hl_lines="58-66 69-74 94"
- {!> ../../../docs_src/security/tutorial003_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="58-66 69-74 94"
- {!> ../../../docs_src/security/tutorial003_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="59-67 70-75 95"
- {!> ../../../docs_src/security/tutorial003_an.py!}
- ```
-
-=== "Python 3.10+ nicht annotiert"
-
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
-
- ```Python hl_lines="56-64 67-70 88"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
-
-=== "Python 3.8+ nicht annotiert"
+{* ../../docs_src/security/tutorial003_an_py310.py hl[58:66,69:74,94] *}
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// info
- ```Python hl_lines="58-66 69-72 90"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+Der zusätzliche Header `WWW-Authenticate` mit dem Wert `Bearer`, den wir hier zurückgeben, ist ebenfalls Teil der Spezifikation.
-!!! info
- Der zusätzliche Header `WWW-Authenticate` mit dem Wert `Bearer`, den wir hier zurückgeben, ist ebenfalls Teil der Spezifikation.
+Jeder HTTP-(Fehler-)Statuscode 401 „UNAUTHORIZED“ soll auch einen `WWW-Authenticate`-Header zurückgeben.
- Jeder HTTP-(Fehler-)Statuscode 401 „UNAUTHORIZED“ soll auch einen `WWW-Authenticate`-Header zurückgeben.
+Im Fall von Bearer-Tokens (in unserem Fall) sollte der Wert dieses Headers `Bearer` lauten.
- Im Fall von Bearer-Tokens (in unserem Fall) sollte der Wert dieses Headers `Bearer` lauten.
+Sie können diesen zusätzlichen Header tatsächlich weglassen und es würde trotzdem funktionieren.
- Sie können diesen zusätzlichen Header tatsächlich weglassen und es würde trotzdem funktionieren.
+Aber er wird hier bereitgestellt, um den Spezifikationen zu entsprechen.
- Aber er wird hier bereitgestellt, um den Spezifikationen zu entsprechen.
+Außerdem gibt es möglicherweise Tools, die ihn erwarten und verwenden (jetzt oder in der Zukunft) und das könnte für Sie oder Ihre Benutzer jetzt oder in der Zukunft nützlich sein.
- Außerdem gibt es möglicherweise Tools, die ihn erwarten und verwenden (jetzt oder in der Zukunft) und das könnte für Sie oder Ihre Benutzer jetzt oder in der Zukunft nützlich sein.
+Das ist der Vorteil von Standards ...
- Das ist der Vorteil von Standards ...
+///
## Es in Aktion sehen
diff --git a/docs/de/docs/tutorial/static-files.md b/docs/de/docs/tutorial/static-files.md
index 1e289e120..50e86d68e 100644
--- a/docs/de/docs/tutorial/static-files.md
+++ b/docs/de/docs/tutorial/static-files.md
@@ -7,14 +7,15 @@ Mit `StaticFiles` können Sie statische Dateien aus einem Verzeichnis automatisc
* Importieren Sie `StaticFiles`.
* „Mounten“ Sie eine `StaticFiles()`-Instanz in einem bestimmten Pfad.
-```Python hl_lines="2 6"
-{!../../../docs_src/static_files/tutorial001.py!}
-```
+{* ../../docs_src/static_files/tutorial001.py hl[2,6] *}
-!!! note "Technische Details"
- Sie könnten auch `from starlette.staticfiles import StaticFiles` verwenden.
+/// note | Technische Details
- **FastAPI** stellt dasselbe `starlette.staticfiles` auch via `fastapi.staticfiles` bereit, als Annehmlichkeit für Sie, den Entwickler. Es kommt aber tatsächlich direkt von Starlette.
+Sie könnten auch `from starlette.staticfiles import StaticFiles` verwenden.
+
+**FastAPI** stellt dasselbe `starlette.staticfiles` auch via `fastapi.staticfiles` bereit, als Annehmlichkeit für Sie, den Entwickler. Es kommt aber tatsächlich direkt von Starlette.
+
+///
### Was ist „Mounten“?
diff --git a/docs/de/docs/tutorial/testing.md b/docs/de/docs/tutorial/testing.md
index 541cc1bf0..e7c1dda95 100644
--- a/docs/de/docs/tutorial/testing.md
+++ b/docs/de/docs/tutorial/testing.md
@@ -8,10 +8,13 @@ Damit können Sie `httpx`.
+/// info
- Z. B. `pip install httpx`.
+Um `TestClient` zu verwenden, installieren Sie zunächst `httpx`.
+
+Z. B. `pip install httpx`.
+
+///
Importieren Sie `TestClient`.
@@ -23,24 +26,31 @@ Verwenden Sie das `TestClient`-Objekt auf die gleiche Weise wie `httpx`.
Schreiben Sie einfache `assert`-Anweisungen mit den Standard-Python-Ausdrücken, die Sie überprüfen müssen (wiederum, Standard-`pytest`).
-```Python hl_lines="2 12 15-18"
-{!../../../docs_src/app_testing/tutorial001.py!}
-```
+{* ../../docs_src/app_testing/tutorial001.py hl[2,12,15:18] *}
+
+/// tip | Tipp
+
+Beachten Sie, dass die Testfunktionen normal `def` und nicht `async def` sind.
-!!! tip "Tipp"
- Beachten Sie, dass die Testfunktionen normal `def` und nicht `async def` sind.
+Und die Anrufe an den Client sind ebenfalls normale Anrufe, die nicht `await` verwenden.
- Und die Anrufe an den Client sind ebenfalls normale Anrufe, die nicht `await` verwenden.
+Dadurch können Sie `pytest` ohne Komplikationen direkt nutzen.
- Dadurch können Sie `pytest` ohne Komplikationen direkt nutzen.
+///
-!!! note "Technische Details"
- Sie könnten auch `from starlette.testclient import TestClient` verwenden.
+/// note | Technische Details
- **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.
+Sie könnten auch `from starlette.testclient import TestClient` verwenden.
-!!! 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.
+**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
@@ -62,9 +72,8 @@ Nehmen wir an, Sie haben eine Dateistruktur wie in [Größere Anwendungen](bigge
In der Datei `main.py` haben Sie Ihre **FastAPI**-Anwendung:
-```Python
-{!../../../docs_src/app_testing/main.py!}
-```
+{* ../../docs_src/app_testing/main.py *}
+
### Testdatei
@@ -80,9 +89,8 @@ Dann könnten Sie eine Datei `test_main.py` mit Ihren Tests haben. Sie könnte s
Da sich diese Datei im selben Package befindet, können Sie relative Importe verwenden, um das Objekt `app` aus dem `main`-Modul (`main.py`) zu importieren:
-```Python hl_lines="3"
-{!../../../docs_src/app_testing/test_main.py!}
-```
+{* ../../docs_src/app_testing/test_main.py hl[3] *}
+
... und haben den Code für die Tests wie zuvor.
@@ -110,50 +118,65 @@ Sie verfügt über eine `POST`-Operation, die mehrere Fehler zurückgeben könnt
Beide *Pfadoperationen* erfordern einen `X-Token`-Header.
-=== "Python 3.10+"
+//// tab | Python 3.10+
+
+```Python
+{!> ../../docs_src/app_testing/app_b_an_py310/main.py!}
+```
+
+////
+
+//// tab | Python 3.9+
- ```Python
- {!> ../../../docs_src/app_testing/app_b_an_py310/main.py!}
- ```
+```Python
+{!> ../../docs_src/app_testing/app_b_an_py39/main.py!}
+```
+
+////
-=== "Python 3.9+"
+//// tab | Python 3.8+
+
+```Python
+{!> ../../docs_src/app_testing/app_b_an/main.py!}
+```
- ```Python
- {!> ../../../docs_src/app_testing/app_b_an_py39/main.py!}
- ```
+////
-=== "Python 3.8+"
+//// tab | Python 3.10+ nicht annotiert
- ```Python
- {!> ../../../docs_src/app_testing/app_b_an/main.py!}
- ```
+/// tip | Tipp
-=== "Python 3.10+ nicht annotiert"
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+///
- ```Python
- {!> ../../../docs_src/app_testing/app_b_py310/main.py!}
- ```
+```Python
+{!> ../../docs_src/app_testing/app_b_py310/main.py!}
+```
-=== "Python 3.8+ nicht annotiert"
+////
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+//// tab | Python 3.8+ nicht annotiert
- ```Python
- {!> ../../../docs_src/app_testing/app_b/main.py!}
- ```
+/// tip | Tipp
-### Erweiterte Testdatei
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-Anschließend könnten Sie `test_main.py` mit den erweiterten Tests aktualisieren:
+///
```Python
-{!> ../../../docs_src/app_testing/app_b/test_main.py!}
+{!> ../../docs_src/app_testing/app_b/main.py!}
```
+////
+
+### Erweiterte Testdatei
+
+Anschließend könnten Sie `test_main.py` mit den erweiterten Tests aktualisieren:
+
+{* ../../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.
@@ -168,10 +191,13 @@ Z. B.:
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.
+/// info
+
+Beachten Sie, dass der `TestClient` Daten empfängt, die nach JSON konvertiert werden können, keine Pydantic-Modelle.
+
+Wenn Sie ein Pydantic-Modell in Ihrem Test haben und dessen Daten während des Testens an die Anwendung senden möchten, können Sie den `jsonable_encoder` verwenden, der in [JSON-kompatibler Encoder](encoder.md){.internal-link target=_blank} beschrieben wird.
- Wenn Sie ein Pydantic-Modell in Ihrem Test haben und dessen Daten während des Testens an die Anwendung senden möchten, können Sie den `jsonable_encoder` verwenden, der in [JSON-kompatibler Encoder](encoder.md){.internal-link target=_blank} beschrieben wird.
+///
## Tests ausführen
diff --git a/docs/em/docs/advanced/additional-responses.md b/docs/em/docs/advanced/additional-responses.md
index 26963c2e3..655fc7ab6 100644
--- a/docs/em/docs/advanced/additional-responses.md
+++ b/docs/em/docs/advanced/additional-responses.md
@@ -1,9 +1,12 @@
# 🌖 📨 🗄
-!!! warning
- 👉 👍 🏧 ❔.
+/// warning
- 🚥 👆 ▶️ ⏮️ **FastAPI**, 👆 💪 🚫 💪 👉.
+👉 👍 🏧 ❔.
+
+🚥 👆 ▶️ ⏮️ **FastAPI**, 👆 💪 🚫 💪 👉.
+
+///
👆 💪 📣 🌖 📨, ⏮️ 🌖 👔 📟, 🔉 🆎, 📛, ♒️.
@@ -23,24 +26,28 @@
🖼, 📣 ➕1️⃣ 📨 ⏮️ 👔 📟 `404` & Pydantic 🏷 `Message`, 👆 💪 ✍:
-```Python hl_lines="18 22"
-{!../../../docs_src/additional_responses/tutorial001.py!}
-```
+{* ../../docs_src/additional_responses/tutorial001.py hl[18,22] *}
+
+/// note
+
+✔️ 🤯 👈 👆 ✔️ 📨 `JSONResponse` 🔗.
+
+///
+
+/// info
-!!! note
- ✔️ 🤯 👈 👆 ✔️ 📨 `JSONResponse` 🔗.
+`model` 🔑 🚫 🍕 🗄.
-!!! info
- `model` 🔑 🚫 🍕 🗄.
+**FastAPI** 🔜 ✊ Pydantic 🏷 ⚪️➡️ 📤, 🏗 `JSON Schema`, & 🚮 ⚫️ ☑ 🥉.
- **FastAPI** 🔜 ✊ Pydantic 🏷 ⚪️➡️ 📤, 🏗 `JSON Schema`, & 🚮 ⚫️ ☑ 🥉.
+☑ 🥉:
- ☑ 🥉:
+* 🔑 `content`, 👈 ✔️ 💲 ➕1️⃣ 🎻 🎚 (`dict`) 👈 🔌:
+ * 🔑 ⏮️ 📻 🆎, ✅ `application/json`, 👈 🔌 💲 ➕1️⃣ 🎻 🎚, 👈 🔌:
+ * 🔑 `schema`, 👈 ✔️ 💲 🎻 🔗 ⚪️➡️ 🏷, 📥 ☑ 🥉.
+ * **FastAPI** 🚮 🔗 📥 🌐 🎻 🔗 ➕1️⃣ 🥉 👆 🗄 ↩️ ✅ ⚫️ 🔗. 👉 🌌, 🎏 🈸 & 👩💻 💪 ⚙️ 👈 🎻 🔗 🔗, 🚚 👻 📟 ⚡ 🧰, ♒️.
- * 🔑 `content`, 👈 ✔️ 💲 ➕1️⃣ 🎻 🎚 (`dict`) 👈 🔌:
- * 🔑 ⏮️ 📻 🆎, ✅ `application/json`, 👈 🔌 💲 ➕1️⃣ 🎻 🎚, 👈 🔌:
- * 🔑 `schema`, 👈 ✔️ 💲 🎻 🔗 ⚪️➡️ 🏷, 📥 ☑ 🥉.
- * **FastAPI** 🚮 🔗 📥 🌐 🎻 🔗 ➕1️⃣ 🥉 👆 🗄 ↩️ ✅ ⚫️ 🔗. 👉 🌌, 🎏 🈸 & 👩💻 💪 ⚙️ 👈 🎻 🔗 🔗, 🚚 👻 📟 ⚡ 🧰, ♒️.
+///
🏗 📨 🗄 👉 *➡ 🛠️* 🔜:
@@ -168,17 +175,21 @@
🖼, 👆 💪 🚮 🌖 📻 🆎 `image/png`, 📣 👈 👆 *➡ 🛠️* 💪 📨 🎻 🎚 (⏮️ 📻 🆎 `application/json`) ⚖️ 🇩🇴 🖼:
-```Python hl_lines="19-24 28"
-{!../../../docs_src/additional_responses/tutorial002.py!}
-```
+{* ../../docs_src/additional_responses/tutorial002.py hl[19:24,28] *}
+
+/// note
+
+👀 👈 👆 ✔️ 📨 🖼 ⚙️ `FileResponse` 🔗.
+
+///
-!!! note
- 👀 👈 👆 ✔️ 📨 🖼 ⚙️ `FileResponse` 🔗.
+/// info
-!!! info
- 🚥 👆 ✔ 🎏 📻 🆎 🎯 👆 `responses` 🔢, FastAPI 🔜 🤔 📨 ✔️ 🎏 📻 🆎 👑 📨 🎓 (🔢 `application/json`).
+🚥 👆 ✔ 🎏 📻 🆎 🎯 👆 `responses` 🔢, FastAPI 🔜 🤔 📨 ✔️ 🎏 📻 🆎 👑 📨 🎓 (🔢 `application/json`).
- ✋️ 🚥 👆 ✔️ ✔ 🛃 📨 🎓 ⏮️ `None` 🚮 📻 🆎, FastAPI 🔜 ⚙️ `application/json` 🙆 🌖 📨 👈 ✔️ 👨💼 🏷.
+✋️ 🚥 👆 ✔️ ✔ 🛃 📨 🎓 ⏮️ `None` 🚮 📻 🆎, FastAPI 🔜 ⚙️ `application/json` 🙆 🌖 📨 👈 ✔️ 👨💼 🏷.
+
+///
## 🌀 ℹ
@@ -192,9 +203,7 @@
& 📨 ⏮️ 👔 📟 `200` 👈 ⚙️ 👆 `response_model`, ✋️ 🔌 🛃 `example`:
-```Python hl_lines="20-31"
-{!../../../docs_src/additional_responses/tutorial003.py!}
-```
+{* ../../docs_src/additional_responses/tutorial003.py hl[20:31] *}
⚫️ 🔜 🌐 🌀 & 🔌 👆 🗄, & 🎦 🛠️ 🩺:
@@ -228,9 +237,7 @@ new_dict = {**old_dict, "new key": "new value"}
🖼:
-```Python hl_lines="13-17 26"
-{!../../../docs_src/additional_responses/tutorial004.py!}
-```
+{* ../../docs_src/additional_responses/tutorial004.py hl[13:17,26] *}
## 🌖 ℹ 🔃 🗄 📨
diff --git a/docs/em/docs/advanced/additional-status-codes.md b/docs/em/docs/advanced/additional-status-codes.md
index 392579df6..907c7e68e 100644
--- a/docs/em/docs/advanced/additional-status-codes.md
+++ b/docs/em/docs/advanced/additional-status-codes.md
@@ -14,21 +14,25 @@
🏆 👈, 🗄 `JSONResponse`, & 📨 👆 🎚 📤 🔗, ⚒ `status_code` 👈 👆 💚:
-```Python hl_lines="4 25"
-{!../../../docs_src/additional_status_codes/tutorial001.py!}
-```
+{* ../../docs_src/additional_status_codes/tutorial001.py hl[4,25] *}
-!!! warning
- 🕐❔ 👆 📨 `Response` 🔗, 💖 🖼 🔛, ⚫️ 🔜 📨 🔗.
+/// warning
- ⚫️ 🏆 🚫 🎻 ⏮️ 🏷, ♒️.
+🕐❔ 👆 📨 `Response` 🔗, 💖 🖼 🔛, ⚫️ 🔜 📨 🔗.
- ⚒ 💭 ⚫️ ✔️ 📊 👆 💚 ⚫️ ✔️, & 👈 💲 ☑ 🎻 (🚥 👆 ⚙️ `JSONResponse`).
+⚫️ 🏆 🚫 🎻 ⏮️ 🏷, ♒️.
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette.responses import JSONResponse`.
+⚒ 💭 ⚫️ ✔️ 📊 👆 💚 ⚫️ ✔️, & 👈 💲 ☑ 🎻 (🚥 👆 ⚙️ `JSONResponse`).
- **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. 🎏 ⏮️ `status`.
+///
+
+/// note | 📡 ℹ
+
+👆 💪 ⚙️ `from starlette.responses import JSONResponse`.
+
+**FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. 🎏 ⏮️ `status`.
+
+///
## 🗄 & 🛠️ 🩺
diff --git a/docs/em/docs/advanced/advanced-dependencies.md b/docs/em/docs/advanced/advanced-dependencies.md
index fa1554734..3404c2687 100644
--- a/docs/em/docs/advanced/advanced-dependencies.md
+++ b/docs/em/docs/advanced/advanced-dependencies.md
@@ -18,9 +18,7 @@
👈, 👥 📣 👩🔬 `__call__`:
-```Python hl_lines="10"
-{!../../../docs_src/dependencies/tutorial011.py!}
-```
+{* ../../docs_src/dependencies/tutorial011.py hl[10] *}
👉 💼, 👉 `__call__` ⚫️❔ **FastAPI** 🔜 ⚙️ ✅ 🌖 🔢 & 🎧-🔗, & 👉 ⚫️❔ 🔜 🤙 🚶♀️ 💲 🔢 👆 *➡ 🛠️ 🔢* ⏪.
@@ -28,9 +26,7 @@
& 🔜, 👥 💪 ⚙️ `__init__` 📣 🔢 👐 👈 👥 💪 ⚙️ "🔗" 🔗:
-```Python hl_lines="7"
-{!../../../docs_src/dependencies/tutorial011.py!}
-```
+{* ../../docs_src/dependencies/tutorial011.py hl[7] *}
👉 💼, **FastAPI** 🏆 🚫 ⏱ 👆 ⚖️ 💅 🔃 `__init__`, 👥 🔜 ⚙️ ⚫️ 🔗 👆 📟.
@@ -38,9 +34,7 @@
👥 💪 ✍ 👐 👉 🎓 ⏮️:
-```Python hl_lines="16"
-{!../../../docs_src/dependencies/tutorial011.py!}
-```
+{* ../../docs_src/dependencies/tutorial011.py hl[16] *}
& 👈 🌌 👥 💪 "🔗" 👆 🔗, 👈 🔜 ✔️ `"bar"` 🔘 ⚫️, 🔢 `checker.fixed_content`.
@@ -56,15 +50,16 @@ checker(q="somequery")
...& 🚶♀️ ⚫️❔ 👈 📨 💲 🔗 👆 *➡ 🛠️ 🔢* 🔢 `fixed_content_included`:
-```Python hl_lines="20"
-{!../../../docs_src/dependencies/tutorial011.py!}
-```
+{* ../../docs_src/dependencies/tutorial011.py hl[20] *}
+
+/// tip
+
+🌐 👉 💪 😑 🎭. & ⚫️ 💪 🚫 📶 🆑 ❔ ⚫️ ⚠.
-!!! tip
- 🌐 👉 💪 😑 🎭. & ⚫️ 💪 🚫 📶 🆑 ❔ ⚫️ ⚠.
+👫 🖼 😫 🙅, ✋️ 🎦 ❔ ⚫️ 🌐 👷.
- 👫 🖼 😫 🙅, ✋️ 🎦 ❔ ⚫️ 🌐 👷.
+📃 🔃 💂♂, 📤 🚙 🔢 👈 🛠️ 👉 🎏 🌌.
- 📃 🔃 💂♂, 📤 🚙 🔢 👈 🛠️ 👉 🎏 🌌.
+🚥 👆 🤔 🌐 👉, 👆 ⏪ 💭 ❔ 👈 🚙 🧰 💂♂ 👷 🔘.
- 🚥 👆 🤔 🌐 👉, 👆 ⏪ 💭 ❔ 👈 🚙 🧰 💂♂ 👷 🔘.
+///
diff --git a/docs/em/docs/advanced/async-tests.md b/docs/em/docs/advanced/async-tests.md
index df94c6ce7..283d4aa09 100644
--- a/docs/em/docs/advanced/async-tests.md
+++ b/docs/em/docs/advanced/async-tests.md
@@ -32,15 +32,11 @@
📁 `main.py` 🔜 ✔️:
-```Python
-{!../../../docs_src/async_tests/main.py!}
-```
+{* ../../docs_src/async_tests/main.py *}
📁 `test_main.py` 🔜 ✔️ 💯 `main.py`, ⚫️ 💪 👀 💖 👉 🔜:
-```Python
-{!../../../docs_src/async_tests/test_main.py!}
-```
+{* ../../docs_src/async_tests/test_main.py *}
## 🏃 ⚫️
@@ -60,18 +56,17 @@ $ pytest
📑 `@pytest.mark.anyio` 💬 ✳ 👈 👉 💯 🔢 🔜 🤙 🔁:
-```Python hl_lines="7"
-{!../../../docs_src/async_tests/test_main.py!}
-```
+{* ../../docs_src/async_tests/test_main.py hl[7] *}
+
+/// tip
-!!! tip
- 🗒 👈 💯 🔢 🔜 `async def` ↩️ `def` ⏭ 🕐❔ ⚙️ `TestClient`.
+🗒 👈 💯 🔢 🔜 `async def` ↩️ `def` ⏭ 🕐❔ ⚙️ `TestClient`.
+
+///
⤴️ 👥 💪 ✍ `AsyncClient` ⏮️ 📱, & 📨 🔁 📨 ⚫️, ⚙️ `await`.
-```Python hl_lines="9-10"
-{!../../../docs_src/async_tests/test_main.py!}
-```
+{* ../../docs_src/async_tests/test_main.py hl[9:12] *}
👉 🌓:
@@ -81,12 +76,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 e3fd26735..8b14152c9 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`
@@ -88,9 +94,7 @@ $ uvicorn main:app --root-path /api/v1
📥 👥 ✅ ⚫️ 📧 🎦 🎯.
-```Python hl_lines="8"
-{!../../../docs_src/behind_a_proxy/tutorial001.py!}
-```
+{* ../../docs_src/behind_a_proxy/tutorial001.py hl[8] *}
⤴️, 🚥 👆 ▶️ Uvicorn ⏮️:
@@ -117,9 +121,7 @@ $ uvicorn main:app --root-path /api/v1
👐, 🚥 👆 🚫 ✔️ 🌌 🚚 📋 ⏸ 🎛 💖 `--root-path` ⚖️ 🌓, 👆 💪 ⚒ `root_path` 🔢 🕐❔ 🏗 👆 FastAPI 📱:
-```Python hl_lines="3"
-{!../../../docs_src/behind_a_proxy/tutorial002.py!}
-```
+{* ../../docs_src/behind_a_proxy/tutorial002.py hl[3] *}
🚶♀️ `root_path` `FastAPI` 🔜 🌓 🚶♀️ `--root-path` 📋 ⏸ 🎛 Uvicorn ⚖️ Hypercorn.
@@ -168,8 +170,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 +240,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 +287,11 @@ $ uvicorn main:app --root-path /api/v1
## 🌖 💽
-!!! warning
- 👉 🌅 🏧 ⚙️ 💼. 💭 🆓 🚶 ⚫️.
+/// warning
+
+👉 🌅 🏧 ⚙️ 💼. 💭 🆓 🚶 ⚫️.
+
+///
🔢, **FastAPI** 🔜 ✍ `server` 🗄 🔗 ⏮️ 📛 `root_path`.
@@ -290,9 +301,7 @@ $ uvicorn main:app --root-path /api/v1
🖼:
-```Python hl_lines="4-7"
-{!../../../docs_src/behind_a_proxy/tutorial003.py!}
-```
+{* ../../docs_src/behind_a_proxy/tutorial003.py hl[4:7] *}
🔜 🏗 🗄 🔗 💖:
@@ -319,23 +328,27 @@ $ 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`
🚥 👆 🚫 💚 **FastAPI** 🔌 🏧 💽 ⚙️ `root_path`, 👆 💪 ⚙️ 🔢 `root_path_in_servers=False`:
-```Python hl_lines="9"
-{!../../../docs_src/behind_a_proxy/tutorial004.py!}
-```
+{* ../../docs_src/behind_a_proxy/tutorial004.py hl[9] *}
& ⤴️ ⚫️ 🏆 🚫 🔌 ⚫️ 🗄 🔗.
diff --git a/docs/em/docs/advanced/custom-response.md b/docs/em/docs/advanced/custom-response.md
index cf76c01d0..ab95b3e7b 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`
@@ -27,19 +30,23 @@
✋️ 🚥 👆 🎯 👈 🎚 👈 👆 🛬 **🎻 ⏮️ 🎻**, 👆 💪 🚶♀️ ⚫️ 🔗 📨 🎓 & ❎ ➕ 🌥 👈 FastAPI 🔜 ✔️ 🚶♀️ 👆 📨 🎚 🔘 `jsonable_encoder` ⏭ 🚶♀️ ⚫️ 📨 🎓.
-```Python hl_lines="2 7"
-{!../../../docs_src/custom_response/tutorial001b.py!}
-```
+{* ../../docs_src/custom_response/tutorial001b.py hl[2,7] *}
+
+/// info
+
+🔢 `response_class` 🔜 ⚙️ 🔬 "📻 🆎" 📨.
-!!! info
- 🔢 `response_class` 🔜 ⚙️ 🔬 "📻 🆎" 📨.
+👉 💼, 🇺🇸🔍 🎚 `Content-Type` 🔜 ⚒ `application/json`.
- 👉 💼, 🇺🇸🔍 🎚 `Content-Type` 🔜 ⚒ `application/json`.
+ & ⚫️ 🔜 📄 ✅ 🗄.
- & ⚫️ 🔜 📄 ✅ 🗄.
+///
-!!! tip
- `ORJSONResponse` ⏳ 🕴 💪 FastAPI, 🚫 💃.
+/// tip
+
+`ORJSONResponse` ⏳ 🕴 💪 FastAPI, 🚫 💃.
+
+///
## 🕸 📨
@@ -48,16 +55,17 @@
* 🗄 `HTMLResponse`.
* 🚶♀️ `HTMLResponse` 🔢 `response_class` 👆 *➡ 🛠️ 👨🎨*.
-```Python hl_lines="2 7"
-{!../../../docs_src/custom_response/tutorial002.py!}
-```
+{* ../../docs_src/custom_response/tutorial002.py hl[2,7] *}
+
+/// info
+
+🔢 `response_class` 🔜 ⚙️ 🔬 "📻 🆎" 📨.
-!!! info
- 🔢 `response_class` 🔜 ⚙️ 🔬 "📻 🆎" 📨.
+👉 💼, 🇺🇸🔍 🎚 `Content-Type` 🔜 ⚒ `text/html`.
- 👉 💼, 🇺🇸🔍 🎚 `Content-Type` 🔜 ⚒ `text/html`.
+ & ⚫️ 🔜 📄 ✅ 🗄.
- & ⚫️ 🔜 📄 ✅ 🗄.
+///
### 📨 `Response`
@@ -65,15 +73,19 @@
🎏 🖼 ⚪️➡️ 🔛, 🛬 `HTMLResponse`, 💪 👀 💖:
-```Python hl_lines="2 7 19"
-{!../../../docs_src/custom_response/tutorial003.py!}
-```
+{* ../../docs_src/custom_response/tutorial003.py hl[2,7,19] *}
+
+/// warning
+
+`Response` 📨 🔗 👆 *➡ 🛠️ 🔢* 🏆 🚫 📄 🗄 (🖼, `Content-Type` 🏆 🚫 📄) & 🏆 🚫 ⭐ 🏧 🎓 🩺.
+
+///
+
+/// info
-!!! warning
- `Response` 📨 🔗 👆 *➡ 🛠️ 🔢* 🏆 🚫 📄 🗄 (🖼, `Content-Type` 🏆 🚫 📄) & 🏆 🚫 ⭐ 🏧 🎓 🩺.
+↗️, ☑ `Content-Type` 🎚, 👔 📟, ♒️, 🔜 👟 ⚪️➡️ `Response` 🎚 👆 📨.
-!!! info
- ↗️, ☑ `Content-Type` 🎚, 👔 📟, ♒️, 🔜 👟 ⚪️➡️ `Response` 🎚 👆 📨.
+///
### 📄 🗄 & 🔐 `Response`
@@ -85,9 +97,7 @@
🖼, ⚫️ 💪 🕳 💖:
-```Python hl_lines="7 21 23"
-{!../../../docs_src/custom_response/tutorial004.py!}
-```
+{* ../../docs_src/custom_response/tutorial004.py hl[7,21,23] *}
👉 🖼, 🔢 `generate_html_response()` ⏪ 🏗 & 📨 `Response` ↩️ 🛬 🕸 `str`.
@@ -103,10 +113,13 @@
✔️ 🤯 👈 👆 💪 ⚙️ `Response` 📨 🕳 🙆, ⚖️ ✍ 🛃 🎧-🎓.
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette.responses import HTMLResponse`.
+/// note | 📡 ℹ
+
+👆 💪 ⚙️ `from starlette.responses import HTMLResponse`.
- **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃.
+**FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃.
+
+///
### `Response`
@@ -123,9 +136,7 @@
FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 🎚, ⚓️ 🔛 = & 🔁 = ✍ 🆎.
-```Python hl_lines="1 18"
-{!../../../docs_src/response_directly/tutorial002.py!}
-```
+{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *}
### `HTMLResponse`
@@ -135,9 +146,7 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎
✊ ✍ ⚖️ 🔢 & 📨 ✅ ✍ 📨.
-```Python hl_lines="2 7 9"
-{!../../../docs_src/custom_response/tutorial005.py!}
-```
+{* ../../docs_src/custom_response/tutorial005.py hl[2,7,9] *}
### `JSONResponse`
@@ -153,15 +162,19 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎
🎛 🎻 📨 ⚙️ `ujson`.
-!!! warning
- `ujson` 🌘 💛 🌘 🐍 🏗-🛠️ ❔ ⚫️ 🍵 📐-💼.
+/// warning
-```Python hl_lines="2 7"
-{!../../../docs_src/custom_response/tutorial001.py!}
-```
+`ujson` 🌘 💛 🌘 🐍 🏗-🛠️ ❔ ⚫️ 🍵 📐-💼.
+
+///
+
+{* ../../docs_src/custom_response/tutorial001.py hl[2,7] *}
+
+/// tip
-!!! tip
- ⚫️ 💪 👈 `ORJSONResponse` 💪 ⏩ 🎛.
+⚫️ 💪 👈 `ORJSONResponse` 💪 ⏩ 🎛.
+
+///
### `RedirectResponse`
@@ -169,18 +182,14 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎
👆 💪 📨 `RedirectResponse` 🔗:
-```Python hl_lines="2 9"
-{!../../../docs_src/custom_response/tutorial006.py!}
-```
+{* ../../docs_src/custom_response/tutorial006.py hl[2,9] *}
---
⚖️ 👆 💪 ⚙️ ⚫️ `response_class` 🔢:
-```Python hl_lines="2 7 9"
-{!../../../docs_src/custom_response/tutorial006b.py!}
-```
+{* ../../docs_src/custom_response/tutorial006b.py hl[2,7,9] *}
🚥 👆 👈, ⤴️ 👆 💪 📨 📛 🔗 ⚪️➡️ 👆 *➡ 🛠️* 🔢.
@@ -190,17 +199,13 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎
👆 💪 ⚙️ `status_code` 🔢 🌀 ⏮️ `response_class` 🔢:
-```Python hl_lines="2 7 9"
-{!../../../docs_src/custom_response/tutorial006c.py!}
-```
+{* ../../docs_src/custom_response/tutorial006c.py hl[2,7,9] *}
### `StreamingResponse`
✊ 🔁 🚂 ⚖️ 😐 🚂/🎻 & 🎏 📨 💪.
-```Python hl_lines="2 14"
-{!../../../docs_src/custom_response/tutorial007.py!}
-```
+{* ../../docs_src/custom_response/tutorial007.py hl[2,14] *}
#### ⚙️ `StreamingResponse` ⏮️ 📁-💖 🎚
@@ -211,7 +216,7 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎
👉 🔌 📚 🗃 🔗 ⏮️ ☁ 💾, 📹 🏭, & 🎏.
```{ .python .annotate hl_lines="2 10-12 14" }
-{!../../../docs_src/custom_response/tutorial008.py!}
+{!../../docs_src/custom_response/tutorial008.py!}
```
1️⃣. 👉 🚂 🔢. ⚫️ "🚂 🔢" ↩️ ⚫️ 🔌 `yield` 📄 🔘.
@@ -222,8 +227,11 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎
🔨 ⚫️ 👉 🌌, 👥 💪 🚮 ⚫️ `with` 🍫, & 👈 🌌, 🚚 👈 ⚫️ 📪 ⏮️ 🏁.
-!!! tip
- 👀 👈 📥 👥 ⚙️ 🐩 `open()` 👈 🚫 🐕🦺 `async` & `await`, 👥 📣 ➡ 🛠️ ⏮️ 😐 `def`.
+/// tip
+
+👀 👈 📥 👥 ⚙️ 🐩 `open()` 👈 🚫 🐕🦺 `async` & `await`, 👥 📣 ➡ 🛠️ ⏮️ 😐 `def`.
+
+///
### `FileResponse`
@@ -238,15 +246,11 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎
📁 📨 🔜 🔌 ☑ `Content-Length`, `Last-Modified` & `ETag` 🎚.
-```Python hl_lines="2 10"
-{!../../../docs_src/custom_response/tutorial009.py!}
-```
+{* ../../docs_src/custom_response/tutorial009.py hl[2,10] *}
👆 💪 ⚙️ `response_class` 🔢:
-```Python hl_lines="2 8 10"
-{!../../../docs_src/custom_response/tutorial009b.py!}
-```
+{* ../../docs_src/custom_response/tutorial009b.py hl[2,8,10] *}
👉 💼, 👆 💪 📨 📁 ➡ 🔗 ⚪️➡️ 👆 *➡ 🛠️* 🔢.
@@ -260,9 +264,7 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎
👆 💪 ✍ `CustomORJSONResponse`. 👑 👜 👆 ✔️ ✍ `Response.render(content)` 👩🔬 👈 📨 🎚 `bytes`:
-```Python hl_lines="9-14 17"
-{!../../../docs_src/custom_response/tutorial009c.py!}
-```
+{* ../../docs_src/custom_response/tutorial009c.py hl[9:14,17] *}
🔜 ↩️ 🛬:
@@ -288,12 +290,13 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎
🖼 🔛, **FastAPI** 🔜 ⚙️ `ORJSONResponse` 🔢, 🌐 *➡ 🛠️*, ↩️ `JSONResponse`.
-```Python hl_lines="2 4"
-{!../../../docs_src/custom_response/tutorial010.py!}
-```
+{* ../../docs_src/custom_response/tutorial010.py hl[2,4] *}
+
+/// tip
+
+👆 💪 🔐 `response_class` *➡ 🛠️* ⏭.
-!!! tip
- 👆 💪 🔐 `response_class` *➡ 🛠️* ⏭.
+///
## 🌖 🧾
diff --git a/docs/em/docs/advanced/dataclasses.md b/docs/em/docs/advanced/dataclasses.md
index e8c4b99a2..4dd597262 100644
--- a/docs/em/docs/advanced/dataclasses.md
+++ b/docs/em/docs/advanced/dataclasses.md
@@ -4,9 +4,7 @@ FastAPI 🏗 🔛 🔝 **Pydantic**, & 👤 ✔️ 🌏 👆 ❔ ⚙️ Pyda
✋️ FastAPI 🐕🦺 ⚙️ `dataclasses` 🎏 🌌:
-```Python hl_lines="1 7-12 19-20"
-{!../../../docs_src/dataclasses/tutorial001.py!}
-```
+{* ../../docs_src/dataclasses/tutorial001.py hl[1,7:12,19:20] *}
👉 🐕🦺 👏 **Pydantic**, ⚫️ ✔️ 🔗 🐕🦺 `dataclasses`.
@@ -20,20 +18,21 @@ FastAPI 🏗 🔛 🔝 **Pydantic**, & 👤 ✔️ 🌏 👆 ❔ ⚙️ Pyda
👉 👷 🎏 🌌 ⏮️ Pydantic 🏷. & ⚫️ 🤙 🏆 🎏 🌌 🔘, ⚙️ Pydantic.
-!!! info
- ✔️ 🤯 👈 🎻 💪 🚫 🌐 Pydantic 🏷 💪.
+/// info
+
+✔️ 🤯 👈 🎻 💪 🚫 🌐 Pydantic 🏷 💪.
- , 👆 5️⃣📆 💪 ⚙️ Pydantic 🏷.
+, 👆 5️⃣📆 💪 ⚙️ Pydantic 🏷.
- ✋️ 🚥 👆 ✔️ 📚 🎻 🤥 🤭, 👉 👌 🎱 ⚙️ 👫 🏋️ 🕸 🛠️ ⚙️ FastAPI. 👶
+✋️ 🚥 👆 ✔️ 📚 🎻 🤥 🤭, 👉 👌 🎱 ⚙️ 👫 🏋️ 🕸 🛠️ ⚙️ FastAPI. 👶
+
+///
## 🎻 `response_model`
👆 💪 ⚙️ `dataclasses` `response_model` 🔢:
-```Python hl_lines="1 7-13 19"
-{!../../../docs_src/dataclasses/tutorial002.py!}
-```
+{* ../../docs_src/dataclasses/tutorial002.py hl[1,7:13,19] *}
🎻 🔜 🔁 🗜 Pydantic 🎻.
@@ -50,7 +49,7 @@ FastAPI 🏗 🔛 🔝 **Pydantic**, & 👤 ✔️ 🌏 👆 ❔ ⚙️ Pyda
👈 💼, 👆 💪 🎯 💱 🐩 `dataclasses` ⏮️ `pydantic.dataclasses`, ❔ 💧-♻:
```{ .python .annotate hl_lines="1 5 8-11 14-17 23-25 28" }
-{!../../../docs_src/dataclasses/tutorial003.py!}
+{!../../docs_src/dataclasses/tutorial003.py!}
```
1️⃣. 👥 🗄 `field` ⚪️➡️ 🐩 `dataclasses`.
diff --git a/docs/em/docs/advanced/events.md b/docs/em/docs/advanced/events.md
index 19421ff58..68adb6d65 100644
--- a/docs/em/docs/advanced/events.md
+++ b/docs/em/docs/advanced/events.md
@@ -30,26 +30,25 @@
👥 ✍ 🔁 🔢 `lifespan()` ⏮️ `yield` 💖 👉:
-```Python hl_lines="16 19"
-{!../../../docs_src/events/tutorial003.py!}
-```
+{* ../../docs_src/events/tutorial003.py hl[16,19] *}
📥 👥 ⚖ 😥 *🕴* 🛠️ 🚚 🏷 🚮 (❌) 🏷 🔢 📖 ⏮️ 🎰 🏫 🏷 ⏭ `yield`. 👉 📟 🔜 🛠️ **⏭** 🈸 **▶️ ✊ 📨**, ⏮️ *🕴*.
& ⤴️, ▶️️ ⏮️ `yield`, 👥 🚚 🏷. 👉 📟 🔜 🛠️ **⏮️** 🈸 **🏁 🚚 📨**, ▶️️ ⏭ *🤫*. 👉 💪, 🖼, 🚀 ℹ 💖 💾 ⚖️ 💻.
-!!! tip
- `shutdown` 🔜 🔨 🕐❔ 👆 **⛔️** 🈸.
+/// tip
+
+`shutdown` 🔜 🔨 🕐❔ 👆 **⛔️** 🈸.
- 🎲 👆 💪 ▶️ 🆕 ⏬, ⚖️ 👆 🤚 🎡 🏃 ⚫️. 🤷
+🎲 👆 💪 ▶️ 🆕 ⏬, ⚖️ 👆 🤚 🎡 🏃 ⚫️. 🤷
+
+///
### 🔆 🔢
🥇 👜 👀, 👈 👥 ⚖ 🔁 🔢 ⏮️ `yield`. 👉 📶 🎏 🔗 ⏮️ `yield`.
-```Python hl_lines="14-19"
-{!../../../docs_src/events/tutorial003.py!}
-```
+{* ../../docs_src/events/tutorial003.py hl[14:19] *}
🥇 🍕 🔢, ⏭ `yield`, 🔜 🛠️ **⏭** 🈸 ▶️.
@@ -61,9 +60,7 @@
👈 🗜 🔢 🔘 🕳 🤙 "**🔁 🔑 👨💼**".
-```Python hl_lines="1 13"
-{!../../../docs_src/events/tutorial003.py!}
-```
+{* ../../docs_src/events/tutorial003.py hl[1,13] *}
**🔑 👨💼** 🐍 🕳 👈 👆 💪 ⚙️ `with` 📄, 🖼, `open()` 💪 ⚙️ 🔑 👨💼:
@@ -85,16 +82,17 @@ async with lifespan(app):
`lifespan` 🔢 `FastAPI` 📱 ✊ **🔁 🔑 👨💼**, 👥 💪 🚶♀️ 👆 🆕 `lifespan` 🔁 🔑 👨💼 ⚫️.
-```Python hl_lines="22"
-{!../../../docs_src/events/tutorial003.py!}
-```
+{* ../../docs_src/events/tutorial003.py hl[22] *}
## 🎛 🎉 (😢)
-!!! warning
- 👍 🌌 🍵 *🕴* & *🤫* ⚙️ `lifespan` 🔢 `FastAPI` 📱 🔬 🔛.
+/// warning
+
+👍 🌌 🍵 *🕴* & *🤫* ⚙️ `lifespan` 🔢 `FastAPI` 📱 🔬 🔛.
+
+👆 💪 🎲 🚶 👉 🍕.
- 👆 💪 🎲 🚶 👉 🍕.
+///
📤 🎛 🌌 🔬 👉 ⚛ 🛠️ ⏮️ *🕴* & ⏮️ *🤫*.
@@ -106,9 +104,7 @@ async with lifespan(app):
🚮 🔢 👈 🔜 🏃 ⏭ 🈸 ▶️, 📣 ⚫️ ⏮️ 🎉 `"startup"`:
-```Python hl_lines="8"
-{!../../../docs_src/events/tutorial001.py!}
-```
+{* ../../docs_src/events/tutorial001.py hl[8] *}
👉 💼, `startup` 🎉 🐕🦺 🔢 🔜 🔢 🏬 "💽" ( `dict`) ⏮️ 💲.
@@ -120,26 +116,33 @@ async with lifespan(app):
🚮 🔢 👈 🔜 🏃 🕐❔ 🈸 🤫 🔽, 📣 ⚫️ ⏮️ 🎉 `"shutdown"`:
-```Python hl_lines="6"
-{!../../../docs_src/events/tutorial002.py!}
-```
+{* ../../docs_src/events/tutorial002.py hl[6] *}
📥, `shutdown` 🎉 🐕🦺 🔢 🔜 ✍ ✍ ⏸ `"Application shutdown"` 📁 `log.txt`.
-!!! info
- `open()` 🔢, `mode="a"` ⛓ "🎻",, ⏸ 🔜 🚮 ⏮️ ⚫️❔ 🔛 👈 📁, 🍵 📁 ⏮️ 🎚.
+/// info
+
+`open()` 🔢, `mode="a"` ⛓ "🎻",, ⏸ 🔜 🚮 ⏮️ ⚫️❔ 🔛 👈 📁, 🍵 📁 ⏮️ 🎚.
+
+///
+
+/// tip
+
+👀 👈 👉 💼 👥 ⚙️ 🐩 🐍 `open()` 🔢 👈 🔗 ⏮️ 📁.
+
+, ⚫️ 🔌 👤/🅾 (🔢/🔢), 👈 🚚 "⌛" 👜 ✍ 💾.
+
+✋️ `open()` 🚫 ⚙️ `async` & `await`.
-!!! tip
- 👀 👈 👉 💼 👥 ⚙️ 🐩 🐍 `open()` 🔢 👈 🔗 ⏮️ 📁.
+, 👥 📣 🎉 🐕🦺 🔢 ⏮️ 🐩 `def` ↩️ `async def`.
- , ⚫️ 🔌 👤/🅾 (🔢/🔢), 👈 🚚 "⌛" 👜 ✍ 💾.
+///
- ✋️ `open()` 🚫 ⚙️ `async` & `await`.
+/// info
- , 👥 📣 🎉 🐕🦺 🔢 ⏮️ 🐩 `def` ↩️ `async def`.
+👆 💪 ✍ 🌅 🔃 👫 🎉 🐕🦺 💃 🎉' 🩺.
-!!! info
- 👆 💪 ✍ 🌅 🔃 👫 🎉 🐕🦺 💃 🎉' 🩺.
+///
### `startup` & `shutdown` 👯♂️
diff --git a/docs/em/docs/advanced/generate-clients.md b/docs/em/docs/advanced/generate-clients.md
index 261f9fb61..a680c9051 100644
--- a/docs/em/docs/advanced/generate-clients.md
+++ b/docs/em/docs/advanced/generate-clients.md
@@ -16,17 +16,7 @@
➡️ ▶️ ⏮️ 🙅 FastAPI 🈸:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```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!}
- ```
+{* ../../docs_src/generate_clients/tutorial001.py hl[9:11,14:15,18,19,23] *}
👀 👈 *➡ 🛠️* 🔬 🏷 👫 ⚙️ 📨 🚀 & 📨 🚀, ⚙️ 🏷 `Item` & `ResponseMessage`.
@@ -111,8 +101,11 @@ frontend-app@1.0.0 generate-client /home/user/code/frontend-app
-!!! tip
- 👀 ✍ `name` & `price`, 👈 🔬 FastAPI 🈸, `Item` 🏷.
+/// tip
+
+👀 ✍ `name` & `price`, 👈 🔬 FastAPI 🈸, `Item` 🏷.
+
+///
👆 🔜 ✔️ ⏸ ❌ 📊 👈 👆 📨:
@@ -129,17 +122,7 @@ frontend-app@1.0.0 generate-client /home/user/code/frontend-app
🖼, 👆 💪 ✔️ 📄 **🏬** & ➕1️⃣ 📄 **👩💻**, & 👫 💪 👽 🔖:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```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!}
- ```
+{* ../../docs_src/generate_clients/tutorial002.py hl[23,28,36] *}
### 🏗 📕 👩💻 ⏮️ 🔖
@@ -186,17 +169,7 @@ FastAPI ⚙️ **😍 🆔** 🔠 *➡ 🛠️*, ⚫️ ⚙️ **🛠️ 🆔**
👆 💪 ⤴️ 🚶♀️ 👈 🛃 🔢 **FastAPI** `generate_unique_id_function` 🔢:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```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!}
- ```
+{* ../../docs_src/generate_clients/tutorial003.py hl[8:9,12] *}
### 🏗 📕 👩💻 ⏮️ 🛃 🛠️ 🆔
@@ -218,9 +191,7 @@ FastAPI ⚙️ **😍 🆔** 🔠 *➡ 🛠️*, ⚫️ ⚙️ **🛠️ 🆔**
👥 💪 ⏬ 🗄 🎻 📁 `openapi.json` & ⤴️ 👥 💪 **❎ 👈 🔡 🔖** ⏮️ ✍ 💖 👉:
-```Python
-{!../../../docs_src/generate_clients/tutorial004.py!}
-```
+{* ../../docs_src/generate_clients/tutorial004.py *}
⏮️ 👈, 🛠️ 🆔 🔜 📁 ⚪️➡️ 👜 💖 `items-get_items` `get_items`, 👈 🌌 👩💻 🚂 💪 🏗 🙅 👩🔬 📛.
diff --git a/docs/em/docs/advanced/index.md b/docs/em/docs/advanced/index.md
index 43bada6b4..48ef8e46d 100644
--- a/docs/em/docs/advanced/index.md
+++ b/docs/em/docs/advanced/index.md
@@ -6,10 +6,13 @@
⏭ 📄 👆 🔜 👀 🎏 🎛, 📳, & 🌖 ⚒.
-!!! tip
- ⏭ 📄 **🚫 🎯 "🏧"**.
+/// tip
- & ⚫️ 💪 👈 👆 ⚙️ 💼, ⚗ 1️⃣ 👫.
+⏭ 📄 **🚫 🎯 "🏧"**.
+
+ & ⚫️ 💪 👈 👆 ⚙️ 💼, ⚗ 1️⃣ 👫.
+
+///
## ✍ 🔰 🥇
diff --git a/docs/em/docs/advanced/middleware.md b/docs/em/docs/advanced/middleware.md
index b3e722ed0..cb04fa3fb 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`
@@ -54,17 +57,13 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow")
🙆 📨 📨 `http` ⚖️ `ws` 🔜 ❎ 🔐 ⚖ ↩️.
-```Python hl_lines="2 6"
-{!../../../docs_src/advanced_middleware/tutorial001.py!}
-```
+{* ../../docs_src/advanced_middleware/tutorial001.py hl[2,6] *}
## `TrustedHostMiddleware`
🛠️ 👈 🌐 📨 📨 ✔️ ☑ ⚒ `Host` 🎚, ✔ 💂♂ 🛡 🇺🇸🔍 🦠 🎚 👊.
-```Python hl_lines="2 6-8"
-{!../../../docs_src/advanced_middleware/tutorial002.py!}
-```
+{* ../../docs_src/advanced_middleware/tutorial002.py hl[2,6:8] *}
📄 ❌ 🐕🦺:
@@ -78,9 +77,7 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow")
🛠️ 🔜 🍵 👯♂️ 🐩 & 🎥 📨.
-```Python hl_lines="2 6"
-{!../../../docs_src/advanced_middleware/tutorial003.py!}
-```
+{* ../../docs_src/advanced_middleware/tutorial003.py hl[2,6] *}
📄 ❌ 🐕🦺:
@@ -92,7 +89,6 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow")
🖼:
-* 🔫
* Uvicorn `ProxyHeadersMiddleware`
* 🇸🇲
diff --git a/docs/em/docs/advanced/openapi-callbacks.md b/docs/em/docs/advanced/openapi-callbacks.md
index 3355d6071..b0a821668 100644
--- a/docs/em/docs/advanced/openapi-callbacks.md
+++ b/docs/em/docs/advanced/openapi-callbacks.md
@@ -31,12 +31,13 @@
👉 🍕 📶 😐, 🌅 📟 🎲 ⏪ 😰 👆:
-```Python hl_lines="9-13 36-53"
-{!../../../docs_src/openapi_callbacks/tutorial001.py!}
-```
+{* ../../docs_src/openapi_callbacks/tutorial001.py hl[9:13,36:53] *}
+
+/// tip
-!!! tip
- `callback_url` 🔢 🔢 ⚙️ Pydantic 📛 🆎.
+`callback_url` 🔢 🔢 ⚙️ Pydantic 📛 🆎.
+
+///
🕴 🆕 👜 `callbacks=messages_callback_router.routes` ❌ *➡ 🛠️ 👨🎨*. 👥 🔜 👀 ⚫️❔ 👈 ⏭.
@@ -61,10 +62,13 @@ httpx.post(callback_url, json={"description": "Invoice paid", "paid": True})
👉 🖼 🚫 🛠️ ⏲ ⚫️ (👈 💪 ⏸ 📟), 🕴 🧾 🍕.
-!!! tip
- ☑ ⏲ 🇺🇸🔍 📨.
+/// tip
+
+☑ ⏲ 🇺🇸🔍 📨.
- 🕐❔ 🛠️ ⏲ 👆, 👆 💪 ⚙️ 🕳 💖 🇸🇲 ⚖️ 📨.
+🕐❔ 🛠️ ⏲ 👆, 👆 💪 ⚙️ 🕳 💖 🇸🇲 ⚖️ 📨.
+
+///
## ✍ ⏲ 🧾 📟
@@ -74,18 +78,19 @@ httpx.post(callback_url, json={"description": "Invoice paid", "paid": True})
👥 🔜 ⚙️ 👈 🎏 💡 📄 ❔ *🔢 🛠️* 🔜 👀 💖... 🏗 *➡ 🛠️(Ⓜ)* 👈 🔢 🛠️ 🔜 🛠️ (🕐 👆 🛠️ 🔜 🤙).
-!!! tip
- 🕐❔ ✍ 📟 📄 ⏲, ⚫️ 💪 ⚠ 🌈 👈 👆 👈 *🔢 👩💻*. & 👈 👆 ⏳ 🛠️ *🔢 🛠️*, 🚫 *👆 🛠️*.
+/// tip
+
+🕐❔ ✍ 📟 📄 ⏲, ⚫️ 💪 ⚠ 🌈 👈 👆 👈 *🔢 👩💻*. & 👈 👆 ⏳ 🛠️ *🔢 🛠️*, 🚫 *👆 🛠️*.
+
+🍕 🛠️ 👉 ☝ 🎑 ( *🔢 👩💻*) 💪 ℹ 👆 💭 💖 ⚫️ 🌅 ⭐ 🌐❔ 🚮 🔢, Pydantic 🏷 💪, 📨, ♒️. 👈 *🔢 🛠️*.
- 🍕 🛠️ 👉 ☝ 🎑 ( *🔢 👩💻*) 💪 ℹ 👆 💭 💖 ⚫️ 🌅 ⭐ 🌐❔ 🚮 🔢, Pydantic 🏷 💪, 📨, ♒️. 👈 *🔢 🛠️*.
+///
### ✍ ⏲ `APIRouter`
🥇 ✍ 🆕 `APIRouter` 👈 🔜 🔌 1️⃣ ⚖️ 🌅 ⏲.
-```Python hl_lines="3 25"
-{!../../../docs_src/openapi_callbacks/tutorial001.py!}
-```
+{* ../../docs_src/openapi_callbacks/tutorial001.py hl[3,25] *}
### ✍ ⏲ *➡ 🛠️*
@@ -96,9 +101,7 @@ httpx.post(callback_url, json={"description": "Invoice paid", "paid": True})
* ⚫️ 🔜 🎲 ✔️ 📄 💪 ⚫️ 🔜 📨, ✅ `body: InvoiceEvent`.
* & ⚫️ 💪 ✔️ 📄 📨 ⚫️ 🔜 📨, ✅ `response_model=InvoiceEventReceived`.
-```Python hl_lines="16-18 21-22 28-32"
-{!../../../docs_src/openapi_callbacks/tutorial001.py!}
-```
+{* ../../docs_src/openapi_callbacks/tutorial001.py hl[16:18,21:22,28:32] *}
📤 2️⃣ 👑 🔺 ⚪️➡️ 😐 *➡ 🛠️*:
@@ -154,8 +157,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`).
+
+///
### 🚮 ⏲ 📻
@@ -163,12 +169,13 @@ https://www.external.org/events/invoices/2expen51ve
🔜 ⚙️ 🔢 `callbacks` *👆 🛠️ ➡ 🛠️ 👨🎨* 🚶♀️ 🔢 `.routes` (👈 🤙 `list` 🛣/*➡ 🛠️*) ⚪️➡️ 👈 ⏲ 📻:
-```Python hl_lines="35"
-{!../../../docs_src/openapi_callbacks/tutorial001.py!}
-```
+{* ../../docs_src/openapi_callbacks/tutorial001.py hl[35] *}
+
+/// tip
+
+👀 👈 👆 🚫 🚶♀️ 📻 ⚫️ (`invoices_callback_router`) `callback=`, ✋️ 🔢 `.routes`, `invoices_callback_router.routes`.
-!!! tip
- 👀 👈 👆 🚫 🚶♀️ 📻 ⚫️ (`invoices_callback_router`) `callback=`, ✋️ 🔢 `.routes`, `invoices_callback_router.routes`.
+///
### ✅ 🩺
diff --git a/docs/em/docs/advanced/path-operation-advanced-configuration.md b/docs/em/docs/advanced/path-operation-advanced-configuration.md
index 3dc5ac536..9d9d5fa8d 100644
--- a/docs/em/docs/advanced/path-operation-advanced-configuration.md
+++ b/docs/em/docs/advanced/path-operation-advanced-configuration.md
@@ -2,16 +2,17 @@
## 🗄 {
-!!! warning
- 🚥 👆 🚫 "🕴" 🗄, 👆 🎲 🚫 💪 👉.
+/// warning
+
+🚥 👆 🚫 "🕴" 🗄, 👆 🎲 🚫 💪 👉.
+
+///
👆 💪 ⚒ 🗄 `operationId` ⚙️ 👆 *➡ 🛠️* ⏮️ 🔢 `operation_id`.
👆 🔜 ✔️ ⚒ 💭 👈 ⚫️ 😍 🔠 🛠️.
-```Python hl_lines="6"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial001.py!}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial001.py hl[6] *}
### ⚙️ *➡ 🛠️ 🔢* 📛 {
@@ -19,25 +20,27 @@
👆 🔜 ⚫️ ⏮️ ❎ 🌐 👆 *➡ 🛠️*.
-```Python hl_lines="2 12-21 24"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial002.py hl[2,12:21,24] *}
+
+/// tip
-!!! tip
- 🚥 👆 ❎ 🤙 `app.openapi()`, 👆 🔜 ℹ `operationId`Ⓜ ⏭ 👈.
+🚥 👆 ❎ 🤙 `app.openapi()`, 👆 🔜 ℹ `operationId`Ⓜ ⏭ 👈.
-!!! warning
- 🚥 👆 👉, 👆 ✔️ ⚒ 💭 🔠 1️⃣ 👆 *➡ 🛠️ 🔢* ✔️ 😍 📛.
+///
- 🚥 👫 🎏 🕹 (🐍 📁).
+/// warning
+
+🚥 👆 👉, 👆 ✔️ ⚒ 💭 🔠 1️⃣ 👆 *➡ 🛠️ 🔢* ✔️ 😍 📛.
+
+🚥 👫 🎏 🕹 (🐍 📁).
+
+///
## 🚫 ⚪️➡️ 🗄
🚫 *➡ 🛠️* ⚪️➡️ 🏗 🗄 🔗 (& ➡️, ⚪️➡️ 🏧 🧾 ⚙️), ⚙️ 🔢 `include_in_schema` & ⚒ ⚫️ `False`:
-```Python hl_lines="6"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial003.py!}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial003.py hl[6] *}
## 🏧 📛 ⚪️➡️ #️⃣
@@ -47,9 +50,7 @@
⚫️ 🏆 🚫 🎦 🆙 🧾, ✋️ 🎏 🧰 (✅ 🐉) 🔜 💪 ⚙️ 🎂.
-```Python hl_lines="19-29"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial004.py!}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial004.py hl[19:29] *}
## 🌖 📨
@@ -65,8 +66,11 @@
🕐❔ 👆 📣 *➡ 🛠️* 👆 🈸, **FastAPI** 🔁 🏗 🔗 🗃 🔃 👈 *➡ 🛠️* 🔌 🗄 🔗.
-!!! note "📡 ℹ"
- 🗄 🔧 ⚫️ 🤙 🛠️ 🎚.
+/// note | 📡 ℹ
+
+🗄 🔧 ⚫️ 🤙 🛠️ 🎚.
+
+///
⚫️ ✔️ 🌐 ℹ 🔃 *➡ 🛠️* & ⚙️ 🏗 🏧 🧾.
@@ -74,10 +78,13 @@
👉 *➡ 🛠️*-🎯 🗄 🔗 🛎 🏗 🔁 **FastAPI**, ✋️ 👆 💪 ↔ ⚫️.
-!!! tip
- 👉 🔅 🎚 ↔ ☝.
+/// tip
+
+👉 🔅 🎚 ↔ ☝.
- 🚥 👆 🕴 💪 📣 🌖 📨, 🌅 🏪 🌌 ⚫️ ⏮️ [🌖 📨 🗄](additional-responses.md){.internal-link target=_blank}.
+🚥 👆 🕴 💪 📣 🌖 📨, 🌅 🏪 🌌 ⚫️ ⏮️ [🌖 📨 🗄](additional-responses.md){.internal-link target=_blank}.
+
+///
👆 💪 ↔ 🗄 🔗 *➡ 🛠️* ⚙️ 🔢 `openapi_extra`.
@@ -85,9 +92,7 @@
👉 `openapi_extra` 💪 👍, 🖼, 📣 [🗄 ↔](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions):
-```Python hl_lines="6"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial005.py!}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial005.py hl[6] *}
🚥 👆 📂 🏧 🛠️ 🩺, 👆 ↔ 🔜 🎦 🆙 🔝 🎯 *➡ 🛠️*.
@@ -134,9 +139,7 @@
👆 💪 👈 ⏮️ `openapi_extra`:
-```Python hl_lines="20-37 39-40"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial006.py!}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial006.py hl[20:37,39:40] *}
👉 🖼, 👥 🚫 📣 🙆 Pydantic 🏷. 👐, 📨 💪 🚫 🎻 🎻, ⚫️ ✍ 🔗 `bytes`, & 🔢 `magic_data_reader()` 🔜 🈚 🎻 ⚫️ 🌌.
@@ -150,9 +153,7 @@
🖼, 👉 🈸 👥 🚫 ⚙️ FastAPI 🛠️ 🛠️ ⚗ 🎻 🔗 ⚪️➡️ Pydantic 🏷 🚫 🏧 🔬 🎻. 👐, 👥 📣 📨 🎚 🆎 📁, 🚫 🎻:
-```Python hl_lines="17-22 24"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial007.py!}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[17:22,24] *}
👐, 👐 👥 🚫 ⚙️ 🔢 🛠️ 🛠️, 👥 ⚙️ Pydantic 🏷 ❎ 🏗 🎻 🔗 💽 👈 👥 💚 📨 📁.
@@ -160,11 +161,12 @@
& ⤴️ 👆 📟, 👥 🎻 👈 📁 🎚 🔗, & ⤴️ 👥 🔄 ⚙️ 🎏 Pydantic 🏷 ✔ 📁 🎚:
-```Python hl_lines="26-33"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial007.py!}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[26:33] *}
+
+/// tip
+
+📥 👥 🏤-⚙️ 🎏 Pydantic 🏷.
-!!! tip
- 📥 👥 🏤-⚙️ 🎏 Pydantic 🏷.
+✋️ 🎏 🌌, 👥 💪 ✔️ ✔ ⚫️ 🎏 🌌.
- ✋️ 🎏 🌌, 👥 💪 ✔️ ✔ ⚫️ 🎏 🌌.
+///
diff --git a/docs/em/docs/advanced/response-change-status-code.md b/docs/em/docs/advanced/response-change-status-code.md
index 156efcc16..4933484dd 100644
--- a/docs/em/docs/advanced/response-change-status-code.md
+++ b/docs/em/docs/advanced/response-change-status-code.md
@@ -20,9 +20,7 @@
& ⤴️ 👆 💪 ⚒ `status_code` 👈 *🔀* 📨 🎚.
-```Python hl_lines="1 9 12"
-{!../../../docs_src/response_change_status_code/tutorial001.py!}
-```
+{* ../../docs_src/response_change_status_code/tutorial001.py hl[1,9,12] *}
& ⤴️ 👆 💪 📨 🙆 🎚 👆 💪, 👆 🛎 🔜 ( `dict`, 💽 🏷, ♒️).
diff --git a/docs/em/docs/advanced/response-cookies.md b/docs/em/docs/advanced/response-cookies.md
index 23fffe1dd..d9fdbaa87 100644
--- a/docs/em/docs/advanced/response-cookies.md
+++ b/docs/em/docs/advanced/response-cookies.md
@@ -6,9 +6,7 @@
& ⤴️ 👆 💪 ⚒ 🍪 👈 *🔀* 📨 🎚.
-```Python hl_lines="1 8-9"
-{!../../../docs_src/response_cookies/tutorial002.py!}
-```
+{* ../../docs_src/response_cookies/tutorial002.py hl[1,8:9] *}
& ⤴️ 👆 💪 📨 🙆 🎚 👆 💪, 👆 🛎 🔜 ( `dict`, 💽 🏷, ♒️).
@@ -26,24 +24,28 @@
⤴️ ⚒ 🍪 ⚫️, & ⤴️ 📨 ⚫️:
-```Python hl_lines="10-12"
-{!../../../docs_src/response_cookies/tutorial001.py!}
-```
+{* ../../docs_src/response_cookies/tutorial001.py hl[10:12] *}
-!!! tip
- ✔️ 🤯 👈 🚥 👆 📨 📨 🔗 ↩️ ⚙️ `Response` 🔢, FastAPI 🔜 📨 ⚫️ 🔗.
+/// tip
- , 👆 🔜 ✔️ ⚒ 💭 👆 💽 ☑ 🆎. 🤶 Ⓜ. ⚫️ 🔗 ⏮️ 🎻, 🚥 👆 🛬 `JSONResponse`.
+✔️ 🤯 👈 🚥 👆 📨 📨 🔗 ↩️ ⚙️ `Response` 🔢, FastAPI 🔜 📨 ⚫️ 🔗.
- & 👈 👆 🚫 📨 🙆 📊 👈 🔜 ✔️ ⛽ `response_model`.
+, 👆 🔜 ✔️ ⚒ 💭 👆 💽 ☑ 🆎. 🤶 Ⓜ. ⚫️ 🔗 ⏮️ 🎻, 🚥 👆 🛬 `JSONResponse`.
+
+ & 👈 👆 🚫 📨 🙆 📊 👈 🔜 ✔️ ⛽ `response_model`.
+
+///
### 🌅 ℹ
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette.responses import Response` ⚖️ `from starlette.responses import JSONResponse`.
+/// note | 📡 ℹ
+
+👆 💪 ⚙️ `from starlette.responses import Response` ⚖️ `from starlette.responses import JSONResponse`.
+
+**FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃.
- **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃.
+ & `Response` 💪 ⚙️ 🛎 ⚒ 🎚 & 🍪, **FastAPI** 🚚 ⚫️ `fastapi.Response`.
- & `Response` 💪 ⚙️ 🛎 ⚒ 🎚 & 🍪, **FastAPI** 🚚 ⚫️ `fastapi.Response`.
+///
👀 🌐 💪 🔢 & 🎛, ✅ 🧾 💃.
diff --git a/docs/em/docs/advanced/response-directly.md b/docs/em/docs/advanced/response-directly.md
index ba09734fb..29819a205 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** 🔜 🚶♀️ ⚫️ 🔗.
@@ -31,14 +34,15 @@
📚 💼, 👆 💪 ⚙️ `jsonable_encoder` 🗜 👆 📊 ⏭ 🚶♀️ ⚫️ 📨:
-```Python hl_lines="6-7 21-22"
-{!../../../docs_src/response_directly/tutorial001.py!}
-```
+{* ../../docs_src/response_directly/tutorial001.py hl[6:7,21:22] *}
+
+/// note | 📡 ℹ
+
+👆 💪 ⚙️ `from starlette.responses import JSONResponse`.
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette.responses import JSONResponse`.
+**FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃.
- **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃.
+///
## 🛬 🛃 `Response`
@@ -50,9 +54,7 @@
👆 💪 🚮 👆 📂 🎚 🎻, 🚮 ⚫️ `Response`, & 📨 ⚫️:
-```Python hl_lines="1 18"
-{!../../../docs_src/response_directly/tutorial002.py!}
-```
+{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *}
## 🗒
diff --git a/docs/em/docs/advanced/response-headers.md b/docs/em/docs/advanced/response-headers.md
index de798982a..e9e1b62d2 100644
--- a/docs/em/docs/advanced/response-headers.md
+++ b/docs/em/docs/advanced/response-headers.md
@@ -6,9 +6,7 @@
& ⤴️ 👆 💪 ⚒ 🎚 👈 *🔀* 📨 🎚.
-```Python hl_lines="1 7-8"
-{!../../../docs_src/response_headers/tutorial002.py!}
-```
+{* ../../docs_src/response_headers/tutorial002.py hl[1,7:8] *}
& ⤴️ 👆 💪 📨 🙆 🎚 👆 💪, 👆 🛎 🔜 ( `dict`, 💽 🏷, ♒️).
@@ -24,16 +22,17 @@
✍ 📨 🔬 [📨 📨 🔗](response-directly.md){.internal-link target=_blank} & 🚶♀️ 🎚 🌖 🔢:
-```Python hl_lines="10-12"
-{!../../../docs_src/response_headers/tutorial001.py!}
-```
+{* ../../docs_src/response_headers/tutorial001.py hl[10:12] *}
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `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/http-basic-auth.md b/docs/em/docs/advanced/security/http-basic-auth.md
index 33470a726..73736f3b3 100644
--- a/docs/em/docs/advanced/security/http-basic-auth.md
+++ b/docs/em/docs/advanced/security/http-basic-auth.md
@@ -20,9 +20,7 @@
* ⚫️ 📨 🎚 🆎 `HTTPBasicCredentials`:
* ⚫️ 🔌 `username` & `password` 📨.
-```Python hl_lines="2 6 10"
-{!../../../docs_src/security/tutorial006.py!}
-```
+{* ../../docs_src/security/tutorial006.py hl[2,6,10] *}
🕐❔ 👆 🔄 📂 📛 🥇 🕰 (⚖️ 🖊 "🛠️" 🔼 🩺) 🖥 🔜 💭 👆 👆 🆔 & 🔐:
@@ -42,9 +40,7 @@
⤴️ 👥 💪 ⚙️ `secrets.compare_digest()` 🚚 👈 `credentials.username` `"stanleyjobson"`, & 👈 `credentials.password` `"swordfish"`.
-```Python hl_lines="1 11-21"
-{!../../../docs_src/security/tutorial007.py!}
-```
+{* ../../docs_src/security/tutorial007.py hl[1,11:21] *}
👉 🔜 🎏:
@@ -108,6 +104,4 @@ if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish":
⏮️ 🔍 👈 🎓 ❌, 📨 `HTTPException` ⏮️ 👔 📟 4️⃣0️⃣1️⃣ (🎏 📨 🕐❔ 🙅♂ 🎓 🚚) & 🚮 🎚 `WWW-Authenticate` ⚒ 🖥 🎦 💳 📋 🔄:
-```Python hl_lines="23-27"
-{!../../../docs_src/security/tutorial007.py!}
-```
+{* ../../docs_src/security/tutorial007.py hl[23:27] *}
diff --git a/docs/em/docs/advanced/security/index.md b/docs/em/docs/advanced/security/index.md
index 10291338e..5cdc47505 100644
--- a/docs/em/docs/advanced/security/index.md
+++ b/docs/em/docs/advanced/security/index.md
@@ -4,10 +4,13 @@
📤 ➕ ⚒ 🍵 💂♂ ↖️ ⚪️➡️ 🕐 📔 [🔰 - 👩💻 🦮: 💂♂](../../tutorial/security/index.md){.internal-link target=_blank}.
-!!! tip
- ⏭ 📄 **🚫 🎯 "🏧"**.
+/// tip
- & ⚫️ 💪 👈 👆 ⚙️ 💼, ⚗ 1️⃣ 👫.
+⏭ 📄 **🚫 🎯 "🏧"**.
+
+ & ⚫️ 💪 👈 👆 ⚙️ 💼, ⚗ 1️⃣ 👫.
+
+///
## ✍ 🔰 🥇
diff --git a/docs/em/docs/advanced/security/oauth2-scopes.md b/docs/em/docs/advanced/security/oauth2-scopes.md
index d82fe152b..b8c49bd11 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,22 +46,23 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀.
* `instagram_basic` ⚙️ 👱📔 / 👱📔.
* `https://www.googleapis.com/auth/drive` ⚙️ 🇺🇸🔍.
-!!! info
- Oauth2️⃣ "↔" 🎻 👈 📣 🎯 ✔ ✔.
+/// info
+
+Oauth2️⃣ "↔" 🎻 👈 📣 🎯 ✔ ✔.
+
+⚫️ 🚫 🤔 🚥 ⚫️ ✔️ 🎏 🦹 💖 `:` ⚖️ 🚥 ⚫️ 📛.
- ⚫️ 🚫 🤔 🚥 ⚫️ ✔️ 🎏 🦹 💖 `:` ⚖️ 🚥 ⚫️ 📛.
+👈 ℹ 🛠️ 🎯.
- 👈 ℹ 🛠️ 🎯.
+Oauth2️⃣ 👫 🎻.
- Oauth2️⃣ 👫 🎻.
+///
## 🌐 🎑
🥇, ➡️ 🔜 👀 🍕 👈 🔀 ⚪️➡️ 🖼 👑 **🔰 - 👩💻 🦮** [Oauth2️⃣ ⏮️ 🔐 (& 🔁), 📨 ⏮️ 🥙 🤝](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. 🔜 ⚙️ Oauth2️⃣ ↔:
-```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155"
-{!../../../docs_src/security/tutorial005.py!}
-```
+{* ../../docs_src/security/tutorial005.py hl[2,4,8,12,46,64,105,107:115,121:124,128:134,139,155] *}
🔜 ➡️ 📄 👈 🔀 🔁 🔁.
@@ -68,9 +72,7 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀.
`scopes` 🔢 📨 `dict` ⏮️ 🔠 ↔ 🔑 & 📛 💲:
-```Python hl_lines="62-65"
-{!../../../docs_src/security/tutorial005.py!}
-```
+{* ../../docs_src/security/tutorial005.py hl[62:65] *}
↩️ 👥 🔜 📣 📚 ↔, 👫 🔜 🎦 🆙 🛠️ 🩺 🕐❔ 👆 🕹-/✔.
@@ -88,14 +90,15 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀.
& 👥 📨 ↔ 🍕 🥙 🤝.
-!!! danger
- 🦁, 📥 👥 ❎ ↔ 📨 🔗 🤝.
+/// danger
- ✋️ 👆 🈸, 💂♂, 👆 🔜 ⚒ 💭 👆 🕴 🚮 ↔ 👈 👩💻 🤙 💪 ✔️, ⚖️ 🕐 👆 ✔️ 🔁.
+🦁, 📥 👥 ❎ ↔ 📨 🔗 🤝.
-```Python hl_lines="155"
-{!../../../docs_src/security/tutorial005.py!}
-```
+✋️ 👆 🈸, 💂♂, 👆 🔜 ⚒ 💭 👆 🕴 🚮 ↔ 👈 👩💻 🤙 💪 ✔️, ⚖️ 🕐 👆 ✔️ 🔁.
+
+///
+
+{* ../../docs_src/security/tutorial005.py hl[155] *}
## 📣 ↔ *➡ 🛠️* & 🔗
@@ -113,21 +116,25 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀.
👉 💼, ⚫️ 🚚 ↔ `me` (⚫️ 💪 🚚 🌅 🌘 1️⃣ ↔).
-!!! note
- 👆 🚫 🎯 💪 🚮 🎏 ↔ 🎏 🥉.
+/// note
+
+👆 🚫 🎯 💪 🚮 🎏 ↔ 🎏 🥉.
- 👥 🔨 ⚫️ 📥 🎦 ❔ **FastAPI** 🍵 ↔ 📣 🎏 🎚.
+👥 🔨 ⚫️ 📥 🎦 ❔ **FastAPI** 🍵 ↔ 📣 🎏 🎚.
-```Python hl_lines="4 139 168"
-{!../../../docs_src/security/tutorial005.py!}
-```
+///
-!!! info "📡 ℹ"
- `Security` 🤙 🏿 `Depends`, & ⚫️ ✔️ 1️⃣ ➕ 🔢 👈 👥 🔜 👀 ⏪.
+{* ../../docs_src/security/tutorial005.py hl[4,139,168] *}
- ✋️ ⚙️ `Security` ↩️ `Depends`, **FastAPI** 🔜 💭 👈 ⚫️ 💪 📣 💂♂ ↔, ⚙️ 👫 🔘, & 📄 🛠️ ⏮️ 🗄.
+/// info | 📡 ℹ
- ✋️ 🕐❔ 👆 🗄 `Query`, `Path`, `Depends`, `Security` & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓.
+`Security` 🤙 🏿 `Depends`, & ⚫️ ✔️ 1️⃣ ➕ 🔢 👈 👥 🔜 👀 ⏪.
+
+✋️ ⚙️ `Security` ↩️ `Depends`, **FastAPI** 🔜 💭 👈 ⚫️ 💪 📣 💂♂ ↔, ⚙️ 👫 🔘, & 📄 🛠️ ⏮️ 🗄.
+
+✋️ 🕐❔ 👆 🗄 `Query`, `Path`, `Depends`, `Security` & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓.
+
+///
## ⚙️ `SecurityScopes`
@@ -143,9 +150,7 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀.
👉 `SecurityScopes` 🎓 🎏 `Request` (`Request` ⚙️ 🤚 📨 🎚 🔗).
-```Python hl_lines="8 105"
-{!../../../docs_src/security/tutorial005.py!}
-```
+{* ../../docs_src/security/tutorial005.py hl[8,105] *}
## ⚙️ `scopes`
@@ -159,9 +164,7 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀.
👉 ⚠, 👥 🔌 ↔ 🚚 (🚥 🙆) 🎻 👽 🚀 (⚙️ `scope_str`). 👥 🚮 👈 🎻 ⚗ ↔ `WWW-Authenticate` 🎚 (👉 🍕 🔌).
-```Python hl_lines="105 107-115"
-{!../../../docs_src/security/tutorial005.py!}
-```
+{* ../../docs_src/security/tutorial005.py hl[105,107:115] *}
## ✔ `username` & 💽 💠
@@ -177,9 +180,7 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀.
👥 ✔ 👈 👥 ✔️ 👩💻 ⏮️ 👈 🆔, & 🚥 🚫, 👥 🤚 👈 🎏 ⚠ 👥 ✍ ⏭.
-```Python hl_lines="46 116-127"
-{!../../../docs_src/security/tutorial005.py!}
-```
+{* ../../docs_src/security/tutorial005.py hl[46,116:127] *}
## ✔ `scopes`
@@ -187,9 +188,7 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀.
👉, 👥 ⚙️ `security_scopes.scopes`, 👈 🔌 `list` ⏮️ 🌐 👫 ↔ `str`.
-```Python hl_lines="128-134"
-{!../../../docs_src/security/tutorial005.py!}
-```
+{* ../../docs_src/security/tutorial005.py hl[128:134] *}
## 🔗 🌲 & ↔
@@ -216,10 +215,13 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀.
* `security_scopes.scopes` 🔜 🔌 `["me"]` *➡ 🛠️* `read_users_me`, ↩️ ⚫️ 📣 🔗 `get_current_active_user`.
* `security_scopes.scopes` 🔜 🔌 `[]` (🕳) *➡ 🛠️* `read_system_status`, ↩️ ⚫️ 🚫 📣 🙆 `Security` ⏮️ `scopes`, & 🚮 🔗, `get_current_user`, 🚫 📣 🙆 `scope` 👯♂️.
-!!! tip
- ⚠ & "🎱" 👜 📥 👈 `get_current_user` 🔜 ✔️ 🎏 📇 `scopes` ✅ 🔠 *➡ 🛠️*.
+/// tip
+
+⚠ & "🎱" 👜 📥 👈 `get_current_user` 🔜 ✔️ 🎏 📇 `scopes` ✅ 🔠 *➡ 🛠️*.
- 🌐 ⚓️ 🔛 `scopes` 📣 🔠 *➡ 🛠️* & 🔠 🔗 🔗 🌲 👈 🎯 *➡ 🛠️*.
+🌐 ⚓️ 🔛 `scopes` 📣 🔠 *➡ 🛠️* & 🔠 🔗 🔗 🌲 👈 🎯 *➡ 🛠️*.
+
+///
## 🌖 ℹ 🔃 `SecurityScopes`
@@ -257,10 +259,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..7fdd0d68a 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** 👷 🔘.
+🚥 👆 ✔️ 📡 💡 (🈶-🏋, 🧵, 🍫, ♒️.) & 😟 🔃 ❔ FastAPI 🍵 `async def` 🆚 😐 `def`, 🚶 ⤴️.
- 🚥 👆 ✔️ 📡 💡 (🈶-🏋, 🧵, 🍫, ♒️.) & 😟 🔃 ❔ FastAPI 🍵 `async def` 🆚 😐 `def`, 🚶 ⤴️.
+///
### ➡ 🛠️ 🔢
diff --git a/docs/em/docs/contributing.md b/docs/em/docs/contributing.md
deleted file mode 100644
index 08561d8f8..000000000
--- a/docs/em/docs/contributing.md
+++ /dev/null
@@ -1,465 +0,0 @@
-# 🛠️ - 📉
-
-🥇, 👆 💪 💚 👀 🔰 🌌 [ℹ FastAPI & 🤚 ℹ](help-fastapi.md){.internal-link target=_blank}.
-
-## 🛠️
-
-🚥 👆 ⏪ 🖖 🗃 & 👆 💭 👈 👆 💪 ⏬ 🤿 📟, 📥 📄 ⚒ 🆙 👆 🌐.
-
-### 🕹 🌐 ⏮️ `venv`
-
-👆 💪 ✍ 🕹 🌐 📁 ⚙️ 🐍 `venv` 🕹:
-
-
+
& ↗️, 🎏 🎰 🔜 🎲 ✔️ **🎏 🛠️** 🏃 👍, ↖️ ⚪️➡️ 👆 🈸.
@@ -238,10 +241,13 @@
* **☁ 🐕🦺** 👈 🍵 👉 👆
* ☁ 🐕🦺 🔜 🎲 **🍵 🧬 👆**. ⚫️ 🔜 🎲 ➡️ 👆 🔬 **🛠️ 🏃**, ⚖️ **📦 🖼** ⚙️, 🙆 💼, ⚫️ 🔜 🌅 🎲 **👁 Uvicorn 🛠️**, & ☁ 🐕🦺 🔜 🈚 🔁 ⚫️.
-!!! tip
- 🚫 😟 🚥 👫 🏬 🔃 **📦**, ☁, ⚖️ Kubernetes 🚫 ⚒ 📚 🔑.
+/// tip
+
+🚫 😟 🚥 👫 🏬 🔃 **📦**, ☁, ⚖️ Kubernetes 🚫 ⚒ 📚 🔑.
+
+👤 🔜 💬 👆 🌅 🔃 📦 🖼, ☁, Kubernetes, ♒️. 🔮 📃: [FastAPI 📦 - ☁](docker.md){.internal-link target=_blank}.
- 👤 🔜 💬 👆 🌅 🔃 📦 🖼, ☁, Kubernetes, ♒️. 🔮 📃: [FastAPI 📦 - ☁](docker.md){.internal-link target=_blank}.
+///
## ⏮️ 🔁 ⏭ ▶️
@@ -257,10 +263,13 @@
↗️, 📤 💼 🌐❔ 📤 🙅♂ ⚠ 🏃 ⏮️ 🔁 💗 🕰, 👈 💼, ⚫️ 📚 ⏩ 🍵.
-!!! tip
- , ✔️ 🤯 👈 ⚓️ 🔛 👆 🖥, 💼 👆 **5️⃣📆 🚫 💪 🙆 ⏮️ 🔁** ⏭ ▶️ 👆 🈸.
+/// tip
- 👈 💼, 👆 🚫🔜 ✔️ 😟 🔃 🙆 👉. 🤷
+, ✔️ 🤯 👈 ⚓️ 🔛 👆 🖥, 💼 👆 **5️⃣📆 🚫 💪 🙆 ⏮️ 🔁** ⏭ ▶️ 👆 🈸.
+
+👈 💼, 👆 🚫🔜 ✔️ 😟 🔃 🙆 👉. 🤷
+
+///
### 🖼 ⏮️ 🔁 🎛
@@ -272,8 +281,11 @@
* 🎉 ✍ 👈 🏃 ⏮️ 🔁 & ⤴️ ▶️ 👆 🈸
* 👆 🔜 💪 🌌 ▶️/⏏ *👈* 🎉 ✍, 🔍 ❌, ♒️.
-!!! tip
- 👤 🔜 🤝 👆 🌅 🧱 🖼 🔨 👉 ⏮️ 📦 🔮 📃: [FastAPI 📦 - ☁](docker.md){.internal-link target=_blank}.
+/// tip
+
+👤 🔜 🤝 👆 🌅 🧱 🖼 🔨 👉 ⏮️ 📦 🔮 📃: [FastAPI 📦 - ☁](docker.md){.internal-link target=_blank}.
+
+///
## ℹ 🛠️
diff --git a/docs/em/docs/deployment/docker.md b/docs/em/docs/deployment/docker.md
index 091eb3bab..2152f1a0e 100644
--- a/docs/em/docs/deployment/docker.md
+++ b/docs/em/docs/deployment/docker.md
@@ -4,8 +4,11 @@
⚙️ 💾 📦 ✔️ 📚 📈 ✅ **💂♂**, **🔬**, **🦁**, & 🎏.
-!!! tip
- 🏃 & ⏪ 💭 👉 💩 ❓ 🦘 [`Dockerfile` 🔛 👶](#fastapi).
+/// tip
+
+🏃 & ⏪ 💭 👉 💩 ❓ 🦘 [`Dockerfile` 🔛 👶](#fastapi).
+
+///
📁 🎮 👶
@@ -130,10 +133,13 @@ Successfully installed fastapi pydantic uvicorn
-!!! info
- 📤 🎏 📁 & 🧰 🔬 & ❎ 📦 🔗.
+/// info
+
+📤 🎏 📁 & 🧰 🔬 & ❎ 📦 🔗.
- 👤 🔜 🎦 👆 🖼 ⚙️ 🎶 ⏪ 📄 🔛. 👶
+👤 🔜 🎦 👆 🖼 ⚙️ 🎶 ⏪ 📄 🔛. 👶
+
+///
### ✍ **FastAPI** 📟
@@ -199,8 +205,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"]
`--no-cache-dir` 🎛 💬 `pip` 🚫 🖊 ⏬ 📦 🌐, 👈 🕴 🚥 `pip` 🔜 🏃 🔄 ❎ 🎏 📦, ✋️ 👈 🚫 💼 🕐❔ 👷 ⏮️ 📦.
- !!! note
- `--no-cache-dir` 🕴 🔗 `pip`, ⚫️ ✔️ 🕳 ⏮️ ☁ ⚖️ 📦.
+ /// note
+
+ `--no-cache-dir` 🕴 🔗 `pip`, ⚫️ ✔️ 🕳 ⏮️ ☁ ⚖️ 📦.
+
+ ///
`--upgrade` 🎛 💬 `pip` ♻ 📦 🚥 👫 ⏪ ❎.
@@ -222,8 +231,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"]
↩️ 📋 🔜 ▶️ `/code` & 🔘 ⚫️ 📁 `./app` ⏮️ 👆 📟, **Uvicorn** 🔜 💪 👀 & **🗄** `app` ⚪️➡️ `app.main`.
-!!! tip
- 📄 ⚫️❔ 🔠 ⏸ 🔨 🖊 🔠 🔢 💭 📟. 👶
+/// tip
+
+📄 ⚫️❔ 🔠 ⏸ 🔨 🖊 🔠 🔢 💭 📟. 👶
+
+///
👆 🔜 🔜 ✔️ 📁 📊 💖:
@@ -293,10 +305,13 @@ $ docker build -t myimage .
-!!! tip
- 👀 `.` 🔚, ⚫️ 🌓 `./`, ⚫️ 💬 ☁ 📁 ⚙️ 🏗 📦 🖼.
+/// tip
+
+👀 `.` 🔚, ⚫️ 🌓 `./`, ⚫️ 💬 ☁ 📁 ⚙️ 🏗 📦 🖼.
- 👉 💼, ⚫️ 🎏 ⏮️ 📁 (`.`).
+👉 💼, ⚫️ 🎏 ⏮️ 📁 (`.`).
+
+///
### ▶️ ☁ 📦
@@ -394,8 +409,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"]
⚫️ 💪 ➕1️⃣ 📦, 🖼 ⏮️ Traefik, 🚚 **🇺🇸🔍** & **🏧** 🛠️ **📄**.
-!!! tip
- Traefik ✔️ 🛠️ ⏮️ ☁, Kubernetes, & 🎏, ⚫️ 📶 ⏩ ⚒ 🆙 & 🔗 🇺🇸🔍 👆 📦 ⏮️ ⚫️.
+/// tip
+
+Traefik ✔️ 🛠️ ⏮️ ☁, Kubernetes, & 🎏, ⚫️ 📶 ⏩ ⚒ 🆙 & 🔗 🇺🇸🔍 👆 📦 ⏮️ ⚫️.
+
+///
👐, 🇺🇸🔍 💪 🍵 ☁ 🐕🦺 1️⃣ 👫 🐕🦺 (⏪ 🏃 🈸 📦).
@@ -423,8 +441,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"]
👉 🦲 🔜 ✊ **📐** 📨 & 📎 👈 👪 👨🏭 (🤞) **⚖** 🌌, ⚫️ 🛎 🤙 **📐 ⚙**.
-!!! tip
- 🎏 **🤝 ❎ 🗳** 🦲 ⚙️ 🇺🇸🔍 🔜 🎲 **📐 ⚙**.
+/// tip
+
+🎏 **🤝 ❎ 🗳** 🦲 ⚙️ 🇺🇸🔍 🔜 🎲 **📐 ⚙**.
+
+///
& 🕐❔ 👷 ⏮️ 📦, 🎏 ⚙️ 👆 ⚙️ ▶️ & 🛠️ 👫 🔜 ⏪ ✔️ 🔗 🧰 📶 **🕸 📻** (✅ 🇺🇸🔍 📨) ⚪️➡️ 👈 **📐 ⚙** (👈 💪 **🤝 ❎ 🗳**) 📦(Ⓜ) ⏮️ 👆 📱.
@@ -503,8 +524,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"]
🚥 👆 ✔️ **💗 📦**, 🎲 🔠 1️⃣ 🏃 **👁 🛠️** (🖼, **Kubernetes** 🌑), ⤴️ 👆 🔜 🎲 💚 ✔️ **🎏 📦** 🔨 👷 **⏮️ 📶** 👁 📦, 🏃 👁 🛠️, **⏭** 🏃 🔁 👨🏭 📦.
-!!! info
- 🚥 👆 ⚙️ Kubernetes, 👉 🔜 🎲 🕑 📦.
+/// info
+
+🚥 👆 ⚙️ Kubernetes, 👉 🔜 🎲 🕑 📦.
+
+///
🚥 👆 ⚙️ 💼 📤 🙅♂ ⚠ 🏃♂ 👈 ⏮️ 📶 **💗 🕰 🔗** (🖼 🚥 👆 🚫 🏃 💽 🛠️, ✋️ ✅ 🚥 💽 🔜), ⤴️ 👆 💪 🚮 👫 🔠 📦 ▶️️ ⏭ ▶️ 👑 🛠️.
@@ -520,8 +544,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"]
* tiangolo/uvicorn-🐁-fastapi.
-!!! warning
- 📤 ↕ 🤞 👈 👆 **🚫** 💪 👉 🧢 🖼 ⚖️ 🙆 🎏 🎏 1️⃣, & 🔜 👻 📆 🏗 🖼 ⚪️➡️ 🖌 [🔬 🔛: 🏗 ☁ 🖼 FastAPI](#fastapi).
+/// warning
+
+📤 ↕ 🤞 👈 👆 **🚫** 💪 👉 🧢 🖼 ⚖️ 🙆 🎏 🎏 1️⃣, & 🔜 👻 📆 🏗 🖼 ⚪️➡️ 🖌 [🔬 🔛: 🏗 ☁ 🖼 FastAPI](#fastapi).
+
+///
👉 🖼 ✔️ **🚘-📳** 🛠️ 🔌 ⚒ **🔢 👨🏭 🛠️** ⚓️ 🔛 💽 🐚 💪.
@@ -529,8 +556,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"]
⚫️ 🐕🦺 🏃 **⏮️ 🔁 ⏭ ▶️** ⏮️ ✍.
-!!! tip
- 👀 🌐 📳 & 🎛, 🚶 ☁ 🖼 📃: Tiangolo/uvicorn-🐁-fastapi.
+/// tip
+
+👀 🌐 📳 & 🎛, 🚶 ☁ 🖼 📃: Tiangolo/uvicorn-🐁-fastapi.
+
+///
### 🔢 🛠️ 🔛 🛂 ☁ 🖼
@@ -657,8 +687,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"]
1️⃣1️⃣. 🏃 `uvicorn` 📋, 💬 ⚫️ ⚙️ `app` 🎚 🗄 ⚪️➡️ `app.main`.
-!!! tip
- 🖊 💭 🔢 👀 ⚫️❔ 🔠 ⏸ 🔨.
+/// tip
+
+🖊 💭 🔢 👀 ⚫️❔ 🔠 ⏸ 🔨.
+
+///
**☁ ▶️** 🍕 `Dockerfile` 👈 👷 **🍕 📦 🖼** 👈 🕴 ⚙️ 🏗 📁 ⚙️ ⏪.
diff --git a/docs/em/docs/deployment/https.md b/docs/em/docs/deployment/https.md
index 3feb3a2c2..6d2641a92 100644
--- a/docs/em/docs/deployment/https.md
+++ b/docs/em/docs/deployment/https.md
@@ -4,8 +4,11 @@
✋️ ⚫️ 🌌 🌖 🏗 🌘 👈.
-!!! tip
- 🚥 👆 🏃 ⚖️ 🚫 💅, 😣 ⏮️ ⏭ 📄 🔁 🔁 👩🌾 ⚒ 🌐 🆙 ⏮️ 🎏 ⚒.
+/// tip
+
+🚥 👆 🏃 ⚖️ 🚫 💅, 😣 ⏮️ ⏭ 📄 🔁 🔁 👩🌾 ⚒ 🌐 🆙 ⏮️ 🎏 ⚒.
+
+///
**💡 🔰 🇺🇸🔍**, ⚪️➡️ 🏬 🤔, ✅ https://howhttps.works/.
@@ -68,8 +71,11 @@
👆 🔜 🎲 👉 🕐, 🥇 🕰, 🕐❔ ⚒ 🌐 🆙.
-!!! tip
- 👉 🆔 📛 🍕 🌌 ⏭ 🇺🇸🔍, ✋️ 🌐 🪀 🔛 🆔 & 📢 📢, ⚫️ 💸 💬 ⚫️ 📥.
+/// tip
+
+👉 🆔 📛 🍕 🌌 ⏭ 🇺🇸🔍, ✋️ 🌐 🪀 🔛 🆔 & 📢 📢, ⚫️ 💸 💬 ⚫️ 📥.
+
+///
### 🏓
@@ -79,7 +85,7 @@
🏓 💽 🔜 💬 🖥 ⚙️ 🎯 **📢 📢**. 👈 🔜 📢 📢 📢 ⚙️ 👆 💽, 👈 👆 🔗 🏓 💽.
-
+
### 🤝 🤝 ▶️
@@ -87,7 +93,7 @@
🥇 🍕 📻 🛠️ 🔗 🖖 👩💻 & 💽 & 💭 🔐 🔑 👫 🔜 ⚙️, ♒️.
-
+
👉 🔗 🖖 👩💻 & 💽 🛠️ 🤝 🔗 🤙 **🤝 🤝**.
@@ -105,7 +111,7 @@
👉 💼, ⚫️ 🔜 ⚙️ 📄 `someapp.example.com`.
-
+
👩💻 ⏪ **💙** 👨💼 👈 🏗 👈 🤝 📄 (👉 💼 ➡️ 🗜, ✋️ 👥 🔜 👀 🔃 👈 ⏪), ⚫️ 💪 **✔** 👈 📄 ☑.
@@ -115,8 +121,11 @@
& 👈 ⚫️❔ **🇺🇸🔍** , ⚫️ ✅ **🇺🇸🔍** 🔘 **🔐 🤝 🔗** ↩️ 😁 (💽) 🕸 🔗.
-!!! tip
- 👀 👈 🔐 📻 🔨 **🕸 🎚**, 🚫 🇺🇸🔍 🎚.
+/// tip
+
+👀 👈 🔐 📻 🔨 **🕸 🎚**, 🚫 🇺🇸🔍 🎚.
+
+///
### 🇺🇸🔍 📨
@@ -124,19 +133,19 @@
, 👩💻 📨 **🇺🇸🔍 📨**. 👉 🇺🇸🔍 📨 🔘 🗜 🤝 🔗.
-
+
### 🗜 📨
🤝 ❎ 🗳 🔜 ⚙️ 🔐 ✔ **🗜 📨**, & 🔜 📶 **✅ (🗜) 🇺🇸🔍 📨** 🛠️ 🏃 🈸 (🖼 🛠️ ⏮️ Uvicorn 🏃♂ FastAPI 🈸).
-
+
### 🇺🇸🔍 📨
🈸 🔜 🛠️ 📨 & 📨 **✅ (💽) 🇺🇸🔍 📨** 🤝 ❎ 🗳.
-
+
### 🇺🇸🔍 📨
@@ -144,7 +153,7 @@
⏭, 🖥 🔜 ✔ 👈 📨 ☑ & 🗜 ⏮️ ▶️️ 🔐 🔑, ♒️. ⚫️ 🔜 ⤴️ **🗜 📨** & 🛠️ ⚫️.
-
+
👩💻 (🖥) 🔜 💭 👈 📨 👟 ⚪️➡️ ☑ 💽 ↩️ ⚫️ ⚙️ ⚛ 👫 ✔ ⚙️ **🇺🇸🔍 📄** ⏭.
@@ -154,7 +163,7 @@
🕴 1️⃣ 🛠️ 💪 🚚 🎯 📢 & ⛴ (🤝 ❎ 🗳 👆 🖼) ✋️ 🎏 🈸/🛠️ 💪 🏃 🔛 💽(Ⓜ) 💁♂️, 📏 👫 🚫 🔄 ⚙️ 🎏 **🌀 📢 📢 & ⛴**.
-
+
👈 🌌, 🤝 ❎ 🗳 💪 🍵 🇺🇸🔍 & 📄 **💗 🆔**, 💗 🈸, & ⤴️ 📶 📨 ▶️️ 🈸 🔠 💼.
@@ -164,7 +173,7 @@
& ⤴️, 📤 🔜 ➕1️⃣ 📋 (💼 ⚫️ ➕1️⃣ 📋, 💼 ⚫️ 💪 🎏 🤝 ❎ 🗳) 👈 🔜 💬 ➡️ 🗜, & ♻ 📄(Ⓜ).
-
+
**🤝 📄** **🔗 ⏮️ 🆔 📛**, 🚫 ⏮️ 📢 📢.
diff --git a/docs/em/docs/deployment/manually.md b/docs/em/docs/deployment/manually.md
index 43cbc9409..8ebe00c7c 100644
--- a/docs/em/docs/deployment/manually.md
+++ b/docs/em/docs/deployment/manually.md
@@ -22,75 +22,89 @@
👆 💪 ❎ 🔫 🔗 💽 ⏮️:
-=== "Uvicorn"
+//// tab | Uvicorn
- * Uvicorn, 🌩-⏩ 🔫 💽, 🏗 🔛 uvloop & httptool.
+* Uvicorn, 🌩-⏩ 🔫 💽, 🏗 🔛 uvloop & httptool.
-
-{% endfor %}
-{% endif %}
-
-{% if sponsors.silver %}
-
-### 🥇1st 💰
-
-{% for sponsor in sponsors.silver -%}
-
-{% endfor %}
-{% endif %}
-
-{% if sponsors.bronze %}
-
-### 🥈2nd 💰
-
-{% for sponsor in sponsors.bronze -%}
-
-{% endfor %}
-{% endif %}
-
-{% endif %}
-
-### 🎯 💰
-
-{% if github_sponsors %}
-{% for group in github_sponsors.sponsors %}
-
-
-
+
@@ -93,7 +93,7 @@ FastAPI 🏛, ⏩ (↕-🎭), 🕸 🛠️ 🏗 🛠️ ⏮️ 🐍 3️⃣.8️
"_🤙, ⚫️❔ 👆 ✔️ 🏗 👀 💎 💠 & 🇵🇱. 📚 🌌, ⚫️ ⚫️❔ 👤 💚 **🤗** - ⚫️ 🤙 😍 👀 👱 🏗 👈._"
-
+
---
@@ -133,7 +133,7 @@ FastAPI 🧍 🔛 ⌚ 🐘:
email_validator
- 📧 🔬.
+* email-validator
- 📧 🔬.
⚙️ 💃:
diff --git a/docs/em/docs/python-types.md b/docs/em/docs/python-types.md
index b3026917a..d2af23bb9 100644
--- a/docs/em/docs/python-types.md
+++ b/docs/em/docs/python-types.md
@@ -12,15 +12,18 @@
✋️ 🚥 👆 🙅 ⚙️ **FastAPI**, 👆 🔜 💰 ⚪️➡️ 🏫 🍖 🔃 👫.
-!!! note
- 🚥 👆 🐍 🕴, & 👆 ⏪ 💭 🌐 🔃 🆎 🔑, 🚶 ⏭ 📃.
+/// note
+
+🚥 👆 🐍 🕴, & 👆 ⏪ 💭 🌐 🔃 🆎 🔑, 🚶 ⏭ 📃.
+
+///
## 🎯
➡️ ▶️ ⏮️ 🙅 🖼:
```Python
-{!../../../docs_src/python_types/tutorial001.py!}
+{!../../docs_src/python_types/tutorial001.py!}
```
🤙 👉 📋 🔢:
@@ -36,7 +39,7 @@ John Doe
* 🔢 👫 ⏮️ 🚀 🖕.
```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial001.py!}
+{!../../docs_src/python_types/tutorial001.py!}
```
### ✍ ⚫️
@@ -80,7 +83,7 @@ John Doe
👈 "🆎 🔑":
```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial002.py!}
+{!../../docs_src/python_types/tutorial002.py!}
```
👈 🚫 🎏 📣 🔢 💲 💖 🔜 ⏮️:
@@ -110,7 +113,7 @@ John Doe
✅ 👉 🔢, ⚫️ ⏪ ✔️ 🆎 🔑:
```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial003.py!}
+{!../../docs_src/python_types/tutorial003.py!}
```
↩️ 👨🎨 💭 🆎 🔢, 👆 🚫 🕴 🤚 🛠️, 👆 🤚 ❌ ✅:
@@ -120,7 +123,7 @@ John Doe
🔜 👆 💭 👈 👆 ✔️ 🔧 ⚫️, 🗜 `age` 🎻 ⏮️ `str(age)`:
```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial004.py!}
+{!../../docs_src/python_types/tutorial004.py!}
```
## 📣 🆎
@@ -141,7 +144,7 @@ John Doe
* `bytes`
```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial005.py!}
+{!../../docs_src/python_types/tutorial005.py!}
```
### 💊 🆎 ⏮️ 🆎 🔢
@@ -164,45 +167,55 @@ John Doe
🖼, ➡️ 🔬 🔢 `list` `str`.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ⚪️➡️ `typing`, 🗄 `List` (⏮️ 🔠 `L`):
+⚪️➡️ `typing`, 🗄 `List` (⏮️ 🔠 `L`):
+
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial006.py!}
+```
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial006.py!}
- ```
+📣 🔢, ⏮️ 🎏 ❤ (`:`) ❕.
- 📣 🔢, ⏮️ 🎏 ❤ (`:`) ❕.
+🆎, 🚮 `List` 👈 👆 🗄 ⚪️➡️ `typing`.
- 🆎, 🚮 `List` 👈 👆 🗄 ⚪️➡️ `typing`.
+📇 🆎 👈 🔌 🔗 🆎, 👆 🚮 👫 ⬜ 🗜:
- 📇 🆎 👈 🔌 🔗 🆎, 👆 🚮 👫 ⬜ 🗜:
+```Python hl_lines="4"
+{!> ../../docs_src/python_types/tutorial006.py!}
+```
- ```Python hl_lines="4"
- {!> ../../../docs_src/python_types/tutorial006.py!}
- ```
+////
-=== "🐍 3️⃣.9️⃣ & 🔛"
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
- 📣 🔢, ⏮️ 🎏 ❤ (`:`) ❕.
+📣 🔢, ⏮️ 🎏 ❤ (`:`) ❕.
- 🆎, 🚮 `list`.
+🆎, 🚮 `list`.
- 📇 🆎 👈 🔌 🔗 🆎, 👆 🚮 👫 ⬜ 🗜:
+📇 🆎 👈 🔌 🔗 🆎, 👆 🚮 👫 ⬜ 🗜:
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial006_py39.py!}
- ```
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial006_py39.py!}
+```
-!!! info
- 👈 🔗 🆎 ⬜ 🗜 🤙 "🆎 🔢".
+////
- 👉 💼, `str` 🆎 🔢 🚶♀️ `List` (⚖️ `list` 🐍 3️⃣.9️⃣ & 🔛).
+/// info
+
+👈 🔗 🆎 ⬜ 🗜 🤙 "🆎 🔢".
+
+👉 💼, `str` 🆎 🔢 🚶♀️ `List` (⚖️ `list` 🐍 3️⃣.9️⃣ & 🔛).
+
+///
👈 ⛓: "🔢 `items` `list`, & 🔠 🏬 👉 📇 `str`".
-!!! tip
- 🚥 👆 ⚙️ 🐍 3️⃣.9️⃣ ⚖️ 🔛, 👆 🚫 ✔️ 🗄 `List` ⚪️➡️ `typing`, 👆 💪 ⚙️ 🎏 🥔 `list` 🆎 ↩️.
+/// tip
+
+🚥 👆 ⚙️ 🐍 3️⃣.9️⃣ ⚖️ 🔛, 👆 🚫 ✔️ 🗄 `List` ⚪️➡️ `typing`, 👆 💪 ⚙️ 🎏 🥔 `list` 🆎 ↩️.
+
+///
🔨 👈, 👆 👨🎨 💪 🚚 🐕🦺 ⏪ 🏭 🏬 ⚪️➡️ 📇:
@@ -218,17 +231,21 @@ John Doe
👆 🔜 🎏 📣 `tuple`Ⓜ & `set`Ⓜ:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial007.py!}
- ```
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial007.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial007_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
+
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial007_py39.py!}
+```
+
+////
👉 ⛓:
@@ -243,17 +260,21 @@ John Doe
🥈 🆎 🔢 💲 `dict`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial008.py!}
+```
+
+////
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial008.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.9️⃣ & 🔛"
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial008_py39.py!}
+```
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial008_py39.py!}
- ```
+////
👉 ⛓:
@@ -269,17 +290,21 @@ John Doe
🐍 3️⃣.1️⃣0️⃣ 📤 **🎛 ❕** 🌐❔ 👆 💪 🚮 💪 🆎 👽 ⏸ ⏸ (`|`).
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial008b.py!}
+```
+
+////
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial008b.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial008b_py310.py!}
+```
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial008b_py310.py!}
- ```
+////
👯♂️ 💼 👉 ⛓ 👈 `item` 💪 `int` ⚖️ `str`.
@@ -290,7 +315,7 @@ John Doe
🐍 3️⃣.6️⃣ & 🔛 (✅ 🐍 3️⃣.1️⃣0️⃣) 👆 💪 📣 ⚫️ 🏭 & ⚙️ `Optional` ⚪️➡️ `typing` 🕹.
```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009.py!}
+{!../../docs_src/python_types/tutorial009.py!}
```
⚙️ `Optional[str]` ↩️ `str` 🔜 ➡️ 👨🎨 ℹ 👆 🔍 ❌ 🌐❔ 👆 💪 🤔 👈 💲 🕧 `str`, 🕐❔ ⚫️ 💪 🤙 `None` 💁♂️.
@@ -299,23 +324,29 @@ John Doe
👉 ⛓ 👈 🐍 3️⃣.1️⃣0️⃣, 👆 💪 ⚙️ `Something | None`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial009.py!}
+```
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial009.py!}
- ```
+////
-=== "🐍 3️⃣.6️⃣ & 🔛 - 🎛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛 - 🎛
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial009b.py!}
- ```
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial009b.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial009_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial009_py310.py!}
+```
+
+////
#### ⚙️ `Union` ⚖️ `Optional`
@@ -333,7 +364,7 @@ John Doe
🖼, ➡️ ✊ 👉 🔢:
```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009c.py!}
+{!../../docs_src/python_types/tutorial009c.py!}
```
🔢 `name` 🔬 `Optional[str]`, ✋️ ⚫️ **🚫 📦**, 👆 🚫🔜 🤙 🔢 🍵 🔢:
@@ -351,7 +382,7 @@ say_hi(name=None) # This works, None is valid 🎉
👍 📰, 🕐 👆 🔛 🐍 3️⃣.1️⃣0️⃣ 👆 🏆 🚫 ✔️ 😟 🔃 👈, 👆 🔜 💪 🎯 ⚙️ `|` 🔬 🇪🇺 🆎:
```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009c_py310.py!}
+{!../../docs_src/python_types/tutorial009c_py310.py!}
```
& ⤴️ 👆 🏆 🚫 ✔️ 😟 🔃 📛 💖 `Optional` & `Union`. 👶
@@ -360,47 +391,53 @@ say_hi(name=None) # This works, None is valid 🎉
👉 🆎 👈 ✊ 🆎 🔢 ⬜ 🗜 🤙 **💊 🆎** ⚖️ **💊**, 🖼:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
+
+* `List`
+* `Tuple`
+* `Set`
+* `Dict`
+* `Union`
+* `Optional`
+* ...& 🎏.
- * `List`
- * `Tuple`
- * `Set`
- * `Dict`
- * `Union`
- * `Optional`
- * ...& 🎏.
+////
-=== "🐍 3️⃣.9️⃣ & 🔛"
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
- 👆 💪 ⚙️ 🎏 💽 🆎 💊 (⏮️ ⬜ 🗜 & 🆎 🔘):
+👆 💪 ⚙️ 🎏 💽 🆎 💊 (⏮️ ⬜ 🗜 & 🆎 🔘):
- * `list`
- * `tuple`
- * `set`
- * `dict`
+* `list`
+* `tuple`
+* `set`
+* `dict`
- & 🎏 ⏮️ 🐍 3️⃣.6️⃣, ⚪️➡️ `typing` 🕹:
+ & 🎏 ⏮️ 🐍 3️⃣.6️⃣, ⚪️➡️ `typing` 🕹:
- * `Union`
- * `Optional`
- * ...& 🎏.
+* `Union`
+* `Optional`
+* ...& 🎏.
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- 👆 💪 ⚙️ 🎏 💽 🆎 💊 (⏮️ ⬜ 🗜 & 🆎 🔘):
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
- * `list`
- * `tuple`
- * `set`
- * `dict`
+👆 💪 ⚙️ 🎏 💽 🆎 💊 (⏮️ ⬜ 🗜 & 🆎 🔘):
- & 🎏 ⏮️ 🐍 3️⃣.6️⃣, ⚪️➡️ `typing` 🕹:
+* `list`
+* `tuple`
+* `set`
+* `dict`
- * `Union`
- * `Optional` (🎏 ⏮️ 🐍 3️⃣.6️⃣)
- * ...& 🎏.
+ & 🎏 ⏮️ 🐍 3️⃣.6️⃣, ⚪️➡️ `typing` 🕹:
- 🐍 3️⃣.1️⃣0️⃣, 🎛 ⚙️ 💊 `Union` & `Optional`, 👆 💪 ⚙️ ⏸ ⏸ (`|`) 📣 🇪🇺 🆎.
+* `Union`
+* `Optional` (🎏 ⏮️ 🐍 3️⃣.6️⃣)
+* ...& 🎏.
+
+🐍 3️⃣.1️⃣0️⃣, 🎛 ⚙️ 💊 `Union` & `Optional`, 👆 💪 ⚙️ ⏸ ⏸ (`|`) 📣 🇪🇺 🆎.
+
+////
### 🎓 🆎
@@ -409,13 +446,13 @@ say_hi(name=None) # This works, None is valid 🎉
➡️ 💬 👆 ✔️ 🎓 `Person`, ⏮️ 📛:
```Python hl_lines="1-3"
-{!../../../docs_src/python_types/tutorial010.py!}
+{!../../docs_src/python_types/tutorial010.py!}
```
⤴️ 👆 💪 📣 🔢 🆎 `Person`:
```Python hl_lines="6"
-{!../../../docs_src/python_types/tutorial010.py!}
+{!../../docs_src/python_types/tutorial010.py!}
```
& ⤴️, 🔄, 👆 🤚 🌐 👨🎨 🐕🦺:
@@ -436,33 +473,45 @@ say_hi(name=None) # This works, None is valid 🎉
🖼 ⚪️➡️ 🛂 Pydantic 🩺:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python
- {!> ../../../docs_src/python_types/tutorial011.py!}
- ```
+```Python
+{!> ../../docs_src/python_types/tutorial011.py!}
+```
+
+////
+
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
+
+```Python
+{!> ../../docs_src/python_types/tutorial011_py39.py!}
+```
+
+////
-=== "🐍 3️⃣.9️⃣ & 🔛"
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
- ```Python
- {!> ../../../docs_src/python_types/tutorial011_py39.py!}
- ```
+```Python
+{!> ../../docs_src/python_types/tutorial011_py310.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python
- {!> ../../../docs_src/python_types/tutorial011_py310.py!}
- ```
+/// info
-!!! info
- 💡 🌖 🔃 Pydantic, ✅ 🚮 🩺.
+💡 🌖 🔃 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..aed60c754 100644
--- a/docs/em/docs/tutorial/background-tasks.md
+++ b/docs/em/docs/tutorial/background-tasks.md
@@ -15,9 +15,7 @@
🥇, 🗄 `BackgroundTasks` & 🔬 🔢 👆 *➡ 🛠️ 🔢* ⏮️ 🆎 📄 `BackgroundTasks`:
-```Python hl_lines="1 13"
-{!../../../docs_src/background_tasks/tutorial001.py!}
-```
+{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *}
**FastAPI** 🔜 ✍ 🎚 🆎 `BackgroundTasks` 👆 & 🚶♀️ ⚫️ 👈 🔢.
@@ -33,17 +31,13 @@
& ✍ 🛠️ 🚫 ⚙️ `async` & `await`, 👥 🔬 🔢 ⏮️ 😐 `def`:
-```Python hl_lines="6-9"
-{!../../../docs_src/background_tasks/tutorial001.py!}
-```
+{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *}
## 🚮 🖥 📋
🔘 👆 *➡ 🛠️ 🔢*, 🚶♀️ 👆 📋 🔢 *🖥 📋* 🎚 ⏮️ 👩🔬 `.add_task()`:
-```Python hl_lines="14"
-{!../../../docs_src/background_tasks/tutorial001.py!}
-```
+{* ../../docs_src/background_tasks/tutorial001.py hl[14] *}
`.add_task()` 📨 ❌:
@@ -57,17 +51,7 @@
**FastAPI** 💭 ⚫️❔ 🔠 💼 & ❔ 🏤-⚙️ 🎏 🎚, 👈 🌐 🖥 📋 🔗 👯♂️ & 🏃 🖥 ⏮️:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```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!}
- ```
+{* ../../docs_src/background_tasks/tutorial002.py hl[13,15,22,25] *}
👉 🖼, 📧 🔜 ✍ `log.txt` 📁 *⏮️* 📨 📨.
@@ -93,8 +77,6 @@
👫 😑 🚚 🌖 🏗 📳, 📧/👨🏭 📤 👨💼, 💖 ✳ ⚖️ ✳, ✋️ 👫 ✔ 👆 🏃 🖥 📋 💗 🛠️, & ✴️, 💗 💽.
-👀 🖼, ✅ [🏗 🚂](../project-generation.md){.internal-link target=_blank}, 👫 🌐 🔌 🥒 ⏪ 📶.
-
✋️ 🚥 👆 💪 🔐 🔢 & 🎚 ⚪️➡️ 🎏 **FastAPI** 📱, ⚖️ 👆 💪 🎭 🤪 🖥 📋 (💖 📨 📧 📨), 👆 💪 🎯 ⚙️ `BackgroundTasks`.
## 🌃
diff --git a/docs/em/docs/tutorial/bigger-applications.md b/docs/em/docs/tutorial/bigger-applications.md
index fc9076aa8..78a321ae6 100644
--- a/docs/em/docs/tutorial/bigger-applications.md
+++ b/docs/em/docs/tutorial/bigger-applications.md
@@ -4,8 +4,11 @@
**FastAPI** 🚚 🏪 🧰 📊 👆 🈸 ⏪ 🚧 🌐 💪.
-!!! info
- 🚥 👆 👟 ⚪️➡️ 🏺, 👉 🔜 🌓 🏺 📗.
+/// info
+
+🚥 👆 👟 ⚪️➡️ 🏺, 👉 🔜 🌓 🏺 📗.
+
+///
## 🖼 📁 📊
@@ -26,16 +29,19 @@
│ └── admin.py
```
-!!! tip
- 📤 📚 `__init__.py` 📁: 1️⃣ 🔠 📁 ⚖️ 📁.
+/// tip
+
+📤 📚 `__init__.py` 📁: 1️⃣ 🔠 📁 ⚖️ 📁.
- 👉 ⚫️❔ ✔ 🏭 📟 ⚪️➡️ 1️⃣ 📁 🔘 ➕1️⃣.
+👉 ⚫️❔ ✔ 🏭 📟 ⚪️➡️ 1️⃣ 📁 🔘 ➕1️⃣.
- 🖼, `app/main.py` 👆 💪 ✔️ ⏸ 💖:
+🖼, `app/main.py` 👆 💪 ✔️ ⏸ 💖:
+
+```
+from app.routers import items
+```
- ```
- from app.routers import items
- ```
+///
* `app` 📁 🔌 🌐. & ⚫️ ✔️ 🛁 📁 `app/__init__.py`, ⚫️ "🐍 📦" (🗃 "🐍 🕹"): `app`.
* ⚫️ 🔌 `app/main.py` 📁. ⚫️ 🔘 🐍 📦 (📁 ⏮️ 📁 `__init__.py`), ⚫️ "🕹" 👈 📦: `app.main`.
@@ -46,7 +52,7 @@
* 📤 📁 `app/internal/` ⏮️ ➕1️⃣ 📁 `__init__.py`, ⚫️ ➕1️⃣ "🐍 📦": `app.internal`.
* & 📁 `app/internal/admin.py` ➕1️⃣ 🔁: `app.internal.admin`.
-
+
🎏 📁 📊 ⏮️ 🏤:
@@ -80,7 +86,7 @@
👆 🗄 ⚫️ & ✍ "👐" 🎏 🌌 👆 🔜 ⏮️ 🎓 `FastAPI`:
```Python hl_lines="1 3" title="app/routers/users.py"
-{!../../../docs_src/bigger_applications/app/routers/users.py!}
+{!../../docs_src/bigger_applications/app/routers/users.py!}
```
### *➡ 🛠️* ⏮️ `APIRouter`
@@ -90,7 +96,7 @@
⚙️ ⚫️ 🎏 🌌 👆 🔜 ⚙️ `FastAPI` 🎓:
```Python hl_lines="6 11 16" title="app/routers/users.py"
-{!../../../docs_src/bigger_applications/app/routers/users.py!}
+{!../../docs_src/bigger_applications/app/routers/users.py!}
```
👆 💪 💭 `APIRouter` "🐩 `FastAPI`" 🎓.
@@ -99,8 +105,11 @@
🌐 🎏 `parameters`, `responses`, `dependencies`, `tags`, ♒️.
-!!! tip
- 👉 🖼, 🔢 🤙 `router`, ✋️ 👆 💪 📛 ⚫️ 👐 👆 💚.
+/// tip
+
+👉 🖼, 🔢 🤙 `router`, ✋️ 👆 💪 📛 ⚫️ 👐 👆 💚.
+
+///
👥 🔜 🔌 👉 `APIRouter` 👑 `FastAPI` 📱, ✋️ 🥇, ➡️ ✅ 🔗 & ➕1️⃣ `APIRouter`.
@@ -113,13 +122,16 @@
👥 🔜 🔜 ⚙️ 🙅 🔗 ✍ 🛃 `X-Token` 🎚:
```Python hl_lines="1 4-6" title="app/dependencies.py"
-{!../../../docs_src/bigger_applications/app/dependencies.py!}
+{!../../docs_src/bigger_applications/app/dependencies.py!}
```
-!!! tip
- 👥 ⚙️ 💭 🎚 📉 👉 🖼.
+/// tip
+
+👥 ⚙️ 💭 🎚 📉 👉 🖼.
+
+✋️ 🎰 💼 👆 🔜 🤚 👍 🏁 ⚙️ 🛠️ [💂♂ 🚙](security/index.md){.internal-link target=_blank}.
- ✋️ 🎰 💼 👆 🔜 🤚 👍 🏁 ⚙️ 🛠️ [💂♂ 🚙](security/index.md){.internal-link target=_blank}.
+///
## ➕1️⃣ 🕹 ⏮️ `APIRouter`
@@ -144,7 +156,7 @@
, ↩️ ❎ 🌐 👈 🔠 *➡ 🛠️*, 👥 💪 🚮 ⚫️ `APIRouter`.
```Python hl_lines="5-10 16 21" title="app/routers/items.py"
-{!../../../docs_src/bigger_applications/app/routers/items.py!}
+{!../../docs_src/bigger_applications/app/routers/items.py!}
```
➡ 🔠 *➡ 🛠️* ✔️ ▶️ ⏮️ `/`, 💖:
@@ -163,8 +175,11 @@ async def read_item(item_id: str):
& 👥 💪 🚮 📇 `dependencies` 👈 🔜 🚮 🌐 *➡ 🛠️* 📻 & 🔜 🛠️/❎ 🔠 📨 ⚒ 👫.
-!!! tip
- 🗒 👈, 🌅 💖 [🔗 *➡ 🛠️ 👨🎨*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, 🙅♂ 💲 🔜 🚶♀️ 👆 *➡ 🛠️ 🔢*.
+/// tip
+
+🗒 👈, 🌅 💖 [🔗 *➡ 🛠️ 👨🎨*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, 🙅♂ 💲 🔜 🚶♀️ 👆 *➡ 🛠️ 🔢*.
+
+///
🔚 🏁 👈 🏬 ➡ 🔜:
@@ -181,11 +196,17 @@ async def read_item(item_id: str):
* 📻 🔗 🛠️ 🥇, ⤴️ [`dependencies` 👨🎨](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, & ⤴️ 😐 🔢 🔗.
* 👆 💪 🚮 [`Security` 🔗 ⏮️ `scopes`](../advanced/security/oauth2-scopes.md){.internal-link target=_blank}.
-!!! tip
- ✔️ `dependencies` `APIRouter` 💪 ⚙️, 🖼, 🚚 🤝 🎂 👪 *➡ 🛠️*. 🚥 🔗 🚫 🚮 📦 🔠 1️⃣ 👫.
+/// tip
+
+✔️ `dependencies` `APIRouter` 💪 ⚙️, 🖼, 🚚 🤝 🎂 👪 *➡ 🛠️*. 🚥 🔗 🚫 🚮 📦 🔠 1️⃣ 👫.
+
+///
+
+/// check
-!!! check
- `prefix`, `tags`, `responses`, & `dependencies` 🔢 (📚 🎏 💼) ⚒ ⚪️➡️ **FastAPI** ℹ 👆 ❎ 📟 ❎.
+`prefix`, `tags`, `responses`, & `dependencies` 🔢 (📚 🎏 💼) ⚒ ⚪️➡️ **FastAPI** ℹ 👆 ❎ 📟 ❎.
+
+///
### 🗄 🔗
@@ -196,13 +217,16 @@ async def read_item(item_id: str):
👥 ⚙️ ⚖ 🗄 ⏮️ `..` 🔗:
```Python hl_lines="3" title="app/routers/items.py"
-{!../../../docs_src/bigger_applications/app/routers/items.py!}
+{!../../docs_src/bigger_applications/app/routers/items.py!}
```
#### ❔ ⚖ 🗄 👷
-!!! tip
- 🚥 👆 💭 👌 ❔ 🗄 👷, 😣 ⏭ 📄 🔛.
+/// tip
+
+🚥 👆 💭 👌 ❔ 🗄 👷, 😣 ⏭ 📄 🔛.
+
+///
👁 ❣ `.`, 💖:
@@ -220,7 +244,7 @@ from .dependencies import get_token_header
💭 ❔ 👆 📱/📁 📊 👀 💖:
-
+
---
@@ -266,13 +290,16 @@ that 🔜 ⛓:
✋️ 👥 💪 🚮 _🌅_ `tags` 👈 🔜 ✔ 🎯 *➡ 🛠️*, & ➕ `responses` 🎯 👈 *➡ 🛠️*:
```Python hl_lines="30-31" title="app/routers/items.py"
-{!../../../docs_src/bigger_applications/app/routers/items.py!}
+{!../../docs_src/bigger_applications/app/routers/items.py!}
```
-!!! tip
- 👉 🏁 ➡ 🛠️ 🔜 ✔️ 🌀 🔖: `["items", "custom"]`.
+/// tip
+
+👉 🏁 ➡ 🛠️ 🔜 ✔️ 🌀 🔖: `["items", "custom"]`.
- & ⚫️ 🔜 ✔️ 👯♂️ 📨 🧾, 1️⃣ `404` & 1️⃣ `403`.
+ & ⚫️ 🔜 ✔️ 👯♂️ 📨 🧾, 1️⃣ `404` & 1️⃣ `403`.
+
+///
## 👑 `FastAPI`
@@ -291,7 +318,7 @@ that 🔜 ⛓:
& 👥 💪 📣 [🌐 🔗](dependencies/global-dependencies.md){.internal-link target=_blank} 👈 🔜 🌀 ⏮️ 🔗 🔠 `APIRouter`:
```Python hl_lines="1 3 7" title="app/main.py"
-{!../../../docs_src/bigger_applications/app/main.py!}
+{!../../docs_src/bigger_applications/app/main.py!}
```
### 🗄 `APIRouter`
@@ -299,7 +326,7 @@ that 🔜 ⛓:
🔜 👥 🗄 🎏 🔁 👈 ✔️ `APIRouter`Ⓜ:
```Python hl_lines="5" title="app/main.py"
-{!../../../docs_src/bigger_applications/app/main.py!}
+{!../../docs_src/bigger_applications/app/main.py!}
```
📁 `app/routers/users.py` & `app/routers/items.py` 🔁 👈 🍕 🎏 🐍 📦 `app`, 👥 💪 ⚙️ 👁 ❣ `.` 🗄 👫 ⚙️ "⚖ 🗄".
@@ -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
- ```
+💡 🌅 🔃 🐍 📦 & 🕹, ✍ 🛂 🐍 🧾 🔃 🕹.
- 💡 🌅 🔃 🐍 📦 & 🕹, ✍ 🛂 🐍 🧾 🔃 🕹.
+///
### ❎ 📛 💥
@@ -361,7 +391,7 @@ from .routers.users import router
, 💪 ⚙️ 👯♂️ 👫 🎏 📁, 👥 🗄 🔁 🔗:
```Python hl_lines="5" title="app/main.py"
-{!../../../docs_src/bigger_applications/app/main.py!}
+{!../../docs_src/bigger_applications/app/main.py!}
```
### 🔌 `APIRouter`Ⓜ `users` & `items`
@@ -369,29 +399,38 @@ from .routers.users import router
🔜, ➡️ 🔌 `router`Ⓜ ⚪️➡️ 🔁 `users` & `items`:
```Python hl_lines="10-11" title="app/main.py"
-{!../../../docs_src/bigger_applications/app/main.py!}
+{!../../docs_src/bigger_applications/app/main.py!}
```
-!!! info
- `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`
@@ -402,7 +441,7 @@ from .routers.users import router
👉 🖼 ⚫️ 🔜 💎 🙅. ✋️ ➡️ 💬 👈 ↩️ ⚫️ 💰 ⏮️ 🎏 🏗 🏢, 👥 🚫🔜 🔀 ⚫️ & 🚮 `prefix`, `dependencies`, `tags`, ♒️. 🔗 `APIRouter`:
```Python hl_lines="3" title="app/internal/admin.py"
-{!../../../docs_src/bigger_applications/app/internal/admin.py!}
+{!../../docs_src/bigger_applications/app/internal/admin.py!}
```
✋️ 👥 💚 ⚒ 🛃 `prefix` 🕐❔ ✅ `APIRouter` 👈 🌐 🚮 *➡ 🛠️* ▶️ ⏮️ `/admin`, 👥 💚 🔐 ⚫️ ⏮️ `dependencies` 👥 ⏪ ✔️ 👉 🏗, & 👥 💚 🔌 `tags` & `responses`.
@@ -410,7 +449,7 @@ from .routers.users import router
👥 💪 📣 🌐 👈 🍵 ✔️ 🔀 ⏮️ `APIRouter` 🚶♀️ 👈 🔢 `app.include_router()`:
```Python hl_lines="14-17" title="app/main.py"
-{!../../../docs_src/bigger_applications/app/main.py!}
+{!../../docs_src/bigger_applications/app/main.py!}
```
👈 🌌, ⏮️ `APIRouter` 🔜 🚧 ⚗, 👥 💪 💰 👈 🎏 `app/internal/admin.py` 📁 ⏮️ 🎏 🏗 🏢.
@@ -433,21 +472,24 @@ from .routers.users import router
📥 👥 ⚫️... 🎦 👈 👥 💪 🤷:
```Python hl_lines="21-23" title="app/main.py"
-{!../../../docs_src/bigger_applications/app/main.py!}
+{!../../docs_src/bigger_applications/app/main.py!}
```
& ⚫️ 🔜 👷 ☑, 👯♂️ ⏮️ 🌐 🎏 *➡ 🛠️* 🚮 ⏮️ `app.include_router()`.
-!!! info "📶 📡 ℹ"
- **🗒**: 👉 📶 📡 ℹ 👈 👆 🎲 💪 **🚶**.
+/// info | 📶 📡 ℹ
+
+**🗒**: 👉 📶 📡 ℹ 👈 👆 🎲 💪 **🚶**.
+
+---
- ---
+ `APIRouter`Ⓜ 🚫 "🗻", 👫 🚫 👽 ⚪️➡️ 🎂 🈸.
- `APIRouter`Ⓜ 🚫 "🗻", 👫 🚫 👽 ⚪️➡️ 🎂 🈸.
+👉 ↩️ 👥 💚 🔌 👫 *➡ 🛠️* 🗄 🔗 & 👩💻 🔢.
- 👉 ↩️ 👥 💚 🔌 👫 *➡ 🛠️* 🗄 🔗 & 👩💻 🔢.
+👥 🚫🔜 ❎ 👫 & "🗻" 👫 ➡ 🎂, *➡ 🛠️* "🖖" (🏤-✍), 🚫 🔌 🔗.
- 👥 🚫🔜 ❎ 👫 & "🗻" 👫 ➡ 🎂, *➡ 🛠️* "🖖" (🏤-✍), 🚫 🔌 🔗.
+///
## ✅ 🏧 🛠️ 🩺
diff --git a/docs/em/docs/tutorial/body-fields.md b/docs/em/docs/tutorial/body-fields.md
index 9f2c914f4..f202284b5 100644
--- a/docs/em/docs/tutorial/body-fields.md
+++ b/docs/em/docs/tutorial/body-fields.md
@@ -6,50 +6,39 @@
🥇, 👆 ✔️ 🗄 ⚫️:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+{* ../../docs_src/body_fields/tutorial001.py hl[4] *}
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001.py!}
- ```
+/// warning
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+👀 👈 `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️⃣ & 🔛"
+{* ../../docs_src/body_fields/tutorial001.py hl[11:14] *}
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001.py!}
- ```
+`Field` 👷 🎏 🌌 `Query`, `Path` & `Body`, ⚫️ ✔️ 🌐 🎏 🔢, ♒️.
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+/// note | 📡 ℹ
- ```Python hl_lines="9-12"
- {!> ../../../docs_src/body_fields/tutorial001_py310.py!}
- ```
+🤙, `Query`, `Path` & 🎏 👆 🔜 👀 ⏭ ✍ 🎚 🏿 ⚠ `Param` 🎓, ❔ ⚫️ 🏿 Pydantic `FieldInfo` 🎓.
-`Field` 👷 🎏 🌌 `Query`, `Path` & `Body`, ⚫️ ✔️ 🌐 🎏 🔢, ♒️.
+ & Pydantic `Field` 📨 👐 `FieldInfo` 👍.
-!!! note "📡 ℹ"
- 🤙, `Query`, `Path` & 🎏 👆 🔜 👀 ⏭ ✍ 🎚 🏿 ⚠ `Param` 🎓, ❔ ⚫️ 🏿 Pydantic `FieldInfo` 🎓.
+`Body` 📨 🎚 🏿 `FieldInfo` 🔗. & 📤 🎏 👆 🔜 👀 ⏪ 👈 🏿 `Body` 🎓.
- & Pydantic `Field` 📨 👐 `FieldInfo` 👍.
+💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓.
- `Body` 📨 🎚 🏿 `FieldInfo` 🔗. & 📤 🎏 👆 🔜 👀 ⏪ 👈 🏿 `Body` 🎓.
+///
- 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓.
+/// tip
-!!! tip
- 👀 ❔ 🔠 🏷 🔢 ⏮️ 🆎, 🔢 💲 & `Field` ✔️ 🎏 📊 *➡ 🛠️ 🔢* 🔢, ⏮️ `Field` ↩️ `Path`, `Query` & `Body`.
+👀 ❔ 🔠 🏷 🔢 ⏮️ 🆎, 🔢 💲 & `Field` ✔️ 🎏 📊 *➡ 🛠️ 🔢* 🔢, ⏮️ `Field` ↩️ `Path`, `Query` & `Body`.
+
+///
## 🚮 ➕ ℹ
@@ -57,9 +46,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..3a2f2bd54 100644
--- a/docs/em/docs/tutorial/body-multiple-params.md
+++ b/docs/em/docs/tutorial/body-multiple-params.md
@@ -8,20 +8,13 @@
& 👆 💪 📣 💪 🔢 📦, ⚒ 🔢 `None`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+{* ../../docs_src/body_multiple_params/tutorial001.py hl[19:21] *}
- ```Python hl_lines="19-21"
- {!> ../../../docs_src/body_multiple_params/tutorial001.py!}
- ```
+/// note
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+👀 👈, 👉 💼, `item` 👈 🔜 ✊ ⚪️➡️ 💪 📦. ⚫️ ✔️ `None` 🔢 💲.
- ```Python hl_lines="17-19"
- {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!}
- ```
-
-!!! note
- 👀 👈, 👉 💼, `item` 👈 🔜 ✊ ⚪️➡️ 💪 📦. ⚫️ ✔️ `None` 🔢 💲.
+///
## 💗 💪 🔢
@@ -38,17 +31,7 @@
✋️ 👆 💪 📣 💗 💪 🔢, ✅ `item` & `user`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```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!}
- ```
+{* ../../docs_src/body_multiple_params/tutorial002.py hl[22] *}
👉 💼, **FastAPI** 🔜 👀 👈 📤 🌅 🌘 1️⃣ 💪 🔢 🔢 (2️⃣ 🔢 👈 Pydantic 🏷).
@@ -69,9 +52,11 @@
}
```
-!!! note
- 👀 👈 ✋️ `item` 📣 🎏 🌌 ⏭, ⚫️ 🔜 ⌛ 🔘 💪 ⏮️ 🔑 `item`.
+/// note
+
+👀 👈 ✋️ `item` 📣 🎏 🌌 ⏭, ⚫️ 🔜 ⌛ 🔘 💪 ⏮️ 🔑 `item`.
+///
**FastAPI** 🔜 🏧 🛠️ ⚪️➡️ 📨, 👈 🔢 `item` 📨 ⚫️ 🎯 🎚 & 🎏 `user`.
@@ -87,17 +72,7 @@
✋️ 👆 💪 💡 **FastAPI** 😥 ⚫️ ➕1️⃣ 💪 🔑 ⚙️ `Body`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```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!}
- ```
+{* ../../docs_src/body_multiple_params/tutorial003.py hl[22] *}
👉 💼, **FastAPI** 🔜 ⌛ 💪 💖:
@@ -137,20 +112,13 @@ q: str | None = None
🖼:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004.py!}
- ```
+{* ../../docs_src/body_multiple_params/tutorial004.py hl[27] *}
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+/// info
- ```Python hl_lines="26"
- {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!}
- ```
+`Body` ✔️ 🌐 🎏 ➕ 🔬 & 🗃 🔢 `Query`,`Path` & 🎏 👆 🔜 👀 ⏪.
-!!! info
- `Body` ✔️ 🌐 🎏 ➕ 🔬 & 🗃 🔢 `Query`,`Path` & 🎏 👆 🔜 👀 ⏪.
+///
## ⏯ 👁 💪 🔢
@@ -166,17 +134,7 @@ item: Item = Body(embed=True)
:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```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!}
- ```
+{* ../../docs_src/body_multiple_params/tutorial005.py hl[17] *}
👉 💼 **FastAPI** 🔜 ⌛ 💪 💖:
diff --git a/docs/em/docs/tutorial/body-nested-models.md b/docs/em/docs/tutorial/body-nested-models.md
index c941fa08a..6c8d5a610 100644
--- a/docs/em/docs/tutorial/body-nested-models.md
+++ b/docs/em/docs/tutorial/body-nested-models.md
@@ -6,17 +6,7 @@
👆 💪 🔬 🔢 🏾. 🖼, 🐍 `list`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```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!}
- ```
+{* ../../docs_src/body_nested_models/tutorial001.py hl[14] *}
👉 🔜 ⚒ `tags` 📇, 👐 ⚫️ 🚫 📣 🆎 🔣 📇.
@@ -30,9 +20,7 @@
✋️ 🐍 ⏬ ⏭ 3️⃣.9️⃣ (3️⃣.6️⃣ & 🔛), 👆 🥇 💪 🗄 `List` ⚪️➡️ 🐩 🐍 `typing` 🕹:
-```Python hl_lines="1"
-{!> ../../../docs_src/body_nested_models/tutorial002.py!}
-```
+{* ../../docs_src/body_nested_models/tutorial002.py hl[1] *}
### 📣 `list` ⏮️ 🆎 🔢
@@ -61,23 +49,7 @@ my_list: List[str]
, 👆 🖼, 👥 💪 ⚒ `tags` 🎯 "📇 🎻":
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```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!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="12"
- {!> ../../../docs_src/body_nested_models/tutorial002_py310.py!}
- ```
+{* ../../docs_src/body_nested_models/tutorial002.py hl[14] *}
## ⚒ 🆎
@@ -87,23 +59,7 @@ my_list: List[str]
⤴️ 👥 💪 📣 `tags` ⚒ 🎻:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```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!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="12"
- {!> ../../../docs_src/body_nested_models/tutorial003_py310.py!}
- ```
+{* ../../docs_src/body_nested_models/tutorial003.py hl[1,14] *}
⏮️ 👉, 🚥 👆 📨 📨 ⏮️ ❎ 📊, ⚫️ 🔜 🗜 ⚒ 😍 🏬.
@@ -125,45 +81,13 @@ my_list: List[str]
🖼, 👥 💪 🔬 `Image` 🏷:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```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!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="7-9"
- {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!}
- ```
+{* ../../docs_src/body_nested_models/tutorial004.py hl[9:11] *}
### ⚙️ 📊 🆎
& ⤴️ 👥 💪 ⚙️ ⚫️ 🆎 🔢:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```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!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="18"
- {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!}
- ```
+{* ../../docs_src/body_nested_models/tutorial004.py hl[20] *}
👉 🔜 ⛓ 👈 **FastAPI** 🔜 ⌛ 💪 🎏:
@@ -196,23 +120,7 @@ my_list: List[str]
🖼, `Image` 🏷 👥 ✔️ `url` 🏑, 👥 💪 📣 ⚫️ ↩️ `str`, Pydantic `HttpUrl`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```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!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="2 8"
- {!> ../../../docs_src/body_nested_models/tutorial005_py310.py!}
- ```
+{* ../../docs_src/body_nested_models/tutorial005.py hl[4,10] *}
🎻 🔜 ✅ ☑ 📛, & 📄 🎻 🔗 / 🗄 ✅.
@@ -220,23 +128,7 @@ my_list: List[str]
👆 💪 ⚙️ Pydantic 🏷 🏾 `list`, `set`, ♒️:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```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!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="18"
- {!> ../../../docs_src/body_nested_models/tutorial006_py310.py!}
- ```
+{* ../../docs_src/body_nested_models/tutorial006.py hl[20] *}
👉 🔜 ⌛ (🗜, ✔, 📄, ♒️) 🎻 💪 💖:
@@ -264,33 +156,23 @@ my_list: List[str]
}
```
-!!! info
- 👀 ❔ `images` 🔑 🔜 ✔️ 📇 🖼 🎚.
+/// info
-## 🙇 🐦 🏷
+👀 ❔ `images` 🔑 🔜 ✔️ 📇 🖼 🎚.
-👆 💪 🔬 🎲 🙇 🐦 🏷:
+///
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```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!}
- ```
+{* ../../docs_src/body_nested_models/tutorial007.py hl[9,14,20,23,27] *}
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+/// info
- ```Python hl_lines="7 12 18 21 25"
- {!> ../../../docs_src/body_nested_models/tutorial007_py310.py!}
- ```
+👀 ❔ `Offer` ✔️ 📇 `Item`Ⓜ, ❔ 🔄 ✔️ 📦 📇 `Image`Ⓜ
-!!! info
- 👀 ❔ `Offer` ✔️ 📇 `Item`Ⓜ, ❔ 🔄 ✔️ 📦 📇 `Image`Ⓜ
+///
## 💪 😁 📇
@@ -308,17 +190,7 @@ images: list[Image]
:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```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!}
- ```
+{* ../../docs_src/body_nested_models/tutorial008.py hl[15] *}
## 👨🎨 🐕🦺 🌐
@@ -348,26 +220,19 @@ images: list[Image]
👉 💼, 👆 🔜 🚫 🙆 `dict` 📏 ⚫️ ✔️ `int` 🔑 ⏮️ `float` 💲:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/body_nested_models/tutorial009.py!}
- ```
+{* ../../docs_src/body_nested_models/tutorial009.py hl[9] *}
-=== "🐍 3️⃣.9️⃣ & 🔛"
+/// tip
- ```Python hl_lines="7"
- {!> ../../../docs_src/body_nested_models/tutorial009_py39.py!}
- ```
+✔️ 🤯 👈 🎻 🕴 🐕🦺 `str` 🔑.
-!!! tip
- ✔️ 🤯 👈 🎻 🕴 🐕🦺 `str` 🔑.
+✋️ Pydantic ✔️ 🏧 💽 🛠️.
- ✋️ Pydantic ✔️ 🏧 💽 🛠️.
+👉 ⛓ 👈, ✋️ 👆 🛠️ 👩💻 💪 🕴 📨 🎻 🔑, 📏 👈 🎻 🔌 😁 🔢, Pydantic 🔜 🗜 👫 & ✔ 👫.
- 👉 ⛓ 👈, ✋️ 👆 🛠️ 👩💻 💪 🕴 📨 🎻 🔑, 📏 👈 🎻 🔌 😁 🔢, Pydantic 🔜 🗜 👫 & ✔ 👫.
+ & `dict` 👆 📨 `weights` 🔜 🤙 ✔️ `int` 🔑 & `float` 💲.
- & `dict` 👆 📨 `weights` 🔜 🤙 ✔️ `int` 🔑 & `float` 💲.
+///
## 🌃
diff --git a/docs/em/docs/tutorial/body-updates.md b/docs/em/docs/tutorial/body-updates.md
index 89bb615f6..7e2fbfaf7 100644
--- a/docs/em/docs/tutorial/body-updates.md
+++ b/docs/em/docs/tutorial/body-updates.md
@@ -6,23 +6,7 @@
👆 💪 ⚙️ `jsonable_encoder` 🗜 🔢 💽 📊 👈 💪 🏪 🎻 (✅ ⏮️ ☁ 💽). 🖼, 🏭 `datetime` `str`.
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```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!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="28-33"
- {!> ../../../docs_src/body_updates/tutorial001_py310.py!}
- ```
+{* ../../docs_src/body_updates/tutorial001.py hl[30:35] *}
`PUT` ⚙️ 📨 💽 👈 🔜 ❎ ♻ 💽.
@@ -48,14 +32,17 @@
👉 ⛓ 👈 👆 💪 📨 🕴 💽 👈 👆 💚 ℹ, 🍂 🎂 🐣.
-!!! note
- `PATCH` 🌘 🛎 ⚙️ & 💭 🌘 `PUT`.
+/// note
- & 📚 🏉 ⚙️ 🕴 `PUT`, 🍕 ℹ.
+`PATCH` 🌘 🛎 ⚙️ & 💭 🌘 `PUT`.
- 👆 **🆓** ⚙️ 👫 👐 👆 💚, **FastAPI** 🚫 🚫 🙆 🚫.
+ & 📚 🏉 ⚙️ 🕴 `PUT`, 🍕 ℹ.
- ✋️ 👉 🦮 🎦 👆, 🌖 ⚖️ 🌘, ❔ 👫 🎯 ⚙️.
+👆 **🆓** ⚙️ 👫 👐 👆 💚, **FastAPI** 🚫 🚫 🙆 🚫.
+
+✋️ 👉 🦮 🎦 👆, 🌖 ⚖️ 🌘, ❔ 👫 🎯 ⚙️.
+
+///
### ⚙️ Pydantic `exclude_unset` 🔢
@@ -67,23 +54,7 @@
⤴️ 👆 💪 ⚙️ 👉 🏗 `dict` ⏮️ 🕴 💽 👈 ⚒ (📨 📨), 🚫 🔢 💲:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="34"
- {!> ../../../docs_src/body_updates/tutorial002.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- ```Python hl_lines="34"
- {!> ../../../docs_src/body_updates/tutorial002_py39.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="32"
- {!> ../../../docs_src/body_updates/tutorial002_py310.py!}
- ```
+{* ../../docs_src/body_updates/tutorial002.py hl[34] *}
### ⚙️ Pydantic `update` 🔢
@@ -91,23 +62,7 @@
💖 `stored_item_model.copy(update=update_data)`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="35"
- {!> ../../../docs_src/body_updates/tutorial002.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- ```Python hl_lines="35"
- {!> ../../../docs_src/body_updates/tutorial002_py39.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="33"
- {!> ../../../docs_src/body_updates/tutorial002_py310.py!}
- ```
+{* ../../docs_src/body_updates/tutorial002.py hl[35] *}
### 🍕 ℹ 🌃
@@ -124,32 +79,22 @@
* 🖊 💽 👆 💽.
* 📨 ℹ 🏷.
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="30-37"
- {!> ../../../docs_src/body_updates/tutorial002.py!}
- ```
+{* ../../docs_src/body_updates/tutorial002.py hl[30:37] *}
-=== "🐍 3️⃣.9️⃣ & 🔛"
+/// tip
- ```Python hl_lines="30-37"
- {!> ../../../docs_src/body_updates/tutorial002_py39.py!}
- ```
+👆 💪 🤙 ⚙️ 👉 🎏 ⚒ ⏮️ 🇺🇸🔍 `PUT` 🛠️.
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+✋️ 🖼 📥 ⚙️ `PATCH` ↩️ ⚫️ ✍ 👫 ⚙️ 💼.
- ```Python hl_lines="28-35"
- {!> ../../../docs_src/body_updates/tutorial002_py310.py!}
- ```
+///
-!!! tip
- 👆 💪 🤙 ⚙️ 👉 🎏 ⚒ ⏮️ 🇺🇸🔍 `PUT` 🛠️.
+/// note
- ✋️ 🖼 📥 ⚙️ `PATCH` ↩️ ⚫️ ✍ 👫 ⚙️ 💼.
+👀 👈 🔢 🏷 ✔.
-!!! note
- 👀 👈 🔢 🏷 ✔.
+, 🚥 👆 💚 📨 🍕 ℹ 👈 💪 🚫 🌐 🔢, 👆 💪 ✔️ 🏷 ⏮️ 🌐 🔢 ™ 📦 (⏮️ 🔢 💲 ⚖️ `None`).
- , 🚥 👆 💚 📨 🍕 ℹ 👈 💪 🚫 🌐 🔢, 👆 💪 ✔️ 🏷 ⏮️ 🌐 🔢 ™ 📦 (⏮️ 🔢 💲 ⚖️ `None`).
+🔬 ⚪️➡️ 🏷 ⏮️ 🌐 📦 💲 **ℹ** & 🏷 ⏮️ ✔ 💲 **🏗**, 👆 💪 ⚙️ 💭 🔬 [➕ 🏷](extra-models.md){.internal-link target=_blank}.
- 🔬 ⚪️➡️ 🏷 ⏮️ 🌐 📦 💲 **ℹ** & 🏷 ⏮️ ✔ 💲 **🏗**, 👆 💪 ⚙️ 💭 🔬 [➕ 🏷](extra-models.md){.internal-link target=_blank}.
+///
diff --git a/docs/em/docs/tutorial/body.md b/docs/em/docs/tutorial/body.md
index 12f5a6315..09e1d7cca 100644
--- a/docs/em/docs/tutorial/body.md
+++ b/docs/em/docs/tutorial/body.md
@@ -8,28 +8,21 @@
📣 **📨** 💪, 👆 ⚙️ Pydantic 🏷 ⏮️ 🌐 👫 🏋️ & 💰.
-!!! info
- 📨 💽, 👆 🔜 ⚙️ 1️⃣: `POST` (🌅 ⚠), `PUT`, `DELETE` ⚖️ `PATCH`.
+/// info
- 📨 💪 ⏮️ `GET` 📨 ✔️ ⚠ 🎭 🔧, 👐, ⚫️ 🐕🦺 FastAPI, 🕴 📶 🏗/😕 ⚙️ 💼.
+📨 💽, 👆 🔜 ⚙️ 1️⃣: `POST` (🌅 ⚠), `PUT`, `DELETE` ⚖️ `PATCH`.
- ⚫️ 🚫, 🎓 🩺 ⏮️ 🦁 🎚 🏆 🚫 🎦 🧾 💪 🕐❔ ⚙️ `GET`, & 🗳 🖕 💪 🚫 🐕🦺 ⚫️.
+📨 💪 ⏮️ `GET` 📨 ✔️ ⚠ 🎭 🔧, 👐, ⚫️ 🐕🦺 FastAPI, 🕴 📶 🏗/😕 ⚙️ 💼.
-## 🗄 Pydantic `BaseModel`
-
-🥇, 👆 💪 🗄 `BaseModel` ⚪️➡️ `pydantic`:
+⚫️ 🚫, 🎓 🩺 ⏮️ 🦁 🎚 🏆 🚫 🎦 🧾 💪 🕐❔ ⚙️ `GET`, & 🗳 🖕 💪 🚫 🐕🦺 ⚫️.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+///
- ```Python hl_lines="4"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
+## 🗄 Pydantic `BaseModel`
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+🥇, 👆 💪 🗄 `BaseModel` ⚪️➡️ `pydantic`:
- ```Python hl_lines="2"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
+{* ../../docs_src/body/tutorial001.py hl[4] *}
## ✍ 👆 💽 🏷
@@ -37,17 +30,7 @@
⚙️ 🐩 🐍 🆎 🌐 🔢:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="7-11"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="5-9"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
+{* ../../docs_src/body/tutorial001.py hl[7:11] *}
🎏 🕐❔ 📣 🔢 🔢, 🕐❔ 🏷 🔢 ✔️ 🔢 💲, ⚫️ 🚫 ✔. ⏪, ⚫️ ✔. ⚙️ `None` ⚒ ⚫️ 📦.
@@ -75,17 +58,7 @@
🚮 ⚫️ 👆 *➡ 🛠️*, 📣 ⚫️ 🎏 🌌 👆 📣 ➡ & 🔢 🔢:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="18"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="16"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
+{* ../../docs_src/body/tutorial001.py hl[18] *}
...& 📣 🚮 🆎 🏷 👆 ✍, `Item`.
@@ -134,32 +107,25 @@
-!!! tip
- 🚥 👆 ⚙️ 🗒 👆 👨🎨, 👆 💪 ⚙️ Pydantic 🗒 📁.
-
- ⚫️ 📉 👨🎨 🐕🦺 Pydantic 🏷, ⏮️:
+/// tip
- * 🚘-🛠️
- * 🆎 ✅
- * 🛠️
- * 🔎
- * 🔬
+🚥 👆 ⚙️ 🗒 👆 👨🎨, 👆 💪 ⚙️ Pydantic 🗒 📁.
-## ⚙️ 🏷
+⚫️ 📉 👨🎨 🐕🦺 Pydantic 🏷, ⏮️:
-🔘 🔢, 👆 💪 🔐 🌐 🔢 🏷 🎚 🔗:
+* 🚘-🛠️
+* 🆎 ✅
+* 🛠️
+* 🔎
+* 🔬
-=== "🐍 3️⃣.6️⃣ & 🔛"
+///
- ```Python hl_lines="21"
- {!> ../../../docs_src/body/tutorial002.py!}
- ```
+## ⚙️ 🏷
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+🔘 🔢, 👆 💪 🔐 🌐 🔢 🏷 🎚 🔗:
- ```Python hl_lines="19"
- {!> ../../../docs_src/body/tutorial002_py310.py!}
- ```
+{* ../../docs_src/body/tutorial002.py hl[21] *}
## 📨 💪 ➕ ➡ 🔢
@@ -167,17 +133,7 @@
**FastAPI** 🔜 🤔 👈 🔢 🔢 👈 🏏 ➡ 🔢 🔜 **✊ ⚪️➡️ ➡**, & 👈 🔢 🔢 👈 📣 Pydantic 🏷 🔜 **✊ ⚪️➡️ 📨 💪**.
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="17-18"
- {!> ../../../docs_src/body/tutorial003.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="15-16"
- {!> ../../../docs_src/body/tutorial003_py310.py!}
- ```
+{* ../../docs_src/body/tutorial003.py hl[17:18] *}
## 📨 💪 ➕ ➡ ➕ 🔢 🔢
@@ -185,17 +141,7 @@
**FastAPI** 🔜 🤔 🔠 👫 & ✊ 📊 ⚪️➡️ ☑ 🥉.
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="18"
- {!> ../../../docs_src/body/tutorial004.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="16"
- {!> ../../../docs_src/body/tutorial004_py310.py!}
- ```
+{* ../../docs_src/body/tutorial004.py hl[18] *}
🔢 🔢 🔜 🤔 ⏩:
@@ -203,10 +149,13 @@
* 🚥 🔢 **⭐ 🆎** (💖 `int`, `float`, `str`, `bool`, ♒️) ⚫️ 🔜 🔬 **🔢** 🔢.
* 🚥 🔢 📣 🆎 **Pydantic 🏷**, ⚫️ 🔜 🔬 📨 **💪**.
-!!! note
- FastAPI 🔜 💭 👈 💲 `q` 🚫 ✔ ↩️ 🔢 💲 `= None`.
+/// note
+
+FastAPI 🔜 💭 👈 💲 `q` 🚫 ✔ ↩️ 🔢 💲 `= None`.
+
+ `Union` `Union[str, None]` 🚫 ⚙️ FastAPI, ✋️ 🔜 ✔ 👆 👨🎨 🤝 👆 👍 🐕🦺 & 🔍 ❌.
- `Union` `Union[str, None]` 🚫 ⚙️ FastAPI, ✋️ 🔜 ✔ 👆 👨🎨 🤝 👆 👍 🐕🦺 & 🔍 ❌.
+///
## 🍵 Pydantic
diff --git a/docs/em/docs/tutorial/cookie-params.md b/docs/em/docs/tutorial/cookie-params.md
index 47f4a62f5..4699fe2a5 100644
--- a/docs/em/docs/tutorial/cookie-params.md
+++ b/docs/em/docs/tutorial/cookie-params.md
@@ -6,17 +6,7 @@
🥇 🗄 `Cookie`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="1"
- {!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
- ```
+{* ../../docs_src/cookie_params/tutorial001.py hl[3] *}
## 📣 `Cookie` 🔢
@@ -24,25 +14,21 @@
🥇 💲 🔢 💲, 👆 💪 🚶♀️ 🌐 ➕ 🔬 ⚖️ ✍ 🔢:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+{* ../../docs_src/cookie_params/tutorial001.py hl[9] *}
+
+/// note | 📡 ℹ
- ```Python hl_lines="9"
- {!> ../../../docs_src/cookie_params/tutorial001.py!}
- ```
+`Cookie` "👭" 🎓 `Path` & `Query`. ⚫️ 😖 ⚪️➡️ 🎏 ⚠ `Param` 🎓.
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+✋️ 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, `Cookie` & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓.
- ```Python hl_lines="7"
- {!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
- ```
+///
-!!! note "📡 ℹ"
- `Cookie` "👭" 🎓 `Path` & `Query`. ⚫️ 😖 ⚪️➡️ 🎏 ⚠ `Param` 🎓.
+/// info
- ✋️ 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, `Cookie` & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓.
+📣 🍪, 👆 💪 ⚙️ `Cookie`, ↩️ ⏪ 🔢 🔜 🔬 🔢 🔢.
-!!! info
- 📣 🍪, 👆 💪 ⚙️ `Cookie`, ↩️ ⏪ 🔢 🔜 🔬 🔢 🔢.
+///
## 🌃
diff --git a/docs/em/docs/tutorial/cors.md b/docs/em/docs/tutorial/cors.md
index 8c5e33ed7..44ab4adc5 100644
--- a/docs/em/docs/tutorial/cors.md
+++ b/docs/em/docs/tutorial/cors.md
@@ -46,9 +46,7 @@
* 🎯 🇺🇸🔍 👩🔬 (`POST`, `PUT`) ⚖️ 🌐 👫 ⏮️ 🃏 `"*"`.
* 🎯 🇺🇸🔍 🎚 ⚖️ 🌐 👫 ⏮️ 🃏 `"*"`.
-```Python hl_lines="2 6-11 13-19"
-{!../../../docs_src/cors/tutorial001.py!}
-```
+{* ../../docs_src/cors/tutorial001.py hl[2,6:11,13:19] *}
🔢 🔢 ⚙️ `CORSMiddleware` 🛠️ 🚫 🔢, 👆 🔜 💪 🎯 🛠️ 🎯 🇨🇳, 👩🔬, ⚖️ 🎚, ✔ 🖥 ✔ ⚙️ 👫 ✖️-🆔 🔑.
@@ -78,7 +76,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..97e61a763 100644
--- a/docs/em/docs/tutorial/debugging.md
+++ b/docs/em/docs/tutorial/debugging.md
@@ -6,9 +6,7 @@
👆 FastAPI 🈸, 🗄 & 🏃 `uvicorn` 🔗:
-```Python hl_lines="1 15"
-{!../../../docs_src/debugging/tutorial001.py!}
-```
+{* ../../docs_src/debugging/tutorial001.py hl[1,15] *}
### 🔃 `__name__ == "__main__"`
@@ -74,8 +72,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..41938bc7b 100644
--- a/docs/em/docs/tutorial/dependencies/classes-as-dependencies.md
+++ b/docs/em/docs/tutorial/dependencies/classes-as-dependencies.md
@@ -6,17 +6,7 @@
⏮️ 🖼, 👥 🛬 `dict` ⚪️➡️ 👆 🔗 ("☑"):
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="7"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+{* ../../docs_src/dependencies/tutorial001.py hl[9] *}
✋️ ⤴️ 👥 🤚 `dict` 🔢 `commons` *➡ 🛠️ 🔢*.
@@ -79,45 +69,15 @@ fluffy = Cat(name="Mr Fluffy")
⤴️, 👥 💪 🔀 🔗 "☑" `common_parameters` ⚪️➡️ 🔛 🎓 `CommonQueryParams`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="11-15"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="9-13"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
+{* ../../docs_src/dependencies/tutorial002.py hl[11:15] *}
💸 🙋 `__init__` 👩🔬 ⚙️ ✍ 👐 🎓:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="12"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
+{* ../../docs_src/dependencies/tutorial002.py hl[12] *}
...⚫️ ✔️ 🎏 🔢 👆 ⏮️ `common_parameters`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="6"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+{* ../../docs_src/dependencies/tutorial001.py hl[9] *}
📚 🔢 ⚫️❔ **FastAPI** 🔜 ⚙️ "❎" 🔗.
@@ -133,17 +93,7 @@ fluffy = Cat(name="Mr Fluffy")
🔜 👆 💪 📣 👆 🔗 ⚙️ 👉 🎓.
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
+{* ../../docs_src/dependencies/tutorial002.py hl[19] *}
**FastAPI** 🤙 `CommonQueryParams` 🎓. 👉 ✍ "👐" 👈 🎓 & 👐 🔜 🚶♀️ 🔢 `commons` 👆 🔢.
@@ -183,17 +133,7 @@ commons = Depends(CommonQueryParams)
...:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial003.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial003_py310.py!}
- ```
+{* ../../docs_src/dependencies/tutorial003.py hl[19] *}
✋️ 📣 🆎 💡 👈 🌌 👆 👨🎨 🔜 💭 ⚫️❔ 🔜 🚶♀️ 🔢 `commons`, & ⤴️ ⚫️ 💪 ℹ 👆 ⏮️ 📟 🛠️, 🆎 ✅, ♒️:
@@ -227,21 +167,14 @@ commons: CommonQueryParams = Depends()
🎏 🖼 🔜 ⤴️ 👀 💖:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial004.py!}
- ```
+{* ../../docs_src/dependencies/tutorial004.py hl[19] *}
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+...& **FastAPI** 🔜 💭 ⚫️❔.
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial004_py310.py!}
- ```
+/// tip
-...& **FastAPI** 🔜 💭 ⚫️❔.
+🚥 👈 😑 🌅 😨 🌘 👍, 🤷♂ ⚫️, 👆 🚫 *💪* ⚫️.
-!!! 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..ab144a497 100644
--- a/docs/em/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
+++ b/docs/em/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
@@ -14,23 +14,27 @@
⚫️ 🔜 `list` `Depends()`:
-```Python hl_lines="17"
-{!../../../docs_src/dependencies/tutorial006.py!}
-```
+{* ../../docs_src/dependencies/tutorial006.py hl[17] *}
👉 🔗 🔜 🛠️/❎ 🎏 🌌 😐 🔗. ✋️ 👫 💲 (🚥 👫 📨 🙆) 🏆 🚫 🚶♀️ 👆 *➡ 🛠️ 🔢*.
-!!! 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}.
+
+///
## 🔗 ❌ & 📨 💲
@@ -40,17 +44,13 @@
👫 💪 📣 📨 📄 (💖 🎚) ⚖️ 🎏 🎧-🔗:
-```Python hl_lines="6 11"
-{!../../../docs_src/dependencies/tutorial006.py!}
-```
+{* ../../docs_src/dependencies/tutorial006.py hl[6,11] *}
### 🤚 ⚠
👫 🔗 💪 `raise` ⚠, 🎏 😐 🔗:
-```Python hl_lines="8 13"
-{!../../../docs_src/dependencies/tutorial006.py!}
-```
+{* ../../docs_src/dependencies/tutorial006.py hl[8,13] *}
### 📨 💲
@@ -58,9 +58,7 @@
, 👆 💪 🏤-⚙️ 😐 🔗 (👈 📨 💲) 👆 ⏪ ⚙️ 👱 🙆, & ✋️ 💲 🏆 🚫 ⚙️, 🔗 🔜 🛠️:
-```Python hl_lines="9 14"
-{!../../../docs_src/dependencies/tutorial006.py!}
-```
+{* ../../docs_src/dependencies/tutorial006.py hl[9,14] *}
## 🔗 👪 *➡ 🛠️*
diff --git a/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md
index 3ed5aeba5..1b37b1cf2 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 🐕🦺 🔗 👈 🔑 👨💼.
+/// note | 📡 ℹ
+
+👉 👷 👏 🐍 🔑 👨💼.
- **FastAPI** ⚙️ 👫 🔘 🏆 👉.
+**FastAPI** ⚙️ 👫 🔘 🏆 👉.
+
+///
## 🔗 ⏮️ `yield` & `HTTPException`
@@ -113,8 +113,11 @@ FastAPI 🐕🦺 🔗 👈 .
+
+✋️ 🚥 👆 ✔️ 🛃 🎚 👈 👆 💚 👩💻 🖥 💪 👀, 👆 💪 🚮 👫 👆 ⚜ 📳 ([⚜ (✖️-🇨🇳 ℹ 🤝)](cors.md){.internal-link target=_blank}) ⚙️ 🔢 `expose_headers` 📄 💃 ⚜ 🩺.
+
+///
-!!! tip
- ✔️ 🤯 👈 🛃 © 🎚 💪 🚮 ⚙️ '✖-' 🔡.
+/// note | 📡 ℹ
- ✋️ 🚥 👆 ✔️ 🛃 🎚 👈 👆 💚 👩💻 🖥 💪 👀, 👆 💪 🚮 👫 👆 ⚜ 📳 ([⚜ (✖️-🇨🇳 ℹ 🤝)](cors.md){.internal-link target=_blank}) ⚙️ 🔢 `expose_headers` 📄 💃 ⚜ 🩺.
+👆 💪 ⚙️ `from starlette.requests import Request`.
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette.requests import Request`.
+**FastAPI** 🚚 ⚫️ 🏪 👆, 👩💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃.
- **FastAPI** 🚚 ⚫️ 🏪 👆, 👩💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃.
+///
### ⏭ & ⏮️ `response`
@@ -50,9 +57,7 @@
🖼, 👆 💪 🚮 🛃 🎚 `X-Process-Time` ⚗ 🕰 🥈 👈 ⚫️ ✊ 🛠️ 📨 & 🏗 📨:
-```Python hl_lines="10 12-13"
-{!../../../docs_src/middleware/tutorial001.py!}
-```
+{* ../../docs_src/middleware/tutorial001.py hl[10,12:13] *}
## 🎏 🛠️
diff --git a/docs/em/docs/tutorial/path-operation-configuration.md b/docs/em/docs/tutorial/path-operation-configuration.md
index 916529258..c6030c089 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,23 @@
✋️ 🚥 👆 🚫 💭 ⚫️❔ 🔠 🔢 📟, 👆 💪 ⚙️ ⌨ 📉 `status`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="3 17"
- {!> ../../../docs_src/path_operation_configuration/tutorial001.py!}
- ```
+{* ../../docs_src/path_operation_configuration/tutorial001.py hl[3,17] *}
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- ```Python hl_lines="3 17"
- {!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+👈 👔 📟 🔜 ⚙️ 📨 & 🔜 🚮 🗄 🔗.
- ```Python hl_lines="1 15"
- {!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!}
- ```
+/// note | 📡 ℹ
-👈 👔 📟 🔜 ⚙️ 📨 & 🔜 🚮 🗄 🔗.
+👆 💪 ⚙️ `from starlette import status`.
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette import status`.
+**FastAPI** 🚚 🎏 `starlette.status` `fastapi.status` 🏪 👆, 👩💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃.
- **FastAPI** 🚚 🎏 `starlette.status` `fastapi.status` 🏪 👆, 👩💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃.
+///
## 🔖
👆 💪 🚮 🔖 👆 *➡ 🛠️*, 🚶♀️ 🔢 `tags` ⏮️ `list` `str` (🛎 1️⃣ `str`):
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```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!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="15 20 25"
- {!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!}
- ```
+{* ../../docs_src/path_operation_configuration/tutorial002.py hl[17,22,27] *}
👫 🔜 🚮 🗄 🔗 & ⚙️ 🏧 🧾 🔢:
@@ -72,31 +46,13 @@
**FastAPI** 🐕🦺 👈 🎏 🌌 ⏮️ ✅ 🎻:
-```Python hl_lines="1 8-10 13 18"
-{!../../../docs_src/path_operation_configuration/tutorial002b.py!}
-```
+{* ../../docs_src/path_operation_configuration/tutorial002b.py hl[1,8:10,13,18] *}
## 📄 & 📛
👆 💪 🚮 `summary` & `description`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```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!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!}
- ```
+{* ../../docs_src/path_operation_configuration/tutorial003.py hl[20:21] *}
## 📛 ⚪️➡️ #️⃣
@@ -104,23 +60,7 @@
👆 💪 ✍ ✍ #️⃣ , ⚫️ 🔜 🔬 & 🖥 ☑ (✊ 🔘 🏧 #️⃣ 📐).
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```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!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="17-25"
- {!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!}
- ```
+{* ../../docs_src/path_operation_configuration/tutorial004.py hl[19:27] *}
⚫️ 🔜 ⚙️ 🎓 🩺:
@@ -130,31 +70,21 @@
👆 💪 ✔ 📨 📛 ⏮️ 🔢 `response_description`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="21"
- {!> ../../../docs_src/path_operation_configuration/tutorial005.py!}
- ```
+{* ../../docs_src/path_operation_configuration/tutorial005.py hl[21] *}
-=== "🐍 3️⃣.9️⃣ & 🔛"
+/// info
- ```Python hl_lines="21"
- {!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!}
- ```
+👀 👈 `response_description` 🔗 🎯 📨, `description` 🔗 *➡ 🛠️* 🏢.
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+///
- ```Python hl_lines="19"
- {!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!}
- ```
+/// check
-!!! info
- 👀 👈 `response_description` 🔗 🎯 📨, `description` 🔗 *➡ 🛠️* 🏢.
+🗄 ✔ 👈 🔠 *➡ 🛠️* 🚚 📨 📛.
-!!! check
- 🗄 ✔ 👈 🔠 *➡ 🛠️* 🚚 📨 📛.
+, 🚥 👆 🚫 🚚 1️⃣, **FastAPI** 🔜 🔁 🏗 1️⃣ "🏆 📨".
- , 🚥 👆 🚫 🚚 1️⃣, **FastAPI** 🔜 🔁 🏗 1️⃣ "🏆 📨".
+///
@@ -162,9 +92,7 @@
🚥 👆 💪 ™ *➡ 🛠️* 😢, ✋️ 🍵 ❎ ⚫️, 🚶♀️ 🔢 `deprecated`:
-```Python hl_lines="16"
-{!../../../docs_src/path_operation_configuration/tutorial006.py!}
-```
+{* ../../docs_src/path_operation_configuration/tutorial006.py hl[16] *}
⚫️ 🔜 🎯 ™ 😢 🎓 🩺:
diff --git a/docs/em/docs/tutorial/path-params-numeric-validations.md b/docs/em/docs/tutorial/path-params-numeric-validations.md
index b1ba2670b..b45e0557b 100644
--- a/docs/em/docs/tutorial/path-params-numeric-validations.md
+++ b/docs/em/docs/tutorial/path-params-numeric-validations.md
@@ -6,17 +6,7 @@
🥇, 🗄 `Path` ⚪️➡️ `fastapi`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```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!}
- ```
+{* ../../docs_src/path_params_numeric_validations/tutorial001.py hl[3] *}
## 📣 🗃
@@ -24,24 +14,17 @@
🖼, 📣 `title` 🗃 💲 ➡ 🔢 `item_id` 👆 💪 🆎:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
- ```
+{* ../../docs_src/path_params_numeric_validations/tutorial001.py hl[10] *}
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+/// note
- ```Python hl_lines="8"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
- ```
+➡ 🔢 🕧 ✔ ⚫️ ✔️ 🍕 ➡.
-!!! note
- ➡ 🔢 🕧 ✔ ⚫️ ✔️ 🍕 ➡.
+, 👆 🔜 📣 ⚫️ ⏮️ `...` ™ ⚫️ ✔.
- , 👆 🔜 📣 ⚫️ ⏮️ `...` ™ ⚫️ ✔.
+👐, 🚥 👆 📣 ⚫️ ⏮️ `None` ⚖️ ⚒ 🔢 💲, ⚫️ 🔜 🚫 📉 🕳, ⚫️ 🔜 🕧 🚚.
- 👐, 🚥 👆 📣 ⚫️ ⏮️ `None` ⚖️ ⚒ 🔢 💲, ⚫️ 🔜 🚫 📉 🕳, ⚫️ 🔜 🕧 🚚.
+///
## ✔ 🔢 👆 💪
@@ -59,9 +42,7 @@
, 👆 💪 📣 👆 🔢:
-```Python hl_lines="7"
-{!../../../docs_src/path_params_numeric_validations/tutorial002.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial002.py hl[7] *}
## ✔ 🔢 👆 💪, 🎱
@@ -71,9 +52,7 @@
🐍 🏆 🚫 🕳 ⏮️ 👈 `*`, ✋️ ⚫️ 🔜 💭 👈 🌐 📄 🔢 🔜 🤙 🇨🇻 ❌ (🔑-💲 👫), 💭
kwargs
. 🚥 👫 🚫 ✔️ 🔢 💲.
-```Python hl_lines="7"
-{!../../../docs_src/path_params_numeric_validations/tutorial003.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *}
## 🔢 🔬: 👑 🌘 ⚖️ 🌓
@@ -81,9 +60,7 @@
📥, ⏮️ `ge=1`, `item_id` 🔜 💪 🔢 🔢 "`g`🅾 🌘 ⚖️ `e`🅾" `1`.
-```Python hl_lines="8"
-{!../../../docs_src/path_params_numeric_validations/tutorial004.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial004.py hl[8] *}
## 🔢 🔬: 🌘 🌘 & 🌘 🌘 ⚖️ 🌓
@@ -92,9 +69,7 @@
* `gt`: `g`🅾 `t`👲
* `le`: `l`👭 🌘 ⚖️ `e`🅾
-```Python hl_lines="9"
-{!../../../docs_src/path_params_numeric_validations/tutorial005.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial005.py hl[9] *}
## 🔢 🔬: 🎈, 🌘 🌘 & 🌘 🌘
@@ -106,9 +81,7 @@
& 🎏 lt
.
-```Python hl_lines="11"
-{!../../../docs_src/path_params_numeric_validations/tutorial006.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial006.py hl[11] *}
## 🌃
@@ -121,18 +94,24 @@
* `lt`: `l`👭 `t`👲
* `le`: `l`👭 🌘 ⚖️ `e`🅾
-!!! info
- `Query`, `Path`, & 🎏 🎓 👆 🔜 👀 ⏪ 🏿 ⚠ `Param` 🎓.
+/// info
+
+`Query`, `Path`, & 🎏 🎓 👆 🔜 👀 ⏪ 🏿 ⚠ `Param` 🎓.
+
+🌐 👫 💰 🎏 🔢 🌖 🔬 & 🗃 👆 ✔️ 👀.
+
+///
+
+/// note | 📡 ℹ
- 🌐 👫 💰 🎏 🔢 🌖 🔬 & 🗃 👆 ✔️ 👀.
+🕐❔ 👆 🗄 `Query`, `Path` & 🎏 ⚪️➡️ `fastapi`, 👫 🤙 🔢.
-!!! note "📡 ℹ"
- 🕐❔ 👆 🗄 `Query`, `Path` & 🎏 ⚪️➡️ `fastapi`, 👫 🤙 🔢.
+👈 🕐❔ 🤙, 📨 👐 🎓 🎏 📛.
- 👈 🕐❔ 🤙, 📨 👐 🎓 🎏 📛.
+, 👆 🗄 `Query`, ❔ 🔢. & 🕐❔ 👆 🤙 ⚫️, ⚫️ 📨 👐 🎓 🌟 `Query`.
- , 👆 🗄 `Query`, ❔ 🔢. & 🕐❔ 👆 🤙 ⚫️, ⚫️ 📨 👐 🎓 🌟 `Query`.
+👫 🔢 📤 (↩️ ⚙️ 🎓 🔗) 👈 👆 👨🎨 🚫 ™ ❌ 🔃 👫 🆎.
- 👫 🔢 📤 (↩️ ⚙️ 🎓 🔗) 👈 👆 👨🎨 🚫 ™ ❌ 🔃 👫 🆎.
+👈 🌌 👆 💪 ⚙️ 👆 😐 👨🎨 & 🛠️ 🧰 🍵 ✔️ 🚮 🛃 📳 🤷♂ 📚 ❌.
- 👈 🌌 👆 💪 ⚙️ 👆 😐 👨🎨 & 🛠️ 🧰 🍵 ✔️ 🚮 🛃 📳 🤷♂ 📚 ❌.
+///
diff --git a/docs/em/docs/tutorial/path-params.md b/docs/em/docs/tutorial/path-params.md
index ac64d2ebb..a914dc905 100644
--- a/docs/em/docs/tutorial/path-params.md
+++ b/docs/em/docs/tutorial/path-params.md
@@ -2,9 +2,7 @@
👆 💪 📣 ➡ "🔢" ⚖️ "🔢" ⏮️ 🎏 ❕ ⚙️ 🐍 📁 🎻:
-```Python hl_lines="6-7"
-{!../../../docs_src/path_params/tutorial001.py!}
-```
+{* ../../docs_src/path_params/tutorial001.py hl[6:7] *}
💲 ➡ 🔢 `item_id` 🔜 🚶♀️ 👆 🔢 ❌ `item_id`.
@@ -18,14 +16,15 @@
👆 💪 📣 🆎 ➡ 🔢 🔢, ⚙️ 🐩 🐍 🆎 ✍:
-```Python hl_lines="7"
-{!../../../docs_src/path_params/tutorial002.py!}
-```
+{* ../../docs_src/path_params/tutorial002.py hl[7] *}
👉 💼, `item_id` 📣 `int`.
-!!! check
- 👉 🔜 🤝 👆 👨🎨 🐕🦺 🔘 👆 🔢, ⏮️ ❌ ✅, 🛠️, ♒️.
+/// check
+
+👉 🔜 🤝 👆 👨🎨 🐕🦺 🔘 👆 🔢, ⏮️ ❌ ✅, 🛠️, ♒️.
+
+///
## 💽 🛠️
@@ -35,10 +34,13 @@
{"item_id":3}
```
-!!! check
- 👀 👈 💲 👆 🔢 📨 (& 📨) `3`, 🐍 `int`, 🚫 🎻 `"3"`.
+/// check
- , ⏮️ 👈 🆎 📄, **FastAPI** 🤝 👆 🏧 📨 "✍".
+👀 👈 💲 👆 🔢 📨 (& 📨) `3`, 🐍 `int`, 🚫 🎻 `"3"`.
+
+, ⏮️ 👈 🆎 📄, **FastAPI** 🤝 👆 🏧 📨 "✍".
+
+///
## 💽 🔬
@@ -63,12 +65,15 @@
🎏 ❌ 🔜 😑 🚥 👆 🚚 `float` ↩️ `int`,: http://127.0.0.1:8000/items/4.2
-!!! check
- , ⏮️ 🎏 🐍 🆎 📄, **FastAPI** 🤝 👆 💽 🔬.
+/// check
+
+, ⏮️ 🎏 🐍 🆎 📄, **FastAPI** 🤝 👆 💽 🔬.
- 👀 👈 ❌ 🎯 🇵🇸 ⚫️❔ ☝ 🌐❔ 🔬 🚫 🚶♀️.
+👀 👈 ❌ 🎯 🇵🇸 ⚫️❔ ☝ 🌐❔ 🔬 🚫 🚶♀️.
- 👉 🙃 👍 ⏪ 🛠️ & 🛠️ 📟 👈 🔗 ⏮️ 👆 🛠️.
+👉 🙃 👍 ⏪ 🛠️ & 🛠️ 📟 👈 🔗 ⏮️ 👆 🛠️.
+
+///
## 🧾
@@ -76,10 +81,13 @@
-!!! check
- 🔄, ⏮️ 👈 🎏 🐍 🆎 📄, **FastAPI** 🤝 👆 🏧, 🎓 🧾 (🛠️ 🦁 🎚).
+/// check
+
+🔄, ⏮️ 👈 🎏 🐍 🆎 📄, **FastAPI** 🤝 👆 🏧, 🎓 🧾 (🛠️ 🦁 🎚).
+
+👀 👈 ➡ 🔢 📣 🔢.
- 👀 👈 ➡ 🔢 📣 🔢.
+///
## 🐩-⚓️ 💰, 🎛 🧾
@@ -109,17 +117,13 @@
↩️ *➡ 🛠️* 🔬 ✔, 👆 💪 ⚒ 💭 👈 ➡ `/users/me` 📣 ⏭ 1️⃣ `/users/{user_id}`:
-```Python hl_lines="6 11"
-{!../../../docs_src/path_params/tutorial003.py!}
-```
+{* ../../docs_src/path_params/tutorial003.py hl[6,11] *}
⏪, ➡ `/users/{user_id}` 🔜 🏏 `/users/me`, "💭" 👈 ⚫️ 📨 🔢 `user_id` ⏮️ 💲 `"me"`.
➡, 👆 🚫🔜 ↔ ➡ 🛠️:
-```Python hl_lines="6 11"
-{!../../../docs_src/path_params/tutorial003b.py!}
-```
+{* ../../docs_src/path_params/tutorial003b.py hl[6,11] *}
🥇 🕐 🔜 🕧 ⚙️ ↩️ ➡ 🏏 🥇.
@@ -135,23 +139,25 @@
⤴️ ✍ 🎓 🔢 ⏮️ 🔧 💲, ❔ 🔜 💪 ☑ 💲:
-```Python hl_lines="1 6-9"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial005.py hl[1,6:9] *}
-!!! info
- 🔢 (⚖️ 🔢) 💪 🐍 ↩️ ⏬ 3️⃣.4️⃣.
+/// info
-!!! tip
- 🚥 👆 💭, "📊", "🎓", & "🍏" 📛 🎰 🏫 🏷.
+🔢 (⚖️ 🔢) 💪 🐍 ↩️ ⏬ 3️⃣.4️⃣.
+
+///
+
+/// tip
+
+🚥 👆 💭, "📊", "🎓", & "🍏" 📛 🎰 🏫 🏷.
+
+///
### 📣 *➡ 🔢*
⤴️ ✍ *➡ 🔢* ⏮️ 🆎 ✍ ⚙️ 🔢 🎓 👆 ✍ (`ModelName`):
-```Python hl_lines="16"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial005.py hl[16] *}
### ✅ 🩺
@@ -167,20 +173,19 @@
👆 💪 🔬 ⚫️ ⏮️ *🔢 👨🎓* 👆 ✍ 🔢 `ModelName`:
-```Python hl_lines="17"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial005.py hl[17] *}
#### 🤚 *🔢 💲*
👆 💪 🤚 ☑ 💲 ( `str` 👉 💼) ⚙️ `model_name.value`, ⚖️ 🏢, `your_enum_member.value`:
-```Python hl_lines="20"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial005.py hl[20] *}
-!!! tip
- 👆 💪 🔐 💲 `"lenet"` ⏮️ `ModelName.lenet.value`.
+/// tip
+
+👆 💪 🔐 💲 `"lenet"` ⏮️ `ModelName.lenet.value`.
+
+///
#### 📨 *🔢 👨🎓*
@@ -188,9 +193,7 @@
👫 🔜 🗜 👫 🔗 💲 (🎻 👉 💼) ⏭ 🛬 👫 👩💻:
-```Python hl_lines="18 21 23"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial005.py hl[18,21,23] *}
👆 👩💻 👆 🔜 🤚 🎻 📨 💖:
@@ -229,14 +232,15 @@
, 👆 💪 ⚙️ ⚫️ ⏮️:
-```Python hl_lines="6"
-{!../../../docs_src/path_params/tutorial004.py!}
-```
+{* ../../docs_src/path_params/tutorial004.py hl[6] *}
+
+/// tip
+
+👆 💪 💪 🔢 🔌 `/home/johndoe/myfile.txt`, ⏮️ 🏁 🔪 (`/`).
-!!! tip
- 👆 💪 💪 🔢 🔌 `/home/johndoe/myfile.txt`, ⏮️ 🏁 🔪 (`/`).
+👈 💼, 📛 🔜: `/files//home/johndoe/myfile.txt`, ⏮️ 2️⃣✖️ 🔪 (`//`) 🖖 `files` & `home`.
- 👈 💼, 📛 🔜: `/files//home/johndoe/myfile.txt`, ⏮️ 2️⃣✖️ 🔪 (`//`) 🖖 `files` & `home`.
+///
## 🌃
diff --git a/docs/em/docs/tutorial/query-params-str-validations.md b/docs/em/docs/tutorial/query-params-str-validations.md
index 1268c0d6e..fd077bf8f 100644
--- a/docs/em/docs/tutorial/query-params-str-validations.md
+++ b/docs/em/docs/tutorial/query-params-str-validations.md
@@ -4,24 +4,17 @@
➡️ ✊ 👉 🈸 🖼:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+{* ../../docs_src/query_params_str_validations/tutorial001.py hl[9] *}
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial001.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+🔢 🔢 `q` 🆎 `Union[str, None]` (⚖️ `str | None` 🐍 3️⃣.1️⃣0️⃣), 👈 ⛓ 👈 ⚫️ 🆎 `str` ✋️ 💪 `None`, & 👐, 🔢 💲 `None`, FastAPI 🔜 💭 ⚫️ 🚫 ✔.
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!}
- ```
+/// note
-🔢 🔢 `q` 🆎 `Union[str, None]` (⚖️ `str | None` 🐍 3️⃣.1️⃣0️⃣), 👈 ⛓ 👈 ⚫️ 🆎 `str` ✋️ 💪 `None`, & 👐, 🔢 💲 `None`, FastAPI 🔜 💭 ⚫️ 🚫 ✔.
+FastAPI 🔜 💭 👈 💲 `q` 🚫 ✔ ↩️ 🔢 💲 `= None`.
-!!! note
- FastAPI 🔜 💭 👈 💲 `q` 🚫 ✔ ↩️ 🔢 💲 `= None`.
+ `Union` `Union[str, None]` 🔜 ✔ 👆 👨🎨 🤝 👆 👍 🐕🦺 & 🔍 ❌.
- `Union` `Union[str, None]` 🔜 ✔ 👆 👨🎨 🤝 👆 👍 🐕🦺 & 🔍 ❌.
+///
## 🌖 🔬
@@ -31,33 +24,13 @@
🏆 👈, 🥇 🗄 `Query` ⚪️➡️ `fastapi`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```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!}
- ```
+{* ../../docs_src/query_params_str_validations/tutorial002.py hl[3] *}
## ⚙️ `Query` 🔢 💲
& 🔜 ⚙️ ⚫️ 🔢 💲 👆 🔢, ⚒ 🔢 `max_length` 5️⃣0️⃣:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```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!}
- ```
+{* ../../docs_src/query_params_str_validations/tutorial002.py hl[9] *}
👥 ✔️ ❎ 🔢 💲 `None` 🔢 ⏮️ `Query()`, 👥 💪 🔜 ⚒ 🔢 💲 ⏮️ 🔢 `Query(default=None)`, ⚫️ 🍦 🎏 🎯 ⚖ 👈 🔢 💲.
@@ -87,22 +60,25 @@ q: str | None = None
✋️ ⚫️ 📣 ⚫️ 🎯 💆♂ 🔢 🔢.
-!!! info
- ✔️ 🤯 👈 🌅 ⚠ 🍕 ⚒ 🔢 📦 🍕:
+/// info
- ```Python
- = None
- ```
+✔️ 🤯 👈 🌅 ⚠ 🍕 ⚒ 🔢 📦 🍕:
- ⚖️:
+```Python
+= None
+```
+
+⚖️:
+
+```Python
+= Query(default=None)
+```
- ```Python
- = Query(default=None)
- ```
+⚫️ 🔜 ⚙️ 👈 `None` 🔢 💲, & 👈 🌌 ⚒ 🔢 **🚫 ✔**.
- ⚫️ 🔜 ⚙️ 👈 `None` 🔢 💲, & 👈 🌌 ⚒ 🔢 **🚫 ✔**.
+ `Union[str, None]` 🍕 ✔ 👆 👨🎨 🚚 👻 🐕🦺, ✋️ ⚫️ 🚫 ⚫️❔ 💬 FastAPI 👈 👉 🔢 🚫 ✔.
- `Union[str, None]` 🍕 ✔ 👆 👨🎨 🚚 👻 🐕🦺, ✋️ ⚫️ 🚫 ⚫️❔ 💬 FastAPI 👈 👉 🔢 🚫 ✔.
+///
⤴️, 👥 💪 🚶♀️ 🌅 🔢 `Query`. 👉 💼, `max_length` 🔢 👈 ✔ 🎻:
@@ -116,33 +92,13 @@ q: Union[str, None] = Query(default=None, max_length=50)
👆 💪 🚮 🔢 `min_length`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```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!}
- ```
+{* ../../docs_src/query_params_str_validations/tutorial003.py hl[10] *}
## 🚮 🥔 🧬
👆 💪 🔬 🥔 🧬 👈 🔢 🔜 🏏:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```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!}
- ```
+{* ../../docs_src/query_params_str_validations/tutorial004.py hl[11] *}
👉 🎯 🥔 🧬 ✅ 👈 📨 🔢 💲:
@@ -160,12 +116,13 @@ q: Union[str, None] = Query(default=None, max_length=50)
➡️ 💬 👈 👆 💚 📣 `q` 🔢 🔢 ✔️ `min_length` `3`, & ✔️ 🔢 💲 `"fixedquery"`:
-```Python hl_lines="7"
-{!../../../docs_src/query_params_str_validations/tutorial005.py!}
-```
+{* ../../docs_src/query_params_str_validations/tutorial005.py hl[7] *}
+
+/// note
-!!! note
- ✔️ 🔢 💲 ⚒ 🔢 📦.
+✔️ 🔢 💲 ⚒ 🔢 📦.
+
+///
## ⚒ ⚫️ ✔
@@ -189,24 +146,7 @@ q: Union[str, None] = Query(default=None, min_length=3)
, 🕐❔ 👆 💪 📣 💲 ✔ ⏪ ⚙️ `Query`, 👆 💪 🎯 🚫 📣 🔢 💲:
-```Python hl_lines="7"
-{!../../../docs_src/query_params_str_validations/tutorial006.py!}
-```
-
-### ✔ ⏮️ ❕ (`...`)
-
-📤 🎛 🌌 🎯 📣 👈 💲 ✔. 👆 💪 ⚒ `default` 🔢 🔑 💲 `...`:
-
-```Python hl_lines="7"
-{!../../../docs_src/query_params_str_validations/tutorial006b.py!}
-```
-
-!!! info
- 🚥 👆 🚫 👀 👈 `...` ⏭: ⚫️ 🎁 👁 💲, ⚫️ 🍕 🐍 & 🤙 "❕".
-
- ⚫️ ⚙️ Pydantic & FastAPI 🎯 📣 👈 💲 ✔.
-
-👉 🔜 ➡️ **FastAPI** 💭 👈 👉 🔢 ✔.
+{* ../../docs_src/query_params_str_validations/tutorial006.py hl[7] *}
### ✔ ⏮️ `None`
@@ -214,31 +154,13 @@ q: Union[str, None] = Query(default=None, min_length=3)
👈, 👆 💪 📣 👈 `None` ☑ 🆎 ✋️ ⚙️ `default=...`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial006c.py!}
- ```
+{* ../../docs_src/query_params_str_validations/tutorial006c.py hl[9] *}
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+/// tip
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!}
- ```
+Pydantic, ❔ ⚫️❔ 🏋️ 🌐 💽 🔬 & 🛠️ FastAPI, ✔️ 🎁 🎭 🕐❔ 👆 ⚙️ `Optional` ⚖️ `Union[Something, None]` 🍵 🔢 💲, 👆 💪 ✍ 🌅 🔃 ⚫️ Pydantic 🩺 🔃 ✔ 📦 🏑.
-!!! tip
- Pydantic, ❔ ⚫️❔ 🏋️ 🌐 💽 🔬 & 🛠️ FastAPI, ✔️ 🎁 🎭 🕐❔ 👆 ⚙️ `Optional` ⚖️ `Union[Something, None]` 🍵 🔢 💲, 👆 💪 ✍ 🌅 🔃 ⚫️ Pydantic 🩺 🔃 ✔ 📦 🏑.
-
-### ⚙️ Pydantic `Required` ↩️ ❕ (`...`)
-
-🚥 👆 💭 😬 ⚙️ `...`, 👆 💪 🗄 & ⚙️ `Required` ⚪️➡️ Pydantic:
-
-```Python hl_lines="2 8"
-{!../../../docs_src/query_params_str_validations/tutorial006d.py!}
-```
-
-!!! tip
- 💭 👈 🌅 💼, 🕐❔ 🕳 🚚, 👆 💪 🎯 🚫 `default` 🔢, 👆 🛎 🚫 ✔️ ⚙️ `...` 🚫 `Required`.
+///
## 🔢 🔢 📇 / 💗 💲
@@ -246,23 +168,7 @@ q: Union[str, None] = Query(default=None, min_length=3)
🖼, 📣 🔢 🔢 `q` 👈 💪 😑 💗 🕰 📛, 👆 💪 ✍:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```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!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial011_py310.py!}
- ```
+{* ../../docs_src/query_params_str_validations/tutorial011.py hl[9] *}
⤴️, ⏮️ 📛 💖:
@@ -283,8 +189,11 @@ http://localhost:8000/items/?q=foo&q=bar
}
```
-!!! tip
- 📣 🔢 🔢 ⏮️ 🆎 `list`, 💖 🖼 🔛, 👆 💪 🎯 ⚙️ `Query`, ⏪ ⚫️ 🔜 🔬 📨 💪.
+/// tip
+
+📣 🔢 🔢 ⏮️ 🆎 `list`, 💖 🖼 🔛, 👆 💪 🎯 ⚙️ `Query`, ⏪ ⚫️ 🔜 🔬 📨 💪.
+
+///
🎓 🛠️ 🩺 🔜 ℹ ➡️, ✔ 💗 💲:
@@ -294,17 +203,7 @@ http://localhost:8000/items/?q=foo&q=bar
& 👆 💪 🔬 🔢 `list` 💲 🚥 👌 🚚:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```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!}
- ```
+{* ../../docs_src/query_params_str_validations/tutorial012.py hl[9] *}
🚥 👆 🚶:
@@ -327,14 +226,15 @@ http://localhost:8000/items/
👆 💪 ⚙️ `list` 🔗 ↩️ `List[str]` (⚖️ `list[str]` 🐍 3️⃣.9️⃣ ➕):
-```Python hl_lines="7"
-{!../../../docs_src/query_params_str_validations/tutorial013.py!}
-```
+{* ../../docs_src/query_params_str_validations/tutorial013.py hl[7] *}
+
+/// note
-!!! note
- ✔️ 🤯 👈 👉 💼, FastAPI 🏆 🚫 ✅ 🎚 📇.
+✔️ 🤯 👈 👉 💼, FastAPI 🏆 🚫 ✅ 🎚 📇.
- 🖼, `List[int]` 🔜 ✅ (& 📄) 👈 🎚 📇 🔢. ✋️ `list` 😞 🚫🔜.
+🖼, `List[int]` 🔜 ✅ (& 📄) 👈 🎚 📇 🔢. ✋️ `list` 😞 🚫🔜.
+
+///
## 📣 🌅 🗃
@@ -342,38 +242,21 @@ http://localhost:8000/items/
👈 ℹ 🔜 🔌 🏗 🗄 & ⚙️ 🧾 👩💻 🔢 & 🔢 🧰.
-!!! note
- ✔️ 🤯 👈 🎏 🧰 5️⃣📆 ✔️ 🎏 🎚 🗄 🐕🦺.
-
- 👫 💪 🚫 🎦 🌐 ➕ ℹ 📣, 👐 🌅 💼, ❌ ⚒ ⏪ 📄 🛠️.
+/// note
-👆 💪 🚮 `title`:
+✔️ 🤯 👈 🎏 🧰 5️⃣📆 ✔️ 🎏 🎚 🗄 🐕🦺.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+👫 💪 🚫 🎦 🌐 ➕ ℹ 📣, 👐 🌅 💼, ❌ ⚒ ⏪ 📄 🛠️.
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial007.py!}
- ```
+///
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+👆 💪 🚮 `title`:
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!}
- ```
+{* ../../docs_src/query_params_str_validations/tutorial007.py hl[10] *}
& `description`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```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!}
- ```
+{* ../../docs_src/query_params_str_validations/tutorial008.py hl[13] *}
## 📛 🔢
@@ -393,17 +276,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems
⤴️ 👆 💪 📣 `alias`, & 👈 📛 ⚫️❔ 🔜 ⚙️ 🔎 🔢 💲:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```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!}
- ```
+{* ../../docs_src/query_params_str_validations/tutorial009.py hl[9] *}
## 😛 🔢
@@ -413,17 +286,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems
⤴️ 🚶♀️ 🔢 `deprecated=True` `Query`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```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!}
- ```
+{* ../../docs_src/query_params_str_validations/tutorial010.py hl[18] *}
🩺 🔜 🎦 ⚫️ 💖 👉:
@@ -433,17 +296,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems
🚫 🔢 🔢 ⚪️➡️ 🏗 🗄 🔗 (& ➡️, ⚪️➡️ 🏧 🧾 ⚙️), ⚒ 🔢 `include_in_schema` `Query` `False`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```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!}
- ```
+{* ../../docs_src/query_params_str_validations/tutorial014.py hl[10] *}
## 🌃
diff --git a/docs/em/docs/tutorial/query-params.md b/docs/em/docs/tutorial/query-params.md
index 746b0af9e..5c8d868a9 100644
--- a/docs/em/docs/tutorial/query-params.md
+++ b/docs/em/docs/tutorial/query-params.md
@@ -2,9 +2,7 @@
🕐❔ 👆 📣 🎏 🔢 🔢 👈 🚫 🍕 ➡ 🔢, 👫 🔁 🔬 "🔢" 🔢.
-```Python hl_lines="9"
-{!../../../docs_src/query_params/tutorial001.py!}
-```
+{* ../../docs_src/query_params/tutorial001.py hl[9] *}
🔢 ⚒ 🔑-💲 👫 👈 🚶 ⏮️ `?` 📛, 🎏 `&` 🦹.
@@ -63,38 +61,21 @@ http://127.0.0.1:8000/items/?skip=20
🎏 🌌, 👆 💪 📣 📦 🔢 🔢, ⚒ 👫 🔢 `None`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params/tutorial002.py!}
- ```
+{* ../../docs_src/query_params/tutorial002.py hl[9] *}
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+👉 💼, 🔢 🔢 `q` 🔜 📦, & 🔜 `None` 🔢.
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params/tutorial002_py310.py!}
- ```
+/// check
-👉 💼, 🔢 🔢 `q` 🔜 📦, & 🔜 `None` 🔢.
+👀 👈 **FastAPI** 🙃 🥃 👀 👈 ➡ 🔢 `item_id` ➡ 🔢 & `q` 🚫,, ⚫️ 🔢 🔢.
-!!! check
- 👀 👈 **FastAPI** 🙃 🥃 👀 👈 ➡ 🔢 `item_id` ➡ 🔢 & `q` 🚫,, ⚫️ 🔢 🔢.
+///
## 🔢 🔢 🆎 🛠️
👆 💪 📣 `bool` 🆎, & 👫 🔜 🗜:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params/tutorial003.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params/tutorial003_py310.py!}
- ```
+{* ../../docs_src/query_params/tutorial003.py hl[9] *}
👉 💼, 🚥 👆 🚶:
@@ -137,17 +118,7 @@ http://127.0.0.1:8000/items/foo?short=yes
👫 🔜 🔬 📛:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```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!}
- ```
+{* ../../docs_src/query_params/tutorial004.py hl[8,10] *}
## ✔ 🔢 🔢
@@ -157,9 +128,7 @@ http://127.0.0.1:8000/items/foo?short=yes
✋️ 🕐❔ 👆 💚 ⚒ 🔢 🔢 ✔, 👆 💪 🚫 📣 🙆 🔢 💲:
-```Python hl_lines="6-7"
-{!../../../docs_src/query_params/tutorial005.py!}
-```
+{* ../../docs_src/query_params/tutorial005.py hl[6:7] *}
📥 🔢 🔢 `needy` ✔ 🔢 🔢 🆎 `str`.
@@ -203,17 +172,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
& ↗️, 👆 💪 🔬 🔢 ✔, ✔️ 🔢 💲, & 🍕 📦:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params/tutorial006.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params/tutorial006_py310.py!}
- ```
+{* ../../docs_src/query_params/tutorial006.py hl[10] *}
👉 💼, 📤 3️⃣ 🔢 🔢:
@@ -221,5 +180,8 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
* `skip`, `int` ⏮️ 🔢 💲 `0`.
* `limit`, 📦 `int`.
-!!! tip
- 👆 💪 ⚙️ `Enum`Ⓜ 🎏 🌌 ⏮️ [➡ 🔢](path-params.md#_7){.internal-link target=_blank}.
+/// tip
+
+👆 💪 ⚙️ `Enum`Ⓜ 🎏 🌌 ⏮️ [➡ 🔢](path-params.md#_7){.internal-link target=_blank}.
+
+///
diff --git a/docs/em/docs/tutorial/request-files.md b/docs/em/docs/tutorial/request-files.md
index be2218f89..c3bdeafd4 100644
--- a/docs/em/docs/tutorial/request-files.md
+++ b/docs/em/docs/tutorial/request-files.md
@@ -2,36 +2,41 @@
👆 💪 🔬 📁 📂 👩💻 ⚙️ `File`.
-!!! info
- 📨 📂 📁, 🥇 ❎ `python-multipart`.
+/// info
- 🤶 Ⓜ. `pip install python-multipart`.
+📨 📂 📁, 🥇 ❎ `python-multipart`.
- 👉 ↩️ 📂 📁 📨 "📨 💽".
+🤶 Ⓜ. `pip install python-multipart`.
+
+👉 ↩️ 📂 📁 📨 "📨 💽".
+
+///
## 🗄 `File`
🗄 `File` & `UploadFile` ⚪️➡️ `fastapi`:
-```Python hl_lines="1"
-{!../../../docs_src/request_files/tutorial001.py!}
-```
+{* ../../docs_src/request_files/tutorial001.py hl[1] *}
## 🔬 `File` 🔢
✍ 📁 🔢 🎏 🌌 👆 🔜 `Body` ⚖️ `Form`:
-```Python hl_lines="7"
-{!../../../docs_src/request_files/tutorial001.py!}
-```
+{* ../../docs_src/request_files/tutorial001.py hl[7] *}
+
+/// info
+
+`File` 🎓 👈 😖 🔗 ⚪️➡️ `Form`.
+
+✋️ 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, `File` & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓.
-!!! info
- `File` 🎓 👈 😖 🔗 ⚪️➡️ `Form`.
+///
- ✋️ 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, `File` & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓.
+/// tip
-!!! tip
- 📣 📁 💪, 👆 💪 ⚙️ `File`, ↩️ ⏪ 🔢 🔜 🔬 🔢 🔢 ⚖️ 💪 (🎻) 🔢.
+📣 📁 💪, 👆 💪 ⚙️ `File`, ↩️ ⏪ 🔢 🔜 🔬 🔢 🔢 ⚖️ 💪 (🎻) 🔢.
+
+///
📁 🔜 📂 "📨 💽".
@@ -45,9 +50,7 @@
🔬 📁 🔢 ⏮️ 🆎 `UploadFile`:
-```Python hl_lines="12"
-{!../../../docs_src/request_files/tutorial001.py!}
-```
+{* ../../docs_src/request_files/tutorial001.py hl[12] *}
⚙️ `UploadFile` ✔️ 📚 📈 🤭 `bytes`:
@@ -90,11 +93,17 @@ contents = await myfile.read()
contents = myfile.file.read()
```
-!!! note "`async` 📡 ℹ"
- 🕐❔ 👆 ⚙️ `async` 👩🔬, **FastAPI** 🏃 📁 👩🔬 🧵 & ⌛ 👫.
+/// note | `async` 📡 ℹ
+
+🕐❔ 👆 ⚙️ `async` 👩🔬, **FastAPI** 🏃 📁 👩🔬 🧵 & ⌛ 👫.
+
+///
+
+/// note | 💃 📡 ℹ
+
+**FastAPI**'Ⓜ `UploadFile` 😖 🔗 ⚪️➡️ **💃**'Ⓜ `UploadFile`, ✋️ 🚮 💪 🍕 ⚒ ⚫️ 🔗 ⏮️ **Pydantic** & 🎏 🍕 FastAPI.
-!!! note "💃 📡 ℹ"
- **FastAPI**'Ⓜ `UploadFile` 😖 🔗 ⚪️➡️ **💃**'Ⓜ `UploadFile`, ✋️ 🚮 💪 🍕 ⚒ ⚫️ 🔗 ⏮️ **Pydantic** & 🎏 🍕 FastAPI.
+///
## ⚫️❔ "📨 💽"
@@ -102,41 +111,35 @@ 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
-👆 💪 ⚒ 📁 📦 ⚙️ 🐩 🆎 ✍ & ⚒ 🔢 💲 `None`:
+👆 💪 📣 💗 `File` & `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `multipart/form-data` ↩️ `application/json`.
+
+👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+///
- ```Python hl_lines="9 17"
- {!> ../../../docs_src/request_files/tutorial001_02.py!}
- ```
+## 📦 📁 📂
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+👆 💪 ⚒ 📁 📦 ⚙️ 🐩 🆎 ✍ & ⚒ 🔢 💲 `None`:
- ```Python hl_lines="7 14"
- {!> ../../../docs_src/request_files/tutorial001_02_py310.py!}
- ```
+{* ../../docs_src/request_files/tutorial001_02.py hl[9,17] *}
## `UploadFile` ⏮️ 🌖 🗃
👆 💪 ⚙️ `File()` ⏮️ `UploadFile`, 🖼, ⚒ 🌖 🗃:
-```Python hl_lines="13"
-{!../../../docs_src/request_files/tutorial001_03.py!}
-```
+{* ../../docs_src/request_files/tutorial001_03.py hl[13] *}
## 💗 📁 📂
@@ -146,40 +149,23 @@ contents = myfile.file.read()
⚙️ 👈, 📣 📇 `bytes` ⚖️ `UploadFile`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+{* ../../docs_src/request_files/tutorial002.py hl[10,15] *}
- ```Python hl_lines="10 15"
- {!> ../../../docs_src/request_files/tutorial002.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
+👆 🔜 📨, 📣, `list` `bytes` ⚖️ `UploadFile`Ⓜ.
- ```Python hl_lines="8 13"
- {!> ../../../docs_src/request_files/tutorial002_py39.py!}
- ```
+/// note | 📡 ℹ
-👆 🔜 📨, 📣, `list` `bytes` ⚖️ `UploadFile`Ⓜ.
+👆 💪 ⚙️ `from starlette.responses import HTMLResponse`.
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette.responses import HTMLResponse`.
+**FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃.
- **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃.
+///
### 💗 📁 📂 ⏮️ 🌖 🗃
& 🎏 🌌 ⏭, 👆 💪 ⚙️ `File()` ⚒ 🌖 🔢, `UploadFile`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="18"
- {!> ../../../docs_src/request_files/tutorial003.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- ```Python hl_lines="16"
- {!> ../../../docs_src/request_files/tutorial003_py39.py!}
- ```
+{* ../../docs_src/request_files/tutorial003.py hl[18] *}
## 🌃
diff --git a/docs/em/docs/tutorial/request-forms-and-files.md b/docs/em/docs/tutorial/request-forms-and-files.md
index 0415dbf01..680b1a96a 100644
--- a/docs/em/docs/tutorial/request-forms-and-files.md
+++ b/docs/em/docs/tutorial/request-forms-and-files.md
@@ -2,33 +2,35 @@
👆 💪 🔬 📁 & 📨 🏑 🎏 🕰 ⚙️ `File` & `Form`.
-!!! info
- 📨 📂 📁 & /⚖️ 📨 📊, 🥇 ❎ `python-multipart`.
+/// info
- 🤶 Ⓜ. `pip install python-multipart`.
+📨 📂 📁 & /⚖️ 📨 📊, 🥇 ❎ `python-multipart`.
+
+🤶 Ⓜ. `pip install python-multipart`.
+
+///
## 🗄 `File` & `Form`
-```Python hl_lines="1"
-{!../../../docs_src/request_forms_and_files/tutorial001.py!}
-```
+{* ../../docs_src/request_forms_and_files/tutorial001.py hl[1] *}
## 🔬 `File` & `Form` 🔢
✍ 📁 & 📨 🔢 🎏 🌌 👆 🔜 `Body` ⚖️ `Query`:
-```Python hl_lines="8"
-{!../../../docs_src/request_forms_and_files/tutorial001.py!}
-```
+{* ../../docs_src/request_forms_and_files/tutorial001.py hl[8] *}
📁 & 📨 🏑 🔜 📂 📨 📊 & 👆 🔜 📨 📁 & 📨 🏑.
& 👆 💪 📣 📁 `bytes` & `UploadFile`.
-!!! warning
- 👆 💪 📣 💗 `File` & `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `multipart/form-data` ↩️ `application/json`.
+/// warning
+
+👆 💪 📣 💗 `File` & `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `multipart/form-data` ↩️ `application/json`.
+
+👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️.
- 👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️.
+///
## 🌃
diff --git a/docs/em/docs/tutorial/request-forms.md b/docs/em/docs/tutorial/request-forms.md
index f12d6e650..1cc1ea5dc 100644
--- a/docs/em/docs/tutorial/request-forms.md
+++ b/docs/em/docs/tutorial/request-forms.md
@@ -2,26 +2,25 @@
🕐❔ 👆 💪 📨 📨 🏑 ↩️ 🎻, 👆 💪 ⚙️ `Form`.
-!!! info
- ⚙️ 📨, 🥇 ❎ `python-multipart`.
+/// info
- 🤶 Ⓜ. `pip install python-multipart`.
+⚙️ 📨, 🥇 ❎ `python-multipart`.
+
+🤶 Ⓜ. `pip install python-multipart`.
+
+///
## 🗄 `Form`
🗄 `Form` ⚪️➡️ `fastapi`:
-```Python hl_lines="1"
-{!../../../docs_src/request_forms/tutorial001.py!}
-```
+{* ../../docs_src/request_forms/tutorial001.py hl[1] *}
## 🔬 `Form` 🔢
✍ 📨 🔢 🎏 🌌 👆 🔜 `Body` ⚖️ `Query`:
-```Python hl_lines="7"
-{!../../../docs_src/request_forms/tutorial001.py!}
-```
+{* ../../docs_src/request_forms/tutorial001.py hl[7] *}
🖼, 1️⃣ 🌌 Oauth2️⃣ 🔧 💪 ⚙️ (🤙 "🔐 💧") ⚫️ ✔ 📨 `username` & `password` 📨 🏑.
@@ -29,11 +28,17 @@
⏮️ `Form` 👆 💪 📣 🎏 📳 ⏮️ `Body` (& `Query`, `Path`, `Cookie`), 🔌 🔬, 🖼, 📛 (✅ `user-name` ↩️ `username`), ♒️.
-!!! info
- `Form` 🎓 👈 😖 🔗 ⚪️➡️ `Body`.
+/// info
+
+`Form` 🎓 👈 😖 🔗 ⚪️➡️ `Body`.
+
+///
+
+/// tip
-!!! tip
- 📣 📨 💪, 👆 💪 ⚙️ `Form` 🎯, ↩️ 🍵 ⚫️ 🔢 🔜 🔬 🔢 🔢 ⚖️ 💪 (🎻) 🔢.
+📣 📨 💪, 👆 💪 ⚙️ `Form` 🎯, ↩️ 🍵 ⚫️ 🔢 🔜 🔬 🔢 🔢 ⚖️ 💪 (🎻) 🔢.
+
+///
## 🔃 "📨 🏑"
@@ -41,17 +46,23 @@
**FastAPI** 🔜 ⚒ 💭 ✍ 👈 📊 ⚪️➡️ ▶️️ 🥉 ↩️ 🎻.
-!!! note "📡 ℹ"
- 📊 ⚪️➡️ 📨 🛎 🗜 ⚙️ "📻 🆎" `application/x-www-form-urlencoded`.
+/// note | 📡 ℹ
+
+📊 ⚪️➡️ 📨 🛎 🗜 ⚙️ "📻 🆎" `application/x-www-form-urlencoded`.
+
+✋️ 🕐❔ 📨 🔌 📁, ⚫️ 🗜 `multipart/form-data`. 👆 🔜 ✍ 🔃 🚚 📁 ⏭ 📃.
+
+🚥 👆 💚 ✍ 🌖 🔃 👉 🔢 & 📨 🏑, 👳 🏇 🕸 🩺 POST
.
+
+///
- ✋️ 🕐❔ 📨 🔌 📁, ⚫️ 🗜 `multipart/form-data`. 👆 🔜 ✍ 🔃 🚚 📁 ⏭ 📃.
+/// warning
- 🚥 👆 💚 ✍ 🌖 🔃 👉 🔢 & 📨 🏑, 👳 🏇 🕸 🩺 POST
.
+👆 💪 📣 💗 `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `application/x-www-form-urlencoded` ↩️ `application/json`.
-!!! warning
- 👆 💪 📣 💗 `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `application/x-www-form-urlencoded` ↩️ `application/json`.
+👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️.
- 👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️.
+///
## 🌃
diff --git a/docs/em/docs/tutorial/response-model.md b/docs/em/docs/tutorial/response-model.md
index 7103e9176..477376458 100644
--- a/docs/em/docs/tutorial/response-model.md
+++ b/docs/em/docs/tutorial/response-model.md
@@ -4,23 +4,7 @@
👆 💪 ⚙️ **🆎 ✍** 🎏 🌌 👆 🔜 🔢 💽 🔢 **🔢**, 👆 💪 ⚙️ Pydantic 🏷, 📇, 📖, 📊 💲 💖 🔢, 🎻, ♒️.
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```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!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="16 21"
- {!> ../../../docs_src/response_model/tutorial001_01_py310.py!}
- ```
+{* ../../docs_src/response_model/tutorial001_01.py hl[18,23] *}
FastAPI 🔜 ⚙️ 👉 📨 🆎:
@@ -53,35 +37,25 @@ FastAPI 🔜 ⚙️ 👉 📨 🆎:
* `@app.delete()`
* ♒️.
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
+{* ../../docs_src/response_model/tutorial001.py hl[17,22,24:27] *}
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001_py39.py!}
- ```
+/// note
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+👀 👈 `response_model` 🔢 "👨🎨" 👩🔬 (`get`, `post`, ♒️). 🚫 👆 *➡ 🛠️ 🔢*, 💖 🌐 🔢 & 💪.
- ```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
+
+🚥 👆 ✔️ ⚠ 🆎 ✅ 👆 👨🎨, ✍, ♒️, 👆 💪 📣 🔢 📨 🆎 `Any`.
- 👈 🌌 👆 💬 👨🎨 👈 👆 😫 🛬 🕳. ✋️ FastAPI 🔜 💽 🧾, 🔬, 🖥, ♒️. ⏮️ `response_model`.
+👈 🌌 👆 💬 👨🎨 👈 👆 😫 🛬 🕳. ✋️ FastAPI 🔜 💽 🧾, 🔬, 🖥, ♒️. ⏮️ `response_model`.
+
+///
### `response_model` 📫
@@ -95,37 +69,20 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & **
📥 👥 📣 `UserIn` 🏷, ⚫️ 🔜 🔌 🔢 🔐:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="9 11"
- {!> ../../../docs_src/response_model/tutorial002.py!}
- ```
+{* ../../docs_src/response_model/tutorial002.py hl[9,11] *}
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+/// info
- ```Python hl_lines="7 9"
- {!> ../../../docs_src/response_model/tutorial002_py310.py!}
- ```
+⚙️ `EmailStr`, 🥇 ❎ `email-validator`.
-!!! info
- ⚙️ `EmailStr`, 🥇 ❎ `email_validator`.
+🤶 Ⓜ. `pip install email-validator`
+⚖️ `pip install pydantic[email]`.
- 🤶 Ⓜ. `pip install email-validator`
- ⚖️ `pip install pydantic[email]`.
+///
& 👥 ⚙️ 👉 🏷 📣 👆 🔢 & 🎏 🏷 📣 👆 🔢:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="18"
- {!> ../../../docs_src/response_model/tutorial002.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="16"
- {!> ../../../docs_src/response_model/tutorial002_py310.py!}
- ```
+{* ../../docs_src/response_model/tutorial002.py hl[18] *}
🔜, 🕐❔ 🖥 🏗 👩💻 ⏮️ 🔐, 🛠️ 🔜 📨 🎏 🔐 📨.
@@ -133,52 +90,25 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & **
✋️ 🚥 👥 ⚙️ 🎏 🏷 ➕1️⃣ *➡ 🛠️*, 👥 💪 📨 👆 👩💻 🔐 🔠 👩💻.
-!!! danger
- 🙅 🏪 ✅ 🔐 👩💻 ⚖️ 📨 ⚫️ 📨 💖 👉, 🚥 👆 💭 🌐 ⚠ & 👆 💭 ⚫️❔ 👆 🔨.
+/// danger
-## 🚮 🔢 🏷
-
-👥 💪 ↩️ ✍ 🔢 🏷 ⏮️ 🔢 🔐 & 🔢 🏷 🍵 ⚫️:
+🙅 🏪 ✅ 🔐 👩💻 ⚖️ 📨 ⚫️ 📨 💖 👉, 🚥 👆 💭 🌐 ⚠ & 👆 💭 ⚫️❔ 👆 🔨.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+///
- ```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!}
- ```
+{* ../../docs_src/response_model/tutorial003.py hl[9,11,16] *}
📥, ✋️ 👆 *➡ 🛠️ 🔢* 🛬 🎏 🔢 👩💻 👈 🔌 🔐:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
+{* ../../docs_src/response_model/tutorial003.py hl[24] *}
...👥 📣 `response_model` 👆 🏷 `UserOut`, 👈 🚫 🔌 🔐:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
+{* ../../docs_src/response_model/tutorial003.py hl[22] *}
, **FastAPI** 🔜 ✊ 💅 🖥 👅 🌐 💽 👈 🚫 📣 🔢 🏷 (⚙️ Pydantic).
@@ -202,17 +132,7 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & **
& 👈 💼, 👥 💪 ⚙️ 🎓 & 🧬 ✊ 📈 🔢 **🆎 ✍** 🤚 👍 🐕🦺 👨🎨 & 🧰, & 🤚 FastAPI **💽 🖥**.
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```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!}
- ```
+{* ../../docs_src/response_model/tutorial003_01.py hl[9:13,15:16,20] *}
⏮️ 👉, 👥 🤚 🏭 🐕🦺, ⚪️➡️ 👨🎨 & ✍ 👉 📟 ☑ ⚖ 🆎, ✋️ 👥 🤚 💽 🖥 ⚪️➡️ FastAPI.
@@ -254,9 +174,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓
🏆 ⚠ 💼 🔜 [🛬 📨 🔗 🔬 ⏪ 🏧 🩺](../advanced/response-directly.md){.internal-link target=_blank}.
-```Python hl_lines="8 10-11"
-{!> ../../../docs_src/response_model/tutorial003_02.py!}
-```
+{* ../../docs_src/response_model/tutorial003_02.py hl[8,10:11] *}
👉 🙅 💼 🍵 🔁 FastAPI ↩️ 📨 🆎 ✍ 🎓 (⚖️ 🏿) `Response`.
@@ -266,9 +184,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓
👆 💪 ⚙️ 🏿 `Response` 🆎 ✍:
-```Python hl_lines="8-9"
-{!> ../../../docs_src/response_model/tutorial003_03.py!}
-```
+{* ../../docs_src/response_model/tutorial003_03.py hl[8:9] *}
👉 🔜 👷 ↩️ `RedirectResponse` 🏿 `Response`, & FastAPI 🔜 🔁 🍵 👉 🙅 💼.
@@ -278,17 +194,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓
🎏 🔜 🔨 🚥 👆 ✔️ 🕳 💖 🇪🇺 🖖 🎏 🆎 🌐❔ 1️⃣ ⚖️ 🌅 👫 🚫 ☑ Pydantic 🆎, 🖼 👉 🔜 ❌ 👶:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```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!}
- ```
+{* ../../docs_src/response_model/tutorial003_04.py hl[10] *}
...👉 ❌ ↩️ 🆎 ✍ 🚫 Pydantic 🆎 & 🚫 👁 `Response` 🎓 ⚖️ 🏿, ⚫️ 🇪🇺 (🙆 2️⃣) 🖖 `Response` & `dict`.
@@ -300,17 +206,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓
👉 💼, 👆 💪 ❎ 📨 🏷 ⚡ ⚒ `response_model=None`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```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!}
- ```
+{* ../../docs_src/response_model/tutorial003_05.py hl[9] *}
👉 🔜 ⚒ FastAPI 🚶 📨 🏷 ⚡ & 👈 🌌 👆 💪 ✔️ 🙆 📨 🆎 ✍ 👆 💪 🍵 ⚫️ 🤕 👆 FastAPI 🈸. 👶
@@ -318,23 +214,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓
👆 📨 🏷 💪 ✔️ 🔢 💲, 💖:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```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!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="9 11-12"
- {!> ../../../docs_src/response_model/tutorial004_py310.py!}
- ```
+{* ../../docs_src/response_model/tutorial004.py hl[11,13:14] *}
* `description: Union[str, None] = None` (⚖️ `str | None = None` 🐍 3️⃣.1️⃣0️⃣) ✔️ 🔢 `None`.
* `tax: float = 10.5` ✔️ 🔢 `10.5`.
@@ -348,23 +228,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓
👆 💪 ⚒ *➡ 🛠️ 👨🎨* 🔢 `response_model_exclude_unset=True`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial004.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial004_py39.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial004_py310.py!}
- ```
+{* ../../docs_src/response_model/tutorial004.py hl[24] *}
& 👈 🔢 💲 🏆 🚫 🔌 📨, 🕴 💲 🤙 ⚒.
@@ -377,16 +241,22 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓
}
```
-!!! info
- FastAPI ⚙️ Pydantic 🏷 `.dict()` ⏮️ 🚮 `exclude_unset` 🔢 🏆 👉.
+/// info
+
+FastAPI ⚙️ Pydantic 🏷 `.dict()` ⏮️ 🚮 `exclude_unset` 🔢 🏆 👉.
+
+///
+
+/// info
-!!! info
- 👆 💪 ⚙️:
+👆 💪 ⚙️:
- * `response_model_exclude_defaults=True`
- * `response_model_exclude_none=True`
+* `response_model_exclude_defaults=True`
+* `response_model_exclude_none=True`
- 🔬 Pydantic 🩺 `exclude_defaults` & `exclude_none`.
+🔬 Pydantic 🩺 `exclude_defaults` & `exclude_none`.
+
+///
#### 📊 ⏮️ 💲 🏑 ⏮️ 🔢
@@ -421,10 +291,13 @@ FastAPI 🙃 🥃 (🤙, Pydantic 🙃 🥃) 🤔 👈, ✋️ `description`, `t
, 👫 🔜 🔌 🎻 📨.
-!!! tip
- 👀 👈 🔢 💲 💪 🕳, 🚫 🕴 `None`.
+/// tip
+
+👀 👈 🔢 💲 💪 🕳, 🚫 🕴 `None`.
- 👫 💪 📇 (`[]`), `float` `10.5`, ♒️.
+👫 💪 📇 (`[]`), `float` `10.5`, ♒️.
+
+///
### `response_model_include` & `response_model_exclude`
@@ -434,45 +307,31 @@ FastAPI 🙃 🥃 (🤙, Pydantic 🙃 🥃) 🤔 👈, ✋️ `description`, `t
👉 💪 ⚙️ ⏩ ⌨ 🚥 👆 ✔️ 🕴 1️⃣ Pydantic 🏷 & 💚 ❎ 💽 ⚪️➡️ 🔢.
-!!! tip
- ✋️ ⚫️ 👍 ⚙️ 💭 🔛, ⚙️ 💗 🎓, ↩️ 👫 🔢.
+/// tip
+
+✋️ ⚫️ 👍 ⚙️ 💭 🔛, ⚙️ 💗 🎓, ↩️ 👫 🔢.
- 👉 ↩️ 🎻 🔗 🏗 👆 📱 🗄 (& 🩺) 🔜 1️⃣ 🏁 🏷, 🚥 👆 ⚙️ `response_model_include` ⚖️ `response_model_exclude` 🚫 🔢.
+👉 ↩️ 🎻 🔗 🏗 👆 📱 🗄 (& 🩺) 🔜 1️⃣ 🏁 🏷, 🚥 👆 ⚙️ `response_model_include` ⚖️ `response_model_exclude` 🚫 🔢.
- 👉 ✔ `response_model_by_alias` 👈 👷 ➡.
+👉 ✔ `response_model_by_alias` 👈 👷 ➡.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+///
- ```Python hl_lines="31 37"
- {!> ../../../docs_src/response_model/tutorial005.py!}
- ```
+{* ../../docs_src/response_model/tutorial005.py hl[31,37] *}
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+/// tip
- ```Python hl_lines="29 35"
- {!> ../../../docs_src/response_model/tutorial005_py310.py!}
- ```
+❕ `{"name", "description"}` ✍ `set` ⏮️ 📚 2️⃣ 💲.
-!!! tip
- ❕ `{"name", "description"}` ✍ `set` ⏮️ 📚 2️⃣ 💲.
+⚫️ 🌓 `set(["name", "description"])`.
- ⚫️ 🌓 `set(["name", "description"])`.
+///
#### ⚙️ `list`Ⓜ ↩️ `set`Ⓜ
🚥 👆 💭 ⚙️ `set` & ⚙️ `list` ⚖️ `tuple` ↩️, FastAPI 🔜 🗜 ⚫️ `set` & ⚫️ 🔜 👷 ☑:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```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!}
- ```
+{* ../../docs_src/response_model/tutorial006.py hl[31,37] *}
## 🌃
diff --git a/docs/em/docs/tutorial/response-status-code.md b/docs/em/docs/tutorial/response-status-code.md
index e5149de7d..413ceb916 100644
--- a/docs/em/docs/tutorial/response-status-code.md
+++ b/docs/em/docs/tutorial/response-status-code.md
@@ -8,17 +8,21 @@
* `@app.delete()`
* ♒️.
-```Python hl_lines="6"
-{!../../../docs_src/response_status_code/tutorial001.py!}
-```
+{* ../../docs_src/response_status_code/tutorial001.py hl[6] *}
-!!! 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 +31,21 @@
-!!! note
- 📨 📟 (👀 ⏭ 📄) 🎦 👈 📨 🔨 🚫 ✔️ 💪.
+/// note
+
+📨 📟 (👀 ⏭ 📄) 🎦 👈 📨 🔨 🚫 ✔️ 💪.
+
+FastAPI 💭 👉, & 🔜 🏭 🗄 🩺 👈 🇵🇸 📤 🙅♂ 📨 💪.
- FastAPI 💭 👉, & 🔜 🏭 🗄 🩺 👈 🇵🇸 📤 🙅♂ 📨 💪.
+///
## 🔃 🇺🇸🔍 👔 📟
-!!! note
- 🚥 👆 ⏪ 💭 ⚫️❔ 🇺🇸🔍 👔 📟, 🚶 ⏭ 📄.
+/// note
+
+🚥 👆 ⏪ 💭 ⚫️❔ 🇺🇸🔍 👔 📟, 🚶 ⏭ 📄.
+
+///
🇺🇸🔍, 👆 📨 🔢 👔 📟 3️⃣ 9️⃣ 🍕 📨.
@@ -54,16 +64,17 @@
* 💊 ❌ ⚪️➡️ 👩💻, 👆 💪 ⚙️ `400`.
* `500` & 🔛 💽 ❌. 👆 🌖 🙅 ⚙️ 👫 🔗. 🕐❔ 🕳 🚶 ❌ 🍕 👆 🈸 📟, ⚖️ 💽, ⚫️ 🔜 🔁 📨 1️⃣ 👫 👔 📟.
-!!! tip
- 💭 🌅 🔃 🔠 👔 📟 & ❔ 📟 ⚫️❔, ✅ 🏇 🧾 🔃 🇺🇸🔍 👔 📟.
+/// tip
+
+💭 🌅 🔃 🔠 👔 📟 & ❔ 📟 ⚫️❔, ✅ 🏇 🧾 🔃 🇺🇸🔍 👔 📟.
+
+///
## ⌨ 💭 📛
➡️ 👀 ⏮️ 🖼 🔄:
-```Python hl_lines="6"
-{!../../../docs_src/response_status_code/tutorial001.py!}
-```
+{* ../../docs_src/response_status_code/tutorial001.py hl[6] *}
`201` 👔 📟 "✍".
@@ -71,18 +82,19 @@
👆 💪 ⚙️ 🏪 🔢 ⚪️➡️ `fastapi.status`.
-```Python hl_lines="1 6"
-{!../../../docs_src/response_status_code/tutorial002.py!}
-```
+{* ../../docs_src/response_status_code/tutorial002.py hl[1,6] *}
👫 🏪, 👫 🧑🤝🧑 🎏 🔢, ✋️ 👈 🌌 👆 💪 ⚙️ 👨🎨 📋 🔎 👫:
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette import status`.
+/// note | 📡 ℹ
+
+👆 💪 ⚙️ `from starlette import status`.
+
+**FastAPI** 🚚 🎏 `starlette.status` `fastapi.status` 🏪 👆, 👩💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃.
- **FastAPI** 🚚 🎏 `starlette.status` `fastapi.status` 🏪 👆, 👩💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃.
+///
## 🔀 🔢
diff --git a/docs/em/docs/tutorial/schema-extra-example.md b/docs/em/docs/tutorial/schema-extra-example.md
index 114d5a84a..1bd314c51 100644
--- a/docs/em/docs/tutorial/schema-extra-example.md
+++ b/docs/em/docs/tutorial/schema-extra-example.md
@@ -8,24 +8,17 @@
👆 💪 📣 `example` Pydantic 🏷 ⚙️ `Config` & `schema_extra`, 🔬 Pydantic 🩺: 🔗 🛃:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+{* ../../docs_src/schema_extra_example/tutorial001.py hl[15:23] *}
- ```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!}
- ```
+/// tip
-👈 ➕ ℹ 🔜 🚮-🔢 **🎻 🔗** 👈 🏷, & ⚫️ 🔜 ⚙️ 🛠️ 🩺.
+👆 💪 ⚙️ 🎏 ⚒ ↔ 🎻 🔗 & 🚮 👆 👍 🛃 ➕ ℹ.
-!!! tip
- 👆 💪 ⚙️ 🎏 ⚒ ↔ 🎻 🔗 & 🚮 👆 👍 🛃 ➕ ℹ.
+🖼 👆 💪 ⚙️ ⚫️ 🚮 🗃 🕸 👩💻 🔢, ♒️.
- 🖼 👆 💪 ⚙️ ⚫️ 🚮 🗃 🕸 👩💻 🔢, ♒️.
+///
## `Field` 🌖 ❌
@@ -33,20 +26,13 @@
👆 💪 ⚙️ 👉 🚮 `example` 🔠 🏑:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+{* ../../docs_src/schema_extra_example/tutorial002.py hl[4,10:13] *}
- ```Python hl_lines="4 10-13"
- {!> ../../../docs_src/schema_extra_example/tutorial002.py!}
- ```
+/// warning
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+🚧 🤯 👈 📚 ➕ ❌ 🚶♀️ 🏆 🚫 🚮 🙆 🔬, 🕴 ➕ ℹ, 🧾 🎯.
- ```Python hl_lines="2 8-11"
- {!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!}
- ```
-
-!!! warning
- 🚧 🤯 👈 📚 ➕ ❌ 🚶♀️ 🏆 🚫 🚮 🙆 🔬, 🕴 ➕ ℹ, 🧾 🎯.
+///
## `example` & `examples` 🗄
@@ -66,17 +52,7 @@
📥 👥 🚶♀️ `example` 📊 ⌛ `Body()`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```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!}
- ```
+{* ../../docs_src/schema_extra_example/tutorial003.py hl[20:25] *}
### 🖼 🩺 🎚
@@ -97,17 +73,7 @@
* `value`: 👉 ☑ 🖼 🎦, ✅ `dict`.
* `externalValue`: 🎛 `value`, 📛 ☝ 🖼. 👐 👉 5️⃣📆 🚫 🐕🦺 📚 🧰 `value`.
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```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!}
- ```
+{* ../../docs_src/schema_extra_example/tutorial004.py hl[21:47] *}
### 🖼 🩺 🎚
@@ -117,10 +83,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..8fb459a65 100644
--- a/docs/em/docs/tutorial/security/first-steps.md
+++ b/docs/em/docs/tutorial/security/first-steps.md
@@ -20,18 +20,19 @@
📁 🖼 📁 `main.py`:
-```Python
-{!../../../docs_src/security/tutorial001.py!}
-```
+{* ../../docs_src/security/tutorial001.py *}
## 🏃 ⚫️
-!!! info
- 🥇 ❎ `python-multipart`.
+/// info
+
+🥇 ❎ `python-multipart`.
- 🤶 Ⓜ. `pip install python-multipart`.
+🤶 Ⓜ. `pip install python-multipart`.
- 👉 ↩️ **Oauth2️⃣** ⚙️ "📨 📊" 📨 `username` & `password`.
+👉 ↩️ **Oauth2️⃣** ⚙️ "📨 📊" 📨 `username` & `password`.
+
+///
🏃 🖼 ⏮️:
@@ -53,17 +54,23 @@ $ uvicorn main:app --reload
-!!! check "✔ 🔼 ❗"
- 👆 ⏪ ✔️ ✨ 🆕 "✔" 🔼.
+/// check | ✔ 🔼 ❗
+
+👆 ⏪ ✔️ ✨ 🆕 "✔" 🔼.
- & 👆 *➡ 🛠️* ✔️ 🐥 🔒 🔝-▶️️ ↩ 👈 👆 💪 🖊.
+ & 👆 *➡ 🛠️* ✔️ 🐥 🔒 🔝-▶️️ ↩ 👈 👆 💪 🖊.
+
+///
& 🚥 👆 🖊 ⚫️, 👆 ✔️ 🐥 ✔ 📨 🆎 `username` & `password` (& 🎏 📦 🏑):
-!!! note
- ⚫️ 🚫 🤔 ⚫️❔ 👆 🆎 📨, ⚫️ 🏆 🚫 👷. ✋️ 👥 🔜 🤚 📤.
+/// note
+
+⚫️ 🚫 🤔 ⚫️❔ 👆 🆎 📨, ⚫️ 🏆 🚫 👷. ✋️ 👥 🔜 🤚 📤.
+
+///
👉 ↗️ 🚫 🕸 🏁 👩💻, ✋️ ⚫️ 👑 🏧 🧰 📄 🖥 🌐 👆 🛠️.
@@ -105,36 +112,43 @@ Oauth2️⃣ 🔧 👈 👩💻 ⚖️ 🛠️ 💪 🔬 💽 👈 🔓 👩
👉 🖼 👥 🔜 ⚙️ **Oauth2️⃣**, ⏮️ **🔐** 💧, ⚙️ **📨** 🤝. 👥 👈 ⚙️ `OAuth2PasswordBearer` 🎓.
-!!! info
- "📨" 🤝 🚫 🕴 🎛.
+/// info
+
+"📨" 🤝 🚫 🕴 🎛.
- ✋️ ⚫️ 🏆 1️⃣ 👆 ⚙️ 💼.
+✋️ ⚫️ 🏆 1️⃣ 👆 ⚙️ 💼.
- & ⚫️ 💪 🏆 🏆 ⚙️ 💼, 🚥 👆 Oauth2️⃣ 🕴 & 💭 ⚫️❔ ⚫️❔ 📤 ➕1️⃣ 🎛 👈 ♣ 👻 👆 💪.
+ & ⚫️ 💪 🏆 🏆 ⚙️ 💼, 🚥 👆 Oauth2️⃣ 🕴 & 💭 ⚫️❔ ⚫️❔ 📤 ➕1️⃣ 🎛 👈 ♣ 👻 👆 💪.
- 👈 💼, **FastAPI** 🚚 👆 ⏮️ 🧰 🏗 ⚫️.
+👈 💼, **FastAPI** 🚚 👆 ⏮️ 🧰 🏗 ⚫️.
+
+///
🕐❔ 👥 ✍ 👐 `OAuth2PasswordBearer` 🎓 👥 🚶♀️ `tokenUrl` 🔢. 👉 🔢 🔌 📛 👈 👩💻 (🕸 🏃 👩💻 🖥) 🔜 ⚙️ 📨 `username` & `password` ✔ 🤚 🤝.
-```Python hl_lines="6"
-{!../../../docs_src/security/tutorial001.py!}
-```
+{* ../../docs_src/security/tutorial001.py hl[6] *}
+
+/// tip
-!!! tip
- 📥 `tokenUrl="token"` 🔗 ⚖ 📛 `token` 👈 👥 🚫 ✍. ⚫️ ⚖ 📛, ⚫️ 🌓 `./token`.
+📥 `tokenUrl="token"` 🔗 ⚖ 📛 `token` 👈 👥 🚫 ✍. ⚫️ ⚖ 📛, ⚫️ 🌓 `./token`.
- ↩️ 👥 ⚙️ ⚖ 📛, 🚥 👆 🛠️ 🔎 `https://example.com/`, ⤴️ ⚫️ 🔜 🔗 `https://example.com/token`. ✋️ 🚥 👆 🛠️ 🔎 `https://example.com/api/v1/`, ⤴️ ⚫️ 🔜 🔗 `https://example.com/api/v1/token`.
+↩️ 👥 ⚙️ ⚖ 📛, 🚥 👆 🛠️ 🔎 `https://example.com/`, ⤴️ ⚫️ 🔜 🔗 `https://example.com/token`. ✋️ 🚥 👆 🛠️ 🔎 `https://example.com/api/v1/`, ⤴️ ⚫️ 🔜 🔗 `https://example.com/api/v1/token`.
- ⚙️ ⚖ 📛 ⚠ ⚒ 💭 👆 🈸 🚧 👷 🏧 ⚙️ 💼 💖 [⛅ 🗳](../../advanced/behind-a-proxy.md){.internal-link target=_blank}.
+⚙️ ⚖ 📛 ⚠ ⚒ 💭 👆 🈸 🚧 👷 🏧 ⚙️ 💼 💖 [⛅ 🗳](../../advanced/behind-a-proxy.md){.internal-link target=_blank}.
+
+///
👉 🔢 🚫 ✍ 👈 🔗 / *➡ 🛠️*, ✋️ 📣 👈 📛 `/token` 🔜 1️⃣ 👈 👩💻 🔜 ⚙️ 🤚 🤝. 👈 ℹ ⚙️ 🗄, & ⤴️ 🎓 🛠️ 🧾 ⚙️.
👥 🔜 🔜 ✍ ☑ ➡ 🛠️.
-!!! info
- 🚥 👆 📶 ⚠ "✍" 👆 💪 👎 👗 🔢 📛 `tokenUrl` ↩️ `token_url`.
+/// info
+
+🚥 👆 📶 ⚠ "✍" 👆 💪 👎 👗 🔢 📛 `tokenUrl` ↩️ `token_url`.
- 👈 ↩️ ⚫️ ⚙️ 🎏 📛 🗄 🔌. 👈 🚥 👆 💪 🔬 🌅 🔃 🙆 👫 💂♂ ⚖ 👆 💪 📁 & 📋 ⚫️ 🔎 🌖 ℹ 🔃 ⚫️.
+👈 ↩️ ⚫️ ⚙️ 🎏 📛 🗄 🔌. 👈 🚥 👆 💪 🔬 🌅 🔃 🙆 👫 💂♂ ⚖ 👆 💪 📁 & 📋 ⚫️ 🔎 🌖 ℹ 🔃 ⚫️.
+
+///
`oauth2_scheme` 🔢 👐 `OAuth2PasswordBearer`, ✋️ ⚫️ "🇧🇲".
@@ -150,18 +164,19 @@ oauth2_scheme(some, parameters)
🔜 👆 💪 🚶♀️ 👈 `oauth2_scheme` 🔗 ⏮️ `Depends`.
-```Python hl_lines="10"
-{!../../../docs_src/security/tutorial001.py!}
-```
+{* ../../docs_src/security/tutorial001.py hl[10] *}
👉 🔗 🔜 🚚 `str` 👈 🛠️ 🔢 `token` *➡ 🛠️ 🔢*.
**FastAPI** 🔜 💭 👈 ⚫️ 💪 ⚙️ 👉 🔗 🔬 "💂♂ ⚖" 🗄 🔗 (& 🏧 🛠️ 🩺).
-!!! info "📡 ℹ"
- **FastAPI** 🔜 💭 👈 ⚫️ 💪 ⚙️ 🎓 `OAuth2PasswordBearer` (📣 🔗) 🔬 💂♂ ⚖ 🗄 ↩️ ⚫️ 😖 ⚪️➡️ `fastapi.security.oauth2.OAuth2`, ❔ 🔄 😖 ⚪️➡️ `fastapi.security.base.SecurityBase`.
+/// info | 📡 ℹ
+
+**FastAPI** 🔜 💭 👈 ⚫️ 💪 ⚙️ 🎓 `OAuth2PasswordBearer` (📣 🔗) 🔬 💂♂ ⚖ 🗄 ↩️ ⚫️ 😖 ⚪️➡️ `fastapi.security.oauth2.OAuth2`, ❔ 🔄 😖 ⚪️➡️ `fastapi.security.base.SecurityBase`.
+
+🌐 💂♂ 🚙 👈 🛠️ ⏮️ 🗄 (& 🏧 🛠️ 🩺) 😖 ⚪️➡️ `SecurityBase`, 👈 ❔ **FastAPI** 💪 💭 ❔ 🛠️ 👫 🗄.
- 🌐 💂♂ 🚙 👈 🛠️ ⏮️ 🗄 (& 🏧 🛠️ 🩺) 😖 ⚪️➡️ `SecurityBase`, 👈 ❔ **FastAPI** 💪 💭 ❔ 🛠️ 👫 🗄.
+///
## ⚫️❔ ⚫️ 🔨
diff --git a/docs/em/docs/tutorial/security/get-current-user.md b/docs/em/docs/tutorial/security/get-current-user.md
index 455cb4f46..2f4a26f35 100644
--- a/docs/em/docs/tutorial/security/get-current-user.md
+++ b/docs/em/docs/tutorial/security/get-current-user.md
@@ -2,9 +2,7 @@
⏮️ 📃 💂♂ ⚙️ (❔ 🧢 🔛 🔗 💉 ⚙️) 🤝 *➡ 🛠️ 🔢* `token` `str`:
-```Python hl_lines="10"
-{!../../../docs_src/security/tutorial001.py!}
-```
+{* ../../docs_src/security/tutorial001.py hl[10] *}
✋️ 👈 🚫 👈 ⚠.
@@ -16,17 +14,7 @@
🎏 🌌 👥 ⚙️ Pydantic 📣 💪, 👥 💪 ⚙️ ⚫️ 🙆 🙆:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```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!}
- ```
+{* ../../docs_src/security/tutorial002.py hl[5,12:16] *}
## ✍ `get_current_user` 🔗
@@ -38,63 +26,39 @@
🎏 👥 🔨 ⏭ *➡ 🛠️* 🔗, 👆 🆕 🔗 `get_current_user` 🔜 📨 `token` `str` ⚪️➡️ 🎧-🔗 `oauth2_scheme`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="25"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="23"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+{* ../../docs_src/security/tutorial002.py hl[25] *}
## 🤚 👩💻
`get_current_user` 🔜 ⚙️ (❌) 🚙 🔢 👥 ✍, 👈 ✊ 🤝 `str` & 📨 👆 Pydantic `User` 🏷:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```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!}
- ```
+{* ../../docs_src/security/tutorial002.py hl[19:22,26:27] *}
## 💉 ⏮️ 👩💻
🔜 👥 💪 ⚙️ 🎏 `Depends` ⏮️ 👆 `get_current_user` *➡ 🛠️*:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+{* ../../docs_src/security/tutorial002.py hl[31] *}
- ```Python hl_lines="31"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+👀 👈 👥 📣 🆎 `current_user` Pydantic 🏷 `User`.
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+👉 🔜 ℹ 🇺🇲 🔘 🔢 ⏮️ 🌐 🛠️ & 🆎 ✅.
- ```Python hl_lines="29"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+/// tip
-👀 👈 👥 📣 🆎 `current_user` Pydantic 🏷 `User`.
+👆 5️⃣📆 💭 👈 📨 💪 📣 ⏮️ Pydantic 🏷.
-👉 🔜 ℹ 🇺🇲 🔘 🔢 ⏮️ 🌐 🛠️ & 🆎 ✅.
+📥 **FastAPI** 🏆 🚫 🤚 😨 ↩️ 👆 ⚙️ `Depends`.
-!!! tip
- 👆 5️⃣📆 💭 👈 📨 💪 📣 ⏮️ Pydantic 🏷.
+///
- 📥 **FastAPI** 🏆 🚫 🤚 😨 ↩️ 👆 ⚙️ `Depends`.
+/// check
-!!! check
- 🌌 👉 🔗 ⚙️ 🏗 ✔ 👥 ✔️ 🎏 🔗 (🎏 "☑") 👈 🌐 📨 `User` 🏷.
+🌌 👉 🔗 ⚙️ 🏗 ✔ 👥 ✔️ 🎏 🔗 (🎏 "☑") 👈 🌐 📨 `User` 🏷.
- 👥 🚫 🚫 ✔️ 🕴 1️⃣ 🔗 👈 💪 📨 👈 🆎 💽.
+👥 🚫 🚫 ✔️ 🕴 1️⃣ 🔗 👈 💪 📨 👈 🆎 💽.
+
+///
## 🎏 🏷
@@ -128,17 +92,7 @@
& 🌐 👉 💯 *➡ 🛠️* 💪 🤪 3️⃣ ⏸:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="30-32"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="28-30"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+{* ../../docs_src/security/tutorial002.py hl[30:32] *}
## 🌃
diff --git a/docs/em/docs/tutorial/security/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..ee7bc2d28 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 +236,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 b9e3deb3c..1fd513d48 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,7 @@ Oauth2️⃣ ✔ 👈 🕐❔ ⚙️ "🔐 💧" (👈 👥 ⚙️) 👩💻/
🥇, 🗄 `OAuth2PasswordRequestForm`, & ⚙️ ⚫️ 🔗 ⏮️ `Depends` *➡ 🛠️* `/token`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="4 76"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="2 74"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+{* ../../docs_src/security/tutorial003.py hl[4,76] *}
`OAuth2PasswordRequestForm` 🎓 🔗 👈 📣 📨 💪 ⏮️:
@@ -68,29 +61,38 @@ Oauth2️⃣ ✔ 👈 🕐❔ ⚙️ "🔐 💧" (👈 👥 ⚙️) 👩💻/
* 📦 `scope` 🏑 🦏 🎻, ✍ 🎻 🎏 🚀.
* 📦 `grant_type`.
-!!! tip
- Oauth2️⃣ 🔌 🤙 *🚚* 🏑 `grant_type` ⏮️ 🔧 💲 `password`, ✋️ `OAuth2PasswordRequestForm` 🚫 🛠️ ⚫️.
+/// tip
+
+Oauth2️⃣ 🔌 🤙 *🚚* 🏑 `grant_type` ⏮️ 🔧 💲 `password`, ✋️ `OAuth2PasswordRequestForm` 🚫 🛠️ ⚫️.
- 🚥 👆 💪 🛠️ ⚫️, ⚙️ `OAuth2PasswordRequestFormStrict` ↩️ `OAuth2PasswordRequestForm`.
+🚥 👆 💪 🛠️ ⚫️, ⚙️ `OAuth2PasswordRequestFormStrict` ↩️ `OAuth2PasswordRequestForm`.
+
+///
* 📦 `client_id` (👥 🚫 💪 ⚫️ 👆 🖼).
* 📦 `client_secret` (👥 🚫 💪 ⚫️ 👆 🖼).
-!!! info
- `OAuth2PasswordRequestForm` 🚫 🎁 🎓 **FastAPI** `OAuth2PasswordBearer`.
+/// info
+
+`OAuth2PasswordRequestForm` 🚫 🎁 🎓 **FastAPI** `OAuth2PasswordBearer`.
+
+`OAuth2PasswordBearer` ⚒ **FastAPI** 💭 👈 ⚫️ 💂♂ ⚖. ⚫️ 🚮 👈 🌌 🗄.
- `OAuth2PasswordBearer` ⚒ **FastAPI** 💭 👈 ⚫️ 💂♂ ⚖. ⚫️ 🚮 👈 🌌 🗄.
+✋️ `OAuth2PasswordRequestForm` 🎓 🔗 👈 👆 💪 ✔️ ✍ 👆, ⚖️ 👆 💪 ✔️ 📣 `Form` 🔢 🔗.
- ✋️ `OAuth2PasswordRequestForm` 🎓 🔗 👈 👆 💪 ✔️ ✍ 👆, ⚖️ 👆 💪 ✔️ 📣 `Form` 🔢 🔗.
+✋️ ⚫️ ⚠ ⚙️ 💼, ⚫️ 🚚 **FastAPI** 🔗, ⚒ ⚫️ ⏩.
- ✋️ ⚫️ ⚠ ⚙️ 💼, ⚫️ 🚚 **FastAPI** 🔗, ⚒ ⚫️ ⏩.
+///
### ⚙️ 📨 💽
-!!! tip
- 👐 🔗 🎓 `OAuth2PasswordRequestForm` 🏆 🚫 ✔️ 🔢 `scope` ⏮️ 📏 🎻 👽 🚀, ↩️, ⚫️ 🔜 ✔️ `scopes` 🔢 ⏮️ ☑ 📇 🎻 🔠 ↔ 📨.
+/// tip
+
+👐 🔗 🎓 `OAuth2PasswordRequestForm` 🏆 🚫 ✔️ 🔢 `scope` ⏮️ 📏 🎻 👽 🚀, ↩️, ⚫️ 🔜 ✔️ `scopes` 🔢 ⏮️ ☑ 📇 🎻 🔠 ↔ 📨.
+
+👥 🚫 ⚙️ `scopes` 👉 🖼, ✋️ 🛠️ 📤 🚥 👆 💪 ⚫️.
- 👥 🚫 ⚙️ `scopes` 👉 🖼, ✋️ 🛠️ 📤 🚥 👆 💪 ⚫️.
+///
🔜, 🤚 👩💻 📊 ⚪️➡️ (❌) 💽, ⚙️ `username` ⚪️➡️ 📨 🏑.
@@ -98,17 +100,7 @@ Oauth2️⃣ ✔ 👈 🕐❔ ⚙️ "🔐 💧" (👈 👥 ⚙️) 👩💻/
❌, 👥 ⚙️ ⚠ `HTTPException`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```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!}
- ```
+{* ../../docs_src/security/tutorial003.py hl[3,77:79] *}
### ✅ 🔐
@@ -134,17 +126,7 @@ Oauth2️⃣ ✔ 👈 🕐❔ ⚙️ "🔐 💧" (👈 👥 ⚙️) 👩💻/
, 🧙♀ 🏆 🚫 💪 🔄 ⚙️ 👈 🎏 🔐 ➕1️⃣ ⚙️ (📚 👩💻 ⚙️ 🎏 🔐 🌐, 👉 🔜 ⚠).
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="80-83"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="78-81"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+{* ../../docs_src/security/tutorial003.py hl[80:83] *}
#### 🔃 `**user_dict`
@@ -162,8 +144,11 @@ UserInDB(
)
```
-!!! info
- 🌅 🏁 🔑 `**👩💻_ #️⃣ ` ✅ 🔙 [🧾 **➕ 🏷**](../extra-models.md#user_indict){.internal-link target=_blank}.
+/// info
+
+🌅 🏁 🔑 `**👩💻_ #️⃣ ` ✅ 🔙 [🧾 **➕ 🏷**](../extra-models.md#user_indict){.internal-link target=_blank}.
+
+///
## 📨 🤝
@@ -175,31 +160,27 @@ UserInDB(
👉 🙅 🖼, 👥 🔜 🍕 😟 & 📨 🎏 `username` 🤝.
-!!! tip
- ⏭ 📃, 👆 🔜 👀 🎰 🔐 🛠️, ⏮️ 🔐 #️⃣ & 🥙 🤝.
+/// tip
- ✋️ 🔜, ➡️ 🎯 🔛 🎯 ℹ 👥 💪.
+⏭ 📃, 👆 🔜 👀 🎰 🔐 🛠️, ⏮️ 🔐 #️⃣ & 🥙 🤝.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+✋️ 🔜, ➡️ 🎯 🔛 🎯 ℹ 👥 💪.
- ```Python hl_lines="85"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+///
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+{* ../../docs_src/security/tutorial003.py hl[85] *}
- ```Python hl_lines="83"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+/// tip
-!!! tip
- 🔌, 👆 🔜 📨 🎻 ⏮️ `access_token` & `token_type`, 🎏 👉 🖼.
+🔌, 👆 🔜 📨 🎻 ⏮️ `access_token` & `token_type`, 🎏 👉 🖼.
- 👉 🕳 👈 👆 ✔️ 👆 👆 📟, & ⚒ 💭 👆 ⚙️ 📚 🎻 🔑.
+👉 🕳 👈 👆 ✔️ 👆 👆 📟, & ⚒ 💭 👆 ⚙️ 📚 🎻 🔑.
- ⚫️ 🌖 🕴 👜 👈 👆 ✔️ 💭 ☑ 👆, 🛠️ ⏮️ 🔧.
+⚫️ 🌖 🕴 👜 👈 👆 ✔️ 💭 ☑ 👆, 🛠️ ⏮️ 🔧.
- 🎂, **FastAPI** 🍵 ⚫️ 👆.
+🎂, **FastAPI** 🍵 ⚫️ 👆.
+
+///
## ℹ 🔗
@@ -213,32 +194,25 @@ UserInDB(
, 👆 🔗, 👥 🔜 🕴 🤚 👩💻 🚥 👩💻 🔀, ☑ 🔓, & 🦁:
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="58-66 69-72 90"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+{* ../../docs_src/security/tutorial003.py hl[58:66,69:72,90] *}
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+/// info
- ```Python hl_lines="55-64 67-70 88"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+🌖 🎚 `WWW-Authenticate` ⏮️ 💲 `Bearer` 👥 🛬 📥 🍕 🔌.
-!!! info
- 🌖 🎚 `WWW-Authenticate` ⏮️ 💲 `Bearer` 👥 🛬 📥 🍕 🔌.
+🙆 🇺🇸🔍 (❌) 👔 📟 4️⃣0️⃣1️⃣ "⛔" 🤔 📨 `WWW-Authenticate` 🎚.
- 🙆 🇺🇸🔍 (❌) 👔 📟 4️⃣0️⃣1️⃣ "⛔" 🤔 📨 `WWW-Authenticate` 🎚.
+💼 📨 🤝 (👆 💼), 💲 👈 🎚 🔜 `Bearer`.
- 💼 📨 🤝 (👆 💼), 💲 👈 🎚 🔜 `Bearer`.
+👆 💪 🤙 🚶 👈 ➕ 🎚 & ⚫️ 🔜 👷.
- 👆 💪 🤙 🚶 👈 ➕ 🎚 & ⚫️ 🔜 👷.
+✋️ ⚫️ 🚚 📥 🛠️ ⏮️ 🔧.
- ✋️ ⚫️ 🚚 📥 🛠️ ⏮️ 🔧.
+, 📤 5️⃣📆 🧰 👈 ⌛ & ⚙️ ⚫️ (🔜 ⚖️ 🔮) & 👈 💪 ⚠ 👆 ⚖️ 👆 👩💻, 🔜 ⚖️ 🔮.
- , 📤 5️⃣📆 🧰 👈 ⌛ & ⚙️ ⚫️ (🔜 ⚖️ 🔮) & 👈 💪 ⚠ 👆 ⚖️ 👆 👩💻, 🔜 ⚖️ 🔮.
+👈 💰 🐩...
- 👈 💰 🐩...
+///
## 👀 ⚫️ 🎯
diff --git a/docs/em/docs/tutorial/sql-databases.md b/docs/em/docs/tutorial/sql-databases.md
deleted file mode 100644
index 5a5227352..000000000
--- a/docs/em/docs/tutorial/sql-databases.md
+++ /dev/null
@@ -1,786 +0,0 @@
-# 🗄 (🔗) 💽
-
-**FastAPI** 🚫 🚚 👆 ⚙️ 🗄 (🔗) 💽.
-
-✋️ 👆 💪 ⚙️ 🙆 🔗 💽 👈 👆 💚.
-
-📥 👥 🔜 👀 🖼 ⚙️ 🇸🇲.
-
-👆 💪 💪 🛠️ ⚫️ 🙆 💽 🐕🦺 🇸🇲, 💖:
-
-* ✳
-* ✳
-* 🗄
-* 🐸
-* 🤸♂ 🗄 💽, ♒️.
-
-👉 🖼, 👥 🔜 ⚙️ **🗄**, ↩️ ⚫️ ⚙️ 👁 📁 & 🐍 ✔️ 🛠️ 🐕🦺. , 👆 💪 📁 👉 🖼 & 🏃 ⚫️.
-
-⏪, 👆 🏭 🈸, 👆 💪 💚 ⚙️ 💽 💽 💖 **✳**.
-
-!!! tip
- 📤 🛂 🏗 🚂 ⏮️ **FastAPI** & **✳**, 🌐 ⚓️ 🔛 **☁**, 🔌 🕸 & 🌖 🧰: https://github.com/tiangolo/full-stack-fastapi-postgresql
-
-!!! note
- 👀 👈 📚 📟 🐩 `SQLAlchemy` 📟 👆 🔜 ⚙️ ⏮️ 🙆 🛠️.
-
- **FastAPI** 🎯 📟 🤪 🕧.
-
-## 🐜
-
-**FastAPI** 👷 ⏮️ 🙆 💽 & 🙆 👗 🗃 💬 💽.
-
-⚠ ⚓ ⚙️ "🐜": "🎚-🔗 🗺" 🗃.
-
-🐜 ✔️ 🧰 🗜 ("*🗺*") 🖖 *🎚* 📟 & 💽 🏓 ("*🔗*").
-
-⏮️ 🐜, 👆 🛎 ✍ 🎓 👈 🎨 🏓 🗄 💽, 🔠 🔢 🎓 🎨 🏓, ⏮️ 📛 & 🆎.
-
-🖼 🎓 `Pet` 💪 🎨 🗄 🏓 `pets`.
-
-& 🔠 *👐* 🎚 👈 🎓 🎨 ⏭ 💽.
-
-🖼 🎚 `orion_cat` (👐 `Pet`) 💪 ✔️ 🔢 `orion_cat.type`, 🏓 `type`. & 💲 👈 🔢 💪, ✅ `"cat"`.
-
-👫 🐜 ✔️ 🧰 ⚒ 🔗 ⚖️ 🔗 🖖 🏓 ⚖️ 👨💼.
-
-👉 🌌, 👆 💪 ✔️ 🔢 `orion_cat.owner` & 👨💼 🔜 🔌 💽 👉 🐶 👨💼, ✊ ⚪️➡️ 🏓 *👨💼*.
-
-, `orion_cat.owner.name` 💪 📛 (⚪️➡️ `name` 🏓 `owners` 🏓) 👉 🐶 👨💼.
-
-⚫️ 💪 ✔️ 💲 💖 `"Arquilian"`.
-
-& 🐜 🔜 🌐 👷 🤚 ℹ ⚪️➡️ 🔗 🏓 *👨💼* 🕐❔ 👆 🔄 🔐 ⚫️ ⚪️➡️ 👆 🐶 🎚.
-
-⚠ 🐜 🖼: ✳-🐜 (🍕 ✳ 🛠️), 🇸🇲 🐜 (🍕 🇸🇲, 🔬 🛠️) & 🏒 (🔬 🛠️), 👪 🎏.
-
-📥 👥 🔜 👀 ❔ 👷 ⏮️ **🇸🇲 🐜**.
-
-🎏 🌌 👆 💪 ⚙️ 🙆 🎏 🐜.
-
-!!! tip
- 📤 🌓 📄 ⚙️ 🏒 📥 🩺.
-
-## 📁 📊
-
-👫 🖼, ➡️ 💬 👆 ✔️ 📁 📛 `my_super_project` 👈 🔌 🎧-📁 🤙 `sql_app` ⏮️ 📊 💖 👉:
-
-```
-.
-└── sql_app
- ├── __init__.py
- ├── crud.py
- ├── database.py
- ├── main.py
- ├── models.py
- └── schemas.py
-```
-
-📁 `__init__.py` 🛁 📁, ✋️ ⚫️ 💬 🐍 👈 `sql_app` ⏮️ 🌐 🚮 🕹 (🐍 📁) 📦.
-
-🔜 ➡️ 👀 ⚫️❔ 🔠 📁/🕹 🔨.
-
-## ❎ `SQLAlchemy`
-
-🥇 👆 💪 ❎ `SQLAlchemy`:
-
-
await
support, we should declare our function with normal `def` instead of `async def`.
-
-Also, Couchbase recommends not using a single `Bucket` object in multiple "threads", so, we can just get the bucket directly and pass it to our utility functions:
-
-```Python hl_lines="49-53"
-{!../../../docs_src/nosql_databases/tutorial001.py!}
-```
-
-## Recap
-
-You can integrate any third party NoSQL database, just using their standard packages.
-
-The same applies to any other external tool, system or API.
diff --git a/docs/en/docs/how-to/separate-openapi-schemas.md b/docs/en/docs/how-to/separate-openapi-schemas.md
index 10be1071a..9a27638fe 100644
--- a/docs/en/docs/how-to/separate-openapi-schemas.md
+++ b/docs/en/docs/how-to/separate-openapi-schemas.md
@@ -10,111 +10,13 @@ Let's see how that works and how to change it if you need to do that.
Let's say you have a Pydantic model with default values, like this one:
-=== "Python 3.10+"
-
- ```Python hl_lines="7"
- {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-7]!}
-
- # Code below omitted 👇
- ```
-
-
-
+
@@ -93,7 +93,7 @@ The key features are:
"_Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted **Hug** to be - it's really inspiring to see someone build that._"
-
+
---
@@ -128,21 +128,25 @@ FastAPI stands on the shoulders of giants:
## Installation
+Create and activate a virtual environment and then install FastAPI:
+
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:
@@ -462,33 +470,26 @@ Used by Starlette:
Used by FastAPI / Starlette:
-* uvicorn
- for the server that loads and serves your application.
+* 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.
-When you install `fastapi` it comes these standard dependencies.
+### Without `standard` Dependencies
-Additional optional 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]"`.
-* orjson
- Required if you want to use `ORJSONResponse`.
-* ujson
- Required if you want to use `UJSONResponse`.
+### Additional Optional Dependencies
-## `fastapi-slim`
+There are some additional dependencies you might want to install.
-If you don't want the extra standard optional dependencies, install `fastapi-slim` instead.
+Additional optional Pydantic dependencies:
-When you install with:
-
-```bash
-pip install fastapi
-```
-
-...it includes the same code and dependencies as:
+* pydantic-settings
- for settings management.
+* pydantic-extra-types
- for extra types to be used with Pydantic.
-```bash
-pip install "fastapi-slim[standard]"
-```
+Additional optional FastAPI dependencies:
-The standard extra dependencies are the ones mentioned above.
+* 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 b7e5236f3..4c0ada312 100644
--- a/docs/en/docs/js/custom.js
+++ b/docs/en/docs/js/custom.js
@@ -1,25 +1,3 @@
-const div = document.querySelector('.github-topic-projects')
-
-async function getDataBatch(page) {
- const response = await fetch(`https://api.github.com/search/repositories?q=topic:fastapi&per_page=100&page=${page}`, { headers: { Accept: 'application/vnd.github.mercy-preview+json' } })
- const data = await response.json()
- return data
-}
-
-async function getData() {
- let page = 1
- let data = []
- let dataBatch = await getDataBatch(page)
- data = data.concat(dataBatch.items)
- const totalCount = dataBatch.total_count
- while (data.length < totalCount) {
- page += 1
- dataBatch = await getDataBatch(page)
- data = data.concat(dataBatch.items)
- }
- return data
-}
-
function setupTermynal() {
document.querySelectorAll(".use-termynal").forEach(node => {
node.style.display = "block";
@@ -147,7 +125,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
}
@@ -158,23 +136,10 @@ async function showRandomAnnouncement(groupId, timeInterval) {
}
async function main() {
- if (div) {
- data = await getData()
- 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:
@@ -271,14 +264,17 @@ And the more exotic ones:
* `@app.patch()`
* `@app.trace()`
-!!! tip
- You are free to use each operation (HTTP method) as you wish.
+/// tip
+
+You are free to use each operation (HTTP method) as you wish.
- **FastAPI** doesn't enforce any specific meaning.
+**FastAPI** doesn't enforce any specific meaning.
- The information here is presented as a guideline, not a requirement.
+The information here is presented as a guideline, not a requirement.
- For example, when using GraphQL you normally perform all the actions using only `POST` operations.
+For example, when using GraphQL you normally perform all the actions using only `POST` operations.
+
+///
### Step 4: define the **path operation function**
@@ -288,9 +284,7 @@ This is our "**path operation function**":
* **operation**: is `get`.
* **function**: is the function below the "decorator" (below `@app.get("/")`).
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[7] *}
This is a Python function.
@@ -302,18 +296,17 @@ In this case, it is an `async` function.
You could also define it as a normal function instead of `async def`:
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial003.py!}
-```
+{* ../../docs_src/first_steps/tutorial003.py hl[7] *}
-!!! 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
-```Python hl_lines="8"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[8] *}
You can return a `dict`, `list`, singular values as `str`, `int`, etc.
diff --git a/docs/en/docs/tutorial/handling-errors.md b/docs/en/docs/tutorial/handling-errors.md
index 6133898e4..5b8e677e4 100644
--- a/docs/en/docs/tutorial/handling-errors.md
+++ b/docs/en/docs/tutorial/handling-errors.md
@@ -25,9 +25,7 @@ To return HTTP responses with errors to the client you use `HTTPException`.
### Import `HTTPException`
-```Python hl_lines="1"
-{!../../../docs_src/handling_errors/tutorial001.py!}
-```
+{* ../../docs_src/handling_errors/tutorial001.py hl[1] *}
### Raise an `HTTPException` in your code
@@ -37,13 +35,11 @@ Because it's a Python exception, you don't `return` it, you `raise` it.
This also means that if you are inside a utility function that you are calling inside of your *path operation function*, and you raise the `HTTPException` from inside of that utility function, it won't run the rest of the code in the *path operation function*, it will terminate that request right away and send the HTTP error from the `HTTPException` to the client.
-The benefit of raising an exception over `return`ing a value will be more evident in the section about Dependencies and Security.
+The benefit of raising an exception over returning a value will be more evident in the section about Dependencies and Security.
In this example, when the client requests an item by an ID that doesn't exist, raise an exception with a status code of `404`:
-```Python hl_lines="11"
-{!../../../docs_src/handling_errors/tutorial001.py!}
-```
+{* ../../docs_src/handling_errors/tutorial001.py hl[11] *}
### The resulting response
@@ -63,12 +59,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
+
+When raising an `HTTPException`, you can pass any value that can be converted to JSON as the parameter `detail`, not only `str`.
+
+You could pass a `dict`, a `list`, etc.
- You could pass a `dict`, a `list`, etc.
+They are handled automatically by **FastAPI** and converted to JSON.
- They are handled automatically by **FastAPI** and converted to JSON.
+///
## Add custom headers
@@ -78,9 +77,7 @@ You probably won't need to use it directly in your code.
But in case you needed it for an advanced scenario, you can add custom headers:
-```Python hl_lines="14"
-{!../../../docs_src/handling_errors/tutorial002.py!}
-```
+{* ../../docs_src/handling_errors/tutorial002.py hl[14] *}
## Install custom exception handlers
@@ -92,9 +89,7 @@ And you want to handle this exception globally with FastAPI.
You could add a custom exception handler with `@app.exception_handler()`:
-```Python hl_lines="5-7 13-18 24"
-{!../../../docs_src/handling_errors/tutorial003.py!}
-```
+{* ../../docs_src/handling_errors/tutorial003.py hl[5:7,13:18,24] *}
Here, if you request `/unicorns/yolo`, the *path operation* will `raise` a `UnicornException`.
@@ -106,10 +101,13 @@ So, you will receive a clean error, with an HTTP status code of `418` and a JSON
{"message": "Oops! yolo did something. There goes a rainbow..."}
```
-!!! note "Technical Details"
- You could also use `from starlette.requests import Request` and `from starlette.responses import JSONResponse`.
+/// note | Technical Details
+
+You could also use `from starlette.requests import Request` and `from starlette.responses import JSONResponse`.
+
+**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. The same with `Request`.
- **FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. The same with `Request`.
+///
## Override the default exception handlers
@@ -129,9 +127,7 @@ To override it, import the `RequestValidationError` and use it with `@app.except
The exception handler will receive a `Request` and the exception.
-```Python hl_lines="2 14-16"
-{!../../../docs_src/handling_errors/tutorial004.py!}
-```
+{* ../../docs_src/handling_errors/tutorial004.py hl[2,14:16] *}
Now, if you go to `/items/foo`, instead of getting the default JSON error with:
@@ -160,14 +156,17 @@ 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`.
**FastAPI** uses it so that, if you use a Pydantic model in `response_model`, and your data has an error, you will see the error in your log.
-But the client/user will not see it. Instead, the client will receive an "Internal Server Error" with a HTTP status code `500`.
+But the client/user will not see it. Instead, the client will receive an "Internal Server Error" with an HTTP status code `500`.
It should be this way because if you have a Pydantic `ValidationError` in your *response* or anywhere in your code (not in the client's *request*), it's actually a bug in your code.
@@ -179,14 +178,15 @@ The same way, you can override the `HTTPException` handler.
For example, you could want to return a plain text response instead of JSON for these errors:
-```Python hl_lines="3-4 9-11 22"
-{!../../../docs_src/handling_errors/tutorial004.py!}
-```
+{* ../../docs_src/handling_errors/tutorial004.py hl[3:4,9:11,22] *}
-!!! note "Technical Details"
- 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
@@ -194,9 +194,7 @@ The `RequestValidationError` contains the `body` it received with invalid data.
You could use it while developing your app to log the body and debug it, return it to the user, etc.
-```Python hl_lines="14"
-{!../../../docs_src/handling_errors/tutorial005.py!}
-```
+{* ../../docs_src/handling_errors/tutorial005.py hl[14] *}
Now try sending an invalid item like:
@@ -250,10 +248,8 @@ from starlette.exceptions import HTTPException as StarletteHTTPException
### Reuse **FastAPI**'s exception handlers
-If you want to use the exception along with the same default exception handlers from **FastAPI**, You can import and reuse the default exception handlers from `fastapi.exception_handlers`:
+If you want to use the exception along with the same default exception handlers from **FastAPI**, you can import and reuse the default exception handlers from `fastapi.exception_handlers`:
-```Python hl_lines="2-5 15 21"
-{!../../../docs_src/handling_errors/tutorial006.py!}
-```
+{* ../../docs_src/handling_errors/tutorial006.py hl[2:5,15,21] *}
-In this example you are just `print`ing the error with a very expressive message, but you get the idea. You can use the exception and then just reuse the default exception handlers.
+In this example you are just printing 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-param-models.md b/docs/en/docs/tutorial/header-param-models.md
new file mode 100644
index 000000000..4cdf09705
--- /dev/null
+++ b/docs/en/docs/tutorial/header-param-models.md
@@ -0,0 +1,72 @@
+# Header Parameter Models
+
+If you have a group of related **header parameters**, you can create a **Pydantic model** to declare them.
+
+This would allow you to **re-use the model** in **multiple places** and also to declare validations and metadata for all the parameters at once. 😎
+
+/// note
+
+This is supported since FastAPI version `0.115.0`. 🤓
+
+///
+
+## Header Parameters with a Pydantic Model
+
+Declare the **header parameters** that you need in a **Pydantic model**, and then declare the parameter as `Header`:
+
+{* ../../docs_src/header_param_models/tutorial001_an_py310.py hl[9:14,18] *}
+
+**FastAPI** will **extract** the data for **each field** from the **headers** in the request and give you the Pydantic model you defined.
+
+## Check the Docs
+
+You can see the required headers in the docs UI at `/docs`:
+
+kwargs
. Even if they don't have a default value.
-```Python hl_lines="7"
-{!../../../docs_src/path_params_numeric_validations/tutorial003.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *}
### Better with `Annotated`
Keep in mind that if you use `Annotated`, as you are not using function parameter default values, you won't have this problem, and you probably won't need to use `*`.
-=== "Python 3.9+"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!}
- ```
+{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py hl[10] *}
## Number validations: greater than or equal
@@ -182,26 +107,7 @@ With `Query` and `Path` (and others you'll see later) you can declare number con
Here, with `ge=1`, `item_id` will need to be an integer number "`g`reater than or `e`qual" to `1`.
-=== "Python 3.9+"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!}
- ```
-
-=== "Python 3.8+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="8"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!}
- ```
+{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py hl[10] *}
## Number validations: greater than and less than or equal
@@ -210,26 +116,7 @@ The same applies for:
* `gt`: `g`reater `t`han
* `le`: `l`ess than or `e`qual
-=== "Python 3.9+"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!}
- ```
-
-=== "Python 3.8+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!}
- ```
+{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py hl[10] *}
## Number validations: floats, greater than and less than
@@ -241,26 +128,7 @@ So, `0.5` would be a valid value. But `0.0` or `0` would not.
And the same for lt
.
-=== "Python 3.9+"
-
- ```Python hl_lines="13"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="12"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!}
- ```
-
-=== "Python 3.8+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="11"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!}
- ```
+{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py hl[13] *}
## Recap
@@ -273,18 +141,24 @@ And you can also declare numeric validations:
* `lt`: `l`ess `t`han
* `le`: `l`ess than or `e`qual
-!!! info
- `Query`, `Path`, and other classes you will see later are subclasses of a common `Param` class.
+/// info
+
+`Query`, `Path`, and other classes you will see later are subclasses of a common `Param` class.
+
+All of them share the same parameters for additional validation and metadata you have seen.
+
+///
+
+/// note | Technical Details
- All of them share the same parameters for additional validation and metadata you have seen.
+When you import `Query`, `Path` and others from `fastapi`, they are actually functions.
-!!! note "Technical Details"
- When you import `Query`, `Path` and others from `fastapi`, they are actually functions.
+That when called, return instances of classes of the same name.
- That when called, return instances of classes of the same name.
+So, you import `Query`, which is a function. And when you call it, it returns an instance of a class also named `Query`.
- So, you import `Query`, which is a function. And when you call it, it returns an instance of a class also named `Query`.
+These functions are there (instead of just using the classes directly) so that your editor doesn't mark errors about their types.
- These functions are there (instead of just using the classes directly) so that your editor doesn't mark errors about their types.
+That way you can use your normal editor and coding tools without having to add custom configurations to disregard those errors.
- That way you can use your normal editor and coding tools without having to add custom configurations to disregard those errors.
+///
diff --git a/docs/en/docs/tutorial/path-params.md b/docs/en/docs/tutorial/path-params.md
index 6246d6680..7e83d3ae5 100644
--- a/docs/en/docs/tutorial/path-params.md
+++ b/docs/en/docs/tutorial/path-params.md
@@ -2,9 +2,7 @@
You can declare path "parameters" or "variables" with the same syntax used by Python format strings:
-```Python hl_lines="6-7"
-{!../../../docs_src/path_params/tutorial001.py!}
-```
+{* ../../docs_src/path_params/tutorial001.py hl[6:7] *}
The value of the path parameter `item_id` will be passed to your function as the argument `item_id`.
@@ -18,14 +16,15 @@ So, if you run this example and go to conversion
@@ -35,10 +34,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 +67,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
+
+So, with the same Python type declaration, **FastAPI** gives you data validation.
- Notice that the error also clearly states exactly the point where the validation didn't pass.
+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.
+This is incredibly helpful while developing and debugging code that interacts with your API.
+
+///
## Documentation
@@ -78,10 +83,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
+
+Again, just with that same Python type declaration, **FastAPI** gives you automatic, interactive documentation (integrating Swagger UI).
+
+Notice that the path parameter is declared to be an integer.
- Notice that the path parameter is declared to be an integer.
+///
## Standards-based benefits, alternative documentation
@@ -111,17 +119,13 @@ And then you can also have a path `/users/{user_id}` to get data about a specifi
Because *path operations* are evaluated in order, you need to make sure that the path for `/users/me` is declared before the one for `/users/{user_id}`:
-```Python hl_lines="6 11"
-{!../../../docs_src/path_params/tutorial003.py!}
-```
+{* ../../docs_src/path_params/tutorial003.py hl[6,11] *}
Otherwise, the path for `/users/{user_id}` would match also for `/users/me`, "thinking" that it's receiving a parameter `user_id` with a value of `"me"`.
Similarly, you cannot redefine a path operation:
-```Python hl_lines="6 11"
-{!../../../docs_src/path_params/tutorial003b.py!}
-```
+{* ../../docs_src/path_params/tutorial003b.py hl[6,11] *}
The first one will always be used since the path matches first.
@@ -137,23 +141,25 @@ By inheriting from `str` the API docs will be able to know that the values must
Then create class attributes with fixed values, which will be the available valid values:
-```Python hl_lines="1 6-9"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial005.py hl[1,6:9] *}
-!!! 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*
Then create a *path parameter* with a type annotation using the enum class you created (`ModelName`):
-```Python hl_lines="16"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial005.py hl[16] *}
### Check the docs
@@ -169,20 +175,19 @@ The value of the *path parameter* will be an *enumeration member*.
You can compare it with the *enumeration member* in your created enum `ModelName`:
-```Python hl_lines="17"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial005.py hl[17] *}
#### Get the *enumeration value*
You can get the actual value (a `str` in this case) using `model_name.value`, or in general, `your_enum_member.value`:
-```Python hl_lines="20"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial005.py hl[20] *}
-!!! 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*
@@ -190,9 +195,7 @@ You can return *enum members* from your *path operation*, even nested in a JSON
They will be converted to their corresponding values (strings in this case) before returning them to the client:
-```Python hl_lines="18 21 23"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial005.py hl[18,21,23] *}
In your client you will get a JSON response like:
@@ -231,14 +234,15 @@ In this case, the name of the parameter is `file_path`, and the last part, `:pat
So, you can use it with:
-```Python hl_lines="6"
-{!../../../docs_src/path_params/tutorial004.py!}
-```
+{* ../../docs_src/path_params/tutorial004.py hl[6] *}
+
+/// tip
+
+You could need the parameter to contain `/home/johndoe/myfile.txt`, with a leading slash (`/`).
-!!! tip
- You could need the parameter to contain `/home/johndoe/myfile.txt`, with a leading slash (`/`).
+In that case, the URL would be: `/files//home/johndoe/myfile.txt`, with a double slash (`//`) between `files` and `home`.
- In that case, the URL would be: `/files//home/johndoe/myfile.txt`, with a double slash (`//`) between `files` and `home`.
+///
## Recap
diff --git a/docs/en/docs/tutorial/query-param-models.md b/docs/en/docs/tutorial/query-param-models.md
new file mode 100644
index 000000000..84d82931a
--- /dev/null
+++ b/docs/en/docs/tutorial/query-param-models.md
@@ -0,0 +1,68 @@
+# Query Parameter Models
+
+If you have a group of **query parameters** that are related, you can create a **Pydantic model** to declare them.
+
+This would allow you to **re-use the model** in **multiple places** and also to declare validations and metadata for all the parameters at once. 😎
+
+/// note
+
+This is supported since FastAPI version `0.115.0`. 🤓
+
+///
+
+## Query Parameters with a Pydantic Model
+
+Declare the **query parameters** that you need in a **Pydantic model**, and then declare the parameter as `Query`:
+
+{* ../../docs_src/query_param_models/tutorial001_an_py310.py hl[9:13,17] *}
+
+**FastAPI** will **extract** the data for **each field** from the **query parameters** in the request and give you the Pydantic model you defined.
+
+## Check the Docs
+
+You can see the query parameters in the docs UI at `/docs`:
+
+POST
.
+///
-!!! 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.
+## What is "Form Data"
-## Optional File Upload
+The way HTML forms (``) sends the data to the server normally uses a "special" encoding for that data, it's different from JSON.
-You can make a file optional by using standard type annotations and setting a default value of `None`:
+**FastAPI** will make sure to read that data from the right place instead of JSON.
-=== "Python 3.10+"
+/// note | Technical Details
- ```Python hl_lines="9 17"
- {!> ../../../docs_src/request_files/tutorial001_02_an_py310.py!}
- ```
+Data from forms is normally encoded using the "media type" `application/x-www-form-urlencoded` when it doesn't include files.
-=== "Python 3.9+"
+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.
- ```Python hl_lines="9 17"
- {!> ../../../docs_src/request_files/tutorial001_02_an_py39.py!}
- ```
+If you want to read more about these encodings and form fields, head to the MDN web docs for POST
.
-=== "Python 3.8+"
+///
- ```Python hl_lines="10 18"
- {!> ../../../docs_src/request_files/tutorial001_02_an.py!}
- ```
+/// warning
-=== "Python 3.10+ non-Annotated"
+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`.
- !!! tip
- Prefer to use the `Annotated` version if possible.
+This is not a limitation of **FastAPI**, it's part of the HTTP protocol.
- ```Python hl_lines="7 15"
- {!> ../../../docs_src/request_files/tutorial001_02_py310.py!}
- ```
+///
-=== "Python 3.8+ non-Annotated"
+## Optional File Upload
- !!! tip
- Prefer to use the `Annotated` version if possible.
+You can make a file optional by using standard type annotations and setting a default value of `None`:
- ```Python hl_lines="9 17"
- {!> ../../../docs_src/request_files/tutorial001_02.py!}
- ```
+{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *}
## `UploadFile` with Additional Metadata
You can also use `File()` with `UploadFile`, for example, to set additional metadata:
-=== "Python 3.9+"
-
- ```Python hl_lines="9 15"
- {!> ../../../docs_src/request_files/tutorial001_03_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="8 14"
- {!> ../../../docs_src/request_files/tutorial001_03_an.py!}
- ```
-
-=== "Python 3.8+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="7 13"
- {!> ../../../docs_src/request_files/tutorial001_03.py!}
- ```
+{* ../../docs_src/request_files/tutorial001_03_an_py39.py hl[9,15] *}
## Multiple File Uploads
@@ -238,76 +153,23 @@ 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+"
-
- ```Python hl_lines="10 15"
- {!> ../../../docs_src/request_files/tutorial002_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="11 16"
- {!> ../../../docs_src/request_files/tutorial002_an.py!}
- ```
-
-=== "Python 3.9+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
+{* ../../docs_src/request_files/tutorial002_an_py39.py hl[10,15] *}
- ```Python hl_lines="8 13"
- {!> ../../../docs_src/request_files/tutorial002_py39.py!}
- ```
-
-=== "Python 3.8+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
+You will receive, as declared, a `list` of `bytes` or `UploadFile`s.
- ```Python hl_lines="10 15"
- {!> ../../../docs_src/request_files/tutorial002.py!}
- ```
+/// note | Technical Details
-You will receive, as declared, a `list` of `bytes` or `UploadFile`s.
+You could also use `from starlette.responses import HTMLResponse`.
-!!! note "Technical Details"
- You could also use `from starlette.responses import HTMLResponse`.
+**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette.
- **FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette.
+///
### Multiple File Uploads with Additional Metadata
And the same way as before, you can use `File()` to set additional parameters, even for `UploadFile`:
-=== "Python 3.9+"
-
- ```Python hl_lines="11 18-20"
- {!> ../../../docs_src/request_files/tutorial003_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="12 19-21"
- {!> ../../../docs_src/request_files/tutorial003_an.py!}
- ```
-
-=== "Python 3.9+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="9 16"
- {!> ../../../docs_src/request_files/tutorial003_py39.py!}
- ```
-
-=== "Python 3.8+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="11 18"
- {!> ../../../docs_src/request_files/tutorial003.py!}
- ```
+{* ../../docs_src/request_files/tutorial003_an_py39.py hl[11,18:20] *}
## Recap
diff --git a/docs/en/docs/tutorial/request-form-models.md b/docs/en/docs/tutorial/request-form-models.md
new file mode 100644
index 000000000..79046a3f6
--- /dev/null
+++ b/docs/en/docs/tutorial/request-form-models.md
@@ -0,0 +1,78 @@
+# Form Models
+
+You can use **Pydantic models** to declare **form fields** in FastAPI.
+
+/// info
+
+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
+```
+
+///
+
+/// note
+
+This is supported since FastAPI version `0.113.0`. 🤓
+
+///
+
+## Pydantic Models for Forms
+
+You just need to declare a **Pydantic model** with the fields you want to receive as **form fields**, and then declare the parameter as `Form`:
+
+{* ../../docs_src/request_form_models/tutorial001_an_py39.py hl[9:11,15] *}
+
+**FastAPI** will **extract** the data for **each field** from the **form data** in the request and give you the Pydantic model you defined.
+
+## Check the Docs
+
+You can verify it in the docs UI at `/docs`:
+
+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
- If you want to read more about these encodings and form fields, head to the MDN web docs for POST
.
+You can declare multiple `Form` parameters in a *path operation*, but you can't also declare `Body` fields that you expect to receive as JSON, as the request will have the body encoded using `application/x-www-form-urlencoded` instead of `application/json`.
-!!! warning
- You can declare multiple `Form` parameters in a *path operation*, but you can't also declare `Body` fields that you expect to receive as JSON, as the request will have the body encoded using `application/x-www-form-urlencoded` instead of `application/json`.
+This is not a limitation of **FastAPI**, it's part of the HTTP protocol.
- This is not a limitation of **FastAPI**, it's part of the HTTP protocol.
+///
## Recap
diff --git a/docs/en/docs/tutorial/response-model.md b/docs/en/docs/tutorial/response-model.md
index 75d5df106..e7837086f 100644
--- a/docs/en/docs/tutorial/response-model.md
+++ b/docs/en/docs/tutorial/response-model.md
@@ -4,23 +4,7 @@ You can declare the type used for the response by annotating the *path operation
You can use **type annotations** the same way you would for input data in function **parameters**, you can use Pydantic models, lists, dictionaries, scalar values like integers, booleans, etc.
-=== "Python 3.10+"
-
- ```Python hl_lines="16 21"
- {!> ../../../docs_src/response_model/tutorial001_01_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="18 23"
- {!> ../../../docs_src/response_model/tutorial001_01_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="18 23"
- {!> ../../../docs_src/response_model/tutorial001_01.py!}
- ```
+{* ../../docs_src/response_model/tutorial001_01_py310.py hl[16,21] *}
FastAPI will use this return type to:
@@ -53,35 +37,25 @@ You can use the `response_model` parameter in any of the *path operations*:
* `@app.delete()`
* etc.
-=== "Python 3.10+"
-
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001_py39.py!}
- ```
+{* ../../docs_src/response_model/tutorial001_py310.py hl[17,22,24:27] *}
-=== "Python 3.8+"
+/// note
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001.py!}
- ```
+Notice that `response_model` is a parameter of the "decorator" method (`get`, `post`, etc). Not of your *path operation function*, like all the parameters and body.
-!!! note
- Notice that `response_model` is a parameter of the "decorator" method (`get`, `post`, etc). Not of your *path operation function*, like all the parameters and body.
+///
`response_model` receives the same type you would declare for a Pydantic model field, so, it can be a Pydantic model, but it can also be, e.g. a `list` of Pydantic models, like `List[Item]`.
FastAPI will use this `response_model` to do all the data documentation, validation, etc. and also to **convert and filter the output data** to its type declaration.
-!!! tip
- If you have strict type checks in your editor, mypy, etc, you can declare the function return type as `Any`.
+/// tip
- 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 +69,29 @@ 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+"
+{* ../../docs_src/response_model/tutorial002_py310.py hl[7,9] *}
- ```Python hl_lines="7 9"
- {!> ../../../docs_src/response_model/tutorial002_py310.py!}
- ```
+/// info
-=== "Python 3.8+"
+To use `EmailStr`, first install `email-validator`.
- ```Python hl_lines="9 11"
- {!> ../../../docs_src/response_model/tutorial002.py!}
- ```
+Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install it, for example:
-!!! info
- To use `EmailStr`, first install `email_validator`.
+```console
+$ pip install email-validator
+```
- E.g. `pip install email-validator`
- or `pip install pydantic[email]`.
+or with:
-And we are using this model to declare our input and the same model to declare our output:
-
-=== "Python 3.10+"
+```console
+$ pip install "pydantic[email]"
+```
- ```Python hl_lines="16"
- {!> ../../../docs_src/response_model/tutorial002_py310.py!}
- ```
+///
-=== "Python 3.8+"
+And we are using this model to declare our input and the same model to declare our output:
- ```Python hl_lines="18"
- {!> ../../../docs_src/response_model/tutorial002.py!}
- ```
+{* ../../docs_src/response_model/tutorial002_py310.py hl[16] *}
Now, whenever a browser is creating a user with a password, the API will return the same password in the response.
@@ -133,52 +99,25 @@ 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
-## Add an output model
-
-We can instead create an input model with the plaintext password and an output model without it:
+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.
-=== "Python 3.10+"
+///
- ```Python hl_lines="9 11 16"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
+## Add an output model
-=== "Python 3.8+"
+We can instead create an input model with the plaintext password and an output model without it:
- ```Python hl_lines="9 11 16"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+{* ../../docs_src/response_model/tutorial003_py310.py hl[9,11,16] *}
Here, even though our *path operation function* is returning the same input user that contains the password:
-=== "Python 3.10+"
-
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+{* ../../docs_src/response_model/tutorial003_py310.py hl[24] *}
...we declared the `response_model` to be our model `UserOut`, that doesn't include the password:
-=== "Python 3.10+"
-
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+{* ../../docs_src/response_model/tutorial003_py310.py hl[22] *}
So, **FastAPI** will take care of filtering out all the data that is not declared in the output model (using Pydantic).
@@ -192,9 +131,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 +141,7 @@ But in most of the cases where we need to do something like this, we want the mo
And in those cases, we can use classes and inheritance to take advantage of function **type annotations** to get better support in the editor and tools, and still get the FastAPI **data filtering**.
-=== "Python 3.10+"
-
- ```Python hl_lines="7-10 13-14 18"
- {!> ../../../docs_src/response_model/tutorial003_01_py310.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="9-13 15-16 20"
- {!> ../../../docs_src/response_model/tutorial003_01.py!}
- ```
+{* ../../docs_src/response_model/tutorial003_01_py310.py hl[7:10,13:14,18] *}
With this, we get tooling support, from editors and mypy as this code is correct in terms of types, but we also get the data filtering from FastAPI.
@@ -254,11 +183,9 @@ There might be cases where you return something that is not a valid Pydantic fie
The most common case would be [returning a Response directly as explained later in the advanced docs](../advanced/response-directly.md){.internal-link target=_blank}.
-```Python hl_lines="8 10-11"
-{!> ../../../docs_src/response_model/tutorial003_02.py!}
-```
+{* ../../docs_src/response_model/tutorial003_02.py hl[8,10:11] *}
-This simple case is handled automatically by FastAPI because the return type annotation is the class (or a subclass) of `Response`.
+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.
@@ -266,9 +193,7 @@ And tools will also be happy because both `RedirectResponse` and `JSONResponse`
You can also use a subclass of `Response` in the type annotation:
-```Python hl_lines="8-9"
-{!> ../../../docs_src/response_model/tutorial003_03.py!}
-```
+{* ../../docs_src/response_model/tutorial003_03.py hl[8:9] *}
This will also work because `RedirectResponse` is a subclass of `Response`, and FastAPI will automatically handle this simple case.
@@ -278,17 +203,7 @@ But when you return some other arbitrary object that is not a valid Pydantic typ
The same would happen if you had something like a union between different types where one or more of them are not valid Pydantic types, for example this would fail 💥:
-=== "Python 3.10+"
-
- ```Python hl_lines="8"
- {!> ../../../docs_src/response_model/tutorial003_04_py310.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/response_model/tutorial003_04.py!}
- ```
+{* ../../docs_src/response_model/tutorial003_04_py310.py hl[8] *}
...this fails because the type annotation is not a Pydantic type and is not just a single `Response` class or subclass, it's a union (any of the two) between a `Response` and a `dict`.
@@ -300,17 +215,7 @@ But you might want to still keep the return type annotation in the function to g
In this case, you can disable the response model generation by setting `response_model=None`:
-=== "Python 3.10+"
-
- ```Python hl_lines="7"
- {!> ../../../docs_src/response_model/tutorial003_05_py310.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/response_model/tutorial003_05.py!}
- ```
+{* ../../docs_src/response_model/tutorial003_05_py310.py hl[7] *}
This will make FastAPI skip the response model generation and that way you can have any return type annotations you need without it affecting your FastAPI application. 🤓
@@ -318,23 +223,7 @@ This will make FastAPI skip the response model generation and that way you can h
Your response model could have default values, like:
-=== "Python 3.10+"
-
- ```Python hl_lines="9 11-12"
- {!> ../../../docs_src/response_model/tutorial004_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="11 13-14"
- {!> ../../../docs_src/response_model/tutorial004_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="11 13-14"
- {!> ../../../docs_src/response_model/tutorial004.py!}
- ```
+{* ../../docs_src/response_model/tutorial004_py310.py hl[9,11:12] *}
* `description: Union[str, None] = None` (or `str | None = None` in Python 3.10) has a default of `None`.
* `tax: float = 10.5` has a default of `10.5`.
@@ -348,23 +237,7 @@ For example, if you have models with many optional attributes in a NoSQL databas
You can set the *path operation decorator* parameter `response_model_exclude_unset=True`:
-=== "Python 3.10+"
-
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial004_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial004_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial004.py!}
- ```
+{* ../../docs_src/response_model/tutorial004_py310.py hl[22] *}
and those default values won't be included in the response, only the values actually set.
@@ -377,21 +250,30 @@ So, if you send a request to that *path operation* for the item with ID `foo`, t
}
```
-!!! info
- In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`.
+/// info
+
+In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`.
+
+The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2.
+
+///
+
+/// info
+
+FastAPI uses Pydantic model's `.dict()` with 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
- FastAPI uses Pydantic model's `.dict()` with its `exclude_unset` parameter to achieve this.
+/// info
-!!! info
- You can also use:
+You can also use:
- * `response_model_exclude_defaults=True`
- * `response_model_exclude_none=True`
+* `response_model_exclude_defaults=True`
+* `response_model_exclude_none=True`
- as described in the Pydantic docs for `exclude_defaults` and `exclude_none`.
+as described in the Pydantic docs for `exclude_defaults` and `exclude_none`.
+
+///
#### Data with values for fields with defaults
@@ -426,10 +308,13 @@ FastAPI is smart enough (actually, Pydantic is smart enough) to realize that, ev
So, they will be included in the JSON response.
-!!! tip
- Notice that the default values can be anything, not only `None`.
+/// tip
+
+Notice that the default values can be anything, not only `None`.
- They can be a list (`[]`), a `float` of `10.5`, etc.
+They can be a list (`[]`), a `float` of `10.5`, etc.
+
+///
### `response_model_include` and `response_model_exclude`
@@ -439,45 +324,31 @@ 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
+
+But it is still recommended to use the ideas above, using multiple classes, instead of these parameters.
- 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.
+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.
- This also applies to `response_model_by_alias` that works similarly.
+This also applies to `response_model_by_alias` that works similarly.
-=== "Python 3.10+"
+///
- ```Python hl_lines="29 35"
- {!> ../../../docs_src/response_model/tutorial005_py310.py!}
- ```
+{* ../../docs_src/response_model/tutorial005_py310.py hl[29,35] *}
-=== "Python 3.8+"
+/// tip
- ```Python hl_lines="31 37"
- {!> ../../../docs_src/response_model/tutorial005.py!}
- ```
+The syntax `{"name", "description"}` creates a `set` with those two values.
-!!! tip
- The syntax `{"name", "description"}` creates a `set` with those two values.
+It is equivalent to `set(["name", "description"])`.
- 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+"
-
- ```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!}
- ```
+{* ../../docs_src/response_model/tutorial006_py310.py hl[29,35] *}
## Recap
diff --git a/docs/en/docs/tutorial/response-status-code.md b/docs/en/docs/tutorial/response-status-code.md
index 646378aa1..41bf02a8f 100644
--- a/docs/en/docs/tutorial/response-status-code.md
+++ b/docs/en/docs/tutorial/response-status-code.md
@@ -8,17 +8,21 @@ The same way you can specify a response model, you can also declare the HTTP sta
* `@app.delete()`
* etc.
-```Python hl_lines="6"
-{!../../../docs_src/response_status_code/tutorial001.py!}
-```
+{* ../../docs_src/response_status_code/tutorial001.py hl[6] *}
-!!! note
- 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 +31,21 @@ It will:
fastapi run --workers 4 main.py +INFO Using path main.py +INFO Resolved absolute path /home/user/code/awesomeapp/main.py +INFO Searching for package file structure from directories with __init__.py files +INFO Importing from /home/user/code/awesomeapp + + ╭─ Python module file ─╮ + │ │ + │ 🐍 main.py │ + │ │ + ╰──────────────────────╯ + +INFO Importing module main +INFO Found importable FastAPI app + + ╭─ Importable FastAPI app ─╮ + │ │ + │ from main import app │ + │ │ + ╰──────────────────────────╯ + +INFO Using import string main:app + + ╭─────────── FastAPI CLI - Production mode ───────────╮ + │ │ + │ Serving at: http://0.0.0.0:8000 │ + │ │ + │ API docs: http://0.0.0.0:8000/docs │ + │ │ + │ Running in production mode, for development use: │ + │ │ + │ fastapi dev │ + │ │ + ╰─────────────────────────────────────────────────────╯ + +INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit) +INFO: Started parent process [27365] +INFO: Started server process [27368] +INFO: Waiting for application startup. +INFO: Application startup complete. +INFO: Started server process [27369] +INFO: Waiting for application startup. +INFO: Application startup complete. +INFO: Started server process [27370] +INFO: Waiting for application startup. +INFO: Application startup complete. +INFO: Started server process [27367] +INFO: Waiting for application startup. +INFO: Application startup complete. ++``` + +
+ +**FastAPI** no existiría si no fuera por el trabajo previo de otros. + +Ha habido muchas herramientas creadas antes que han ayudado a inspirar su creación. + +He estado evitando la creación de un nuevo framework durante varios años. Primero traté de resolver todas las funcionalidades cubiertas por **FastAPI** usando varios frameworks, complementos y herramientas diferentes. + +Pero en algún momento, no había otra opción que crear algo que proporcionara todas estas funcionalidades, tomando las mejores ideas de herramientas anteriores y combinándolas de la mejor manera posible, usando funcionalidades del lenguaje que ni siquiera estaban disponibles antes (anotaciones de tipos de Python 3.6+). + ++ +## Investigación + +Al usar todas las alternativas anteriores, tuve la oportunidad de aprender de todas ellas, tomar ideas y combinarlas de la mejor manera que pude encontrar para mí y los equipos de desarrolladores con los que he trabajado. + +Por ejemplo, estaba claro que idealmente debería estar basado en las anotaciones de tipos estándar de Python. + +También, el mejor enfoque era usar estándares ya existentes. + +Entonces, antes de siquiera empezar a programar **FastAPI**, pasé varios meses estudiando las especificaciones de OpenAPI, JSON Schema, OAuth2, etc. Entendiendo su relación, superposición y diferencias. + +## Diseño + +Luego pasé algún tiempo diseñando la "API" de desarrollador que quería tener como usuario (como desarrollador usando FastAPI). + +Probé varias ideas en los editores de Python más populares: PyCharm, VS Code, editores basados en Jedi. + +Según la última Encuesta de Desarrolladores de Python, estos editores cubren alrededor del 80% de los usuarios. + +Esto significa que **FastAPI** fue específicamente probado con los editores usados por el 80% de los desarrolladores de Python. Y como la mayoría de los otros editores tienden a funcionar de manera similar, todos sus beneficios deberían funcionar prácticamente para todos los editores. + +De esa manera, pude encontrar las mejores maneras de reducir la duplicación de código tanto como fuera posible, para tener autocompletado en todas partes, chequeos de tipos y errores, etc. + +Todo de una manera que proporcionara la mejor experiencia de desarrollo para todos los desarrolladores. + +## Requisitos + +Después de probar varias alternativas, decidí que iba a usar **Pydantic** por sus ventajas. + +Luego contribuí a este, para hacerlo totalmente compatible con JSON Schema, para soportar diferentes maneras de definir declaraciones de restricciones, y para mejorar el soporte de los editores (chequeo de tipos, autocompletado) basado en las pruebas en varios editores. + +Durante el desarrollo, también contribuí a **Starlette**, el otro requisito clave. + +## Desarrollo + +Para cuando comencé a crear el propio **FastAPI**, la mayoría de las piezas ya estaban en su lugar, el diseño estaba definido, los requisitos y herramientas estaban listos, y el conocimiento sobre los estándares y especificaciones estaba claro y fresco. + +## Futuro + +A este punto, ya está claro que **FastAPI** con sus ideas está siendo útil para muchas personas. + +Está siendo elegido sobre alternativas anteriores por adaptarse mejor a muchos casos de uso. + +Muchos desarrolladores y equipos ya dependen de **FastAPI** para sus proyectos (incluyéndome a mí y a mi equipo). + +Pero aún así, hay muchas mejoras y funcionalidades por venir. + +**FastAPI** tiene un gran futuro por delante. + +Y [tu ayuda](help-fastapi.md){.internal-link target=_blank} es muy apreciada. diff --git a/docs/es/docs/how-to/conditional-openapi.md b/docs/es/docs/how-to/conditional-openapi.md new file mode 100644 index 000000000..4f806ef6c --- /dev/null +++ b/docs/es/docs/how-to/conditional-openapi.md @@ -0,0 +1,56 @@ +# OpenAPI Condicional + +Si lo necesitaras, podrías usar configuraciones y variables de entorno para configurar OpenAPI condicionalmente según el entorno, e incluso desactivarlo por completo. + +## Sobre seguridad, APIs y documentación + +Ocultar las interfaces de usuario de la documentación en producción *no debería* ser la forma de proteger tu API. + +Eso no añade ninguna seguridad extra a tu API, las *path operations* seguirán estando disponibles donde están. + +Si hay una falla de seguridad en tu código, seguirá existiendo. + +Ocultar la documentación solo hace que sea más difícil entender cómo interactuar con tu API y podría dificultar más depurarla en producción. Podría considerarse simplemente una forma de Seguridad mediante oscuridad. + +Si quieres asegurar tu API, hay varias cosas mejores que puedes hacer, por ejemplo: + +* Asegúrate de tener modelos Pydantic bien definidos para tus request bodies y responses. +* Configura los permisos y roles necesarios usando dependencias. +* Nunca guardes contraseñas en texto plano, solo hashes de contraseñas. +* Implementa y utiliza herramientas criptográficas bien conocidas, como Passlib y JWT tokens, etc. +* Añade controles de permisos más detallados con OAuth2 scopes donde sea necesario. +* ...etc. + +No obstante, podrías tener un caso de uso muy específico donde realmente necesites desactivar la documentación de la API para algún entorno (por ejemplo, para producción) o dependiendo de configuraciones de variables de entorno. + +## OpenAPI condicional desde configuraciones y variables de entorno + +Puedes usar fácilmente las mismas configuraciones de Pydantic para configurar tu OpenAPI generado y las interfaces de usuario de la documentación. + +Por ejemplo: + +{* ../../docs_src/conditional_openapi/tutorial001.py hl[6,11] *} + +Aquí declaramos la configuración `openapi_url` con el mismo valor predeterminado de `"/openapi.json"`. + +Y luego la usamos al crear la app de `FastAPI`. + +Entonces podrías desactivar OpenAPI (incluyendo las UI de documentación) configurando la variable de entorno `OPENAPI_URL` a una string vacía, así: + +
- FastAPI framework, alto desempeño, fácil de aprender, rápido de programar, listo para producción + FastAPI framework, alto rendimiento, fácil de aprender, rápido de programar, listo para producción
--- @@ -29,21 +32,21 @@ **Código Fuente**: https://github.com/fastapi/fastapi --- -FastAPI es un web framework moderno y rápido (de alto rendimiento) para construir APIs con Python basado en las anotaciones de tipos estándar de Python. -Sus características principales son: +FastAPI es un framework web moderno, rápido (de alto rendimiento), para construir APIs con Python basado en las anotaciones de tipos estándar de Python. -* **Rapidez**: Alto rendimiento, a la par con **NodeJS** y **Go** (gracias a Starlette y Pydantic). [Uno de los frameworks de Python más rápidos](#rendimiento). +Las características clave son: -* **Rápido de programar**: Incrementa la velocidad de desarrollo entre 200% y 300%. * -* **Menos errores**: Reduce los errores humanos (de programador) aproximadamente un 40%. * -* **Intuitivo**: Gran soporte en los editores con auto completado en todas partes. Gasta menos tiempo debugging. -* **Fácil**: Está diseñado para ser fácil de usar y aprender. Gastando menos tiempo leyendo documentación. -* **Corto**: Minimiza la duplicación de código. Múltiples funcionalidades con cada declaración de parámetros. Menos errores. -* **Robusto**: Crea código listo para producción con documentación automática interactiva. -* **Basado en estándares**: Basado y totalmente compatible con los estándares abiertos para APIs: OpenAPI (conocido previamente como Swagger) y JSON Schema. +* **Rápido**: Muy alto rendimiento, a la par con **NodeJS** y **Go** (gracias a Starlette y Pydantic). [Uno de los frameworks Python más rápidos disponibles](#performance). +* **Rápido de programar**: Aumenta la velocidad para desarrollar funcionalidades en aproximadamente un 200% a 300%. * +* **Menos bugs**: Reduce en aproximadamente un 40% los errores inducidos por humanos (desarrolladores). * +* **Intuitivo**: Gran soporte para editores. Autocompletado en todas partes. Menos tiempo depurando. +* **Fácil**: Diseñado para ser fácil de usar y aprender. Menos tiempo leyendo documentación. +* **Corto**: Minimiza la duplicación de código. Múltiples funcionalidades desde cada declaración de parámetro. Menos bugs. +* **Robusto**: Obtén código listo para producción. Con documentación interactiva automática. +* **Basado en estándares**: Basado (y completamente compatible) con los estándares abiertos para APIs: OpenAPI (anteriormente conocido como Swagger) y JSON Schema. -* Esta estimación está basada en pruebas con un equipo de desarrollo interno construyendo aplicaciones listas para producción. +* estimación basada en pruebas con un equipo de desarrollo interno, construyendo aplicaciones de producción. ## Sponsors @@ -64,41 +67,47 @@ Sus características principales son: ## Opiniones -"_[...] I'm using **FastAPI** a ton these days. [...] I'm actually planning to use it for all of my team's **ML services at Microsoft**. Some of them are getting integrated into the core **Windows** product and some **Office** products._" +"_[...] Estoy usando **FastAPI** un montón estos días. [...] De hecho, estoy planeando usarlo para todos los servicios de **ML de mi equipo en Microsoft**. Algunos de ellos se están integrando en el núcleo del producto **Windows** y algunos productos de **Office**._"uvicorn main:app --reload
...fastapi dev main.py
...email_validator
- para validación de emails.
+* email-validator
- para validación de correos electrónicos.
+
+Usadas por Starlette:
+
+* httpx
- Requerido si deseas usar el `TestClient`.
+* jinja2
- Requerido si deseas usar la configuración de plantilla predeterminada.
+* python-multipart
- Requerido si deseas soportar "parsing" de forms, con `request.form()`.
+
+Usadas por FastAPI / Starlette:
+
+* uvicorn
- para el servidor que carga y sirve tu aplicación. Esto incluye `uvicorn[standard]`, que incluye algunas dependencias (por ejemplo, `uvloop`) necesarias para servir con alto rendimiento.
+* `fastapi-cli` - para proporcionar el comando `fastapi`.
+
+### Sin Dependencias `standard`
+
+Si no deseas incluir las dependencias opcionales `standard`, puedes instalar con `pip install fastapi` en lugar de `pip install "fastapi[standard]"`.
+
+### Dependencias Opcionales Adicionales
-Usados por Starlette:
+Existen algunas dependencias adicionales que podrías querer instalar.
-* httpx
- Requerido si quieres usar el `TestClient`.
-* jinja2
- Requerido si quieres usar la configuración por defecto de templates.
-* python-multipart
- Requerido si quieres dar soporte a "parsing" de formularios, con `request.form()`.
-* itsdangerous
- Requerido para dar soporte a `SessionMiddleware`.
-* pyyaml
- Requerido para dar soporte al `SchemaGenerator` de Starlette (probablemente no lo necesites con FastAPI).
-* graphene
- Requerido para dar soporte a `GraphQLApp`.
+Dependencias opcionales adicionales de Pydantic:
-Usado por FastAPI / Starlette:
+* pydantic-settings
- para la gestión de configuraciones.
+* pydantic-extra-types
- para tipos extra para ser usados con Pydantic.
-* uvicorn
- para el servidor que carga y sirve tu aplicación.
-* orjson
- Requerido si quieres usar `ORJSONResponse`.
-* ujson
- Requerido si quieres usar `UJSONResponse`.
+Dependencias opcionales adicionales de FastAPI:
-Puedes instalarlos con `pip install fastapi[all]`.
+* orjson
- Requerido si deseas usar `ORJSONResponse`.
+* ujson
- Requerido si deseas usar `UJSONResponse`.
## Licencia
-Este proyecto está licenciado bajo los términos de la licencia del MIT.
+Este proyecto tiene licencia bajo los términos de la licencia MIT.
diff --git a/docs/es/docs/learn/index.md b/docs/es/docs/learn/index.md
index b8d26cf34..cc6c7cc3f 100644
--- a/docs/es/docs/learn/index.md
+++ b/docs/es/docs/learn/index.md
@@ -1,5 +1,5 @@
-# Aprender
+# Aprende
Aquí están las secciones introductorias y los tutoriales para aprender **FastAPI**.
-Podrías considerar esto como un **libro**, un **curso**, la forma **oficial** y recomendada de aprender FastAPI. 😎
+Podrías considerar esto un **libro**, un **curso**, la forma **oficial** y recomendada de aprender FastAPI. 😎
diff --git a/docs/es/docs/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..559995151
--- /dev/null
+++ b/docs/es/docs/project-generation.md
@@ -0,0 +1,28 @@
+# Plantilla Full Stack FastAPI
+
+Las plantillas, aunque normalmente vienen con una configuración específica, están diseñadas para ser flexibles y personalizables. Esto te permite modificarlas y adaptarlas a los requisitos de tu proyecto, haciéndolas un excelente punto de partida. 🏁
+
+Puedes usar esta plantilla para comenzar, ya que incluye gran parte de la configuración inicial, seguridad, base de datos y algunos endpoints de API ya hechos para ti.
+
+Repositorio de GitHub: Plantilla Full Stack FastAPI
+
+## Plantilla Full Stack FastAPI - Tecnología y Funcionalidades
+
+- ⚡ [**FastAPI**](https://fastapi.tiangolo.com) para la API del backend en Python.
+ - 🧰 [SQLModel](https://sqlmodel.tiangolo.com) para las interacciones con bases de datos SQL en Python (ORM).
+ - 🔍 [Pydantic](https://docs.pydantic.dev), utilizado por FastAPI, para la validación de datos y gestión de configuraciones.
+ - 💾 [PostgreSQL](https://www.postgresql.org) como base de datos SQL.
+- 🚀 [React](https://react.dev) para el frontend.
+ - 💃 Usando TypeScript, hooks, [Vite](https://vitejs.dev), y otras partes de una stack moderna de frontend.
+ - 🎨 [Chakra UI](https://chakra-ui.com) para los componentes del frontend.
+ - 🤖 Un cliente de frontend generado automáticamente.
+ - 🧪 [Playwright](https://playwright.dev) para pruebas End-to-End.
+ - 🦇 Soporte para modo oscuro.
+- 🐋 [Docker Compose](https://www.docker.com) para desarrollo y producción.
+- 🔒 Hashing seguro de contraseñas por defecto.
+- 🔑 Autenticación con tokens JWT.
+- 📫 Recuperación de contraseñas basada en email.
+- ✅ Pruebas con [Pytest](https://pytest.org).
+- 📞 [Traefik](https://traefik.io) como proxy inverso / balanceador de carga.
+- 🚢 Instrucciones de despliegue usando Docker Compose, incluyendo cómo configurar un proxy Traefik frontend para manejar certificados HTTPS automáticos.
+- 🏭 CI (integración continua) y CD (despliegue continuo) basados en GitHub Actions.
diff --git a/docs/es/docs/python-types.md b/docs/es/docs/python-types.md
index 89edbb31e..769204f8f 100644
--- a/docs/es/docs/python-types.md
+++ b/docs/es/docs/python-types.md
@@ -1,29 +1,30 @@
-# Introducción a los Tipos de Python
+# Introducción a Tipos en Python
-**Python 3.6+** tiene soporte para "type hints" opcionales.
+Python tiene soporte para "anotaciones de tipos" opcionales (también llamadas "type hints").
-Estos **type hints** son una nueva sintaxis, desde Python 3.6+, que permite declarar el tipo de una variable.
+Estas **"anotaciones de tipos"** o type hints son una sintaxis especial que permite declarar el tipo de una variable.
-Usando las declaraciones de tipos para tus variables, los editores y otras herramientas pueden proveerte un soporte mejor.
+Al declarar tipos para tus variables, los editores y herramientas te pueden proporcionar un mejor soporte.
-Este es solo un **tutorial corto** sobre los Python type hints. Solo cubre lo mínimo necesario para usarlos con **FastAPI**... realmente es muy poco lo que necesitas.
+Este es solo un **tutorial rápido / recordatorio** sobre las anotaciones de tipos en Python. Cubre solo lo mínimo necesario para usarlas con **FastAPI**... que en realidad es muy poco.
-Todo **FastAPI** está basado en estos type hints, lo que le da muchas ventajas y beneficios.
+**FastAPI** se basa completamente en estas anotaciones de tipos, dándole muchas ventajas y beneficios.
-Pero, así nunca uses **FastAPI** te beneficiarás de aprender un poco sobre los type hints.
+Pero incluso si nunca usas **FastAPI**, te beneficiaría aprender un poco sobre ellas.
-!!! note "Nota"
- Si eres un experto en Python y ya lo sabes todo sobre los type hints, salta al siguiente capítulo.
+/// note | Nota
+
+Si eres un experto en Python, y ya sabes todo sobre las anotaciones de tipos, salta al siguiente capítulo.
+
+///
## Motivación
Comencemos con un ejemplo simple:
-```Python
-{!../../../docs_src/python_types/tutorial001.py!}
-```
+{* ../../docs_src/python_types/tutorial001.py *}
-Llamar este programa nos muestra el siguiente output:
+Llamar a este programa genera:
```
John Doe
@@ -31,39 +32,37 @@ John Doe
La función hace lo siguiente:
-* Toma un `first_name` y un `last_name`.
-* Convierte la primera letra de cada uno en una letra mayúscula con `title()`.
-* Las concatena con un espacio en la mitad.
+* Toma un `first_name` y `last_name`.
+* Convierte la primera letra de cada uno a mayúsculas con `title()`.
+* Concatena ambos con un espacio en el medio.
-```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial001.py!}
-```
+{* ../../docs_src/python_types/tutorial001.py hl[2] *}
### Edítalo
Es un programa muy simple.
-Ahora, imagina que lo estás escribiendo desde ceros.
+Pero ahora imagina que lo escribieras desde cero.
-En algún punto habrías comenzado con la definición de la función, tenías los parámetros listos...
+En algún momento habrías empezado la definición de la función, tenías los parámetros listos...
-Pero, luego tienes que llamar "ese método que convierte la primera letra en una mayúscula".
+Pero luego tienes que llamar "ese método que convierte la primera letra a mayúscula".
-Era `upper`? O era `uppercase`? `first_uppercase`? `capitalize`?
+¿Era `upper`? ¿Era `uppercase`? `first_uppercase`? `capitalize`?
-Luego lo intentas con el viejo amigo de los programadores, el auto-completado del editor.
+Entonces, pruebas con el amigo del viejo programador, el autocompletado del editor.
-Escribes el primer parámetro de la función `first_name`, luego un punto (`.`) y luego presionas `Ctrl+Space` para iniciar el auto-completado.
+Escribes el primer parámetro de la función, `first_name`, luego un punto (`.`) y luego presionas `Ctrl+Espacio` para activar el autocompletado.
-Tristemente, no obtienes nada útil:
+Pero, tristemente, no obtienes nada útil:
-get
+* usando una get
operation
-!!! 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` en Python se llama un "decorador".
- Un "decorador" toma la función que tiene debajo y hace algo con ella.
+Lo pones encima de una función. Como un bonito sombrero decorativo (supongo que de ahí viene el término).
- 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 de abajo 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 de abajo corresponde al **path** `/` con una **operation** `get`.
+
+Es el "**path operation decorator**".
+
+///
También puedes usar las otras operaciones:
@@ -267,67 +265,67 @@ También puedes usar las otras operaciones:
* `@app.put()`
* `@app.delete()`
-y las más exóticas:
+Y los más exóticos:
* `@app.options()`
* `@app.head()`
* `@app.patch()`
* `@app.trace()`
-!!! tip "Consejo"
- Tienes la libertad de usar cada operación (método de HTTP) como quieras.
+/// tip
+
+Eres libre de usar cada operación (método HTTP) como quieras.
- **FastAPI** no impone ningún significado específico.
+**FastAPI** no fuerza ningún significado específico.
- La información que está presentada aquí es una guía, no un requerimiento.
+La información aquí se presenta como una guía, no un requisito.
- Por ejemplo, cuando usas GraphQL normalmente realizas todas las acciones usando únicamente operaciones `POST`.
+Por ejemplo, cuando usas GraphQL normalmente realizas todas las acciones usando solo operaciones `POST`.
-### Paso 4: define la **función de la operación de path**
+///
-Esta es nuestra "**función de la operación de path**":
+### Paso 4: define la **path operation function**
+
+Esta es nuestra "**path operation function**":
* **path**: es `/`.
-* **operación**: es `get`.
-* **función**: es la función debajo del "decorador" (debajo de `@app.get("/")`).
+* **operation**: es `get`.
+* **function**: es la función debajo del "decorador" (debajo de `@app.get("/")`).
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[7] *}
-Esto es una función de Python.
+Esta es una función de Python.
-Esta función será llamada por **FastAPI** cada vez que reciba un request en la URL "`/`" usando una operación `GET`.
+Será llamada por **FastAPI** cuando reciba un request en la URL "`/`" usando una operación `GET`.
-En este caso es una función `async`.
+En este caso, es una función `async`.
---
-También podrías definirla como una función estándar en lugar de `async def`:
+También podrías definirla como una función normal en lugar de `async def`:
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial003.py!}
-```
+{* ../../docs_src/first_steps/tutorial003.py hl[7] *}
-!!! note "Nota"
- Si no sabes la diferencia, revisa el [Async: *"¿Tienes prisa?"*](../async.md#tienes-prisa){.internal-link target=_blank}.
+/// note | Nota
-### Paso 5: devuelve el contenido
+Si no sabes la diferencia, revisa la sección [Async: *"¿Tienes prisa?"*](../async.md#in-a-hurry){.internal-link target=_blank}.
-```Python hl_lines="8"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+///
+
+### Paso 5: retorna el contenido
+
+{* ../../docs_src/first_steps/tutorial001.py hl[8] *}
-Puedes devolver `dict`, `list`, valores singulares como un `str`, `int`, etc.
+Puedes retornar un `dict`, `list`, valores singulares como `str`, `int`, etc.
-También puedes devolver modelos de Pydantic (ya verás más sobre esto más adelante).
+También puedes retornar modelos de Pydantic (verás más sobre eso más adelante).
-Hay muchos objetos y modelos que pueden ser convertidos automáticamente a JSON (incluyendo ORMs, etc.). Intenta usar tus favoritos, es muy probable que ya tengan soporte.
+Hay muchos otros objetos y modelos que serán automáticamente convertidos a JSON (incluyendo ORMs, etc). Intenta usar tus favoritos, es altamente probable que ya sean compatibles.
-## Repaso
+## Recapitulación
* Importa `FastAPI`.
-* Crea un instance de `app`.
-* Escribe un **decorador de operación de path** (como `@app.get("/")`).
-* Escribe una **función de la operación de path** (como `def root(): ...` arriba).
-* Corre el servidor de desarrollo (como `uvicorn main:app --reload`).
+* Crea una instancia `app`.
+* Escribe un **path operation decorator** usando decoradores como `@app.get("/")`.
+* Define una **path operation function**; por ejemplo, `def root(): ...`.
+* Ejecuta el servidor de desarrollo usando el comando `fastapi dev`.
diff --git a/docs/es/docs/tutorial/handling-errors.md b/docs/es/docs/tutorial/handling-errors.md
new file mode 100644
index 000000000..2e4464989
--- /dev/null
+++ b/docs/es/docs/tutorial/handling-errors.md
@@ -0,0 +1,255 @@
+# Manejo de Errores
+
+Existen muchas situaciones en las que necesitas notificar un error a un cliente que está usando tu API.
+
+Este cliente podría ser un navegador con un frontend, un código de otra persona, un dispositivo IoT, etc.
+
+Podrías necesitar decirle al cliente que:
+
+* El cliente no tiene suficientes privilegios para esa operación.
+* El cliente no tiene acceso a ese recurso.
+* El ítem al que el cliente intentaba acceder no existe.
+* etc.
+
+En estos casos, normalmente devolverías un **código de estado HTTP** en el rango de **400** (de 400 a 499).
+
+Esto es similar a los códigos de estado HTTP 200 (de 200 a 299). Esos códigos de estado "200" significan que de alguna manera hubo un "éxito" en el request.
+
+Los códigos de estado en el rango de 400 significan que hubo un error por parte del cliente.
+
+¿Recuerdas todos esos errores de **"404 Not Found"** (y chistes)?
+
+## Usa `HTTPException`
+
+Para devolver responses HTTP con errores al cliente, usa `HTTPException`.
+
+### Importa `HTTPException`
+
+{* ../../docs_src/handling_errors/tutorial001.py hl[1] *}
+
+### Lanza un `HTTPException` en tu código
+
+`HTTPException` es una excepción de Python normal con datos adicionales relevantes para APIs.
+
+Debido a que es una excepción de Python, no la `return`, sino que la `raise`.
+
+Esto también significa que si estás dentro de una función de utilidad que estás llamando dentro de tu *path operation function*, y lanzas el `HTTPException` desde dentro de esa función de utilidad, no se ejecutará el resto del código en la *path operation function*, terminará ese request de inmediato y enviará el error HTTP del `HTTPException` al cliente.
+
+El beneficio de lanzar una excepción en lugar de `return`ar un valor será más evidente en la sección sobre Dependencias y Seguridad.
+
+En este ejemplo, cuando el cliente solicita un ítem por un ID que no existe, lanza una excepción con un código de estado de `404`:
+
+{* ../../docs_src/handling_errors/tutorial001.py hl[11] *}
+
+### El response resultante
+
+Si el cliente solicita `http://example.com/items/foo` (un `item_id` `"foo"`), ese cliente recibirá un código de estado HTTP de 200, y un response JSON de:
+
+```JSON
+{
+ "item": "The Foo Wrestlers"
+}
+```
+
+Pero si el cliente solicita `http://example.com/items/bar` (un `item_id` inexistente `"bar"`), ese cliente recibirá un código de estado HTTP de 404 (el error "no encontrado"), y un response JSON de:
+
+```JSON
+{
+ "detail": "Item not found"
+}
+```
+
+/// tip | Consejo
+
+Cuando lanzas un `HTTPException`, puedes pasar cualquier valor que pueda convertirse a JSON como el parámetro `detail`, no solo `str`.
+
+Podrías pasar un `dict`, un `list`, etc.
+
+Son manejados automáticamente por **FastAPI** y convertidos a JSON.
+
+///
+
+## Agrega headers personalizados
+
+Existen algunas situaciones en las que es útil poder agregar headers personalizados al error HTTP. Por ejemplo, para algunos tipos de seguridad.
+
+Probablemente no necesitarás usarlos directamente en tu código.
+
+Pero en caso de que los necesites para un escenario avanzado, puedes agregar headers personalizados:
+
+{* ../../docs_src/handling_errors/tutorial002.py hl[14] *}
+
+## Instalar manejadores de excepciones personalizados
+
+Puedes agregar manejadores de excepciones personalizados con las mismas utilidades de excepciones de Starlette.
+
+Supongamos que tienes una excepción personalizada `UnicornException` que tú (o un paquete que usas) podría lanzar.
+
+Y quieres manejar esta excepción globalmente con FastAPI.
+
+Podrías agregar un manejador de excepciones personalizado con `@app.exception_handler()`:
+
+{* ../../docs_src/handling_errors/tutorial003.py hl[5:7,13:18,24] *}
+
+Aquí, si solicitas `/unicorns/yolo`, la *path operation* lanzará un `UnicornException`.
+
+Pero será manejado por el `unicorn_exception_handler`.
+
+Así que recibirás un error limpio, con un código de estado HTTP de `418` y un contenido JSON de:
+
+```JSON
+{"message": "Oops! yolo did something. There goes a rainbow..."}
+```
+
+/// note | Nota Técnica
+
+También podrías usar `from starlette.requests import Request` y `from starlette.responses import JSONResponse`.
+
+**FastAPI** ofrece las mismas `starlette.responses` como `fastapi.responses` solo como una conveniencia para ti, el desarrollador. Pero la mayoría de los responses disponibles vienen directamente de Starlette. Lo mismo con `Request`.
+
+///
+
+## Sobrescribir los manejadores de excepciones predeterminados
+
+**FastAPI** tiene algunos manejadores de excepciones predeterminados.
+
+Estos manejadores se encargan de devolver los responses JSON predeterminadas cuando lanzas un `HTTPException` y cuando el request tiene datos inválidos.
+
+Puedes sobrescribir estos manejadores de excepciones con los tuyos propios.
+
+### Sobrescribir excepciones de validación de request
+
+Cuando un request contiene datos inválidos, **FastAPI** lanza internamente un `RequestValidationError`.
+
+Y también incluye un manejador de excepciones predeterminado para ello.
+
+Para sobrescribirlo, importa el `RequestValidationError` y úsalo con `@app.exception_handler(RequestValidationError)` para decorar el manejador de excepciones.
+
+El manejador de excepciones recibirá un `Request` y la excepción.
+
+{* ../../docs_src/handling_errors/tutorial004.py hl[2,14:16] *}
+
+Ahora, si vas a `/items/foo`, en lugar de obtener el error JSON por defecto con:
+
+```JSON
+{
+ "detail": [
+ {
+ "loc": [
+ "path",
+ "item_id"
+ ],
+ "msg": "value is not a valid integer",
+ "type": "type_error.integer"
+ }
+ ]
+}
+```
+
+obtendrás una versión en texto, con:
+
+```
+1 validation error
+path -> item_id
+ value is not a valid integer (type=type_error.integer)
+```
+
+#### `RequestValidationError` vs `ValidationError`
+
+/// warning | Advertencia
+
+Estos son detalles técnicos que podrías omitir si no es importante para ti en este momento.
+
+///
+
+`RequestValidationError` es una subclase de `ValidationError` de Pydantic.
+
+**FastAPI** la usa para que, si usas un modelo Pydantic en `response_model`, y tus datos tienen un error, lo verás en tu log.
+
+Pero el cliente/usuario no lo verá. En su lugar, el cliente recibirá un "Error Interno del Servidor" con un código de estado HTTP `500`.
+
+Debería ser así porque si tienes un `ValidationError` de Pydantic en tu *response* o en cualquier lugar de tu código (no en el *request* del cliente), en realidad es un bug en tu código.
+
+Y mientras lo arreglas, tus clientes/usuarios no deberían tener acceso a información interna sobre el error, ya que eso podría exponer una vulnerabilidad de seguridad.
+
+### Sobrescribir el manejador de errores de `HTTPException`
+
+De la misma manera, puedes sobrescribir el manejador de `HTTPException`.
+
+Por ejemplo, podrías querer devolver un response de texto plano en lugar de JSON para estos errores:
+
+{* ../../docs_src/handling_errors/tutorial004.py hl[3:4,9:11,22] *}
+
+/// note | Nota Técnica
+
+También podrías usar `from starlette.responses import PlainTextResponse`.
+
+**FastAPI** ofrece las mismas `starlette.responses` como `fastapi.responses` solo como una conveniencia para ti, el desarrollador. Pero la mayoría de los responses disponibles vienen directamente de Starlette.
+
+///
+
+### Usar el body de `RequestValidationError`
+
+El `RequestValidationError` contiene el `body` que recibió con datos inválidos.
+
+Podrías usarlo mientras desarrollas tu aplicación para registrar el body y depurarlo, devolverlo al usuario, etc.
+
+{* ../../docs_src/handling_errors/tutorial005.py hl[14] *}
+
+Ahora intenta enviar un ítem inválido como:
+
+```JSON
+{
+ "title": "towel",
+ "size": "XL"
+}
+```
+
+Recibirás un response que te dirá que los datos son inválidos conteniendo el body recibido:
+
+```JSON hl_lines="12-15"
+{
+ "detail": [
+ {
+ "loc": [
+ "body",
+ "size"
+ ],
+ "msg": "value is not a valid integer",
+ "type": "type_error.integer"
+ }
+ ],
+ "body": {
+ "title": "towel",
+ "size": "XL"
+ }
+}
+```
+
+#### `HTTPException` de FastAPI vs `HTTPException` de Starlette
+
+**FastAPI** tiene su propio `HTTPException`.
+
+Y la clase de error `HTTPException` de **FastAPI** hereda de la clase de error `HTTPException` de Starlette.
+
+La única diferencia es que el `HTTPException` de **FastAPI** acepta cualquier dato JSON-able para el campo `detail`, mientras que el `HTTPException` de Starlette solo acepta strings para ello.
+
+Así que puedes seguir lanzando un `HTTPException` de **FastAPI** como de costumbre en tu código.
+
+Pero cuando registras un manejador de excepciones, deberías registrarlo para el `HTTPException` de Starlette.
+
+De esta manera, si alguna parte del código interno de Starlette, o una extensión o complemento de Starlette, lanza un `HTTPException` de Starlette, tu manejador podrá capturarlo y manejarlo.
+
+En este ejemplo, para poder tener ambos `HTTPException` en el mismo código, las excepciones de Starlette son renombradas a `StarletteHTTPException`:
+
+```Python
+from starlette.exceptions import HTTPException as StarletteHTTPException
+```
+
+### Reutilizar los manejadores de excepciones de **FastAPI**
+
+Si quieres usar la excepción junto con los mismos manejadores de excepciones predeterminados de **FastAPI**, puedes importar y reutilizar los manejadores de excepciones predeterminados de `fastapi.exception_handlers`:
+
+{* ../../docs_src/handling_errors/tutorial006.py hl[2:5,15,21] *}
+
+En este ejemplo solo estás `print`eando el error con un mensaje muy expresivo, pero te haces una idea. Puedes usar la excepción y luego simplemente reutilizar los manejadores de excepciones predeterminados.
diff --git a/docs/es/docs/tutorial/header-param-models.md b/docs/es/docs/tutorial/header-param-models.md
new file mode 100644
index 000000000..3676231e6
--- /dev/null
+++ b/docs/es/docs/tutorial/header-param-models.md
@@ -0,0 +1,56 @@
+# Modelos de Parámetros de Header
+
+Si tienes un grupo de **parámetros de header** relacionados, puedes crear un **modelo Pydantic** para declararlos.
+
+Esto te permitirá **reutilizar el modelo** en **múltiples lugares** y también declarar validaciones y metadatos para todos los parámetros al mismo tiempo. 😎
+
+/// note | Nota
+
+Esto es compatible desde la versión `0.115.0` de FastAPI. 🤓
+
+///
+
+## Parámetros de Header con un Modelo Pydantic
+
+Declara los **parámetros de header** que necesitas en un **modelo Pydantic**, y luego declara el parámetro como `Header`:
+
+{* ../../docs_src/header_param_models/tutorial001_an_py310.py hl[9:14,18] *}
+
+**FastAPI** **extraerá** los datos para **cada campo** de los **headers** en el request y te dará el modelo Pydantic que definiste.
+
+## Revisa la Documentación
+
+Puedes ver los headers requeridos en la interfaz de documentación en `/docs`:
+
+contact
fieldsParámetro | Tipo | Descripción |
---|---|---|
name | str | El nombre identificativo de la persona/organización de contacto. |
url | str | La URL que apunta a la información de contacto. DEBE tener el formato de una URL. |
email | str | La dirección de correo electrónico de la persona/organización de contacto. DEBE tener el formato de una dirección de correo. |
license_info
fieldsParámetro | Tipo | Descripción |
---|---|---|
name | str | REQUERIDO (si se establece un license_info ). El nombre de la licencia utilizada para la API. |
identifier | str | Una expresión de licencia SPDX para la API. El campo identifier es mutuamente excluyente del campo url . Disponible desde OpenAPI 3.1.0, FastAPI 0.99.0. |
url | str | Una URL a la licencia utilizada para la API. DEBE tener el formato de una URL. |
kwargs
. Incluso si no tienen un valor por defecto.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *}
+
+### Mejor con `Annotated`
+
+Ten en cuenta que si usas `Annotated`, como no estás usando valores por defecto de los parámetros de la función, no tendrás este problema y probablemente no necesitarás usar `*`.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py hl[10] *}
+
+## Validaciones numéricas: mayor o igual
+
+Con `Query` y `Path` (y otros que verás más adelante) puedes declarar restricciones numéricas.
+
+Aquí, con `ge=1`, `item_id` necesitará ser un número entero "`g`reater than or `e`qual" a `1`.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py hl[10] *}
+
+## Validaciones numéricas: mayor que y menor o igual
+
+Lo mismo aplica para:
+
+* `gt`: `g`reater `t`han
+* `le`: `l`ess than or `e`qual
+
+{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py hl[10] *}
+
+## Validaciones numéricas: flotantes, mayor y menor
+
+Las validaciones numéricas también funcionan para valores `float`.
+
+Aquí es donde se convierte en importante poder declarar gt
y no solo ge
. Ya que con esto puedes requerir, por ejemplo, que un valor sea mayor que `0`, incluso si es menor que `1`.
+
+Así, `0.5` sería un valor válido. Pero `0.0` o `0` no lo serían.
+
+Y lo mismo para lt
.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py hl[13] *}
+
+## Resumen
+
+Con `Query`, `Path` (y otros que aún no has visto) puedes declarar metadatos y validaciones de string de las mismas maneras que con [Parámetros de Query y Validaciones de String](query-params-str-validations.md){.internal-link target=_blank}.
+
+Y también puedes declarar validaciones numéricas:
+
+* `gt`: `g`reater `t`han
+* `ge`: `g`reater than or `e`qual
+* `lt`: `l`ess `t`han
+* `le`: `l`ess than or `e`qual
+
+/// info | Información
+
+`Query`, `Path` y otras clases que verás más adelante son subclases de una clase común `Param`.
+
+Todas ellas comparten los mismos parámetros para validación adicional y metadatos que has visto.
+
+///
+
+/// note | Nota técnica
+
+Cuando importas `Query`, `Path` y otros de `fastapi`, en realidad son funciones.
+
+Que cuando se llaman, retornan instances de clases con el mismo nombre.
+
+Así que importas `Query`, que es una función. Y cuando la llamas, retorna una instance de una clase también llamada `Query`.
+
+Estas funciones están allí (en lugar de usar simplemente las clases directamente) para que tu editor no marque errores sobre sus tipos.
+
+De esa forma puedes usar tu editor y herramientas de programación normales sin tener que agregar configuraciones personalizadas para omitir esos errores.
+
+///
diff --git a/docs/es/docs/tutorial/path-params.md b/docs/es/docs/tutorial/path-params.md
index 7faa92f51..12a1b647b 100644
--- a/docs/es/docs/tutorial/path-params.md
+++ b/docs/es/docs/tutorial/path-params.md
@@ -1,14 +1,12 @@
-# Parámetros de path
+# Parámetros de Path
-Puedes declarar los "parámetros" o "variables" con la misma sintaxis que usan los format strings de Python:
+Puedes declarar "parámetros" o "variables" de path con la misma sintaxis que se usa en los format strings de Python:
-```Python hl_lines="6-7"
-{!../../../docs_src/path_params/tutorial001.py!}
-```
+{* ../../docs_src/path_params/tutorial001.py hl[6:7] *}
-El valor del parámetro de path `item_id` será pasado a tu función como el argumento `item_id`.
+El valor del parámetro de path `item_id` se pasará a tu función como el argumento `item_id`.
-Entonces, si corres este ejemplo y vas a http://127.0.0.1:8000/items/foo, verás una respuesta de:
+Así que, si ejecutas este ejemplo y vas a http://127.0.0.1:8000/items/foo, verás un response de:
```JSON
{"item_id":"foo"}
@@ -16,175 +14,190 @@ Entonces, si corres este ejemplo y vas a Conversión de datos
+## Conversión de datos
-Si corres este ejemplo y abres tu navegador en http://127.0.0.1:8000/items/3 verás una respuesta de:
+Si ejecutas este ejemplo y abres tu navegador en http://127.0.0.1:8000/items/3, verás un response de:
```JSON
{"item_id":3}
```
-!!! check "Revisa"
- Observa que el valor que recibió (y devolvió) tu función es `3`, como un Python `int`, y no un string `"3"`.
+/// check | Revisa
- Entonces, con esa declaración de tipos **FastAPI** te da "parsing" automático del request.
+Nota que el valor que tu función recibió (y devolvió) es `3`, como un `int` de Python, no un string `"3"`.
+
+Entonces, con esa declaración de tipo, **FastAPI** te ofrece "parsing" automático de requests.
+
+///
## Validación de datos
-Pero si abres tu navegador en http://127.0.0.1:8000/items/foo verás este lindo error de HTTP:
+Pero si vas al navegador en http://127.0.0.1:8000/items/foo, verás un bonito error HTTP de:
```JSON
{
- "detail": [
- {
- "loc": [
- "path",
- "item_id"
- ],
- "msg": "value is not a valid integer",
- "type": "type_error.integer"
- }
- ]
+ "detail": [
+ {
+ "type": "int_parsing",
+ "loc": [
+ "path",
+ "item_id"
+ ],
+ "msg": "Input should be a valid integer, unable to parse string as an integer",
+ "input": "foo",
+ "url": "https://errors.pydantic.dev/2.1/v/int_parsing"
+ }
+ ]
}
```
-debido a que el parámetro de path `item_id` tenía el valor `"foo"`, que no es un `int`.
+porque el parámetro de path `item_id` tenía un valor de `"foo"`, que no es un `int`.
+
+El mismo error aparecería si proporcionaras un `float` en lugar de un `int`, como en: http://127.0.0.1:8000/items/4.2
-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
-!!! check "Revisa"
- Así, con la misma declaración de tipo de Python, **FastAPI** te da validación de datos.
+Entonces, con la misma declaración de tipo de Python, **FastAPI** te ofrece validación de datos.
- Observa que el error también muestra claramente el punto exacto en el que no pasó la validación.
+Nota que el error también indica claramente el punto exacto donde la validación falló.
- Esto es increíblemente útil cuando estás desarrollando y debugging código que interactúa con tu API.
+Esto es increíblemente útil mientras desarrollas y depuras código que interactúa con tu API.
+
+///
## Documentación
-Cuando abras tu navegador en http://127.0.0.1:8000/docs verás la documentación automática e interactiva del API como:
+Y cuando abras tu navegador en http://127.0.0.1:8000/docs, verás una documentación de API automática e interactiva como:
POST
.
+
+///
+
+/// warning | Advertencia
+
+Puedes declarar múltiples parámetros `File` y `Form` en una *path operation*, pero no puedes declarar campos `Body` que esperas recibir como JSON, ya que el request tendrá el cuerpo codificado usando `multipart/form-data` en lugar de `application/json`.
+
+Esto no es una limitación de **FastAPI**, es parte del protocolo HTTP.
+
+///
+
+## Subida de Archivos Opcional
+
+Puedes hacer un archivo opcional utilizando anotaciones de tipos estándar y estableciendo un valor por defecto de `None`:
+
+{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *}
+
+## `UploadFile` con Metadatos Adicionales
+
+También puedes usar `File()` con `UploadFile`, por ejemplo, para establecer metadatos adicionales:
+
+{* ../../docs_src/request_files/tutorial001_03_an_py39.py hl[9,15] *}
+
+## Subidas de Múltiples Archivos
+
+Es posible subir varios archivos al mismo tiempo.
+
+Estarían asociados al mismo "campo de formulario" enviado usando "form data".
+
+Para usar eso, declara una lista de `bytes` o `UploadFile`:
+
+{* ../../docs_src/request_files/tutorial002_an_py39.py hl[10,15] *}
+
+Recibirás, como se declaró, una `list` de `bytes` o `UploadFile`s.
+
+/// note | Detalles Técnicos
+
+También podrías usar `from starlette.responses import HTMLResponse`.
+
+**FastAPI** proporciona las mismas `starlette.responses` como `fastapi.responses` solo como una conveniencia para ti, el desarrollador. Pero la mayoría de los responses disponibles vienen directamente de Starlette.
+
+///
+
+### Subidas de Múltiples Archivos con Metadatos Adicionales
+
+Y de la misma manera que antes, puedes usar `File()` para establecer parámetros adicionales, incluso para `UploadFile`:
+
+{* ../../docs_src/request_files/tutorial003_an_py39.py hl[11,18:20] *}
+
+## Recapitulación
+
+Usa `File`, `bytes` y `UploadFile` para declarar archivos que se subirán en el request, enviados como form data.
diff --git a/docs/es/docs/tutorial/request-form-models.md b/docs/es/docs/tutorial/request-form-models.md
new file mode 100644
index 000000000..9d5d7495a
--- /dev/null
+++ b/docs/es/docs/tutorial/request-form-models.md
@@ -0,0 +1,78 @@
+# Modelos de Formulario
+
+Puedes usar **modelos de Pydantic** para declarar **campos de formulario** en FastAPI.
+
+/// info | Información
+
+Para usar formularios, primero instala `python-multipart`.
+
+Asegúrate de crear un [entorno virtual](../virtual-environments.md){.internal-link target=_blank}, activarlo, y luego instalarlo, por ejemplo:
+
+```console
+$ pip install python-multipart
+```
+
+///
+
+/// note | Nota
+
+Esto es compatible desde la versión `0.113.0` de FastAPI. 🤓
+
+///
+
+## Modelos de Pydantic para Formularios
+
+Solo necesitas declarar un **modelo de Pydantic** con los campos que quieres recibir como **campos de formulario**, y luego declarar el parámetro como `Form`:
+
+{* ../../docs_src/request_form_models/tutorial001_an_py39.py hl[9:11,15] *}
+
+**FastAPI** **extraerá** los datos de **cada campo** de los **form data** en el request y te dará el modelo de Pydantic que definiste.
+
+## Revisa la Documentación
+
+Puedes verificarlo en la interfaz de documentación en `/docs`:
+
+POST
.
+
+///
+
+/// warning | Advertencia
+
+Puedes declarar múltiples parámetros `Form` en una *path operation*, pero no puedes también declarar campos `Body` que esperas recibir como JSON, ya que el request tendrá el body codificado usando `application/x-www-form-urlencoded` en lugar de `application/json`.
+
+Esto no es una limitación de **FastAPI**, es parte del protocolo HTTP.
+
+///
+
+## Recapitulación
+
+Usa `Form` para declarar parámetros de entrada de datos de formulario.
diff --git a/docs/es/docs/tutorial/response-model.md b/docs/es/docs/tutorial/response-model.md
new file mode 100644
index 000000000..09682f51b
--- /dev/null
+++ b/docs/es/docs/tutorial/response-model.md
@@ -0,0 +1,357 @@
+# Modelo de Response - Tipo de Retorno
+
+Puedes declarar el tipo utilizado para el response anotando el **tipo de retorno** de la *path operation function*.
+
+Puedes utilizar **anotaciones de tipos** de la misma manera que lo harías para datos de entrada en **parámetros** de función, puedes utilizar modelos de Pydantic, listas, diccionarios, valores escalares como enteros, booleanos, etc.
+
+{* ../../docs_src/response_model/tutorial001_01_py310.py hl[16,21] *}
+
+FastAPI usará este tipo de retorno para:
+
+* **Validar** los datos devueltos.
+ * Si los datos son inválidos (por ejemplo, falta un campo), significa que el código de *tu* aplicación está defectuoso, no devolviendo lo que debería, y retornará un error del servidor en lugar de devolver datos incorrectos. De esta manera, tú y tus clientes pueden estar seguros de que recibirán los datos y la forma de los datos esperada.
+* Agregar un **JSON Schema** para el response, en la *path operation* de OpenAPI.
+ * Esto será utilizado por la **documentación automática**.
+ * También será utilizado por herramientas de generación automática de código de cliente.
+
+Pero lo más importante:
+
+* **Limitará y filtrará** los datos de salida a lo que se define en el tipo de retorno.
+ * Esto es particularmente importante para la **seguridad**, veremos más sobre eso a continuación.
+
+## Parámetro `response_model`
+
+Hay algunos casos en los que necesitas o quieres devolver algunos datos que no son exactamente lo que declara el tipo.
+
+Por ejemplo, podrías querer **devolver un diccionario** u objeto de base de datos, pero **declararlo como un modelo de Pydantic**. De esta manera el modelo de Pydantic haría toda la documentación de datos, validación, etc. para el objeto que devolviste (por ejemplo, un diccionario u objeto de base de datos).
+
+Si añadiste la anotación del tipo de retorno, las herramientas y editores se quejarían con un error (correcto) diciéndote que tu función está devolviendo un tipo (por ejemplo, un dict) que es diferente de lo que declaraste (por ejemplo, un modelo de Pydantic).
+
+En esos casos, puedes usar el parámetro del decorador de path operation `response_model` en lugar del tipo de retorno.
+
+Puedes usar el parámetro `response_model` en cualquiera de las *path operations*:
+
+* `@app.get()`
+* `@app.post()`
+* `@app.put()`
+* `@app.delete()`
+* etc.
+
+{* ../../docs_src/response_model/tutorial001_py310.py hl[17,22,24:27] *}
+
+/// note | Nota
+
+Observa que `response_model` es un parámetro del método "decorador" (`get`, `post`, etc). No de tu *path operation function*, como todos los parámetros y el cuerpo.
+
+///
+
+`response_model` recibe el mismo tipo que declararías para un campo de modelo Pydantic, por lo que puede ser un modelo de Pydantic, pero también puede ser, por ejemplo, un `list` de modelos de Pydantic, como `List[Item]`.
+
+FastAPI usará este `response_model` para hacer toda la documentación de datos, validación, etc. y también para **convertir y filtrar los datos de salida** a su declaración de tipo.
+
+/// tip | Consejo
+
+Si tienes chequeos estrictos de tipos en tu editor, mypy, etc., puedes declarar el tipo de retorno de la función como `Any`.
+
+De esa manera le dices al editor que intencionalmente estás devolviendo cualquier cosa. Pero FastAPI todavía hará la documentación de datos, validación, filtrado, etc. con `response_model`.
+
+///
+
+### Prioridad del `response_model`
+
+Si declaras tanto un tipo de retorno como un `response_model`, el `response_model` tomará prioridad y será utilizado por FastAPI.
+
+De esta manera puedes añadir anotaciones de tipos correctas a tus funciones incluso cuando estás devolviendo un tipo diferente al modelo de response, para ser utilizado por el editor y herramientas como mypy. Y aún así puedes hacer que FastAPI realice la validación de datos, documentación, etc. usando el `response_model`.
+
+También puedes usar `response_model=None` para desactivar la creación de un modelo de response para esa *path operation*, podrías necesitar hacerlo si estás añadiendo anotaciones de tipos para cosas que no son campos válidos de Pydantic, verás un ejemplo de eso en una de las secciones a continuación.
+
+## Devolver los mismos datos de entrada
+
+Aquí estamos declarando un modelo `UserIn`, contendrá una contraseña en texto plano:
+
+{* ../../docs_src/response_model/tutorial002_py310.py hl[7,9] *}
+
+/// info | Información
+
+Para usar `EmailStr`, primero instala `email-validator`.
+
+Asegúrate de crear un [entorno virtual](../virtual-environments.md){.internal-link target=_blank}, activarlo, y luego instalarlo, por ejemplo:
+
+```console
+$ pip install email-validator
+```
+
+o con:
+
+```console
+$ pip install "pydantic[email]"
+```
+
+///
+
+Y estamos usando este modelo para declarar nuestra entrada y el mismo modelo para declarar nuestra salida:
+
+{* ../../docs_src/response_model/tutorial002_py310.py hl[16] *}
+
+Ahora, cada vez que un navegador esté creando un usuario con una contraseña, la API devolverá la misma contraseña en el response.
+
+En este caso, podría no ser un problema, porque es el mismo usuario que envía la contraseña.
+
+Pero si usamos el mismo modelo para otra *path operation*, podríamos estar enviando las contraseñas de nuestros usuarios a cada cliente.
+
+/// danger | Peligro
+
+Nunca almacenes la contraseña en texto plano de un usuario ni la envíes en un response como esta, a menos que conozcas todas las advertencias y sepas lo que estás haciendo.
+
+///
+
+## Añadir un modelo de salida
+
+Podemos en cambio crear un modelo de entrada con la contraseña en texto plano y un modelo de salida sin ella:
+
+{* ../../docs_src/response_model/tutorial003_py310.py hl[9,11,16] *}
+
+Aquí, aunque nuestra *path operation function* está devolviendo el mismo usuario de entrada que contiene la contraseña:
+
+{* ../../docs_src/response_model/tutorial003_py310.py hl[24] *}
+
+...hemos declarado el `response_model` para ser nuestro modelo `UserOut`, que no incluye la contraseña:
+
+{* ../../docs_src/response_model/tutorial003_py310.py hl[22] *}
+
+Entonces, **FastAPI** se encargará de filtrar todos los datos que no estén declarados en el modelo de salida (usando Pydantic).
+
+### `response_model` o Tipo de Retorno
+
+En este caso, como los dos modelos son diferentes, si anotáramos el tipo de retorno de la función como `UserOut`, el editor y las herramientas se quejarían de que estamos devolviendo un tipo inválido, ya que son clases diferentes.
+
+Por eso en este ejemplo tenemos que declararlo en el parámetro `response_model`.
+
+...pero sigue leyendo abajo para ver cómo superar eso.
+
+## Tipo de Retorno y Filtrado de Datos
+
+Continuemos con el ejemplo anterior. Queríamos **anotar la función con un tipo**, pero queríamos poder devolver desde la función algo que en realidad incluya **más datos**.
+
+Queremos que FastAPI continúe **filtrando** los datos usando el modelo de response. Para que, incluso cuando la función devuelva más datos, el response solo incluya los campos declarados en el modelo de response.
+
+En el ejemplo anterior, debido a que las clases eran diferentes, tuvimos que usar el parámetro `response_model`. Pero eso también significa que no obtenemos el soporte del editor y las herramientas verificando el tipo de retorno de la función.
+
+Pero en la mayoría de los casos en los que necesitamos hacer algo como esto, queremos que el modelo solo **filtre/elimine** algunos de los datos como en este ejemplo.
+
+Y en esos casos, podemos usar clases y herencia para aprovechar las **anotaciones de tipos** de funciones para obtener mejor soporte en el editor y herramientas, y aún así obtener el **filtrado de datos** de FastAPI.
+
+{* ../../docs_src/response_model/tutorial003_01_py310.py hl[7:10,13:14,18] *}
+
+Con esto, obtenemos soporte de las herramientas, de los editores y mypy ya que este código es correcto en términos de tipos, pero también obtenemos el filtrado de datos de FastAPI.
+
+¿Cómo funciona esto? Vamos a echarle un vistazo. 🤓
+
+### Anotaciones de Tipos y Herramientas
+
+Primero vamos a ver cómo los editores, mypy y otras herramientas verían esto.
+
+`BaseUser` tiene los campos base. Luego `UserIn` hereda de `BaseUser` y añade el campo `password`, por lo que incluirá todos los campos de ambos modelos.
+
+Anotamos el tipo de retorno de la función como `BaseUser`, pero en realidad estamos devolviendo una instancia de `UserIn`.
+
+El editor, mypy y otras herramientas no se quejarán de esto porque, en términos de tipificación, `UserIn` es una subclase de `BaseUser`, lo que significa que es un tipo *válido* cuando se espera algo que es un `BaseUser`.
+
+### Filtrado de Datos en FastAPI
+
+Ahora, para FastAPI, verá el tipo de retorno y se asegurará de que lo que devuelves incluya **solo** los campos que están declarados en el tipo.
+
+FastAPI realiza varias cosas internamente con Pydantic para asegurarse de que esas mismas reglas de herencia de clases no se utilicen para el filtrado de datos devueltos, de lo contrario, podrías terminar devolviendo muchos más datos de los que esperabas.
+
+De esta manera, puedes obtener lo mejor de ambos mundos: anotaciones de tipos con **soporte de herramientas** y **filtrado de datos**.
+
+## Verlo en la documentación
+
+Cuando veas la documentación automática, puedes verificar que el modelo de entrada y el modelo de salida tendrán cada uno su propio JSON Schema:
+
+
-
-
+
+
-
-
+
+
@@ -90,7 +90,7 @@ FastAPI یک وب فریمورک مدرن و سریع (با کارایی با
email_validator
- برای اعتبارسنجی آدرسهای ایمیل.
+* email-validator
- برای اعتبارسنجی آدرسهای ایمیل.
استفاده شده توسط Starlette:
diff --git a/docs/fa/docs/learn/index.md b/docs/fa/docs/learn/index.md
new file mode 100644
index 000000000..06aa7f00e
--- /dev/null
+++ b/docs/fa/docs/learn/index.md
@@ -0,0 +1,5 @@
+# یادگیری
+
+اینجا بخشهای مقدماتی و آموزشهایی هستن که برای یادگیری **FastAPI** بهت کمک میکنن.
+
+میتونی اینو یه **کتاب**، یه **دوره آموزشی**، یا راه **رسمی** و پیشنهادی برای یادگیری FastAPI در نظر بگیری. 😎
diff --git a/docs/fa/docs/tutorial/middleware.md b/docs/fa/docs/tutorial/middleware.md
index c5752a4b5..75b1c4c5c 100644
--- a/docs/fa/docs/tutorial/middleware.md
+++ b/docs/fa/docs/tutorial/middleware.md
@@ -11,10 +11,13 @@
* می تواند کاری با **پاسخ** انجام دهید یا هر کد مورد نیازتان را اجرا کند.
* سپس **پاسخ** را برمی گرداند.
-!!! توجه "جزئیات فنی"
- در صورت وجود وابستگی هایی با `yield`، کد خروجی **پس از** اجرای میانافزار اجرا خواهد شد.
+/// توجه | جزئیات فنی
- در صورت وجود هر گونه وظایف پس زمینه (که در ادامه توضیح داده میشوند)، تمام میانافزارها *پس از آن* اجرا خواهند شد.
+در صورت وجود وابستگی هایی با `yield`، کد خروجی **پس از** اجرای میانافزار اجرا خواهد شد.
+
+در صورت وجود هر گونه وظایف پس زمینه (که در ادامه توضیح داده میشوند)، تمام میانافزارها *پس از آن* اجرا خواهند شد.
+
+///
## ساخت یک میان افزار
@@ -27,18 +30,21 @@
* سپس `پاسخ` تولید شده توسط *path operation* مربوطه را برمیگرداند.
* شما میتوانید سپس `پاسخ` را تغییر داده و پس از آن را برگردانید.
-```Python hl_lines="8-9 11 14"
-{!../../../docs_src/middleware/tutorial001.py!}
-```
+{* ../../docs_src/middleware/tutorial001.py hl[8:9,11,14] *}
+
+/// نکته | به خاطر داشته باشید که هدرهای اختصاصی سفارشی را می توان با استفاده از پیشوند "X-" اضافه کرد.
+
+اما اگر هدرهای سفارشی دارید که میخواهید مرورگر کاربر بتواند آنها را ببیند، باید آنها را با استفاده از پارامتر `expose_headers` که در مستندات CORS از Starlette توضیح داده شده است، به پیکربندی CORS خود اضافه کنید.
+
+///
-!!! نکته به خاطر داشته باشید که هدرهای اختصاصی سفارشی را می توان با استفاده از پیشوند "X-" اضافه کرد.
+/// توجه | جزئیات فنی
- اما اگر هدرهای سفارشی دارید که میخواهید مرورگر کاربر بتواند آنها را ببیند، باید آنها را با استفاده از پارامتر `expose_headers` که در مستندات CORS از Starlette توضیح داده شده است، به پیکربندی CORS خود اضافه کنید.
+شما همچنین میتوانید از `from starlette.requests import Request` استفاده کنید.
-!!! توجه "جزئیات فنی"
- شما همچنین میتوانید از `from starlette.requests import Request` استفاده کنید.
+**FastAPI** این را به عنوان یک سهولت برای شما به عنوان برنامهنویس فراهم میکند. اما این مستقیما از Starlette به دست میآید.
- **FastAPI** این را به عنوان یک سهولت برای شما به عنوان برنامهنویس فراهم میکند. اما این مستقیما از Starlette به دست میآید.
+///
### قبل و بعد از `پاسخ`
@@ -48,9 +54,7 @@
به عنوان مثال، میتوانید یک هدر سفارشی به نام `X-Process-Time` که شامل زمان پردازش درخواست و تولید پاسخ به صورت ثانیه است، اضافه کنید.
-```Python hl_lines="10 12-13"
-{!../../../docs_src/middleware/tutorial001.py!}
-```
+{* ../../docs_src/middleware/tutorial001.py hl[10,12:13] *}
## سایر میان افزار
diff --git a/docs/fa/docs/tutorial/security/index.md b/docs/fa/docs/tutorial/security/index.md
index 4e68ba961..c0827a8b3 100644
--- a/docs/fa/docs/tutorial/security/index.md
+++ b/docs/fa/docs/tutorial/security/index.md
@@ -33,8 +33,11 @@
پروتکل استاندارد OAuth2 روش رمزگذاری ارتباط را مشخص نمی کند، بلکه انتظار دارد که برنامه شما با HTTPS سرویس دهی شود.
-!!! نکته
- در بخش در مورد **استقرار** ، شما یاد خواهید گرفت که چگونه با استفاده از Traefik و Let's Encrypt رایگان HTTPS را راه اندازی کنید.
+/// نکته
+
+در بخش در مورد **استقرار** ، شما یاد خواهید گرفت که چگونه با استفاده از Traefik و Let's Encrypt رایگان HTTPS را راه اندازی کنید.
+
+///
## استاندارد OpenID Connect
@@ -86,10 +89,13 @@
* شیوه `openIdConnect`: یک روش برای تعریف نحوه کشف دادههای احراز هویت OAuth2 به صورت خودکار.
* کشف خودکار این موضوع را که در مشخصه OpenID Connect تعریف شده است، مشخص میکند.
-!!! نکته
- ادغام سایر ارائهدهندگان احراز هویت/اجازهدهی مانند گوگل، فیسبوک، توییتر، گیتهاب و غیره نیز امکانپذیر و نسبتاً آسان است.
+/// نکته
+
+ادغام سایر ارائهدهندگان احراز هویت/اجازهدهی مانند گوگل، فیسبوک، توییتر، گیتهاب و غیره نیز امکانپذیر و نسبتاً آسان است.
+
+مشکل پیچیدهترین مسئله، ساخت یک ارائهدهنده احراز هویت/اجازهدهی مانند آنها است، اما **FastAPI** ابزارهای لازم برای انجام این کار را با سهولت به شما میدهد و همه کارهای سنگین را برای شما انجام میدهد.
- مشکل پیچیدهترین مسئله، ساخت یک ارائهدهنده احراز هویت/اجازهدهی مانند آنها است، اما **FastAPI** ابزارهای لازم برای انجام این کار را با سهولت به شما میدهد و همه کارهای سنگین را برای شما انجام میدهد.
+///
## ابزارهای **FastAPI**
diff --git a/docs/fr/docs/advanced/additional-responses.md b/docs/fr/docs/advanced/additional-responses.md
index 685a054ad..38527aad3 100644
--- a/docs/fr/docs/advanced/additional-responses.md
+++ b/docs/fr/docs/advanced/additional-responses.md
@@ -1,9 +1,12 @@
# Réponses supplémentaires dans OpenAPI
-!!! warning "Attention"
- Ceci concerne un sujet plutôt avancé.
+/// warning | Attention
- Si vous débutez avec **FastAPI**, vous n'en aurez peut-être pas besoin.
+Ceci concerne un sujet plutôt avancé.
+
+Si vous débutez avec **FastAPI**, vous n'en aurez peut-être pas besoin.
+
+///
Vous pouvez déclarer des réponses supplémentaires, avec des codes HTTP, des types de médias, des descriptions, etc.
@@ -23,24 +26,28 @@ Chacun de ces `dict` de réponse peut avoir une clé `model`, contenant un modè
Par exemple, pour déclarer une autre réponse avec un code HTTP `404` et un modèle Pydantic `Message`, vous pouvez écrire :
-```Python hl_lines="18 22"
-{!../../../docs_src/additional_responses/tutorial001.py!}
-```
+{* ../../docs_src/additional_responses/tutorial001.py hl[18,22] *}
+
+/// note | Remarque
+
+Gardez à l'esprit que vous devez renvoyer directement `JSONResponse`.
+
+///
+
+/// info
-!!! note "Remarque"
- Gardez à l'esprit que vous devez renvoyer directement `JSONResponse`.
+La clé `model` ne fait pas partie d'OpenAPI.
-!!! info
- La clé `model` ne fait pas partie d'OpenAPI.
+**FastAPI** prendra le modèle Pydantic à partir de là, générera le `JSON Schema` et le placera au bon endroit.
- **FastAPI** prendra le modèle Pydantic à partir de là, générera le `JSON Schema` et le placera au bon endroit.
+Le bon endroit est :
- Le bon endroit est :
+* Dans la clé `content`, qui a pour valeur un autre objet JSON (`dict`) qui contient :
+ * Une clé avec le type de support, par ex. `application/json`, qui contient comme valeur un autre objet JSON, qui contient :
+ * Une clé `schema`, qui a pour valeur le schéma JSON du modèle, voici le bon endroit.
+ * **FastAPI** ajoute ici une référence aux schémas JSON globaux à un autre endroit de votre OpenAPI au lieu de l'inclure directement. De cette façon, d'autres applications et clients peuvent utiliser ces schémas JSON directement, fournir de meilleurs outils de génération de code, etc.
- * Dans la clé `content`, qui a pour valeur un autre objet JSON (`dict`) qui contient :
- * Une clé avec le type de support, par ex. `application/json`, qui contient comme valeur un autre objet JSON, qui contient :
- * Une clé `schema`, qui a pour valeur le schéma JSON du modèle, voici le bon endroit.
- * **FastAPI** ajoute ici une référence aux schémas JSON globaux à un autre endroit de votre OpenAPI au lieu de l'inclure directement. De cette façon, d'autres applications et clients peuvent utiliser ces schémas JSON directement, fournir de meilleurs outils de génération de code, etc.
+///
Les réponses générées au format OpenAPI pour cette *opération de chemin* seront :
@@ -168,17 +175,21 @@ Vous pouvez utiliser ce même paramètre `responses` pour ajouter différents ty
Par exemple, vous pouvez ajouter un type de média supplémentaire `image/png`, en déclarant que votre *opération de chemin* peut renvoyer un objet JSON (avec le type de média `application/json`) ou une image PNG :
-```Python hl_lines="19-24 28"
-{!../../../docs_src/additional_responses/tutorial002.py!}
-```
+{* ../../docs_src/additional_responses/tutorial002.py hl[19:24,28] *}
+
+/// note | Remarque
+
+Notez que vous devez retourner l'image en utilisant directement un `FileResponse`.
+
+///
-!!! note "Remarque"
- Notez que vous devez retourner l'image en utilisant directement un `FileResponse`.
+/// info
-!!! 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`).
+À moins que vous ne spécifiiez explicitement un type de média différent dans votre paramètre `responses`, FastAPI supposera que la réponse a le même type de média que la classe de réponse principale (par défaut `application/json`).
- Mais si vous avez spécifié une classe de réponse personnalisée avec `None` comme type de média, FastAPI utilisera `application/json` pour toute réponse supplémentaire associée à un modèle.
+Mais si vous avez spécifié une classe de réponse personnalisée avec `None` comme type de média, FastAPI utilisera `application/json` pour toute réponse supplémentaire associée à un modèle.
+
+///
## Combinaison d'informations
@@ -192,9 +203,7 @@ Par exemple, vous pouvez déclarer une réponse avec un code HTTP `404` qui util
Et une réponse avec un code HTTP `200` qui utilise votre `response_model`, mais inclut un `example` personnalisé :
-```Python hl_lines="20-31"
-{!../../../docs_src/additional_responses/tutorial003.py!}
-```
+{* ../../docs_src/additional_responses/tutorial003.py hl[20:31] *}
Tout sera combiné et inclus dans votre OpenAPI, et affiché dans la documentation de l'API :
@@ -228,9 +237,7 @@ Vous pouvez utiliser cette technique pour réutiliser certaines réponses préd
Par exemple:
-```Python hl_lines="13-17 26"
-{!../../../docs_src/additional_responses/tutorial004.py!}
-```
+{* ../../docs_src/additional_responses/tutorial004.py hl[13:17,26] *}
## Plus d'informations sur les réponses OpenAPI
diff --git a/docs/fr/docs/advanced/additional-status-codes.md b/docs/fr/docs/advanced/additional-status-codes.md
index 51f0db737..dde6b9a63 100644
--- a/docs/fr/docs/advanced/additional-status-codes.md
+++ b/docs/fr/docs/advanced/additional-status-codes.md
@@ -14,21 +14,25 @@ Mais vous voulez aussi qu'il accepte de nouveaux éléments. Et lorsque les él
Pour y parvenir, importez `JSONResponse` et renvoyez-y directement votre contenu, en définissant le `status_code` que vous souhaitez :
-```Python hl_lines="4 25"
-{!../../../docs_src/additional_status_codes/tutorial001.py!}
-```
+{* ../../docs_src/additional_status_codes/tutorial001.py hl[4,25] *}
-!!! warning "Attention"
- Lorsque vous renvoyez une `Response` directement, comme dans l'exemple ci-dessus, elle sera renvoyée directement.
+/// warning | Attention
- Elle ne sera pas sérialisée avec un modèle.
+Lorsque vous renvoyez une `Response` directement, comme dans l'exemple ci-dessus, elle sera renvoyée directement.
- Assurez-vous qu'il contient les données souhaitées et que les valeurs soient dans un format JSON valides (si vous utilisez une `JSONResponse`).
+Elle ne sera pas sérialisée avec un modèle.
-!!! note "Détails techniques"
- Vous pouvez également utiliser `from starlette.responses import JSONResponse`.
+Assurez-vous qu'il contient les données souhaitées et que les valeurs soient dans un format JSON valides (si vous utilisez une `JSONResponse`).
- Pour plus de commodités, **FastAPI** fournit les objets `starlette.responses` sous forme d'un alias accessible par `fastapi.responses`. Mais la plupart des réponses disponibles proviennent directement de Starlette. Il en est de même avec l'objet `statut`.
+///
+
+/// note | Détails techniques
+
+Vous pouvez également utiliser `from starlette.responses import JSONResponse`.
+
+Pour plus de commodités, **FastAPI** fournit les objets `starlette.responses` sous forme d'un alias accessible par `fastapi.responses`. Mais la plupart des réponses disponibles proviennent directement de Starlette. Il en est de même avec l'objet `statut`.
+
+///
## Documents OpenAPI et API
diff --git a/docs/fr/docs/advanced/index.md b/docs/fr/docs/advanced/index.md
index 4599bcb6f..d9d8ad8e6 100644
--- a/docs/fr/docs/advanced/index.md
+++ b/docs/fr/docs/advanced/index.md
@@ -6,10 +6,13 @@ Le [Tutoriel - Guide de l'utilisateur](../tutorial/index.md){.internal-link targ
Dans les sections suivantes, vous verrez des options, configurations et fonctionnalités supplémentaires.
-!!! note "Remarque"
- Les sections de ce chapitre ne sont **pas nécessairement "avancées"**.
+/// note | Remarque
- Et il est possible que pour votre cas d'utilisation, la solution se trouve dans l'un d'entre eux.
+Les sections de ce chapitre ne sont **pas nécessairement "avancées"**.
+
+Et il est possible que pour votre cas d'utilisation, la solution se trouve dans l'un d'entre eux.
+
+///
## Lisez d'abord le didacticiel
diff --git a/docs/fr/docs/advanced/path-operation-advanced-configuration.md b/docs/fr/docs/advanced/path-operation-advanced-configuration.md
index 77f551aea..7daf0fc65 100644
--- a/docs/fr/docs/advanced/path-operation-advanced-configuration.md
+++ b/docs/fr/docs/advanced/path-operation-advanced-configuration.md
@@ -2,16 +2,17 @@
## ID d'opération OpenAPI
-!!! warning "Attention"
- Si vous n'êtes pas un "expert" en OpenAPI, vous n'en avez probablement pas besoin.
+/// warning | Attention
+
+Si vous n'êtes pas un "expert" en OpenAPI, vous n'en avez probablement pas besoin.
+
+///
Dans OpenAPI, les chemins sont des ressources, tels que /users/ ou /items/, exposées par votre API, et les opérations sont les méthodes HTTP utilisées pour manipuler ces chemins, telles que GET, POST ou DELETE. Les operationId sont des chaînes uniques facultatives utilisées pour identifier une opération d'un chemin. Vous pouvez définir l'OpenAPI `operationId` à utiliser dans votre *opération de chemin* avec le paramètre `operation_id`.
Vous devez vous assurer qu'il est unique pour chaque opération.
-```Python hl_lines="6"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial001.py!}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial001.py hl[6] *}
### Utilisation du nom *path operation function* comme operationId
@@ -19,25 +20,27 @@ Si vous souhaitez utiliser les noms de fonction de vos API comme `operationId`,
Vous devriez le faire après avoir ajouté toutes vos *paramètres de chemin*.
-```Python hl_lines="2 12-21 24"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial002.py hl[2,12:21,24] *}
+
+/// tip | Astuce
-!!! tip "Astuce"
- Si vous appelez manuellement `app.openapi()`, vous devez mettre à jour les `operationId` avant.
+Si vous appelez manuellement `app.openapi()`, vous devez mettre à jour les `operationId` avant.
-!!! warning "Attention"
- Pour faire cela, vous devez vous assurer que chacun de vos *chemin* ait un nom unique.
+///
- 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
Pour exclure un *chemin* du schéma OpenAPI généré (et donc des systèmes de documentation automatiques), utilisez le paramètre `include_in_schema` et assignez-lui la valeur `False` :
-```Python hl_lines="6"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial003.py!}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial003.py hl[6] *}
## Description avancée de docstring
@@ -47,9 +50,7 @@ L'ajout d'un `\f` (un caractère d'échappement "form feed") va permettre à **F
Il n'apparaîtra pas dans la documentation, mais d'autres outils (tel que Sphinx) pourront utiliser le reste.
-```Python hl_lines="19-29"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial004.py!}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial004.py hl[19:29] *}
## Réponses supplémentaires
@@ -65,8 +66,11 @@ Il y a un chapitre entier ici dans la documentation à ce sujet, vous pouvez le
Lorsque vous déclarez un *chemin* dans votre application, **FastAPI** génère automatiquement les métadonnées concernant ce *chemin* à inclure dans le schéma OpenAPI.
-!!! note "Détails techniques"
- La spécification OpenAPI appelle ces métadonnées des 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 +78,11 @@ Il inclut les `tags`, `parameters`, `requestBody`, `responses`, etc.
Ce schéma OpenAPI spécifique aux *operations* est normalement généré automatiquement par **FastAPI**, mais vous pouvez également l'étendre.
-!!! tip "Astuce"
- Si vous avez seulement besoin de déclarer des réponses supplémentaires, un moyen plus pratique de le faire est d'utiliser les [réponses supplémentaires dans OpenAPI](additional-responses.md){.internal-link target=_blank}.
+/// tip | Astuce
+
+Si vous avez seulement besoin de déclarer des réponses supplémentaires, un moyen plus pratique de le faire est d'utiliser les [réponses supplémentaires dans OpenAPI](additional-responses.md){.internal-link target=_blank}.
+
+///
Vous pouvez étendre le schéma OpenAPI pour une *opération de chemin* en utilisant le paramètre `openapi_extra`.
@@ -83,9 +90,7 @@ Vous pouvez étendre le schéma OpenAPI pour une *opération de chemin* en utili
Cet `openapi_extra` peut être utile, par exemple, pour déclarer [OpenAPI Extensions](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions) :
-```Python hl_lines="6"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial005.py!}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial005.py hl[6] *}
Si vous ouvrez la documentation automatique de l'API, votre extension apparaîtra au bas du *chemin* spécifique.
@@ -132,9 +137,7 @@ Par exemple, vous pouvez décider de lire et de valider la requête avec votre p
Vous pouvez le faire avec `openapi_extra` :
-```Python hl_lines="20-37 39-40"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial006.py !}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial006.py hl[20:37,39:40] *}
Dans cet exemple, nous n'avons déclaré aucun modèle Pydantic. En fait, le corps de la requête n'est même pas parsé en tant que JSON, il est lu directement en tant que `bytes`, et la fonction `magic_data_reader()` serait chargé de l'analyser d'une manière ou d'une autre.
@@ -148,9 +151,7 @@ Et vous pouvez le faire même si le type de données dans la requête n'est pas
Dans cet exemple, nous n'utilisons pas les fonctionnalités de FastAPI pour extraire le schéma JSON des modèles Pydantic ni la validation automatique pour JSON. En fait, nous déclarons le type de contenu de la requête en tant que YAML, et non JSON :
-```Python hl_lines="17-22 24"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial007.py!}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[17:22,24] *}
Néanmoins, bien que nous n'utilisions pas la fonctionnalité par défaut, nous utilisons toujours un modèle Pydantic pour générer manuellement le schéma JSON pour les données que nous souhaitons recevoir en YAML.
@@ -158,11 +159,12 @@ Ensuite, nous utilisons directement la requête et extrayons son contenu en tant
Et nous analysons directement ce contenu YAML, puis nous utilisons à nouveau le même modèle Pydantic pour valider le contenu YAML :
-```Python hl_lines="26-33"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial007.py!}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[26:33] *}
+
+/// tip | Astuce
+
+Ici, nous réutilisons le même modèle Pydantic.
-!!! tip "Astuce"
- Ici, nous réutilisons le même modèle Pydantic.
+Mais nous aurions pu tout aussi bien pu le valider d'une autre manière.
- Mais nous aurions pu tout aussi bien pu le valider d'une autre manière.
+///
diff --git a/docs/fr/docs/advanced/response-directly.md b/docs/fr/docs/advanced/response-directly.md
index ed29446d4..4ff883c77 100644
--- a/docs/fr/docs/advanced/response-directly.md
+++ b/docs/fr/docs/advanced/response-directly.md
@@ -14,8 +14,11 @@ Cela peut être utile, par exemple, pour retourner des en-têtes personnalisés
En fait, vous pouvez retourner n'importe quelle `Response` ou n'importe quelle sous-classe de celle-ci.
-!!! note "Remarque"
- `JSONResponse` est elle-même une sous-classe de `Response`.
+/// note | Remarque
+
+`JSONResponse` est elle-même une sous-classe de `Response`.
+
+///
Et quand vous retournez une `Response`, **FastAPI** la transmet directement.
@@ -31,14 +34,15 @@ Par exemple, vous ne pouvez pas mettre un modèle Pydantic dans une `JSONRespons
Pour ces cas, vous pouvez spécifier un appel à `jsonable_encoder` pour convertir vos données avant de les passer à une réponse :
-```Python hl_lines="6-7 21-22"
-{!../../../docs_src/response_directly/tutorial001.py!}
-```
+{* ../../docs_src/response_directly/tutorial001.py hl[6:7,21:22] *}
+
+/// note | Détails techniques
+
+Vous pouvez aussi utiliser `from starlette.responses import JSONResponse`.
-!!! note "Détails techniques"
- Vous pouvez aussi utiliser `from starlette.responses import JSONResponse`.
+**FastAPI** fournit le même objet `starlette.responses` que `fastapi.responses` juste par commodité pour le développeur. Mais la plupart des réponses disponibles proviennent directement de Starlette.
- **FastAPI** fournit le même objet `starlette.responses` que `fastapi.responses` juste par commodité pour le développeur. Mais la plupart des réponses disponibles proviennent directement de Starlette.
+///
## Renvoyer une `Response` personnalisée
@@ -50,9 +54,7 @@ Disons que vous voulez retourner une réponse 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,12 +343,15 @@ 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
+### Hug
Hug a été l'un des premiers frameworks à implémenter la déclaration des types de paramètres d'API en utilisant les type hints Python. C'était une excellente idée qui a inspiré d'autres outils à faire de même.
@@ -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 eabd9686a..0ff5fa5d1 100644
--- a/docs/fr/docs/async.md
+++ b/docs/fr/docs/async.md
@@ -20,8 +20,11 @@ async def read_results():
return results
```
-!!! note
- Vous pouvez uniquement utiliser `await` dans les fonctions créées avec `async def`.
+/// note
+
+Vous pouvez uniquement utiliser `await` dans les fonctions créées avec `async def`.
+
+///
---
@@ -135,8 +138,11 @@ Vous et votre crush 😍 mangez les burgers 🍔 et passez un bon moment ✨.
-!!! info
- Illustrations proposées par Ketrina Thompson. 🎨
+/// info
+
+Illustrations proposées par Ketrina Thompson. 🎨
+
+///
---
@@ -198,8 +204,11 @@ Vous les mangez, et vous avez terminé 🍔 ⏹.
Durant tout ce processus, il n'y a presque pas eu de discussions ou de flirts car la plupart de votre temps à été passé à attendre 🕙 devant le comptoir 😞.
-!!! info
- Illustrations proposées par Ketrina Thompson. 🎨
+/// info
+
+Illustrations proposées par Ketrina Thompson. 🎨
+
+///
---
@@ -384,12 +393,15 @@ Tout ceci est donc ce qui donne sa force à **FastAPI** (à travers Starlette) e
## Détails très techniques
-!!! warning "Attention !"
- Vous pouvez probablement ignorer cela.
+/// warning | Attention !
+
+Vous pouvez probablement ignorer cela.
+
+Ce sont des détails très poussés sur comment **FastAPI** fonctionne en arrière-plan.
- Ce sont des détails très poussés sur comment **FastAPI** fonctionne en arrière-plan.
+Si vous avez de bonnes connaissances techniques (coroutines, threads, code bloquant, etc.) et êtes curieux de comment **FastAPI** gère `async def` versus le `def` classique, cette partie est faite pour vous.
- Si vous avez de bonnes connaissances techniques (coroutines, threads, code bloquant, etc.) et êtes curieux de comment **FastAPI** gère `async def` versus le `def` classique, cette partie est faite pour vous.
+///
### Fonctions de chemin
diff --git a/docs/fr/docs/contributing.md b/docs/fr/docs/contributing.md
deleted file mode 100644
index ed4d32f5a..000000000
--- a/docs/fr/docs/contributing.md
+++ /dev/null
@@ -1,501 +0,0 @@
-# Développement - Contribuer
-
-Tout d'abord, vous voudrez peut-être voir les moyens de base pour [aider FastAPI et obtenir de l'aide](help-fastapi.md){.internal-link target=_blank}.
-
-## Développement
-
-Si vous avez déjà cloné le dépôt et que vous savez que vous devez vous plonger dans le code, voici quelques directives pour mettre en place votre environnement.
-
-### Environnement virtuel avec `venv`
-
-Vous pouvez créer un environnement virtuel dans un répertoire en utilisant le module `venv` de Python :
-
-
-{% endfor %}
-{% endif %}
-
-{% if sponsors.silver %}
-
-### Silver Sponsors
-
-{% for sponsor in sponsors.silver -%}
-
-{% endfor %}
-{% endif %}
-
-{% if sponsors.bronze %}
-
-### Bronze Sponsors
-
-{% for sponsor in sponsors.bronze -%}
-
-{% endfor %}
-{% endif %}
-
-{% endif %}
-### Individual Sponsors
-
-{% if github_sponsors %}
-{% for group in github_sponsors.sponsors %}
-
-
-
+
@@ -93,7 +93,7 @@ Les principales fonctionnalités sont :
"_Honnêtement, ce que vous avez construit a l'air super solide et élégant. A bien des égards, c'est comme ça que je voulais que **Hug** soit - c'est vraiment inspirant de voir quelqu'un construire ça._"
-
+
---
@@ -449,7 +449,7 @@ Pour en savoir plus, consultez la section
email_validator
- pour la validation des adresses email.
+* email-validator
- pour la validation des adresses email.
Utilisées par Starlette :
diff --git a/docs/fr/docs/python-types.md b/docs/fr/docs/python-types.md
index 4232633e3..99ca90827 100644
--- a/docs/fr/docs/python-types.md
+++ b/docs/fr/docs/python-types.md
@@ -13,16 +13,17 @@ 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
Prenons un exemple simple :
-```Python
-{!../../../docs_src/python_types/tutorial001.py!}
-```
+{*../../docs_src/python_types/tutorial001.py*}
Exécuter ce programe affiche :
@@ -36,9 +37,7 @@ La fonction :
* Convertit la première lettre de chaque paramètre en majuscules grâce à `title()`.
* Concatène les résultats avec un espace entre les deux.
-```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial001.py!}
-```
+{*../../docs_src/python_types/tutorial001.py hl[2] *}
### Limitations
@@ -81,9 +80,7 @@ C'est tout.
Ce sont des annotations de types :
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial002.py!}
-```
+{*../../docs_src/python_types/tutorial002.py hl[1] *}
À ne pas confondre avec la déclaration de valeurs par défaut comme ici :
@@ -111,9 +108,7 @@ Vous pouvez donc dérouler les options jusqu'à trouver la méthode à laquelle
Cette fonction possède déjà des annotations de type :
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial003.py!}
-```
+{*../../docs_src/python_types/tutorial003.py hl[1] *}
Comme l'éditeur connaît le type des variables, vous n'avez pas seulement l'auto-complétion, mais aussi de la détection d'erreurs :
@@ -121,9 +116,7 @@ Comme l'éditeur connaît le type des variables, vous n'avez pas seulement l'aut
Maintenant que vous avez connaissance du problème, convertissez `age` en chaîne de caractères grâce à `str(age)` :
-```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial004.py!}
-```
+{*../../docs_src/python_types/tutorial004.py hl[2] *}
## Déclarer des types
@@ -142,9 +135,7 @@ Comme par exemple :
* `bool`
* `bytes`
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial005.py!}
-```
+{*../../docs_src/python_types/tutorial005.py hl[1] *}
### Types génériques avec des paramètres de types
@@ -160,9 +151,7 @@ Par exemple, définissons une variable comme `list` de `str`.
Importez `List` (avec un `L` majuscule) depuis `typing`.
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial006.py!}
-```
+{*../../docs_src/python_types/tutorial006.py hl[1] *}
Déclarez la variable, en utilisant la syntaxe des deux-points (`:`).
@@ -170,14 +159,15 @@ Et comme type, mettez `List`.
Les listes étant un type contenant des types internes, mettez ces derniers entre crochets (`[`, `]`) :
-```Python hl_lines="4"
-{!../../../docs_src/python_types/tutorial006.py!}
-```
+{*../../docs_src/python_types/tutorial006.py hl[4] *}
+
+/// tip | Astuce
+
+Ces types internes entre crochets sont appelés des "paramètres de type".
-!!! tip "Astuce"
- Ces types internes entre crochets sont appelés des "paramètres de type".
+Ici, `str` est un paramètre de type passé à `List`.
- Ici, `str` est un paramètre de type passé à `List`.
+///
Ce qui signifie : "la variable `items` est une `list`, et chacun de ses éléments a pour type `str`.
@@ -195,9 +185,7 @@ Et pourtant, l'éditeur sait qu'elle est de type `str` et pourra donc vous aider
C'est le même fonctionnement pour déclarer un `tuple` ou un `set` :
-```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial007.py!}
-```
+{*../../docs_src/python_types/tutorial007.py hl[1,4] *}
Dans cet exemple :
@@ -210,9 +198,7 @@ Pour définir un `dict`, il faut lui passer 2 paramètres, séparés par une vir
Le premier paramètre de type est pour les clés et le second pour les valeurs du dictionnaire (`dict`).
-```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial008.py!}
-```
+{*../../docs_src/python_types/tutorial008.py hl[1,4] *}
Dans cet exemple :
@@ -224,9 +210,7 @@ Dans cet exemple :
Vous pouvez aussi utiliser `Optional` pour déclarer qu'une variable a un type, comme `str` mais qu'il est "optionnel" signifiant qu'il pourrait aussi être `None`.
-```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009.py!}
-```
+{*../../docs_src/python_types/tutorial009.py hl[1,4] *}
Utiliser `Optional[str]` plutôt que `str` permettra à l'éditeur de vous aider à détecter les erreurs où vous supposeriez qu'une valeur est toujours de type `str`, alors qu'elle pourrait aussi être `None`.
@@ -249,15 +233,12 @@ Vous pouvez aussi déclarer une classe comme type d'une variable.
Disons que vous avez une classe `Person`, avec une variable `name` :
-```Python hl_lines="1-3"
-{!../../../docs_src/python_types/tutorial010.py!}
-```
+{*../../docs_src/python_types/tutorial010.py hl[1:3] *}
+
Vous pouvez ensuite déclarer une variable de type `Person` :
-```Python hl_lines="6"
-{!../../../docs_src/python_types/tutorial010.py!}
-```
+{*../../docs_src/python_types/tutorial010.py hl[6] *}
Et vous aurez accès, encore une fois, au support complet offert par l'éditeur :
@@ -277,12 +258,13 @@ Ainsi, votre éditeur vous offrira un support adapté pour l'objet résultant.
Extrait de la documentation officielle de **Pydantic** :
-```Python
-{!../../../docs_src/python_types/tutorial011.py!}
-```
+{*../../docs_src/python_types/tutorial011.py*}
+
+/// info
-!!! info
- Pour en savoir plus à propos de Pydantic, allez jeter un coup d'oeil à sa documentation.
+Pour en savoir plus à propos de Pydantic, allez jeter un coup d'oeil à sa documentation.
+
+///
**FastAPI** est basé entièrement sur **Pydantic**.
@@ -310,5 +292,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/background-tasks.md b/docs/fr/docs/tutorial/background-tasks.md
index f7cf1a6cc..2065ca58e 100644
--- a/docs/fr/docs/tutorial/background-tasks.md
+++ b/docs/fr/docs/tutorial/background-tasks.md
@@ -16,9 +16,7 @@ Cela comprend, par exemple :
Pour commencer, importez `BackgroundTasks` et définissez un paramètre dans votre *fonction de chemin* avec `BackgroundTasks` comme type déclaré.
-```Python hl_lines="1 13"
-{!../../../docs_src/background_tasks/tutorial001.py!}
-```
+{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *}
**FastAPI** créera l'objet de type `BackgroundTasks` pour vous et le passera comme paramètre.
@@ -32,18 +30,14 @@ Dans cet exemple, la fonction de tâche écrira dans un fichier (afin de simuler
L'opération d'écriture n'utilisant ni `async` ni `await`, on définit la fonction avec un `def` normal.
-```Python hl_lines="6-9"
-{!../../../docs_src/background_tasks/tutorial001.py!}
-```
+{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *}
## Ajouter une tâche d'arrière-plan
Dans votre *fonction de chemin*, passez votre fonction de tâche à l'objet de type `BackgroundTasks` (`background_tasks` ici) grâce à la méthode `.add_task()` :
-```Python hl_lines="14"
-{!../../../docs_src/background_tasks/tutorial001.py!}
-```
+{* ../../docs_src/background_tasks/tutorial001.py hl[14] *}
`.add_task()` reçoit comme arguments :
@@ -57,9 +51,7 @@ Utiliser `BackgroundTasks` fonctionne aussi avec le système d'injection de dép
**FastAPI** sait quoi faire dans chaque cas et comment réutiliser le même objet, afin que tous les paramètres de type `BackgroundTasks` soient fusionnés et que les tâches soient exécutées en arrière-plan :
-```Python hl_lines="13 15 22 25"
-{!../../../docs_src/background_tasks/tutorial002.py!}
-```
+{* ../../docs_src/background_tasks/tutorial002.py hl[13,15,22,25] *}
Dans cet exemple, les messages seront écrits dans le fichier `log.txt` après que la réponse soit envoyée.
@@ -85,8 +77,6 @@ Si vous avez besoin de réaliser des traitements lourds en tâche d'arrière-pla
Ces outils nécessitent généralement des configurations plus complexes ainsi qu'un gestionnaire de queue de message, comme RabbitMQ ou Redis, mais ils permettent d'exécuter des tâches d'arrière-plan dans différents process, et potentiellement, sur plusieurs serveurs.
-Pour voir un exemple, allez voir les [Générateurs de projets](../project-generation.md){.internal-link target=_blank}, ils incluent tous Celery déjà configuré.
-
Mais si vous avez besoin d'accéder aux variables et objets de la même application **FastAPI**, ou si vous avez besoin d'effectuer de petites tâches d'arrière-plan (comme envoyer des notifications par email), vous pouvez simplement vous contenter d'utiliser `BackgroundTasks`.
## Résumé
diff --git a/docs/fr/docs/tutorial/body-multiple-params.md b/docs/fr/docs/tutorial/body-multiple-params.md
new file mode 100644
index 000000000..0541acc74
--- /dev/null
+++ b/docs/fr/docs/tutorial/body-multiple-params.md
@@ -0,0 +1,171 @@
+# 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` :
+
+{* ../../docs_src/body_multiple_params/tutorial001_an_py310.py hl[18:20] *}
+
+/// 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 :
+
+{* ../../docs_src/body_multiple_params/tutorial002_py310.py hl[20] *}
+
+Dans ce cas, **FastAPI** détectera qu'il y a plus d'un paramètre dans le body (chacun correspondant à un modèle Pydantic).
+
+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` :
+
+{* ../../docs_src/body_multiple_params/tutorial003_an_py310.py hl[23] *}
+
+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 :
+
+{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[27] *}
+
+/// 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 :
+
+{* ../../docs_src/body_multiple_params/tutorial005_an_py310.py hl[17] *}
+
+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..760b6d80a 100644
--- a/docs/fr/docs/tutorial/body.md
+++ b/docs/fr/docs/tutorial/body.md
@@ -8,20 +8,21 @@ 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
Commencez par importer la classe `BaseModel` du module `pydantic` :
-```Python hl_lines="4"
-{!../../../docs_src/body/tutorial001.py!}
-```
+{* ../../docs_src/body/tutorial001.py hl[4] *}
## Créez votre modèle de données
@@ -29,9 +30,7 @@ Déclarez ensuite votre modèle de données en tant que classe qui hérite de `B
Utilisez les types Python standard pour tous les attributs :
-```Python hl_lines="7-11"
-{!../../../docs_src/body/tutorial001.py!}
-```
+{* ../../docs_src/body/tutorial001.py hl[7:11] *}
Tout comme pour la déclaration de paramètres de requête, quand un attribut de modèle a une valeur par défaut, il n'est pas nécessaire. Sinon, cet attribut doit être renseigné dans le corps de la requête. Pour rendre ce champ optionnel simplement, utilisez `None` comme valeur par défaut.
@@ -59,9 +58,7 @@ Par exemple, le modèle ci-dessus déclare un "objet" JSON (ou `dict` Python) te
Pour l'ajouter à votre *opération de chemin*, déclarez-le comme vous déclareriez des paramètres de chemin ou de requête :
-```Python hl_lines="18"
-{!../../../docs_src/body/tutorial001.py!}
-```
+{* ../../docs_src/body/tutorial001.py hl[18] *}
...et déclarez que son type est le modèle que vous avez créé : `Item`.
@@ -110,24 +107,25 @@ 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
+
+Si vous utilisez PyCharm comme éditeur, vous pouvez utiliser le Plugin Pydantic PyCharm Plugin.
- Ce qui améliore le support pour les modèles Pydantic avec :
+Ce qui améliore le support pour les modèles Pydantic avec :
- * de l'auto-complétion
- * des vérifications de type
- * du "refactoring" (ou remaniement de code)
- * de la recherche
- * de l'inspection
+* de l'auto-complétion
+* des vérifications de type
+* du "refactoring" (ou remaniement de code)
+* de la recherche
+* de l'inspection
+
+///
## Utilisez le modèle
Dans la fonction, vous pouvez accéder à tous les attributs de l'objet du modèle directement :
-```Python hl_lines="21"
-{!../../../docs_src/body/tutorial002.py!}
-```
+{* ../../docs_src/body/tutorial002.py hl[21] *}
## Corps de la requête + paramètres de chemin
@@ -135,9 +133,7 @@ Vous pouvez déclarer des paramètres de chemin et un corps de requête pour la
**FastAPI** est capable de reconnaître que les paramètres de la fonction qui correspondent aux paramètres de chemin doivent être **récupérés depuis le chemin**, et que les paramètres de fonctions déclarés comme modèles Pydantic devraient être **récupérés depuis le corps de la requête**.
-```Python hl_lines="17-18"
-{!../../../docs_src/body/tutorial003.py!}
-```
+{* ../../docs_src/body/tutorial003.py hl[17:18] *}
## Corps de la requête + paramètres de chemin et de requête
@@ -145,9 +141,7 @@ Vous pouvez aussi déclarer un **corps**, et des paramètres de **chemin** et de
**FastAPI** saura reconnaître chacun d'entre eux et récupérer la bonne donnée au bon endroit.
-```Python hl_lines="18"
-{!../../../docs_src/body/tutorial004.py!}
-```
+{* ../../docs_src/body/tutorial004.py hl[18] *}
Les paramètres de la fonction seront reconnus comme tel :
@@ -155,10 +149,13 @@ Les paramètres de la fonction seront reconnus comme tel :
* Si le paramètre est d'un **type singulier** (comme `int`, `float`, `str`, `bool`, etc.), il sera interprété comme un paramètre de **requête**.
* Si le paramètre est déclaré comme ayant pour type un **modèle Pydantic**, il sera interprété comme faisant partie du **corps** de la requête.
-!!! note
- **FastAPI** saura que la valeur de `q` n'est pas requise grâce à la valeur par défaut `=None`.
+/// note
+
+**FastAPI** saura que la valeur de `q` n'est pas requise grâce à la valeur par défaut `=None`.
+
+Le type `Optional` dans `Optional[str]` n'est pas utilisé par **FastAPI**, mais sera utile à votre éditeur pour améliorer le support offert par ce dernier et détecter plus facilement des erreurs de type.
- Le type `Optional` dans `Optional[str]` n'est pas utilisé par **FastAPI**, mais sera utile à votre éditeur pour améliorer le support offert par ce dernier et détecter plus facilement des erreurs de type.
+///
## Sans Pydantic
diff --git a/docs/fr/docs/tutorial/debugging.md b/docs/fr/docs/tutorial/debugging.md
index e58872d30..ab00fbdeb 100644
--- a/docs/fr/docs/tutorial/debugging.md
+++ b/docs/fr/docs/tutorial/debugging.md
@@ -6,9 +6,7 @@ Vous pouvez connecter le débogueur da
Dans votre application FastAPI, importez et exécutez directement `uvicorn` :
-```Python hl_lines="1 15"
-{!../../../docs_src/debugging/tutorial001.py!}
-```
+{* ../../docs_src/debugging/tutorial001.py hl[1,15] *}
### À propos de `__name__ == "__main__"`
@@ -74,9 +72,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..758145362 100644
--- a/docs/fr/docs/tutorial/first-steps.md
+++ b/docs/fr/docs/tutorial/first-steps.md
@@ -2,9 +2,7 @@
Le fichier **FastAPI** le plus simple possible pourrait ressembler à cela :
-```Python
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py *}
Copiez ce code dans un fichier nommé `main.py`.
@@ -24,12 +22,15 @@ $ uvicorn main:app --reload
-!!! note
- La commande `uvicorn main:app` fait référence à :
+/// note
+
+La commande `uvicorn main:app` fait référence à :
+
+* `main` : le fichier `main.py` (le module Python).
+* `app` : l'objet créé dans `main.py` via la ligne `app = FastAPI()`.
+* `--reload` : l'option disant à uvicorn de redémarrer le serveur à chaque changement du code. À ne pas utiliser en production !
- * `main` : le fichier `main.py` (le module Python).
- * `app` : l'objet créé dans `main.py` via la ligne `app = FastAPI()`.
- * `--reload` : l'option disant à uvicorn de redémarrer le serveur à chaque changement du code. À ne pas utiliser en production !
+///
Vous devriez voir dans la console, une ligne semblable à la suivante :
@@ -131,22 +132,21 @@ Vous pourriez aussi l'utiliser pour générer du code automatiquement, pour les
### Étape 1 : import `FastAPI`
-```Python hl_lines="1"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[1] *}
`FastAPI` est une classe Python qui fournit toutes les fonctionnalités nécessaires au lancement de votre API.
-!!! note "Détails techniques"
- `FastAPI` est une classe héritant directement de `Starlette`.
+/// note | Détails techniques
+
+`FastAPI` est une classe héritant directement de `Starlette`.
- Vous pouvez donc aussi utiliser toutes les fonctionnalités de Starlette depuis `FastAPI`.
+Vous pouvez donc aussi utiliser toutes les fonctionnalités de Starlette depuis `FastAPI`.
+
+///
### Étape 2 : créer une "instance" `FastAPI`
-```Python hl_lines="3"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[3] *}
Ici la variable `app` sera une "instance" de la classe `FastAPI`.
@@ -166,9 +166,7 @@ $ uvicorn main:app --reload
Si vous créez votre app avec :
-```Python hl_lines="3"
-{!../../../docs_src/first_steps/tutorial002.py!}
-```
+{* ../../docs_src/first_steps/tutorial002.py hl[3] *}
Et la mettez dans un fichier `main.py`, alors vous appelleriez `uvicorn` avec :
@@ -200,9 +198,11 @@ https://example.com/items/foo
/items/foo
```
-!!! info
- Un chemin, ou "path" est aussi souvent appelé route ou "endpoint".
+/// info
+Un chemin, ou "path" est aussi souvent appelé route ou "endpoint".
+
+///
#### Opération
@@ -242,25 +242,26 @@ Nous allons donc aussi appeler ces dernières des "**opérations**".
#### Définir un *décorateur d'opération de chemin*
-```Python hl_lines="6"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[6] *}
Le `@app.get("/")` dit à **FastAPI** que la fonction en dessous est chargée de gérer les requêtes qui vont sur :
* le chemin `/`
* en utilisant une opération 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 +276,17 @@ Tout comme celles les plus exotiques :
* `@app.patch()`
* `@app.trace()`
-!!! tip "Astuce"
- Vous êtes libres d'utiliser chaque opération (méthode HTTP) comme vous le désirez.
+/// tip | Astuce
+
+Vous êtes libres d'utiliser chaque opération (méthode HTTP) comme vous le désirez.
- **FastAPI** n'impose pas de sens spécifique à chacune d'elle.
+**FastAPI** n'impose pas de sens spécifique à chacune d'elle.
- Les informations qui sont présentées ici forment une directive générale, pas des obligations.
+Les informations qui sont présentées ici forment une directive générale, pas des obligations.
- Par exemple, quand l'on utilise **GraphQL**, toutes les actions sont effectuées en utilisant uniquement des opérations `POST`.
+Par exemple, quand l'on utilise **GraphQL**, toutes les actions sont effectuées en utilisant uniquement des opérations `POST`.
+
+///
### Étape 4 : définir la **fonction de chemin**.
@@ -292,9 +296,7 @@ Voici notre "**fonction de chemin**" (ou fonction d'opération de chemin) :
* **opération** : `get`.
* **fonction** : la fonction sous le "décorateur" (sous `@app.get("/")`).
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[7] *}
C'est une fonction Python.
@@ -306,18 +308,17 @@ Ici, c'est une fonction asynchrone (définie avec `async def`).
Vous pourriez aussi la définir comme une fonction classique plutôt qu'avec `async def` :
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial003.py!}
-```
+{* ../../docs_src/first_steps/tutorial003.py hl[7] *}
+
+/// note
-!!! 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}.
+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
-```Python hl_lines="8"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[8] *}
Vous pouvez retourner un dictionnaire (`dict`), une liste (`list`), des valeurs seules comme des chaines de caractères (`str`) et des entiers (`int`), etc.
diff --git a/docs/fr/docs/tutorial/index.md b/docs/fr/docs/tutorial/index.md
index 4dc202b33..83cc5f9e8 100644
--- a/docs/fr/docs/tutorial/index.md
+++ b/docs/fr/docs/tutorial/index.md
@@ -52,22 +52,25 @@ $ pip install fastapi[all]
... qui comprend également `uvicorn`, que vous pouvez utiliser comme serveur pour exécuter votre code.
-!!! note
- Vous pouvez également l'installer pièce par pièce.
+/// note
- C'est ce que vous feriez probablement une fois que vous voudrez déployer votre application en production :
+Vous pouvez également l'installer pièce par pièce.
- ```
- pip install fastapi
- ```
+C'est ce que vous feriez probablement une fois que vous voudrez déployer votre application en production :
- Installez également `uvicorn` pour qu'il fonctionne comme serveur :
+```
+pip install fastapi
+```
+
+Installez également `uvicorn` pour qu'il fonctionne comme serveur :
+
+```
+pip install uvicorn
+```
- ```
- pip install uvicorn
- ```
+Et la même chose pour chacune des dépendances facultatives que vous voulez utiliser.
- Et la même chose pour chacune des dépendances facultatives que vous voulez utiliser.
+///
## Guide utilisateur avancé
diff --git a/docs/fr/docs/tutorial/path-params-numeric-validations.md b/docs/fr/docs/tutorial/path-params-numeric-validations.md
new file mode 100644
index 000000000..3f3280e64
--- /dev/null
+++ b/docs/fr/docs/tutorial/path-params-numeric-validations.md
@@ -0,0 +1,163 @@
+# 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` :
+
+{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[1,3] *}
+
+/// 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 :
+
+{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[10] *}
+
+/// 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 :
+
+{* ../../docs_src/path_params_numeric_validations/tutorial002.py hl[7] *}
+
+Mais gardez à l'esprit que si vous utilisez `Annotated`, vous n'aurez pas ce problème, cela n'aura pas d'importance car vous n'utilisez pas les valeurs par défaut des paramètres de fonction pour `Query()` ou `Path()`.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py hl[10] *}
+
+## 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.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *}
+
+# Avec `Annotated`
+
+Gardez à l'esprit que si vous utilisez `Annotated`, comme vous n'utilisez pas les valeurs par défaut des paramètres de fonction, vous n'aurez pas ce problème, et vous n'aurez probablement pas besoin d'utiliser `*`.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py hl[10] *}
+
+## 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`.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py hl[10] *}
+
+## 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
+
+{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py hl[10] *}
+
+## 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
+
+{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py hl[10] *}
+
+## 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
.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py hl[13] *}
+
+## 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 523e2c8c2..71c96b18e 100644
--- a/docs/fr/docs/tutorial/path-params.md
+++ b/docs/fr/docs/tutorial/path-params.md
@@ -4,9 +4,7 @@ Vous pouvez déclarer des "paramètres" ou "variables" de chemin avec la même s
formatage de chaîne Python :
-```Python hl_lines="6-7"
-{!../../../docs_src/path_params/tutorial001.py!}
-```
+{* ../../docs_src/path_params/tutorial001.py hl[6:7] *}
La valeur du paramètre `item_id` sera transmise à la fonction dans l'argument `item_id`.
@@ -22,15 +20,16 @@ vous verrez comme réponse :
Vous pouvez déclarer le type d'un paramètre de chemin dans la fonction, en utilisant les annotations de type Python :
-```Python hl_lines="7"
-{!../../../docs_src/path_params/tutorial002.py!}
-```
+{* ../../docs_src/path_params/tutorial002.py hl[7] *}
Ici, `item_id` est déclaré comme `int`.
-!!! check "vérifier"
- Ceci vous permettra d'obtenir des fonctionnalités de l'éditeur dans votre fonction, telles
- que des vérifications d'erreur, de l'auto-complétion, etc.
+/// check | vérifier
+
+Ceci vous permettra d'obtenir des fonctionnalités de l'éditeur dans votre fonction, telles
+que des vérifications d'erreur, de l'auto-complétion, etc.
+
+///
## Conversion de données
@@ -40,12 +39,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 +74,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.
-!!! check "vérifier"
- Donc, avec ces mêmes déclarations de type Python, **FastAPI** vous fournit de la validation de données.
+/// check | vérifier
+
+Donc, avec ces mêmes déclarations de type Python, **FastAPI** vous fournit de la validation de données.
- Notez que l'erreur mentionne le point exact où la validation n'a pas réussi.
+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.
+Ce qui est incroyablement utile au moment de développer et débugger du code qui interagit avec votre API.
+
+///
## Documentation
@@ -86,10 +91,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
+
+À nouveau, en utilisant uniquement les déclarations de type Python, **FastAPI** vous fournit automatiquement une documentation interactive (via Swagger UI).
+
+On voit bien dans la documentation que `item_id` est déclaré comme entier.
- On voit bien dans la documentation que `item_id` est déclaré comme entier.
+///
## Les avantages d'avoir une documentation basée sur une norme, et la documentation alternative.
@@ -119,9 +127,7 @@ Et vous avez un second chemin : `/users/{user_id}` pour récupérer de la donné
Les *fonctions de chemin* étant évaluées dans l'ordre, il faut s'assurer que la fonction correspondant à `/users/me` est déclarée avant celle de `/users/{user_id}` :
-```Python hl_lines="6 11"
-{!../../../docs_src/path_params/tutorial003.py!}
-```
+{* ../../docs_src/path_params/tutorial003.py hl[6,11] *}
Sinon, le chemin `/users/{user_id}` correspondrait aussi à `/users/me`, la fonction "croyant" qu'elle a reçu un paramètre `user_id` avec pour valeur `"me"`.
@@ -137,23 +143,25 @@ En héritant de `str` la documentation sera capable de savoir que les valeurs do
Créez ensuite des attributs de classe avec des valeurs fixes, qui seront les valeurs autorisées pour cette énumération.
-```Python hl_lines="1 6-9"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial005.py hl[1,6:9] *}
+
+/// info
-!!! info
- Les énumérations (ou enums) sont disponibles en Python depuis la version 3.4.
+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.
+///
+
+/// 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
Créez ensuite un *paramètre de chemin* avec une annotation de type désignant l'énumération créée précédemment (`ModelName`) :
-```Python hl_lines="16"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial005.py hl[16] *}
### Documentation
@@ -169,20 +177,19 @@ La valeur du *paramètre de chemin* sera un des "membres" de l'énumération.
Vous pouvez comparer ce paramètre avec les membres de votre énumération `ModelName` :
-```Python hl_lines="17"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial005.py hl[17] *}
#### Récupérer la *valeur de l'énumération*
Vous pouvez obtenir la valeur réel d'un membre (une chaîne de caractères ici), avec `model_name.value`, ou en général, `votre_membre_d'enum.value` :
-```Python hl_lines="20"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial005.py hl[20] *}
-!!! tip "Astuce"
- 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*
@@ -190,9 +197,7 @@ Vous pouvez retourner des *membres d'énumération* dans vos *fonctions de chemi
Ils seront convertis vers leurs valeurs correspondantes (chaînes de caractères ici) avant d'être transmis au client :
-```Python hl_lines="18 21 23"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial005.py hl[18,21,23] *}
Le client recevra une réponse JSON comme celle-ci :
@@ -231,14 +236,15 @@ Dans ce cas, le nom du paramètre est `file_path`, et la dernière partie, `:pat
Vous pouvez donc l'utilisez comme tel :
-```Python hl_lines="6"
-{!../../../docs_src/path_params/tutorial004.py!}
-```
+{* ../../docs_src/path_params/tutorial004.py hl[6] *}
+
+/// tip | Astuce
+
+Vous pourriez avoir besoin que le paramètre contienne `/home/johndoe/myfile.txt`, avec un slash au début (`/`).
-!!! tip "Astuce"
- Vous pourriez avoir besoin que le paramètre contienne `/home/johndoe/myfile.txt`, avec un slash au début (`/`).
+Dans ce cas, l'URL serait : `/files//home/johndoe/myfile.txt`, avec un double slash (`//`) entre `files` et `home`.
- Dans ce cas, l'URL serait : `/files//home/johndoe/myfile.txt`, avec un double slash (`//`) entre `files` et `home`.
+///
## Récapitulatif
diff --git a/docs/fr/docs/tutorial/query-params-str-validations.md b/docs/fr/docs/tutorial/query-params-str-validations.md
index f5248fe8b..c54c0c717 100644
--- a/docs/fr/docs/tutorial/query-params-str-validations.md
+++ b/docs/fr/docs/tutorial/query-params-str-validations.md
@@ -4,16 +4,17 @@
Commençons avec cette application pour exemple :
-```Python hl_lines="9"
-{!../../../docs_src/query_params_str_validations/tutorial001.py!}
-```
+{* ../../docs_src/query_params_str_validations/tutorial001.py hl[9] *}
Le paramètre de requête `q` a pour type `Union[str, None]` (ou `str | None` en Python 3.10), signifiant qu'il est de type `str` mais pourrait aussi être égal à `None`, et bien sûr, la valeur par défaut est `None`, donc **FastAPI** saura qu'il n'est pas requis.
-!!! note
- **FastAPI** saura que la valeur de `q` n'est pas requise grâce à la valeur par défaut `= None`.
+/// note
+
+**FastAPI** saura que la valeur de `q` n'est pas requise grâce à la valeur par défaut `= None`.
- Le `Union` dans `Union[str, None]` permettra à votre éditeur de vous offrir un meilleur support et de détecter les erreurs.
+Le `Union` dans `Union[str, None]` permettra à votre éditeur de vous offrir un meilleur support et de détecter les erreurs.
+
+///
## Validation additionnelle
@@ -23,17 +24,13 @@ Nous allons imposer que bien que `q` soit un paramètre optionnel, dès qu'il es
Pour cela, importez d'abord `Query` depuis `fastapi` :
-```Python hl_lines="3"
-{!../../../docs_src/query_params_str_validations/tutorial002.py!}
-```
+{* ../../docs_src/query_params_str_validations/tutorial002.py hl[3] *}
## Utiliser `Query` comme valeur par défaut
Construisez ensuite la valeur par défaut de votre paramètre avec `Query`, en choisissant 50 comme `max_length` :
-```Python hl_lines="9"
-{!../../../docs_src/query_params_str_validations/tutorial002.py!}
-```
+{* ../../docs_src/query_params_str_validations/tutorial002.py hl[9] *}
Comme nous devons remplacer la valeur par défaut `None` dans la fonction par `Query()`, nous pouvons maintenant définir la valeur par défaut avec le paramètre `Query(default=None)`, il sert le même objectif qui est de définir cette valeur par défaut.
@@ -51,22 +48,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
+
+Gardez à l'esprit que la partie la plus importante pour rendre un paramètre optionnel est :
+
+```Python
+= None
+```
- ```Python
- = None
- ```
+ou :
- ou :
+```Python
+= Query(None)
+```
- ```Python
- = Query(None)
- ```
+et utilisera ce `None` pour détecter que ce paramètre de requête **n'est pas requis**.
- et utilisera ce `None` pour détecter que ce paramètre de requête **n'est pas requis**.
+Le `Union[str, None]` est uniquement là pour permettre à votre éditeur un meilleur support.
- Le `Union[str, None]` est uniquement là pour permettre à votre éditeur un meilleur support.
+///
Ensuite, nous pouvons passer d'autres paramètres à `Query`. Dans cet exemple, le paramètre `max_length` qui s'applique aux chaînes de caractères :
@@ -80,17 +80,13 @@ Cela va valider les données, montrer une erreur claire si ces dernières ne son
Vous pouvez aussi rajouter un second paramètre `min_length` :
-```Python hl_lines="9"
-{!../../../docs_src/query_params_str_validations/tutorial003.py!}
-```
+{* ../../docs_src/query_params_str_validations/tutorial003.py hl[9] *}
## Ajouter des validations par expressions régulières
On peut définir une expression régulière à laquelle le paramètre doit correspondre :
-```Python hl_lines="10"
-{!../../../docs_src/query_params_str_validations/tutorial004.py!}
-```
+{* ../../docs_src/query_params_str_validations/tutorial004.py hl[10] *}
Cette expression régulière vérifie que la valeur passée comme paramètre :
@@ -108,12 +104,13 @@ De la même façon que vous pouvez passer `None` comme premier argument pour l'u
Disons que vous déclarez le paramètre `q` comme ayant une longueur minimale de `3`, et une valeur par défaut étant `"fixedquery"` :
-```Python hl_lines="7"
-{!../../../docs_src/query_params_str_validations/tutorial005.py!}
-```
+{* ../../docs_src/query_params_str_validations/tutorial005.py hl[7] *}
+
+/// note | Rappel
+
+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
@@ -137,12 +134,13 @@ q: Union[str, None] = Query(default=None, min_length=3)
Donc pour déclarer une valeur comme requise tout en utilisant `Query`, il faut utiliser `...` comme premier argument :
-```Python hl_lines="7"
-{!../../../docs_src/query_params_str_validations/tutorial006.py!}
-```
+{* ../../docs_src/query_params_str_validations/tutorial006.py hl[7] *}
+
+/// info
-!!! info
- Si vous n'avez jamais vu ce `...` auparavant : c'est une des constantes natives de Python appelée "Ellipsis".
+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.
@@ -152,9 +150,7 @@ Quand on définit un paramètre de requête explicitement avec `Query` on peut a
Par exemple, pour déclarer un paramètre de requête `q` qui peut apparaître plusieurs fois dans une URL, on écrit :
-```Python hl_lines="9"
-{!../../../docs_src/query_params_str_validations/tutorial011.py!}
-```
+{* ../../docs_src/query_params_str_validations/tutorial011.py hl[9] *}
Ce qui fait qu'avec une URL comme :
@@ -175,8 +171,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 :
@@ -186,9 +185,7 @@ La documentation sera donc mise à jour automatiquement pour autoriser plusieurs
Et l'on peut aussi définir une liste de valeurs par défaut si aucune n'est fournie :
-```Python hl_lines="9"
-{!../../../docs_src/query_params_str_validations/tutorial012.py!}
-```
+{* ../../docs_src/query_params_str_validations/tutorial012.py hl[9] *}
Si vous allez à :
@@ -213,14 +210,15 @@ et la réponse sera :
Il est aussi possible d'utiliser directement `list` plutôt que `List[str]` :
-```Python hl_lines="7"
-{!../../../docs_src/query_params_str_validations/tutorial013.py!}
-```
+{* ../../docs_src/query_params_str_validations/tutorial013.py hl[7] *}
-!!! note
- 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,22 +226,21 @@ On peut aussi ajouter plus d'informations sur le paramètre.
Ces informations seront incluses dans le schéma `OpenAPI` généré et utilisées par la documentation interactive ou les outils externes utilisés.
-!!! note
- Gardez en tête que les outils externes utilisés ne supportent pas forcément tous parfaitement OpenAPI.
+/// note
+
+Gardez en tête que les outils externes utilisés ne supportent pas forcément tous parfaitement OpenAPI.
+
+Il se peut donc que certains d'entre eux n'utilisent pas toutes les métadonnées que vous avez déclarées pour le moment, bien que dans la plupart des cas, les fonctionnalités manquantes ont prévu d'être implémentées.
- Il se peut donc que certains d'entre eux n'utilisent pas toutes les métadonnées que vous avez déclarées pour le moment, bien que dans la plupart des cas, les fonctionnalités manquantes ont prévu d'être implémentées.
+///
Vous pouvez ajouter un `title` :
-```Python hl_lines="10"
-{!../../../docs_src/query_params_str_validations/tutorial007.py!}
-```
+{* ../../docs_src/query_params_str_validations/tutorial007.py hl[10] *}
Et une `description` :
-```Python hl_lines="13"
-{!../../../docs_src/query_params_str_validations/tutorial008.py!}
-```
+{* ../../docs_src/query_params_str_validations/tutorial008.py hl[13] *}
## Alias de paramètres
@@ -263,9 +260,7 @@ Mais vous avez vraiment envie que ce soit exactement `item-query`...
Pour cela vous pouvez déclarer un `alias`, et cet alias est ce qui sera utilisé pour trouver la valeur du paramètre :
-```Python hl_lines="9"
-{!../../../docs_src/query_params_str_validations/tutorial009.py!}
-```
+{* ../../docs_src/query_params_str_validations/tutorial009.py hl[9] *}
## Déprécier des paramètres
@@ -275,9 +270,7 @@ Il faut qu'il continue à exister pendant un certain temps car vos clients l'uti
On utilise alors l'argument `deprecated=True` de `Query` :
-```Python hl_lines="18"
-{!../../../docs_src/query_params_str_validations/tutorial010.py!}
-```
+{* ../../docs_src/query_params_str_validations/tutorial010.py hl[18] *}
La documentation le présentera comme il suit :
diff --git a/docs/fr/docs/tutorial/query-params.md b/docs/fr/docs/tutorial/query-params.md
index 962135f63..b87c26c78 100644
--- a/docs/fr/docs/tutorial/query-params.md
+++ b/docs/fr/docs/tutorial/query-params.md
@@ -2,9 +2,7 @@
Quand vous déclarez des paramètres dans votre fonction de chemin qui ne font pas partie des paramètres indiqués dans le chemin associé, ces paramètres sont automatiquement considérés comme des paramètres de "requête".
-```Python hl_lines="9"
-{!../../../docs_src/query_params/tutorial001.py!}
-```
+{* ../../docs_src/query_params/tutorial001.py hl[9] *}
La partie appelée requête (ou **query**) dans une URL est l'ensemble des paires clés-valeurs placées après le `?` , séparées par des `&`.
@@ -63,28 +61,29 @@ Les valeurs des paramètres de votre fonction seront :
De la même façon, vous pouvez définir des paramètres de requête comme optionnels, en leur donnant comme valeur par défaut `None` :
-```Python hl_lines="9"
-{!../../../docs_src/query_params/tutorial002.py!}
-```
+{* ../../docs_src/query_params/tutorial002.py hl[9] *}
Ici, le paramètre `q` sera optionnel, et aura `None` comme valeur par défaut.
-!!! 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
+
+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.
-!!! 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.
+/// 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
Vous pouvez aussi déclarer des paramètres de requête comme booléens (`bool`), **FastAPI** les convertira :
-```Python hl_lines="9"
-{!../../../docs_src/query_params/tutorial003.py!}
-```
+{* ../../docs_src/query_params/tutorial003.py hl[9] *}
Avec ce code, en allant sur :
@@ -126,9 +125,7 @@ Et vous n'avez pas besoin de les déclarer dans un ordre spécifique.
Ils seront détectés par leurs noms :
-```Python hl_lines="8 10"
-{!../../../docs_src/query_params/tutorial004.py!}
-```
+{* ../../docs_src/query_params/tutorial004.py hl[8,10] *}
## Paramètres de requête requis
@@ -138,9 +135,7 @@ Si vous ne voulez pas leur donner de valeur par défaut mais juste les rendre op
Mais si vous voulez rendre un paramètre de requête obligatoire, vous pouvez juste ne pas y affecter de valeur par défaut :
-```Python hl_lines="6-7"
-{!../../../docs_src/query_params/tutorial005.py!}
-```
+{* ../../docs_src/query_params/tutorial005.py hl[6:7] *}
Ici le paramètre `needy` est un paramètre requis (ou obligatoire) de type `str`.
@@ -184,9 +179,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
Et bien sur, vous pouvez définir certains paramètres comme requis, certains avec des valeurs par défaut et certains entièrement optionnels :
-```Python hl_lines="10"
-{!../../../docs_src/query_params/tutorial006.py!}
-```
+{* ../../docs_src/query_params/tutorial006.py hl[10] *}
Ici, on a donc 3 paramètres de requête :
@@ -194,5 +187,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 3af166ab0..bd166f205 100644
--- a/docs/he/docs/index.md
+++ b/docs/he/docs/index.md
@@ -12,10 +12,10 @@
-
+
-
-
+
+
@@ -94,7 +94,7 @@ FastAPI היא תשתית רשת מודרנית ומהירה (ביצועים ג
"_Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted **Hug** to be - it's really inspiring to see someone build that._"
-
+
---
@@ -446,7 +446,7 @@ item: Item
בשימוש Pydantic:
--
email_validator
- לאימות כתובות אימייל.
+- email-validator
- לאימות כתובות אימייל.
בשימוש Starlette:
diff --git a/docs/hu/docs/index.md b/docs/hu/docs/index.md
index b7231ad56..45ff49c3b 100644
--- a/docs/hu/docs/index.md
+++ b/docs/hu/docs/index.md
@@ -6,7 +6,7 @@
-
+
@@ -87,7 +87,7 @@ Kulcs funkciók:
"_Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted **Hug** to be - it's really inspiring to see someone build that._"
-
+
---
@@ -376,7 +376,7 @@ Visszatérve az előző kód példához. A **FastAPI**:
* Validálja hogy van egy `item_id` mező a `GET` és `PUT` kérésekben.
* Validálja hogy az `item_id` `int` típusú a `GET` és `PUT` kérésekben.
* Ha nem akkor látni fogunk egy tiszta hibát ezzel kapcsolatban.
-* ellenőrzi hogyha van egy opcionális query paraméter `q` névvel (azaz `http://127.0.0.1:8000/items/foo?q=somequery`) `GET` kérések esetén.
+* ellenőrzi hogyha van egy opcionális query paraméter `q` névvel (azaz `http://127.0.0.1:8000/items/foo?q=somequery`) `GET` kérések esetén.
* Mivel a `q` paraméter `= None`-al van deklarálva, ezért opcionális.
* `None` nélkül ez a mező kötelező lenne (mint például a body `PUT` kérések esetén).
* a `/items/{item_id}` címre érkező `PUT` kérések esetén, a JSON-t a következőképpen olvassa be:
@@ -443,7 +443,7 @@ Ezeknek a további megértéséhez:
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.
diff --git a/docs/id/docs/index.md b/docs/id/docs/index.md
new file mode 100644
index 000000000..5fb0c4c9c
--- /dev/null
+++ b/docs/id/docs/index.md
@@ -0,0 +1,495 @@
+# FastAPI
+
+
+
+
+ FastAPI, framework performa tinggi, mudah dipelajari, cepat untuk coding, siap untuk pengembangan +
+ + +--- + +**Dokumentasi**: https://fastapi.tiangolo.com + +**Kode Sumber**: https://github.com/fastapi/fastapi + +--- + +FastAPI adalah *framework* *web* moderen, cepat (performa-tinggi) untuk membangun API dengan Python berdasarkan tipe petunjuk Python. + +Fitur utama FastAPI: + +* **Cepat**: Performa sangat tinggi, setara **NodeJS** dan **Go** (berkat Starlette dan Pydantic). [Salah satu *framework* Python tercepat yang ada](#performa). +* **Cepat untuk coding**: Meningkatkan kecepatan pengembangan fitur dari 200% sampai 300%. * +* **Sedikit bug**: Mengurangi hingga 40% kesalahan dari manusia (pemrogram). * +* **Intuitif**: Dukungan editor hebat. Penyelesaian di mana pun. Lebih sedikit *debugging*. +* **Mudah**: Dibuat mudah digunakan dan dipelajari. Sedikit waktu membaca dokumentasi. +* **Ringkas**: Mengurasi duplikasi kode. Beragam fitur dari setiap deklarasi parameter. Lebih sedikit *bug*. +* **Handal**: Dapatkan kode siap-digunakan. Dengan dokumentasi otomatis interaktif. +* **Standar-resmi**: Berdasarkan (kompatibel dengan ) standar umum untuk API: OpenAPI (sebelumnya disebut Swagger) dan JSON Schema. + +* estimasi berdasarkan pengujian tim internal pengembangan applikasi siap pakai. + +## Sponsor + + + +{% if sponsors %} +{% for sponsor in sponsors.gold -%} +async def
...fastapi dev main.py
...email-validator
- untuk validasi email.
+
+Digunakan oleh Starlette:
+
+* httpx
- Dibutuhkan jika anda menggunakan `TestClient`.
+* jinja2
- Dibutuhkan jika anda menggunakan konfigurasi template bawaan.
+* python-multipart
- Dibutuhkan jika anda menggunakan form dukungan "parsing", dengan `request.form()`.
+
+Digunakan oleh FastAPI / Starlette:
+
+* uvicorn
- untuk server yang memuat dan melayani aplikasi anda. Termasuk `uvicorn[standard]`, yang memasukan sejumlah dependensi (misal `uvloop`) untuk needed melayani dengan performa tinggi.
+* `fastapi-cli` - untuk menyediakan perintah `fastapi`.
+
+### Tanpda dependensi `standard`
+
+Jika anda tidak ingin menambahkan dependensi opsional `standard`, anda dapat menggunakan `pip install fastapi` daripada `pip install "fastapi[standard]"`.
+
+### Dependensi Opsional Tambahan
+
+Ada beberapa dependensi opsional yang bisa anda install.
+
+Dependensi opsional tambahan Pydantic:
+
+* pydantic-settings
- untuk manajemen setting.
+* pydantic-extra-types
- untuk tipe tambahan yang digunakan dengan Pydantic.
+
+Dependensi tambahan opsional FastAPI:
+
+* orjson
- Diperlukan jika anda akan menggunakan`ORJSONResponse`.
+* ujson
- Diperlukan jika anda akan menggunakan `UJSONResponse`.
+
+## Lisensi
+
+Project terlisensi dengan lisensi MIT.
diff --git a/docs/id/docs/tutorial/first-steps.md b/docs/id/docs/tutorial/first-steps.md
new file mode 100644
index 000000000..9b461507d
--- /dev/null
+++ b/docs/id/docs/tutorial/first-steps.md
@@ -0,0 +1,332 @@
+# Langkah Pertama
+
+File FastAPI yang paling sederhana bisa seperti berikut:
+
+{* ../../docs_src/first_steps/tutorial001.py *}
+
+Salin file tersebut ke `main.py`.
+
+Jalankan di server:
+
+get
+
+/// info | `@decorator` Info
+
+Sintaksis `@sesuatu` di Python disebut "dekorator".
+
+Dekorator ditempatkan di atas fungsi. Seperti sebuah topi cantik (Saya pikir istilah ini berasal dari situ).
+
+"dekorator" memanggil dan bekerja dengan fungsi yang ada di bawahnya
+
+Pada kondisi ini, dekorator ini memberi tahu **FastAPI** bahwa fungsi di bawah nya berhubungan dengan **path** `/` dengan **operasi** `get`.
+
+Sehingga disebut **dekorator operasi path**.
+
+///
+
+Operasi lainnya yang bisa digunakan:
+
+* `@app.post()`
+* `@app.put()`
+* `@app.delete()`
+
+Dan operasi unik lainnya:
+
+* `@app.options()`
+* `@app.head()`
+* `@app.patch()`
+* `@app.trace()`
+
+/// tip | Tips
+
+Jika anda bisa menggunakan operasi apa saja (metode HTTP).
+
+**FastAPI** tidak mengharuskan anda menggunakan operasi tertentu.
+
+Informasi di sini hanyalah sebagai panduan, bukan keharusan.
+
+Sebagai contoh, ketika menggunakan GraphQL, semua operasi umumnya hanya menggunakan `POST`.
+
+///
+
+### Langkah 4: mendefinisikan **fungsi operasi path**
+
+Ini "**fungsi operasi path**" kita:
+
+* **path**: adalah `/`.
+* **operasi**: adalah `get`.
+* **fungsi**: adalah fungsi yang ada di bawah dekorator (di bawah `@app.get("/")`).
+
+{* ../../docs_src/first_steps/tutorial001.py hl[7] *}
+
+Ini adalah fungsi Python.
+
+Fungsi ini dipanggil **FastAPI** setiap kali menerima request ke URL "`/`" dengan operasi `GET`.
+
+Di kondisi ini, ini adalah sebuah fungsi `async`.
+
+---
+
+Anda bisa mendefinisikan fungsi ini sebagai fungsi normal daripada `async def`:
+
+{* ../../docs_src/first_steps/tutorial003.py hl[7] *}
+
+/// note | Catatan
+
+Jika anda tidak tahu perbedaannya, kunjungi [Async: *"Panduan cepat"*](../async.md#in-a-hurry){.internal-link target=_blank}.
+
+///
+
+### Langkah 5: hasilkan konten
+
+{* ../../docs_src/first_steps/tutorial001.py hl[8] *}
+
+Anda bisa menghasilkan `dict`, `list`, nilai singular seperti `str`, `int`, dll.
+
+Anda juga bisa menghasilkan model Pydantic (anda akan belajar mengenai ini nanti).
+
+Ada banyak objek dan model yang secara otomatis dikonversi ke JSON (termasuk ORM, dll). Anda bisa menggunakan yang anda suka, kemungkinan sudah didukung.
+
+## Ringkasan
+
+* Impor `FastAPI`.
+* Buat sebuah instance `app`.
+* Tulis **dekorator operasi path** menggunakan dekorator seperti `@app.get("/")`.
+* Definisikan **fungsi operasi path**; sebagai contoh, `def root(): ...`.
+* Jalankan server development dengan perintah `fastapi dev`.
diff --git a/docs/id/docs/tutorial/index.md b/docs/id/docs/tutorial/index.md
index 6b6de24f0..c01ec9a89 100644
--- a/docs/id/docs/tutorial/index.md
+++ b/docs/id/docs/tutorial/index.md
@@ -52,22 +52,25 @@ $ pip install "fastapi[all]"
...yang juga termasuk `uvicorn`, yang dapat kamu gunakan sebagai server yang menjalankan kodemu.
-!!! note "Catatan"
- Kamu juga dapat meng-installnya bagian demi bagian.
+/// note | Catatan
- Hal ini mungkin yang akan kamu lakukan ketika kamu hendak menyebarkan (men-deploy) aplikasimu ke tahap produksi:
+Kamu juga dapat meng-installnya bagian demi bagian.
- ```
- pip install fastapi
- ```
+Hal ini mungkin yang akan kamu lakukan ketika kamu hendak menyebarkan (men-deploy) aplikasimu ke tahap produksi:
- Juga install `uvicorn` untuk menjalankan server"
+```
+pip install fastapi
+```
+
+Juga install `uvicorn` untuk menjalankan server"
+
+```
+pip install "uvicorn[standard]"
+```
- ```
- pip install "uvicorn[standard]"
- ```
+Dan demikian juga untuk pilihan dependensi yang hendak kamu gunakan.
- Dan demikian juga untuk pilihan dependensi yang hendak kamu gunakan.
+///
## Pedoman Pengguna Lanjutan
diff --git a/docs/id/docs/tutorial/path-params.md b/docs/id/docs/tutorial/path-params.md
new file mode 100644
index 000000000..7c24de4d3
--- /dev/null
+++ b/docs/id/docs/tutorial/path-params.md
@@ -0,0 +1,258 @@
+# Parameter Path
+
+"parameter" atau "variabel" path didefinisikan dengan sintaksis Python format string:
+
+{* ../../docs_src/path_params/tutorial001.py hl[6:7] *}
+
+Nilai parameter path `item_id` akan dikirim ke fungsi sebagai argument `item_id`:
+
+Jika anda menjalankan contoh berikut dan kunjungi http://127.0.0.1:8000/items/foo, anda akan melihat respon:
+
+```JSON
+{"item_id":"foo"}
+```
+
+## Parameter path dengan tipe data
+
+Tipe data parameter path bisa didefinisikan di dalam fungsi, menggunakan anotasi tipe data standar Python:
+
+{* ../../docs_src/path_params/tutorial002.py hl[7] *}
+
+Dalam hal ini `item_id` didefinisikan sebagai `int`.
+
+/// check | Periksa
+
+Penyunting kode anda bisa membantu periksa di dalam fungsi seperti pemeriksaan kesalahan, kelengkapan kode, dll.
+
+///
+
+## Konversi data
+
+Jika contoh berikut dijalankan dan diakses browser melalui http://127.0.0.1:8000/items/3, anda akan melihat respon:
+
+```JSON
+{"item_id":3}
+```
+
+/// check | Periksa
+
+Perhatikan nilai fungsi yang diterima (dan dihasilkan) adalah `3`, sebagai `int` di Python, dan bukan string `"3"`.
+
+Sehingga dengan deklarasi tipe data **FastAPI** memberikan request otomatis "parsing".
+
+///
+
+## Validasi Data
+
+Tetapi jika di browser anda akses http://127.0.0.1:8000/items/foo, anda akan melihat pesan kesalahan HTTP:
+
+```JSON
+{
+ "detail": [
+ {
+ "type": "int_parsing",
+ "loc": [
+ "path",
+ "item_id"
+ ],
+ "msg": "Input should be a valid integer, unable to parse string as an integer",
+ "input": "foo",
+ "url": "https://errors.pydantic.dev/2.1/v/int_parsing"
+ }
+ ]
+}
+```
+
+Karena parameter path `item_id` bernilai `"foo"` yang bukan tipe data `int`.
+
+Kesalahan yang sama akan muncul jika menggunakan `float` daripada `int`, seperti di: http://127.0.0.1:8000/items/4.2
+
+/// check | Periksa
+
+Dengan deklarasi tipe data Python, **FastAPI** melakukan validasi data.
+
+Perhatikan kesalahan tersebut juga menjelaskan validasi apa yang tidak sesuai.
+
+Validasi ini sangat membantu ketika mengembangkan dan men-*debug* kode yang berhubungan dengan API anda.
+
+///
+
+## Dokumentasi
+
+Ketika anda membuka browser di http://127.0.0.1:8000/docs, anda melihat dokumentasi API interaktif otomatis berikut:
+
+FastAPI framework, alte prestazioni, facile da imparare, rapido da implementare, pronto per il rilascio in produzione
+ @@ -88,7 +88,7 @@ Le sue caratteristiche principali sono: "_Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted **Hug** to be - it's really inspiring to see someone build that._" - + --- @@ -438,7 +438,7 @@ Per approfondire, consulta la sezioneemail_validator
- per la validazione di email.
+* email-validator
- per la validazione di email.
Usate da Starlette:
diff --git a/docs/ja/docs/advanced/additional-status-codes.md b/docs/ja/docs/advanced/additional-status-codes.md
index d1f8e6451..33457f591 100644
--- a/docs/ja/docs/advanced/additional-status-codes.md
+++ b/docs/ja/docs/advanced/additional-status-codes.md
@@ -14,21 +14,25 @@
これを達成するには、 `JSONResponse` をインポートし、 `status_code` を設定して直接内容を返します。
-```Python hl_lines="4 25"
-{!../../../docs_src/additional_status_codes/tutorial001.py!}
-```
+{* ../../docs_src/additional_status_codes/tutorial001.py hl[4,25] *}
-!!! warning "注意"
- 上記の例のように `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..1b2cd914d 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` を使う
@@ -21,19 +24,23 @@
使いたい `Response` クラス (サブクラス) をインポートし、 *path operationデコレータ* に宣言します。
-```Python hl_lines="2 7"
-{!../../../docs_src/custom_response/tutorial001b.py!}
-```
+{* ../../docs_src/custom_response/tutorial001b.py hl[2,7] *}
+
+/// info | 情報
+
+パラメータ `response_class` は、レスポンスの「メディアタイプ」を定義するために利用することもできます。
+
+この場合、HTTPヘッダー `Content-Type` には `application/json` がセットされます。
+
+そして、OpenAPIにはそのようにドキュメントされます。
-!!! info "情報"
- パラメータ `response_class` は、レスポンスの「メディアタイプ」を定義するために利用することもできます。
+///
- この場合、HTTPヘッダー `Content-Type` には `application/json` がセットされます。
+/// tip | 豆知識
- そして、OpenAPIにはそのようにドキュメントされます。
+`ORJSONResponse` は、現在はFastAPIのみで利用可能で、Starletteでは利用できません。
-!!! tip "豆知識"
- `ORJSONResponse` は、現在はFastAPIのみで利用可能で、Starletteでは利用できません。
+///
## HTMLレスポンス
@@ -42,16 +49,17 @@
* `HTMLResponse` をインポートする。
* *path operation* のパラメータ `content_type` に `HTMLResponse` を渡す。
-```Python hl_lines="2 7"
-{!../../../docs_src/custom_response/tutorial002.py!}
-```
+{* ../../docs_src/custom_response/tutorial002.py hl[2,7] *}
-!!! info "情報"
- パラメータ `response_class` は、レスポンスの「メディアタイプ」を定義するために利用されます。
+/// info | 情報
- この場合、HTTPヘッダー `Content-Type` には `text/html` がセットされます。
+パラメータ `response_class` は、レスポンスの「メディアタイプ」を定義するために利用されます。
- そして、OpenAPIにはそのようにドキュメント化されます。
+この場合、HTTPヘッダー `Content-Type` には `text/html` がセットされます。
+
+そして、OpenAPIにはそのようにドキュメント化されます。
+
+///
### `Response` を返す
@@ -59,15 +67,19 @@
上記と同じ例において、 `HTMLResponse` を返すと、このようになります:
-```Python hl_lines="2 7 19"
-{!../../../docs_src/custom_response/tutorial003.py!}
-```
+{* ../../docs_src/custom_response/tutorial003.py hl[2,7,19] *}
+
+/// warning | 注意
+
+*path operation関数* から直接返される `Response` は、OpenAPIにドキュメントされず (例えば、 `Content-Type` がドキュメントされない) 、自動的な対話的ドキュメントからも閲覧できません。
+
+///
-!!! warning "注意"
- *path operation関数* から直接返される `Response` は、OpenAPIにドキュメントされず (例えば、 `Content-Type` がドキュメントされない) 、自動的な対話的ドキュメントからも閲覧できません。
+/// info | 情報
-!!! info "情報"
- もちろん、実際の `Content-Type` ヘッダーやステータスコードなどは、返された `Response` オブジェクトに由来しています。
+もちろん、実際の `Content-Type` ヘッダーやステータスコードなどは、返された `Response` オブジェクトに由来しています。
+
+///
### OpenAPIドキュメントと `Response` のオーバーライド
@@ -79,9 +91,7 @@
例えば、このようになります:
-```Python hl_lines="7 21 23"
-{!../../../docs_src/custom_response/tutorial004.py!}
-```
+{* ../../docs_src/custom_response/tutorial004.py hl[7,21,23] *}
この例では、関数 `generate_html_response()` は、`str` のHTMLを返すのではなく `Response` を生成して返しています。
@@ -97,10 +107,13 @@
`Response` を使って他の何かを返せますし、カスタムのサブクラスも作れることを覚えておいてください。
-!!! note "技術詳細"
- `from starlette.responses import HTMLResponse` も利用できます。
+/// note | 技術詳細
+
+`from starlette.responses import HTMLResponse` も利用できます。
+
+**FastAPI** は開発者の利便性のために `fastapi.responses` として `starlette.responses` と同じものを提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。
- **FastAPI** は開発者の利便性のために `fastapi.responses` として `starlette.responses` と同じものを提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。
+///
### `Response`
@@ -117,9 +130,7 @@
FastAPI (実際にはStarlette) は自動的にContent-Lengthヘッダーを含みます。また、media_typeに基づいたContent-Typeヘッダーを含み、テキストタイプのためにcharsetを追加します。
-```Python hl_lines="1 18"
-{!../../../docs_src/response_directly/tutorial002.py!}
-```
+{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *}
### `HTMLResponse`
@@ -129,9 +140,7 @@ FastAPI (実際にはStarlette) は自動的にContent-Lengthヘッダーを含
テキストやバイトを受け取り、プレーンテキストのレスポンスを返します。
-```Python hl_lines="2 7 9"
-{!../../../docs_src/custom_response/tutorial005.py!}
-```
+{* ../../docs_src/custom_response/tutorial005.py hl[2,7,9] *}
### `JSONResponse`
@@ -147,31 +156,31 @@ FastAPI (実際にはStarlette) は自動的にContent-Lengthヘッダーを含
`ujson`を使った、代替のJSONレスポンスです。
-!!! warning "注意"
- `ujson` は、いくつかのエッジケースの取り扱いについて、Pythonにビルトインされた実装よりも作りこまれていません。
+/// warning | 注意
+
+`ujson` は、いくつかのエッジケースの取り扱いについて、Pythonにビルトインされた実装よりも作りこまれていません。
+
+///
+
+{* ../../docs_src/custom_response/tutorial001.py hl[2,7] *}
-```Python hl_lines="2 7"
-{!../../../docs_src/custom_response/tutorial001.py!}
-```
+/// tip | 豆知識
-!!! tip "豆知識"
- `ORJSONResponse` のほうが高速な代替かもしれません。
+`ORJSONResponse` のほうが高速な代替かもしれません。
+
+///
### `RedirectResponse`
HTTPリダイレクトを返します。デフォルトでは307ステータスコード (Temporary Redirect) となります。
-```Python hl_lines="2 9"
-{!../../../docs_src/custom_response/tutorial006.py!}
-```
+{* ../../docs_src/custom_response/tutorial006.py hl[2,9] *}
### `StreamingResponse`
非同期なジェネレータか通常のジェネレータ・イテレータを受け取り、レスポンスボディをストリームします。
-```Python hl_lines="2 14"
-{!../../../docs_src/custom_response/tutorial007.py!}
-```
+{* ../../docs_src/custom_response/tutorial007.py hl[2,14] *}
#### `StreamingResponse` をファイルライクなオブジェクトとともに使う
@@ -179,12 +188,13 @@ HTTPリダイレクトを返します。デフォルトでは307ステータス
これにはクラウドストレージとの連携や映像処理など、多くのライブラリが含まれています。
-```Python hl_lines="2 10-12 14"
-{!../../../docs_src/custom_response/tutorial008.py!}
-```
+{* ../../docs_src/custom_response/tutorial008.py hl[2,10:12,14] *}
+
+/// tip | 豆知識
+
+ここでは `async` や `await` をサポートしていない標準の `open()` を使っているので、通常の `def` でpath operationを宣言していることに注意してください。
-!!! tip "豆知識"
- ここでは `async` や `await` をサポートしていない標準の `open()` を使っているので、通常の `def` でpath operationを宣言していることに注意してください。
+///
### `FileResponse`
@@ -199,9 +209,7 @@ HTTPリダイレクトを返します。デフォルトでは307ステータス
ファイルレスポンスには、適切な `Content-Length` 、 `Last-Modified` 、 `ETag` ヘッダーが含まれます。
-```Python hl_lines="2 10"
-{!../../../docs_src/custom_response/tutorial009.py!}
-```
+{* ../../docs_src/custom_response/tutorial009.py hl[2,10] *}
## デフォルトレスポンスクラス
@@ -211,12 +219,13 @@ HTTPリダイレクトを返します。デフォルトでは307ステータス
以下の例では、 **FastAPI** は、全ての *path operation* で `JSONResponse` の代わりに `ORJSONResponse` をデフォルトとして利用します。
-```Python hl_lines="2 4"
-{!../../../docs_src/custom_response/tutorial010.py!}
-```
+{* ../../docs_src/custom_response/tutorial010.py hl[2,4] *}
+
+/// tip | 豆知識
+
+前に見たように、 *path operation* の中で `response_class` をオーバーライドできます。
-!!! tip "豆知識"
- 前に見たように、 *path operation* の中で `response_class` をオーバーライドできます。
+///
## その他のドキュメント
diff --git a/docs/ja/docs/advanced/index.md b/docs/ja/docs/advanced/index.md
index 2d60e7489..22eaf6eb8 100644
--- a/docs/ja/docs/advanced/index.md
+++ b/docs/ja/docs/advanced/index.md
@@ -6,10 +6,13 @@
以降のセクションでは、チュートリアルでは説明しきれなかったオプションや設定、および機能について説明します。
-!!! tip "豆知識"
- 以降のセクションは、 **必ずしも"応用編"ではありません**。
+/// tip | 豆知識
- ユースケースによっては、その中から解決策を見つけられるかもしれません。
+以降のセクションは、 **必ずしも"応用編"ではありません**。
+
+ユースケースによっては、その中から解決策を見つけられるかもしれません。
+
+///
## 先にチュートリアルを読む
diff --git a/docs/ja/docs/advanced/path-operation-advanced-configuration.md b/docs/ja/docs/advanced/path-operation-advanced-configuration.md
index 35b381cae..05188d5b2 100644
--- a/docs/ja/docs/advanced/path-operation-advanced-configuration.md
+++ b/docs/ja/docs/advanced/path-operation-advanced-configuration.md
@@ -2,16 +2,17 @@
## OpenAPI operationId
-!!! warning "注意"
- あなたがOpenAPIの「エキスパート」でなければ、これは必要ないかもしれません。
+/// warning | 注意
+
+あなたがOpenAPIの「エキスパート」でなければ、これは必要ないかもしれません。
+
+///
*path operation* で `operation_id` パラメータを利用することで、OpenAPIの `operationId` を設定できます。
`operation_id` は各オペレーションで一意にする必要があります。
-```Python hl_lines="6"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial001.py!}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial001.py hl[6] *}
### *path operation関数* の名前をoperationIdとして使用する
@@ -19,25 +20,27 @@ APIの関数名を `operationId` として利用したい場合、すべてのAP
そうする場合は、すべての *path operation* を追加した後に行う必要があります。
-```Python hl_lines="2 12-21 24"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial002.py hl[2,12:21,24] *}
+
+/// tip | 豆知識
+
+`app.openapi()` を手動でコールする場合、その前に`operationId`を更新する必要があります。
+
+///
+
+/// warning | 注意
-!!! tip "豆知識"
- `app.openapi()` を手動でコールする場合、その前に`operationId`を更新する必要があります。
+この方法をとる場合、各 *path operation関数* が一意な名前である必要があります。
-!!! warning "注意"
- この方法をとる場合、各 *path operation関数* が一意な名前である必要があります。
+それらが異なるモジュール (Pythonファイル) にあるとしてもです。
- それらが異なるモジュール (Pythonファイル) にあるとしてもです。
+///
## OpenAPIから除外する
生成されるOpenAPIスキーマ (つまり、自動ドキュメント生成の仕組み) から *path operation* を除外するには、 `include_in_schema` パラメータを `False` にします。
-```Python hl_lines="6"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial003.py!}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial003.py hl[6] *}
## docstringによる説明の高度な設定
@@ -47,6 +50,4 @@ APIの関数名を `operationId` として利用したい場合、すべてのAP
ドキュメントには表示されませんが、他のツール (例えばSphinx) では残りの部分を利用できるでしょう。
-```Python hl_lines="19-29"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial004.py!}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial004.py hl[19:29] *}
diff --git a/docs/ja/docs/advanced/response-directly.md b/docs/ja/docs/advanced/response-directly.md
index 10ec88548..42412d507 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** は直接それを返します。
@@ -31,14 +34,15 @@
このようなケースでは、レスポンスにデータを含める前に `jsonable_encoder` を使ってデータを変換できます。
-```Python hl_lines="6-7 21-22"
-{!../../../docs_src/response_directly/tutorial001.py!}
-```
+{* ../../docs_src/response_directly/tutorial001.py hl[6:7,21:22] *}
+
+/// note | 技術詳細
+
+また、`from starlette.responses import JSONResponse` も利用できます。
-!!! note "技術詳細"
- また、`from starlette.responses import JSONResponse` も利用できます。
+**FastAPI** は開発者の利便性のために `fastapi.responses` という `starlette.responses` と同じものを提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。
- **FastAPI** は開発者の利便性のために `fastapi.responses` という `starlette.responses` と同じものを提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。
+///
## カスタム `Response` を返す
@@ -50,9 +54,7 @@
XMLを文字列にし、`Response` に含め、それを返します。
-```Python hl_lines="1 18"
-{!../../../docs_src/response_directly/tutorial002.py!}
-```
+{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *}
## 備考
diff --git a/docs/ja/docs/advanced/websockets.md b/docs/ja/docs/advanced/websockets.md
index 65e4112a6..43009eba8 100644
--- a/docs/ja/docs/advanced/websockets.md
+++ b/docs/ja/docs/advanced/websockets.md
@@ -38,30 +38,27 @@ $ pip install websockets
しかし、これはWebSocketのサーバーサイドに焦点を当て、実用的な例を示す最も簡単な方法です。
-```Python hl_lines="2 6-38 41-43"
-{!../../../docs_src/websockets/tutorial001.py!}
-```
+{* ../../docs_src/websockets/tutorial001.py hl[2,6:38,41:43] *}
## `websocket` を作成する
**FastAPI** アプリケーションで、`websocket` を作成します。
-```Python hl_lines="1 46-47"
-{!../../../docs_src/websockets/tutorial001.py!}
-```
+{* ../../docs_src/websockets/tutorial001.py hl[1,46:47] *}
+
+/// note | 技術詳細
+
+`from starlette.websockets import WebSocket` を使用しても構いません.
-!!! note "技術詳細"
- `from starlette.websockets import WebSocket` を使用しても構いません.
+**FastAPI** は開発者の利便性のために、同じ `WebSocket` を提供します。しかし、こちらはStarletteから直接提供されるものです。
- **FastAPI** は開発者の利便性のために、同じ `WebSocket` を提供します。しかし、こちらはStarletteから直接提供されるものです。
+///
## メッセージの送受信
WebSocketルートでは、 `await` を使ってメッセージの送受信ができます。
-```Python hl_lines="48-52"
-{!../../../docs_src/websockets/tutorial001.py!}
-```
+{* ../../docs_src/websockets/tutorial001.py hl[48:52] *}
バイナリやテキストデータ、JSONデータを送受信できます。
@@ -112,16 +109,17 @@ WebSocketエンドポイントでは、`fastapi` から以下をインポート
これらは、他のFastAPI エンドポイント/*path operation* の場合と同じように機能します。
-```Python hl_lines="58-65 68-83"
-{!../../../docs_src/websockets/tutorial002.py!}
-```
+{* ../../docs_src/websockets/tutorial002.py hl[58:65,68:83] *}
+
+/// info | 情報
-!!! info "情報"
- WebSocket で `HTTPException` を発生させることはあまり意味がありません。したがって、WebSocketの接続を直接閉じる方がよいでしょう。
+WebSocket で `HTTPException` を発生させることはあまり意味がありません。したがって、WebSocketの接続を直接閉じる方がよいでしょう。
- クロージングコードは、仕様で定義された有効なコードの中から使用することができます。
+クロージングコードは、仕様で定義された有効なコードの中から使用することができます。
- 将来的には、どこからでも `raise` できる `WebSocketException` が用意され、専用の例外ハンドラを追加できるようになる予定です。これは、Starlette の PR #527 に依存するものです。
+将来的には、どこからでも `raise` できる `WebSocketException` が用意され、専用の例外ハンドラを追加できるようになる予定です。これは、Starlette の PR #527 に依存するものです。
+
+///
### 依存関係を用いてWebSocketsを試してみる
@@ -144,8 +142,11 @@ $ uvicorn main:app --reload
* パスで使用される「Item ID」
* クエリパラメータとして使用される「Token」
-!!! tip "豆知識"
- クエリ `token` は依存パッケージによって処理されることに注意してください。
+/// tip | 豆知識
+
+クエリ `token` は依存パッケージによって処理されることに注意してください。
+
+///
これにより、WebSocketに接続してメッセージを送受信できます。
@@ -155,9 +156,7 @@ $ uvicorn main:app --reload
WebSocket接続が閉じられると、 `await websocket.receive_text()` は例外 `WebSocketDisconnect` を発生させ、この例のようにキャッチして処理することができます。
-```Python hl_lines="81-83"
-{!../../../docs_src/websockets/tutorial003.py!}
-```
+{* ../../docs_src/websockets/tutorial003.py hl[81:83] *}
試してみるには、
@@ -171,12 +170,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..8129a7002 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 | 情報
+
+Webargsは、Marshmallowと同じ開発者により作られました。
+
+///
-!!! check "**FastAPI**へ与えたインスピレーション"
- 受信したデータに対する自動的なバリデーションを持っている点。
+/// check | **FastAPI**へ与えたインスピレーション
+
+受信したデータに対する自動的なバリデーションを持っている点。
+
+///
### APISpec
@@ -171,11 +193,17 @@ Flask, Starlette, Responderなどにおいてはそのように動作します
エディタでは、この問題を解決することはできません。また、パラメータやMarshmallowスキーマを変更したときに、YAMLのdocstringを変更するのを忘れてしまうと、生成されたスキーマが古くなってしまいます。
-!!! info "情報"
- APISpecは、Marshmallowと同じ開発者により作成されました。
+/// info | 情報
+
+APISpecは、Marshmallowと同じ開発者により作成されました。
+
+///
+
+/// check | **FastAPI**へ与えたインスピレーション
+
+OpenAPIという、APIについてのオープンな標準をサポートしている点。
-!!! 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`引数を関数に持つことにインスピレーションを与えました。
- Hug (HugはFalconをベースにしています) と一緒に、**FastAPI**が`response`引数を関数に持つことにインスピレーションを与えました。
+**FastAPI**では任意ですが、ヘッダーやCookieやステータスコードを設定するために利用されています。
- **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 | 情報
+
+HugはTimothy Crosleyにより作成されました。彼は`isort`など、Pythonのファイル内のインポートの並び替えを自動的におこうなう素晴らしいツールの開発者です。
+
+///
+
+/// check | **FastAPI**へ与えたインスピレーション
+
+HugはAPIStarに部分的なインスピレーションを与えており、私が発見した中ではAPIStarと同様に最も期待の持てるツールの一つでした。
-!!! check "**FastAPI**へ与えたインスピレーション"
- HugはAPIStarに部分的なインスピレーションを与えており、私が発見した中ではAPIStarと同様に最も期待の持てるツールの一つでした。
+Hugは、**FastAPI**がPythonの型ヒントを用いてパラメータを宣言し自動的にAPIを定義するスキーマを生成することを触発しました。
- Hugは、**FastAPI**がPythonの型ヒントを用いてパラメータを宣言し自動的にAPIを定義するスキーマを生成することを触発しました。
+Hugは、**FastAPI**がヘッダーやクッキーを設定するために関数に `response`引数を宣言することにインスピレーションを与えました。
- Hugは、**FastAPI**がヘッダーやクッキーを設定するために関数に `response`引数を宣言することにインスピレーションを与えました。
+///
### 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**での使用用途
+
+データのバリデーション、データのシリアライゼーション、自動的なモデルの (JSON Schemaに基づいた) ドキュメント化の全てを扱えます。
+
+**FastAPI**はJSON SchemaのデータをOpenAPIに利用します。
- **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**が推奨する理由
+
+**FastAPI**アプリケーションを実行するメインのウェブサーバーである点。
+
+Gunicornと組み合わせることで、非同期でマルチプロセスなサーバーを持つことがきます。
- Gunicornと組み合わせることで、非同期でマルチプロセスなサーバーを持つことがきます。
+詳細は[デプロイ](deployment/index.md){.internal-link target=_blank}の項目で確認してください。
- 詳細は[デプロイ](deployment/index.md){.internal-link target=_blank}の項目で確認してください。
+///
## ベンチマーク と スピード
diff --git a/docs/ja/docs/async.md b/docs/ja/docs/async.md
index 5e38d1cec..d1da1f82d 100644
--- a/docs/ja/docs/async.md
+++ b/docs/ja/docs/async.md
@@ -21,8 +21,11 @@ async def read_results():
return results
```
-!!! note "備考"
- `async def` を使用して作成された関数の内部でしか `await` は使用できません。
+/// note | 備考
+
+`async def` を使用して作成された関数の内部でしか `await` は使用できません。
+
+///
---
@@ -355,12 +358,15 @@ async def read_burgers():
## 非常に発展的な技術的詳細
-!!! warning "注意"
- 恐らくスキップしても良いでしょう。
+/// warning | 注意
+
+恐らくスキップしても良いでしょう。
+
+この部分は**FastAPI**の仕組みに関する非常に技術的な詳細です。
- この部分は**FastAPI**の仕組みに関する非常に技術的な詳細です。
+かなりの技術知識 (コルーチン、スレッド、ブロッキングなど) があり、FastAPIが `async def` と通常の `def` をどのように処理するか知りたい場合は、先に進んでください。
- かなりの技術知識 (コルーチン、スレッド、ブロッキングなど) があり、FastAPIが `async def` と通常の `def` をどのように処理するか知りたい場合は、先に進んでください。
+///
### Path operation 関数
diff --git a/docs/ja/docs/contributing.md b/docs/ja/docs/contributing.md
deleted file mode 100644
index be8e9280e..000000000
--- a/docs/ja/docs/contributing.md
+++ /dev/null
@@ -1,470 +0,0 @@
-# 開発 - 貢献
-
-まず、[FastAPIを応援 - ヘルプの入手](help-fastapi.md){.internal-link target=_blank}の基本的な方法を見て、ヘルプを得た方がいいかもしれません。
-
-## 開発
-
-すでにリポジトリをクローンし、コードを詳しく調べる必要があるとわかっている場合に、環境構築のためのガイドラインをいくつか紹介します。
-
-### `venv`を使用した仮想環境
-
-Pythonの`venv`モジュールを使用して、ディレクトリに仮想環境を作成します:
-
-email_validator
- E メールの検証
+- email-validator
- E メールの検証
Starlette によって使用されるもの:
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/python-types.md b/docs/ja/docs/python-types.md
index f8e02fdc3..a847ce5d5 100644
--- a/docs/ja/docs/python-types.md
+++ b/docs/ja/docs/python-types.md
@@ -12,16 +12,18 @@
しかしたとえまったく **FastAPI** を使用しない場合でも、それらについて少し学ぶことで利点を得ることができるでしょう。
-!!! note "備考"
- もしあなたがPythonの専門家で、すでに型ヒントについてすべて知っているのであれば、次の章まで読み飛ばしてください。
+/// note | 備考
+
+もしあなたがPythonの専門家で、すでに型ヒントについてすべて知っているのであれば、次の章まで読み飛ばしてください。
+
+///
## 動機
簡単な例から始めてみましょう:
-```Python
-{!../../../docs_src/python_types/tutorial001.py!}
-```
+{* ../../docs_src/python_types/tutorial001.py *}
+
このプログラムを実行すると以下が出力されます:
@@ -35,9 +37,8 @@ John Doe
* `title()`を用いて、それぞれの最初の文字を大文字に変換します。
* 真ん中にスペースを入れて連結します。
-```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial001.py!}
-```
+{* ../../docs_src/python_types/tutorial001.py hl[2] *}
+
### 編集
@@ -79,9 +80,8 @@ John Doe
それが「型ヒント」です:
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial002.py!}
-```
+{* ../../docs_src/python_types/tutorial002.py hl[1] *}
+
これは、以下のようにデフォルト値を宣言するのと同じではありません:
@@ -109,9 +109,8 @@ John Doe
この関数を見てください。すでに型ヒントを持っています:
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial003.py!}
-```
+{* ../../docs_src/python_types/tutorial003.py hl[1] *}
+
エディタは変数の型を知っているので、補完だけでなく、エラーチェックをすることもできます。
@@ -119,9 +118,8 @@ John Doe
これで`age`を`str(age)`で文字列に変換して修正する必要があることがわかります:
-```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial004.py!}
-```
+{* ../../docs_src/python_types/tutorial004.py hl[2] *}
+
## 型の宣言
@@ -140,9 +138,8 @@ John Doe
* `bool`
* `bytes`
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial005.py!}
-```
+{* ../../docs_src/python_types/tutorial005.py hl[1] *}
+
### 型パラメータを持つジェネリック型
@@ -158,9 +155,8 @@ John Doe
`typing`から`List`をインポートします(大文字の`L`を含む):
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial006.py!}
-```
+{* ../../docs_src/python_types/tutorial006.py hl[1] *}
+
同じようにコロン(`:`)の構文で変数を宣言します。
@@ -168,14 +164,16 @@ John Doe
リストはいくつかの内部の型を含む型なので、それらを角括弧で囲んでいます。
-```Python hl_lines="4"
-{!../../../docs_src/python_types/tutorial006.py!}
-```
+{* ../../docs_src/python_types/tutorial006.py hl[4] *}
+
-!!! tip "豆知識"
- 角括弧内の内部の型は「型パラメータ」と呼ばれています。
+/// tip | 豆知識
- この場合、`str`は`List`に渡される型パラメータです。
+角括弧内の内部の型は「型パラメータ」と呼ばれています。
+
+この場合、`str`は`List`に渡される型パラメータです。
+
+///
つまり: 変数`items`は`list`であり、このリストの各項目は`str`です。
@@ -193,9 +191,8 @@ John Doe
`tuple`と`set`の宣言も同様です:
-```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial007.py!}
-```
+{* ../../docs_src/python_types/tutorial007.py hl[1,4] *}
+
つまり:
@@ -211,9 +208,8 @@ John Doe
2番目の型パラメータは`dict`の値です。
-```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial008.py!}
-```
+{* ../../docs_src/python_types/tutorial008.py hl[1,4] *}
+
つまり:
@@ -226,7 +222,7 @@ John Doe
また、`Optional`を使用して、変数が`str`のような型を持つことを宣言することもできますが、それは「オプション」であり、`None`にすることもできます。
```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009.py!}
+{!../../docs_src/python_types/tutorial009.py!}
```
ただの`str`の代わりに`Optional[str]`を使用することで、エディタは値が常に`str`であると仮定している場合に実際には`None`である可能性があるエラーを検出するのに役立ちます。
@@ -250,15 +246,13 @@ John Doe
例えば、`Person`クラスという名前のクラスがあるとしましょう:
-```Python hl_lines="1 2 3"
-{!../../../docs_src/python_types/tutorial010.py!}
-```
+{* ../../docs_src/python_types/tutorial010.py hl[1,2,3] *}
+
変数の型を`Person`として宣言することができます:
-```Python hl_lines="6"
-{!../../../docs_src/python_types/tutorial010.py!}
-```
+{* ../../docs_src/python_types/tutorial010.py hl[6] *}
+
そして、再び、すべてのエディタのサポートを得ることができます:
@@ -278,12 +272,14 @@ John Doe
Pydanticの公式ドキュメントから引用:
-```Python
-{!../../../docs_src/python_types/tutorial011.py!}
-```
+{* ../../docs_src/python_types/tutorial011.py *}
+
-!!! info "情報"
- Pydanticについてより学びたい方はドキュメントを参照してください.
+/// info | 情報
+
+Pydanticについてより学びたい方はドキュメントを参照してください.
+
+///
**FastAPI** はすべてPydanticをベースにしています。
@@ -311,5 +307,8 @@ Pydanticの公式ドキュメントから引用:
重要なのは、Pythonの標準的な型を使うことで、(クラスやデコレータなどを追加するのではなく)1つの場所で **FastAPI** が多くの作業を代わりにやってくれているということです。
-!!! info "情報"
- すでにすべてのチュートリアルを終えて、型についての詳細を見るためにこのページに戻ってきた場合は、`mypy`のチートシートを参照してください
+/// info | 情報
+
+すでにすべてのチュートリアルを終えて、型についての詳細を見るためにこのページに戻ってきた場合は、`mypy`のチートシートを参照してください
+
+///
diff --git a/docs/ja/docs/tutorial/background-tasks.md b/docs/ja/docs/tutorial/background-tasks.md
index 6094c370f..650a079fb 100644
--- a/docs/ja/docs/tutorial/background-tasks.md
+++ b/docs/ja/docs/tutorial/background-tasks.md
@@ -15,9 +15,7 @@
まず初めに、`BackgroundTasks` をインポートし、` BackgroundTasks` の型宣言と共に、*path operation 関数* のパラメーターを定義します:
-```Python hl_lines="1 13"
-{!../../../docs_src/background_tasks/tutorial001.py!}
-```
+{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *}
**FastAPI** は、`BackgroundTasks` 型のオブジェクトを作成し、そのパラメーターに渡します。
@@ -33,17 +31,13 @@
また、書き込み操作では `async` と `await` を使用しないため、通常の `def` で関数を定義します。
-```Python hl_lines="6-9"
-{!../../../docs_src/background_tasks/tutorial001.py!}
-```
+{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *}
## バックグラウンドタスクの追加
*path operations 関数* 内で、`.add_task()` メソッドを使用してタスク関数を *background tasks* オブジェクトに渡します。
-```Python hl_lines="14"
-{!../../../docs_src/background_tasks/tutorial001.py!}
-```
+{* ../../docs_src/background_tasks/tutorial001.py hl[14] *}
`.add_task()` は以下の引数を受け取ります:
@@ -57,9 +51,7 @@
**FastAPI** は、それぞれの場合の処理方法と同じオブジェクトの再利用方法を知っているため、すべてのバックグラウンドタスクがマージされ、バックグラウンドで後で実行されます。
-```Python hl_lines="13 15 22 25"
-{!../../../docs_src/background_tasks/tutorial002.py!}
-```
+{* ../../docs_src/background_tasks/tutorial002.py hl[13,15,22,25] *}
この例では、レスポンスが送信された *後* にメッセージが `log.txt` ファイルに書き込まれます。
@@ -85,8 +77,6 @@
これらは、より複雑な構成、RabbitMQ や Redis などのメッセージ/ジョブキューマネージャーを必要とする傾向がありますが、複数のプロセス、特に複数のサーバーでバックグラウンドタスクを実行できます。
-例を確認するには、[Project Generators](../project-generation.md){.internal-link target=_blank} を参照してください。これらにはすべて、Celery が構築済みです。
-
ただし、同じ **FastAPI** アプリから変数とオブジェクトにアクセスする必要がある場合、または小さなバックグラウンドタスク (電子メール通知の送信など) を実行する必要がある場合は、単に `BackgroundTasks` を使用できます。
## まとめ
diff --git a/docs/ja/docs/tutorial/body-fields.md b/docs/ja/docs/tutorial/body-fields.md
index 8f01e8216..ce5630351 100644
--- a/docs/ja/docs/tutorial/body-fields.md
+++ b/docs/ja/docs/tutorial/body-fields.md
@@ -6,40 +6,45 @@
まず、以下のようにインポートします:
-```Python hl_lines="4"
-{!../../../docs_src/body_fields/tutorial001.py!}
-```
+{* ../../docs_src/body_fields/tutorial001.py hl[4] *}
-!!! warning "注意"
- `Field`は他の全てのもの(`Query`、`Path`、`Body`など)とは違い、`fastapi`からではなく、`pydantic`から直接インポートされていることに注意してください。
+/// warning | 注意
+
+`Field`は他の全てのもの(`Query`、`Path`、`Body`など)とは違い、`fastapi`からではなく、`pydantic`から直接インポートされていることに注意してください。
+
+///
## モデルの属性の宣言
以下のように`Field`をモデルの属性として使用することができます:
-```Python hl_lines="11 12 13 14"
-{!../../../docs_src/body_fields/tutorial001.py!}
-```
+{* ../../docs_src/body_fields/tutorial001.py hl[11,12,13,14] *}
`Field`は`Query`や`Path`、`Body`と同じように動作し、全く同様のパラメータなどを持ちます。
-!!! note "技術詳細"
- 実際には次に見る`Query`や`Path`などは、共通の`Param`クラスのサブクラスのオブジェクトを作成しますが、それ自体はPydanticの`FieldInfo`クラスのサブクラスです。
+/// note | 技術詳細
+
+実際には次に見る`Query`や`Path`などは、共通の`Param`クラスのサブクラスのオブジェクトを作成しますが、それ自体はPydanticの`FieldInfo`クラスのサブクラスです。
+
+また、Pydanticの`Field`は`FieldInfo`のインスタンスも返します。
+
+`Body`は`FieldInfo`のサブクラスのオブジェクトを直接返すこともできます。そして、他にも`Body`クラスのサブクラスであるものがあります。
+
+`fastapi`から`Query`や`Path`などをインポートする場合、これらは実際には特殊なクラスを返す関数であることに注意してください。
- また、Pydanticの`Field`は`FieldInfo`のインスタンスも返します。
+///
- `Body`は`FieldInfo`のサブクラスのオブジェクトを直接返すこともできます。そして、他にも`Body`クラスのサブクラスであるものがあります。
+/// tip | 豆知識
- `fastapi`から`Query`や`Path`などをインポートする場合、これらは実際には特殊なクラスを返す関数であることに注意してください。
+型、デフォルト値、`Field`を持つ各モデルの属性が、`Path`や`Query`、`Body`の代わりに`Field`を持つ、*path operation 関数の*パラメータと同じ構造になっていることに注目してください。
-!!! tip "豆知識"
- 型、デフォルト値、`Field`を持つ各モデルの属性が、`Path`や`Query`、`Body`の代わりに`Field`を持つ、*path operation 関数の*パラメータと同じ構造になっていることに注目してください。
+///
## 追加情報の追加
追加情報は`Field`や`Query`、`Body`などで宣言することができます。そしてそれは生成されたJSONスキーマに含まれます。
-後に例を用いて宣言を学ぶ際に、追加情報を句悪方法を学べます。
+後に例を用いて宣言を学ぶ際に、追加情報を追加する方法を学べます。
## まとめ
diff --git a/docs/ja/docs/tutorial/body-multiple-params.md b/docs/ja/docs/tutorial/body-multiple-params.md
index 2ba10c583..cbfdda4b2 100644
--- a/docs/ja/docs/tutorial/body-multiple-params.md
+++ b/docs/ja/docs/tutorial/body-multiple-params.md
@@ -8,12 +8,13 @@
また、デフォルトの`None`を設定することで、ボディパラメータをオプションとして宣言することもできます:
-```Python hl_lines="19 20 21"
-{!../../../docs_src/body_multiple_params/tutorial001.py!}
-```
+{* ../../docs_src/body_multiple_params/tutorial001.py hl[19,20,21] *}
+
+/// note | 備考
+
+この場合、ボディから取得する`item`はオプションであることに注意してください。デフォルト値は`None`です。
-!!! note "備考"
- この場合、ボディから取得する`item`はオプションであることに注意してください。デフォルト値は`None`です。
+///
## 複数のボディパラメータ
@@ -30,9 +31,7 @@
しかし、`item`と`user`のように複数のボディパラメータを宣言することもできます:
-```Python hl_lines="22"
-{!../../../docs_src/body_multiple_params/tutorial002.py!}
-```
+{* ../../docs_src/body_multiple_params/tutorial002.py hl[22] *}
この場合、**FastAPI**は関数内に複数のボディパラメータ(Pydanticモデルである2つのパラメータ)があることに気付きます。
@@ -53,8 +52,11 @@
}
```
-!!! note "備考"
- 以前と同じように`item`が宣言されていたにもかかわらず、`item`はキー`item`を持つボディの内部にあることが期待されていることに注意してください。
+/// note | 備考
+
+以前と同じように`item`が宣言されていたにもかかわらず、`item`はキー`item`を持つボディの内部にあることが期待されていることに注意してください。
+
+///
**FastAPI** はリクエストから自動で変換を行い、パラメータ`item`が特定の内容を受け取り、`user`も同じように特定の内容を受け取ります。
@@ -71,9 +73,7 @@
しかし、`Body`を使用して、**FastAPI** に別のボディキーとして扱うように指示することができます:
-```Python hl_lines="23"
-{!../../../docs_src/body_multiple_params/tutorial003.py!}
-```
+{* ../../docs_src/body_multiple_params/tutorial003.py hl[23] *}
この場合、**FastAPI** は以下のようなボディを期待します:
@@ -108,13 +108,13 @@ q: str = None
以下において:
-```Python hl_lines="27"
-{!../../../docs_src/body_multiple_params/tutorial004.py!}
-```
+{* ../../docs_src/body_multiple_params/tutorial004.py hl[27] *}
-!!! info "情報"
- `Body`もまた、後述する `Query` や `Path` などと同様に、すべての検証パラメータとメタデータパラメータを持っています。
+/// info | 情報
+`Body`もまた、後述する `Query` や `Path` などと同様に、すべての検証パラメータとメタデータパラメータを持っています。
+
+///
## 単一のボディパラメータの埋め込み
@@ -130,9 +130,7 @@ item: Item = Body(..., embed=True)
以下において:
-```Python hl_lines="17"
-{!../../../docs_src/body_multiple_params/tutorial005.py!}
-```
+{* ../../docs_src/body_multiple_params/tutorial005.py hl[17] *}
この場合、**FastAPI** は以下のようなボディを期待します:
diff --git a/docs/ja/docs/tutorial/body-nested-models.md b/docs/ja/docs/tutorial/body-nested-models.md
index 092e25798..a1680d10f 100644
--- a/docs/ja/docs/tutorial/body-nested-models.md
+++ b/docs/ja/docs/tutorial/body-nested-models.md
@@ -6,9 +6,7 @@
属性をサブタイプとして定義することができます。例えば、Pythonの`list`は以下のように定義できます:
-```Python hl_lines="12"
-{!../../../docs_src/body_nested_models/tutorial001.py!}
-```
+{* ../../docs_src/body_nested_models/tutorial001.py hl[12] *}
これにより、各項目の型は宣言されていませんが、`tags`はある項目のリストになります。
@@ -20,9 +18,7 @@
まず、Pythonの標準の`typing`モジュールから`List`をインポートします:
-```Python hl_lines="1"
-{!../../../docs_src/body_nested_models/tutorial002.py!}
-```
+{* ../../docs_src/body_nested_models/tutorial002.py hl[1] *}
### タイプパラメータを持つ`List`の宣言
@@ -43,9 +39,7 @@ my_list: List[str]
そのため、以下の例では`tags`を具体的な「文字列のリスト」にすることができます:
-```Python hl_lines="14"
-{!../../../docs_src/body_nested_models/tutorial002.py!}
-```
+{* ../../docs_src/body_nested_models/tutorial002.py hl[14] *}
## セット型
@@ -55,9 +49,7 @@ my_list: List[str]
そのため、以下のように、`Set`をインポートして`str`の`set`として`tags`を宣言することができます:
-```Python hl_lines="1 14"
-{!../../../docs_src/body_nested_models/tutorial003.py!}
-```
+{* ../../docs_src/body_nested_models/tutorial003.py hl[1,14] *}
これを使えば、データが重複しているリクエストを受けた場合でも、ユニークな項目のセットに変換されます。
@@ -79,17 +71,13 @@ Pydanticモデルの各属性には型があります。
例えば、`Image`モデルを定義することができます:
-```Python hl_lines="9 10 11"
-{!../../../docs_src/body_nested_models/tutorial004.py!}
-```
+{* ../../docs_src/body_nested_models/tutorial004.py hl[9,10,11] *}
### サブモデルを型として使用
そして、それを属性の型として使用することができます:
-```Python hl_lines="20"
-{!../../../docs_src/body_nested_models/tutorial004.py!}
-```
+{* ../../docs_src/body_nested_models/tutorial004.py hl[20] *}
これは **FastAPI** が以下のようなボディを期待することを意味します:
@@ -122,9 +110,7 @@ Pydanticモデルの各属性には型があります。
例えば、`Image`モデルのように`url`フィールドがある場合、`str`の代わりにPydanticの`HttpUrl`を指定することができます:
-```Python hl_lines="4 10"
-{!../../../docs_src/body_nested_models/tutorial005.py!}
-```
+{* ../../docs_src/body_nested_models/tutorial005.py hl[4,10] *}
文字列は有効なURLであることが確認され、そのようにJSONスキーマ・OpenAPIで文書化されます。
@@ -132,9 +118,7 @@ Pydanticモデルの各属性には型があります。
Pydanticモデルを`list`や`set`などのサブタイプとして使用することもできます:
-```Python hl_lines="20"
-{!../../../docs_src/body_nested_models/tutorial006.py!}
-```
+{* ../../docs_src/body_nested_models/tutorial006.py hl[20] *}
これは、次のようなJSONボディを期待します(変換、検証、ドキュメントなど):
@@ -162,19 +146,23 @@ Pydanticモデルを`list`や`set`などのサブタイプとして使用する
}
```
-!!! info "情報"
- `images`キーが画像オブジェクトのリストを持つようになったことに注目してください。
+/// info | 情報
+
+`images`キーが画像オブジェクトのリストを持つようになったことに注目してください。
+
+///
## 深くネストされたモデル
深くネストされた任意のモデルを定義することができます:
-```Python hl_lines="9 14 20 23 27"
-{!../../../docs_src/body_nested_models/tutorial007.py!}
-```
+{* ../../docs_src/body_nested_models/tutorial007.py hl[9,14,20,23,27] *}
+
+/// info | 情報
+
+`Offer`は`Item`のリストであり、オプションの`Image`のリストを持っていることに注目してください。
-!!! info "情報"
- `Offer`は`Item`のリストであり、オプションの`Image`のリストを持っていることに注目してください。
+///
## 純粋なリストのボディ
@@ -186,9 +174,7 @@ images: List[Image]
以下のように:
-```Python hl_lines="15"
-{!../../../docs_src/body_nested_models/tutorial008.py!}
-```
+{* ../../docs_src/body_nested_models/tutorial008.py hl[15] *}
## あらゆる場所でのエディタサポート
@@ -218,18 +204,19 @@ Pydanticモデルではなく、`dict`を直接使用している場合はこの
この場合、`int`のキーと`float`の値を持つものであれば、どんな`dict`でも受け入れることができます:
-```Python hl_lines="15"
-{!../../../docs_src/body_nested_models/tutorial009.py!}
-```
+{* ../../docs_src/body_nested_models/tutorial009.py hl[15] *}
+
+/// tip | 豆知識
+
+JSONはキーとして`str`しかサポートしていないことに注意してください。
-!!! tip "豆知識"
- JSONはキーとして`str`しかサポートしていないことに注意してください。
+しかしPydanticには自動データ変換機能があります。
- しかしPydanticには自動データ変換機能があります。
+これは、APIクライアントがキーとして文字列しか送信できなくても、それらの文字列に純粋な整数が含まれている限り、Pydanticが変換して検証することを意味します。
- これは、APIクライアントがキーとして文字列しか送信できなくても、それらの文字列に純粋な整数が含まれている限り、Pydanticが変換して検証することを意味します。
+そして、`weights`として受け取る`dict`は、実際には`int`のキーと`float`の値を持つことになります。
- そして、`weights`として受け取る`dict`は、実際には`int`のキーと`float`の値を持つことになります。
+///
## まとめ
diff --git a/docs/ja/docs/tutorial/body-updates.md b/docs/ja/docs/tutorial/body-updates.md
index 95d328ec5..ffbe52e1d 100644
--- a/docs/ja/docs/tutorial/body-updates.md
+++ b/docs/ja/docs/tutorial/body-updates.md
@@ -6,9 +6,7 @@
`jsonable_encoder`を用いて、入力データをJSON形式で保存できるデータに変換することができます(例:NoSQLデータベース)。例えば、`datetime`を`str`に変換します。
-```Python hl_lines="30 31 32 33 34 35"
-{!../../../docs_src/body_updates/tutorial001.py!}
-```
+{* ../../docs_src/body_updates/tutorial001.py hl[30,31,32,33,34,35] *}
既存のデータを置き換えるべきデータを受け取るために`PUT`は使用されます。
@@ -34,14 +32,17 @@
つまり、更新したいデータだけを送信して、残りはそのままにしておくことができます。
-!!! note "備考"
- `PATCH`は`PUT`よりもあまり使われておらず、知られていません。
+/// note | 備考
+
+`PATCH`は`PUT`よりもあまり使われておらず、知られていません。
+
+また、多くのチームは部分的な更新であっても`PUT`だけを使用しています。
- また、多くのチームは部分的な更新であっても`PUT`だけを使用しています。
+**FastAPI** はどんな制限も課けていないので、それらを使うのは **自由** です。
- **FastAPI** はどんな制限も課けていないので、それらを使うのは **自由** です。
+しかし、このガイドでは、それらがどのように使用されることを意図しているかを多かれ少なかれ、示しています。
- しかし、このガイドでは、それらがどのように使用されることを意図しているかを多かれ少なかれ、示しています。
+///
### Pydanticの`exclude_unset`パラメータの使用
@@ -53,9 +54,7 @@
これを使うことで、デフォルト値を省略して、設定された(リクエストで送られた)データのみを含む`dict`を生成することができます:
-```Python hl_lines="34"
-{!../../../docs_src/body_updates/tutorial002.py!}
-```
+{* ../../docs_src/body_updates/tutorial002.py hl[34] *}
### Pydanticの`update`パラメータ
@@ -63,9 +62,7 @@
`stored_item_model.copy(update=update_data)`のように:
-```Python hl_lines="35"
-{!../../../docs_src/body_updates/tutorial002.py!}
-```
+{* ../../docs_src/body_updates/tutorial002.py hl[35] *}
### 部分的更新のまとめ
@@ -82,18 +79,22 @@
* データをDBに保存します。
* 更新されたモデルを返します。
-```Python hl_lines="30 31 32 33 34 35 36 37"
-{!../../../docs_src/body_updates/tutorial002.py!}
-```
+{* ../../docs_src/body_updates/tutorial002.py hl[30,31,32,33,34,35,36,37] *}
+
+/// tip | 豆知識
+
+実際には、HTTPの`PUT`操作でも同じテクニックを使用することができます。
+
+しかし、これらのユースケースのために作成されたので、ここでの例では`PATCH`を使用しています。
+
+///
-!!! tip "豆知識"
- 実際には、HTTPの`PUT`操作でも同じテクニックを使用することができます。
+/// note | 備考
- しかし、これらのユースケースのために作成されたので、ここでの例では`PATCH`を使用しています。
+入力モデルがまだ検証されていることに注目してください。
-!!! note "備考"
- 入力モデルがまだ検証されていることに注目してください。
+そのため、すべての属性を省略できる部分的な変更を受け取りたい場合は、すべての属性をオプションとしてマークしたモデルを用意する必要があります(デフォルト値または`None`を使用して)。
- そのため、すべての属性を省略できる部分的な変更を受け取りたい場合は、すべての属性をオプションとしてマークしたモデルを用意する必要があります(デフォルト値または`None`を使用して)。
+**更新** のためのオプション値がすべて設定されているモデルと、**作成** のための必須値が設定されているモデルを区別するには、[追加モデル](extra-models.md){.internal-link target=_blank}で説明されている考え方を利用することができます。
- **更新** のためのオプション値がすべて設定されているモデルと、**作成** のための必須値が設定されているモデルを区別するには、[追加モデル](extra-models.md){.internal-link target=_blank}で説明されている考え方を利用することができます。
+///
diff --git a/docs/ja/docs/tutorial/body.md b/docs/ja/docs/tutorial/body.md
index ccce9484d..8376959d5 100644
--- a/docs/ja/docs/tutorial/body.md
+++ b/docs/ja/docs/tutorial/body.md
@@ -8,20 +8,21 @@ APIはほとんどの場合 **レスポンス** ボディを送らなければ
**リクエスト** ボディを宣言するために Pydantic モデルを使用します。そして、その全てのパワーとメリットを利用します。
-!!! info "情報"
- データを送るには、`POST` (もっともよく使われる)、`PUT`、`DELETE` または `PATCH` を使うべきです。
+/// info | 情報
- GET リクエストでボディを送信することは、仕様では未定義の動作ですが、FastAPI でサポートされており、非常に複雑な(極端な)ユースケースにのみ対応しています。
+データを送るには、`POST` (もっともよく使われる)、`PUT`、`DELETE` または `PATCH` を使うべきです。
- 非推奨なので、Swagger UIを使った対話型のドキュメントにはGETのボディ情報は表示されません。さらに、中継するプロキシが対応していない可能性があります。
+GET リクエストでボディを送信することは、仕様では未定義の動作ですが、FastAPI でサポートされており、非常に複雑な(極端な)ユースケースにのみ対応しています。
+
+非推奨なので、Swagger UIを使った対話型のドキュメントにはGETのボディ情報は表示されません。さらに、中継するプロキシが対応していない可能性があります。
+
+///
## Pydanticの `BaseModel` をインポート
ます初めに、 `pydantic` から `BaseModel` をインポートする必要があります:
-```Python hl_lines="2"
-{!../../../docs_src/body/tutorial001.py!}
-```
+{* ../../docs_src/body/tutorial001.py hl[2] *}
## データモデルの作成
@@ -29,9 +30,7 @@ APIはほとんどの場合 **レスポンス** ボディを送らなければ
すべての属性にpython標準の型を使用します:
-```Python hl_lines="5-9"
-{!../../../docs_src/body/tutorial001.py!}
-```
+{* ../../docs_src/body/tutorial001.py hl[5:9] *}
クエリパラメータの宣言と同様に、モデル属性がデフォルト値をもつとき、必須な属性ではなくなります。それ以外は必須になります。オプショナルな属性にしたい場合は `None` を使用してください。
@@ -59,9 +58,7 @@ APIはほとんどの場合 **レスポンス** ボディを送らなければ
*パスオペレーション* に加えるために、パスパラメータやクエリパラメータと同じ様に宣言します:
-```Python hl_lines="16"
-{!../../../docs_src/body/tutorial001.py!}
-```
+{* ../../docs_src/body/tutorial001.py hl[16] *}
...そして、作成したモデル `Item` で型を宣言します。
@@ -110,24 +107,25 @@ APIはほとんどの場合 **レスポンス** ボディを送らなければ
kwargs
としても知られています。たとえデフォルト値がなくても。
-```Python hl_lines="8"
-{!../../../docs_src/path_params_numeric_validations/tutorial003.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[8] *}
## 数値の検証: 以上
`Query`と`Path`(、そして後述する他のもの)を用いて、文字列の制約を宣言することができますが、数値の制約も同様に宣言できます。
-ここで、`ge=1`の場合、`item_id`は`1`「より大きい`g`か、同じ`e`」整数でなれけばなりません。
+ここで、`ge=1`の場合、`item_id`は`1`「より大きい`g`か、同じ`e`」整数でなれけばなりません。
-```Python hl_lines="8"
-{!../../../docs_src/path_params_numeric_validations/tutorial004.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial004.py hl[8] *}
## 数値の検証: より大きいと小なりイコール
@@ -76,9 +69,7 @@ Pythonはその`*`で何かをすることはありませんが、それ以降
* `gt`: より大きい(`g`reater `t`han)
* `le`: 小なりイコール(`l`ess than or `e`qual)
-```Python hl_lines="9"
-{!../../../docs_src/path_params_numeric_validations/tutorial005.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial005.py hl[9] *}
## 数値の検証: 浮動小数点、 大なり小なり
@@ -90,9 +81,7 @@ Pythonはその`*`で何かをすることはありませんが、それ以降
これはlt
も同じです。
-```Python hl_lines="11"
-{!../../../docs_src/path_params_numeric_validations/tutorial006.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial006.py hl[11] *}
## まとめ
@@ -105,18 +94,24 @@ Pythonはその`*`で何かをすることはありませんが、それ以降
* `lt`: より小さい(`l`ess `t`han)
* `le`: 以下(`l`ess than or `e`qual)
-!!! info "情報"
- `Query`、`Path`などは後に共通の`Param`クラスのサブクラスを見ることになります。(使う必要はありません)
+/// info | 情報
+
+`Query`、`Path`などは後に共通の`Param`クラスのサブクラスを見ることになります。(使う必要はありません)
+
+そして、それらすべては、これまで見てきた追加のバリデーションとメタデータと同じパラメータを共有しています。
+
+///
+
+/// note | 技術詳細
- そして、それらすべては、これまで見てきた追加のバリデーションとメタデータと同じパラメータを共有しています。
+`fastapi`から`Query`、`Path`などをインポートすると、これらは実際には関数です。
-!!! note "技術詳細"
- `fastapi`から`Query`、`Path`などをインポートすると、これらは実際には関数です。
+呼び出されると、同じ名前のクラスのインスタンスを返します。
- 呼び出されると、同じ名前のクラスのインスタンスを返します。
+そのため、関数である`Query`をインポートし、それを呼び出すと、`Query`という名前のクラスのインスタンスが返されます。
- そのため、関数である`Query`をインポートし、それを呼び出すと、`Query`という名前のクラスのインスタンスが返されます。
+これらの関数は(クラスを直接使うのではなく)エディタが型についてエラーとしないようにするために存在します。
- これらの関数は(クラスを直接使うのではなく)エディタが型についてエラーとしないようにするために存在します。
+この方法によって、これらのエラーを無視するための設定を追加することなく、通常のエディタやコーディングツールを使用することができます。
- この方法によって、これらのエラーを無視するための設定を追加することなく、通常のエディタやコーディングツールを使用することができます。
+///
diff --git a/docs/ja/docs/tutorial/path-params.md b/docs/ja/docs/tutorial/path-params.md
index b395dc41d..1893ec12f 100644
--- a/docs/ja/docs/tutorial/path-params.md
+++ b/docs/ja/docs/tutorial/path-params.md
@@ -2,9 +2,7 @@
Pythonのformat文字列と同様のシンタックスで「パスパラメータ」や「パス変数」を宣言できます:
-```Python hl_lines="6 7"
-{!../../../docs_src/path_params/tutorial001.py!}
-```
+{* ../../docs_src/path_params/tutorial001.py hl[6,7] *}
パスパラメータ `item_id` の値は、引数 `item_id` として関数に渡されます。
@@ -18,14 +16,15 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー
標準のPythonの型アノテーションを使用して、関数内のパスパラメータの型を宣言できます:
-```Python hl_lines="7"
-{!../../../docs_src/path_params/tutorial002.py!}
-```
+{* ../../docs_src/path_params/tutorial002.py hl[7] *}
ここでは、 `item_id` は `int` として宣言されています。
-!!! check "確認"
- これにより、関数内でのエディターサポート (エラーチェックや補完など) が提供されます。
+/// check | 確認
+
+これにより、関数内でのエディターサポート (エラーチェックや補完など) が提供されます。
+
+///
## データ変換
@@ -35,10 +34,13 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー
{"item_id":3}
```
-!!! check "確認"
- 関数が受け取った(および返した)値は、文字列の `"3"` ではなく、Pythonの `int` としての `3` であることに注意してください。
+/// check | 確認
- したがって、型宣言を使用すると、**FastAPI**は自動リクエスト "解析" を行います。
+関数が受け取った(および返した)値は、文字列の `"3"` ではなく、Pythonの `int` としての `3` であることに注意してください。
+
+したがって、型宣言を使用すると、**FastAPI**は自動リクエスト "解析" を行います。
+
+///
## データバリデーション
@@ -63,12 +65,15 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー
http://127.0.0.1:8000/items/4.2 で見られるように、intのかわりに `float` が与えられた場合にも同様なエラーが表示されます。
-!!! check "確認"
- したがって、Pythonの型宣言を使用することで、**FastAPI**はデータのバリデーションを行います。
+/// check | 確認
+
+したがって、Pythonの型宣言を使用することで、**FastAPI**はデータのバリデーションを行います。
- 表示されたエラーには問題のある箇所が明確に指摘されていることに注意してください。
+表示されたエラーには問題のある箇所が明確に指摘されていることに注意してください。
- これは、APIに関連するコードの開発およびデバッグに非常に役立ちます。
+これは、APIに関連するコードの開発およびデバッグに非常に役立ちます。
+
+///
## ドキュメント
@@ -76,10 +81,13 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー
POST
のウェブドキュメントを参照してください。
+
+///
- しかし、フォームがファイルを含む場合は、`multipart/form-data`としてエンコードされます。ファイルの扱いについては次の章で説明します。
+/// warning | 注意
- これらのエンコーディングやフォームフィールドの詳細については、MDNのPOST
のウェブドキュメントを参照してください。
+*path operation*で複数の`Form`パラメータを宣言することができますが、JSONとして受け取ることを期待している`Body`フィールドを宣言することはできません。なぜなら、リクエストは`application/json`の代わりに`application/x-www-form-urlencoded`を使ってボディをエンコードするからです。
-!!! warning "注意"
- *path operation*で複数の`Form`パラメータを宣言することができますが、JSONとして受け取ることを期待している`Body`フィールドを宣言することはできません。なぜなら、リクエストは`application/json`の代わりに`application/x-www-form-urlencoded`を使ってボディをエンコードするからです。
+これは **FastAPI**の制限ではなく、HTTPプロトコルの一部です。
- これは **FastAPI**の制限ではなく、HTTPプロトコルの一部です。
+///
## まとめ
diff --git a/docs/ja/docs/tutorial/response-model.md b/docs/ja/docs/tutorial/response-model.md
index b8b6978d4..b8464a4c7 100644
--- a/docs/ja/docs/tutorial/response-model.md
+++ b/docs/ja/docs/tutorial/response-model.md
@@ -8,12 +8,13 @@
* `@app.delete()`
* など。
-```Python hl_lines="17"
-{!../../../docs_src/response_model/tutorial001.py!}
-```
+{* ../../docs_src/response_model/tutorial001.py hl[17] *}
+
+/// note | 備考
-!!! note "備考"
- `response_model`は「デコレータ」メソッド(`get`、`post`など)のパラメータであることに注意してください。すべてのパラメータやボディのように、*path operation関数* のパラメータではありません。
+`response_model`は「デコレータ」メソッド(`get`、`post`など)のパラメータであることに注意してください。すべてのパラメータやボディのように、*path operation関数* のパラメータではありません。
+
+///
Pydanticモデルの属性に対して宣言するのと同じ型を受け取るので、Pydanticモデルになることもできますが、例えば、`List[Item]`のようなPydanticモデルの`list`になることもできます。
@@ -28,22 +29,21 @@ FastAPIは`response_model`を使って以下のことをします:
* 出力データをモデルのデータに限定します。これがどのように重要なのか以下で見ていきましょう。
-!!! note "技術詳細"
- レスポンスモデルは、関数の戻り値のアノテーションではなく、このパラメータで宣言されています。なぜなら、パス関数は実際にはそのレスポンスモデルを返すのではなく、`dict`やデータベースオブジェクト、あるいは他のモデルを返し、`response_model`を使用してフィールドの制限やシリアライズを行うからです。
+/// note | 技術詳細
+
+レスポンスモデルは、関数の戻り値のアノテーションではなく、このパラメータで宣言されています。なぜなら、パス関数は実際にはそのレスポンスモデルを返すのではなく、`dict`やデータベースオブジェクト、あるいは他のモデルを返し、`response_model`を使用してフィールドの制限やシリアライズを行うからです。
+
+///
## 同じ入力データの返却
ここでは`UserIn`モデルを宣言しています。それには平文のパスワードが含まれています:
-```Python hl_lines="9 11"
-{!../../../docs_src/response_model/tutorial002.py!}
-```
+{* ../../docs_src/response_model/tutorial002.py hl[9,11] *}
そして、このモデルを使用して入力を宣言し、同じモデルを使って出力を宣言しています:
-```Python hl_lines="17 18"
-{!../../../docs_src/response_model/tutorial002.py!}
-```
+{* ../../docs_src/response_model/tutorial002.py hl[17,18] *}
これで、ブラウザがパスワードを使ってユーザーを作成する際に、APIがレスポンスで同じパスワードを返すようになりました。
@@ -51,28 +51,25 @@ FastAPIは`response_model`を使って以下のことをします:
しかし、同じモデルを別の*path operation*に使用すると、すべてのクライアントにユーザーのパスワードを送信してしまうことになります。
-!!! danger "危険"
- ユーザーの平文のパスワードを保存したり、レスポンスで送信したりすることは絶対にしないでください。
+/// danger | 危険
+
+ユーザーの平文のパスワードを保存したり、レスポンスで送信したりすることは絶対にしないでください。
+
+///
## 出力モデルの追加
代わりに、平文のパスワードを持つ入力モデルと、パスワードを持たない出力モデルを作成することができます:
-```Python hl_lines="9 11 16"
-{!../../../docs_src/response_model/tutorial003.py!}
-```
+{* ../../docs_src/response_model/tutorial003.py hl[9,11,16] *}
ここでは、*path operation関数*がパスワードを含む同じ入力ユーザーを返しているにもかかわらず:
-```Python hl_lines="24"
-{!../../../docs_src/response_model/tutorial003.py!}
-```
+{* ../../docs_src/response_model/tutorial003.py hl[24] *}
...`response_model`を`UserOut`と宣言したことで、パスワードが含まれていません:
-```Python hl_lines="22"
-{!../../../docs_src/response_model/tutorial003.py!}
-```
+{* ../../docs_src/response_model/tutorial003.py hl[22] *}
そのため、**FastAPI** は出力モデルで宣言されていない全てのデータをフィルタリングしてくれます(Pydanticを使用)。
@@ -90,9 +87,7 @@ FastAPIは`response_model`を使って以下のことをします:
レスポンスモデルにはデフォルト値を設定することができます:
-```Python hl_lines="11 13 14"
-{!../../../docs_src/response_model/tutorial004.py!}
-```
+{* ../../docs_src/response_model/tutorial004.py hl[11,13,14] *}
* `description: str = None`は`None`がデフォルト値です。
* `tax: float = 10.5`は`10.5`がデフォルト値です。
@@ -106,9 +101,7 @@ FastAPIは`response_model`を使って以下のことをします:
*path operation デコレータ*に`response_model_exclude_unset=True`パラメータを設定することができます:
-```Python hl_lines="24"
-{!../../../docs_src/response_model/tutorial004.py!}
-```
+{* ../../docs_src/response_model/tutorial004.py hl[24] *}
そして、これらのデフォルト値はレスポンスに含まれず、実際に設定された値のみが含まれます。
@@ -121,16 +114,22 @@ FastAPIは`response_model`を使って以下のことをします:
}
```
-!!! info "情報"
- FastAPIはこれをするために、Pydanticモデルの`.dict()`をその`exclude_unset`パラメータで使用しています。
+/// info | 情報
+
+FastAPIはこれをするために、Pydanticモデルの`.dict()`をその`exclude_unset`パラメータで使用しています。
+
+///
+
+/// info | 情報
-!!! info "情報"
- 以下も使用することができます:
+以下も使用することができます:
- * `response_model_exclude_defaults=True`
- * `response_model_exclude_none=True`
+* `response_model_exclude_defaults=True`
+* `response_model_exclude_none=True`
- `exclude_defaults`と`exclude_none`については、Pydanticのドキュメントで説明されている通りです。
+`exclude_defaults`と`exclude_none`については、Pydanticのドキュメントで説明されている通りです。
+
+///
#### デフォルト値を持つフィールドの値を持つデータ
@@ -165,9 +164,12 @@ FastAPIは十分に賢いので(実際には、Pydanticが十分に賢い)`d
そのため、それらはJSONレスポンスに含まれることになります。
-!!! tip "豆知識"
- デフォルト値は`None`だけでなく、なんでも良いことに注意してください。
- 例えば、リスト(`[]`)や`10.5`の`float`などです。
+/// tip | 豆知識
+
+デフォルト値は`None`だけでなく、なんでも良いことに注意してください。
+例えば、リスト(`[]`)や`10.5`の`float`などです。
+
+///
### `response_model_include`と`response_model_exclude`
@@ -177,29 +179,31 @@ 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が完全なモデルになるからです。
-```Python hl_lines="31 37"
-{!../../../docs_src/response_model/tutorial005.py!}
-```
+同様に動作する`response_model_by_alias`にも当てはまります。
+
+///
+
+{* ../../docs_src/response_model/tutorial005.py hl[31,37] *}
-!!! tip "豆知識"
- `{"name", "description"}`の構文はこれら2つの値をもつ`set`を作成します。
+/// tip | 豆知識
- これは`set(["name", "description"])`と同等です。
+`{"name", "description"}`の構文はこれら2つの値をもつ`set`を作成します。
+
+これは`set(["name", "description"])`と同等です。
+
+///
#### `set`の代わりに`list`を使用する
もし`set`を使用することを忘れて、代わりに`list`や`tuple`を使用しても、FastAPIはそれを`set`に変換して正しく動作します:
-```Python hl_lines="31 37"
-{!../../../docs_src/response_model/tutorial006.py!}
-```
+{* ../../docs_src/response_model/tutorial006.py hl[31,37] *}
## まとめ
diff --git a/docs/ja/docs/tutorial/response-status-code.md b/docs/ja/docs/tutorial/response-status-code.md
index ead2addda..6d197d543 100644
--- a/docs/ja/docs/tutorial/response-status-code.md
+++ b/docs/ja/docs/tutorial/response-status-code.md
@@ -8,17 +8,21 @@
* `@app.delete()`
* など。
-```Python hl_lines="6"
-{!../../../docs_src/response_status_code/tutorial001.py!}
-```
+{* ../../docs_src/response_status_code/tutorial001.py hl[6] *}
-!!! 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 +31,21 @@
email_validator
- 이메일 유효성 검사.
+* email-validator
- 이메일 유효성 검사.
Starlette이 사용하는:
diff --git a/docs/ko/docs/openapi-webhooks.md b/docs/ko/docs/openapi-webhooks.md
new file mode 100644
index 000000000..96339aa96
--- /dev/null
+++ b/docs/ko/docs/openapi-webhooks.md
@@ -0,0 +1,55 @@
+# OpenAPI 웹훅(Webhooks)
+
+API **사용자**에게 특정 **이벤트**가 발생할 때 *그들*의 앱(시스템)에 요청을 보내 **알림**을 전달할 수 있다는 것을 알리고 싶은 경우가 있습니다.
+
+즉, 일반적으로 사용자가 API에 요청을 보내는 것과는 반대로, **API**(또는 앱)가 **사용자의 시스템**(그들의 API나 앱)으로 **요청을 보내는** 상황을 의미합니다.
+
+이를 흔히 **웹훅(Webhook)**이라고 부릅니다.
+
+## 웹훅 스텝
+
+**코드에서** 웹훅으로 보낼 메시지, 즉 요청의 **바디(body)**를 정의하는 것이 일반적인 프로세스입니다.
+
+앱에서 해당 요청이나 이벤트를 전송할 **시점**을 정의합니다.
+
+**사용자**는 앱이 해당 요청을 보낼 **URL**을 정의합니다. (예: 웹 대시보드에서 설정)
+
+웹훅의 URL을 등록하는 방법과 이러한 요청을 실제로 전송하는 코드에 대한 모든 로직은 여러분에게 달려 있습니다. 원하는대로 **고유의 코드**를 작성하면 됩니다.
+
+## **FastAPI**와 OpenAPI로 웹훅 문서화하기
+
+**FastAPI**를 사용하여 OpenAPI와 함께 웹훅의 이름, 앱이 보낼 수 있는 HTTP 작업 유형(예: `POST`, `PUT` 등), 그리고 보낼 요청의 **바디**를 정의할 수 있습니다.
+
+이를 통해 사용자가 **웹훅** 요청을 수신할 **API 구현**을 훨씬 쉽게 할 수 있으며, 경우에 따라 사용자 API 코드의 일부를 자동 생성할 수도 있습니다.
+
+/// info
+
+웹훅은 OpenAPI 3.1.0 이상에서 지원되며, FastAPI `0.99.0` 이상 버전에서 사용할 수 있습니다.
+
+///
+
+## 웹훅이 포함된 앱 만들기
+
+**FastAPI** 애플리케이션을 만들 때, `webhooks` 속성을 사용하여 *웹훅*을 정의할 수 있습니다. 이는 `@app.webhooks.post()`와 같은 방식으로 *경로(path) 작업*을 정의하는 것과 비슷합니다.
+
+{* ../../docs_src/openapi_webhooks/tutorial001.py hl[9:13,36:53] *}
+
+이렇게 정의한 웹훅은 **OpenAPI** 스키마와 자동 **문서화 UI**에 표시됩니다.
+
+/// info
+
+`app.webhooks` 객체는 사실 `APIRouter`일 뿐이며, 여러 파일로 앱을 구성할 때 사용하는 것과 동일한 타입입니다.
+
+///
+
+웹훅에서는 실제 **경로(path)** (예: `/items/`)를 선언하지 않는 점에 유의해야 합니다. 여기서 전달하는 텍스트는 **식별자**로, 웹훅의 이름(이벤트 이름)입니다. 예를 들어, `@app.webhooks.post("new-subscription")`에서 웹훅 이름은 `new-subscription`입니다.
+
+이는 실제 **URL 경로**는 **사용자**가 다른 방법(예: 웹 대시보드)을 통해 지정하도록 기대되기 때문입니다.
+
+### 문서 확인하기
+
+이제 앱을 시작하고 http://127.0.0.1:8000/docs로 이동해 봅시다.
+
+문서에서 기존 *경로 작업*뿐만 아니라 **웹훅**도 표시된 것을 확인할 수 있습니다:
+
+get
작동 사용
-!!! info "`@decorator` 정보"
- 이 `@something` 문법은 파이썬에서 "데코레이터"라 부릅니다.
+/// info | `@decorator` 정보
+
+이 `@something` 문법은 파이썬에서 "데코레이터"라 부릅니다.
+
+마치 예쁜 장식용(Decorative) 모자처럼(개인적으로 이 용어가 여기서 유래한 것 같습니다) 함수 맨 위에 놓습니다.
- 마치 예쁜 장식용(Decorative) 모자처럼(개인적으로 이 용어가 여기서 유래한 것 같습니다) 함수 맨 위에 놓습니다.
+"데코레이터"는 아래 있는 함수를 받아 그것으로 무언가를 합니다.
- "데코레이터"는 아래 있는 함수를 받아 그것으로 무언가를 합니다.
+우리의 경우, 이 데코레이터는 **FastAPI**에게 아래 함수가 **경로** `/`의 `get` **작동**에 해당한다고 알려줍니다.
- 우리의 경우, 이 데코레이터는 **FastAPI**에게 아래 함수가 **경로** `/`의 `get` **작동**에 해당한다고 알려줍니다.
+이것이 "**경로 작동 데코레이터**"입니다.
- 이것이 "**경로 작동 데코레이터**"입니다.
+///
다른 작동도 사용할 수 있습니다:
@@ -274,14 +276,17 @@ API를 설계할 때 일반적으로 특정 행동을 수행하기 위해 특정
* `@app.patch()`
* `@app.trace()`
-!!! tip "팁"
- 각 작동(HTTP 메소드)을 원하는 대로 사용해도 됩니다.
+/// tip | 팁
+
+각 작동(HTTP 메소드)을 원하는 대로 사용해도 됩니다.
+
+**FastAPI**는 특정 의미를 강제하지 않습니다.
- **FastAPI**는 특정 의미를 강제하지 않습니다.
+여기서 정보는 지침서일뿐 강제사항이 아닙니다.
- 여기서 정보는 지침서일뿐 강제사항이 아닙니다.
+예를 들어 GraphQL을 사용하는 경우, 일반적으로 `POST` 작동만 사용하여 모든 행동을 수행합니다.
- 예를 들어 GraphQL을 사용하는 경우, 일반적으로 `POST` 작동만 사용하여 모든 행동을 수행합니다.
+///
### 4 단계: **경로 작동 함수** 정의
@@ -291,9 +296,7 @@ API를 설계할 때 일반적으로 특정 행동을 수행하기 위해 특정
* **작동**: 은 `get`입니다.
* **함수**: 는 "데코레이터" 아래에 있는 함수입니다 (`@app.get("/")` 아래).
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[7] *}
이것은 파이썬 함수입니다.
@@ -305,18 +308,17 @@ URL "`/`"에 대한 `GET` 작동을 사용하는 요청을 받을 때마다 **Fa
`async def`을 이용하는 대신 일반 함수로 정의할 수 있습니다:
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial003.py!}
-```
+{* ../../docs_src/first_steps/tutorial003.py hl[7] *}
+
+/// note | 참고
-!!! note "참고"
- 차이점을 모르겠다면 [Async: *"바쁘신 경우"*](../async.md#_1){.internal-link target=_blank}을 확인하세요.
+차이점을 모르겠다면 [Async: *"바쁘신 경우"*](../async.md#_1){.internal-link target=_blank}을 확인하세요.
+
+///
### 5 단계: 콘텐츠 반환
-```Python hl_lines="8"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[8] *}
`dict`, `list`, 단일값을 가진 `str`, `int` 등을 반환할 수 있습니다.
diff --git a/docs/ko/docs/tutorial/header-param-models.md b/docs/ko/docs/tutorial/header-param-models.md
new file mode 100644
index 000000000..bab7291e3
--- /dev/null
+++ b/docs/ko/docs/tutorial/header-param-models.md
@@ -0,0 +1,56 @@
+# 헤더 매개변수 모델
+
+관련 있는 **헤더 매개변수** 그룹이 있는 경우, **Pydantic 모델**을 생성하여 선언할 수 있습니다.
+
+이를 통해 **여러 위치**에서 **모델을 재사용** 할 수 있고 모든 매개변수에 대한 유효성 검사 및 메타데이터를 한 번에 선언할 수도 있습니다. 😎
+
+/// note | 참고
+
+이 기능은 FastAPI 버전 `0.115.0` 이후부터 지원됩니다. 🤓
+
+///
+
+## Pydantic 모델을 사용한 헤더 매개변수
+
+**Pydantic 모델**에 필요한 **헤더 매개변수**를 선언한 다음, 해당 매개변수를 `Header`로 선언합니다:
+
+{* ../../docs_src/header_param_models/tutorial001_an_py310.py hl[9:14,18] *}
+
+**FastAPI**는 요청에서 받은 **헤더**에서 **각 필드**에 대한 데이터를 **추출**하고 정의한 Pydantic 모델을 줍니다.
+
+## 문서 확인하기
+
+문서 UI `/docs`에서 필요한 헤더를 볼 수 있습니다:
+
+contact
필드매개변수 | 타입 | 설명 |
---|---|---|
name | str | 연락처 인물/조직의 식별명입니다. |
url | str | 연락처 정보가 담긴 URL입니다. URL 형식이어야 합니다. |
email | str | 연락처 인물/조직의 이메일 주소입니다. 이메일 주소 형식이어야 합니다. |
license_info
필드매개변수 | 타입 | 설명 |
---|---|---|
name | str | 필수 (license_info 가 설정된 경우). API에 사용된 라이선스 이름입니다. |
identifier | str | API에 대한 SPDX 라이선스 표현입니다. identifier 필드는 url 필드와 상호 배타적입니다. OpenAPI 3.1.0, FastAPI 0.99.0부터 사용 가능 |
url | str | API에 사용된 라이선스의 URL입니다. URL 형식이어야 합니다. |
kwargs
로도 알려진 키워드 인자(키-값 쌍)여야 함을 인지합니다. 기본값을 가지고 있지 않더라도 그렇습니다.
-```Python hl_lines="7"
-{!../../../docs_src/path_params_numeric_validations/tutorial003.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *}
## 숫자 검증: 크거나 같음
@@ -65,9 +60,7 @@
여기서 `ge=1`인 경우, `item_id`는 `1`보다 "크거나(`g`reater) 같은(`e`qual)" 정수형 숫자여야 합니다.
-```Python hl_lines="8"
-{!../../../docs_src/path_params_numeric_validations/tutorial004.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial004.py hl[8] *}
## 숫자 검증: 크거나 같음 및 작거나 같음
@@ -76,9 +69,7 @@
* `gt`: 크거나(`g`reater `t`han)
* `le`: 작거나 같은(`l`ess than or `e`qual)
-```Python hl_lines="9"
-{!../../../docs_src/path_params_numeric_validations/tutorial005.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial005.py hl[9] *}
## 숫자 검증: 부동소수, 크거나 및 작거나
@@ -90,9 +81,7 @@
lt
역시 마찬가지입니다.
-```Python hl_lines="11"
-{!../../../docs_src/path_params_numeric_validations/tutorial006.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial006.py hl[11] *}
## 요약
@@ -105,18 +94,24 @@
* `lt`: 작거나(`l`ess `t`han)
* `le`: 작거나 같은(`l`ess than or `e`qual)
-!!! info "정보"
- `Query`, `Path`, 그리고 나중에게 보게될 것들은 (여러분이 사용할 필요가 없는) 공통 `Param` 클래스의 서브 클래스입니다.
+/// info | 정보
+
+`Query`, `Path`, 그리고 나중에게 보게될 것들은 (여러분이 사용할 필요가 없는) 공통 `Param` 클래스의 서브 클래스입니다.
+
+그리고 이들 모두는 여태까지 본 추가 검증과 메타데이터의 동일한 모든 매개변수를 공유합니다.
+
+///
+
+/// note | 기술 세부사항
- 그리고 이들 모두는 여태까지 본 추가 검증과 메타데이터의 동일한 모든 매개변수를 공유합니다.
+`fastapi`에서 `Query`, `Path` 등을 임포트 할 때, 이것들은 실제로 함수입니다.
-!!! note "기술 세부사항"
- `fastapi`에서 `Query`, `Path` 등을 임포트 할 때, 이것들은 실제로 함수입니다.
+호출되면 동일한 이름의 클래스의 인스턴스를 반환합니다.
- 호출되면 동일한 이름의 클래스의 인스턴스를 반환합니다.
+즉, 함수인 `Query`를 임포트한 겁니다. 그리고 호출하면 `Query`라는 이름을 가진 클래스의 인스턴스를 반환합니다.
- 즉, 함수인 `Query`를 임포트한 겁니다. 그리고 호출하면 `Query`라는 이름을 가진 클래스의 인스턴스를 반환합니다.
+편집기에서 타입에 대한 오류를 표시하지 않도록 하기 위해 (클래스를 직접 사용하는 대신) 이러한 함수들이 있습니다.
- 편집기에서 타입에 대한 오류를 표시하지 않도록 하기 위해 (클래스를 직접 사용하는 대신) 이러한 함수들이 있습니다.
+이렇게 하면 오류를 무시하기 위한 사용자 설정을 추가하지 않고도 일반 편집기와 코딩 도구를 사용할 수 있습니다.
- 이렇게 하면 오류를 무시하기 위한 사용자 설정을 추가하지 않고도 일반 편집기와 코딩 도구를 사용할 수 있습니다.
+///
diff --git a/docs/ko/docs/tutorial/path-params.md b/docs/ko/docs/tutorial/path-params.md
index a75c3cc8c..b72787e0b 100644
--- a/docs/ko/docs/tutorial/path-params.md
+++ b/docs/ko/docs/tutorial/path-params.md
@@ -2,9 +2,7 @@
파이썬의 포맷 문자열 리터럴에서 사용되는 문법을 이용하여 경로 "매개변수" 또는 "변수"를 선언할 수 있습니다:
-```Python hl_lines="6-7"
-{!../../../docs_src/path_params/tutorial001.py!}
-```
+{* ../../docs_src/path_params/tutorial001.py hl[6:7] *}
경로 매개변수 `item_id`의 값은 함수의 `item_id` 인자로 전달됩니다.
@@ -18,14 +16,15 @@
파이썬 표준 타입 어노테이션을 사용하여 함수에 있는 경로 매개변수의 타입을 선언할 수 있습니다:
-```Python hl_lines="7"
-{!../../../docs_src/path_params/tutorial002.py!}
-```
+{* ../../docs_src/path_params/tutorial002.py hl[7] *}
위의 예시에서, `item_id`는 `int`로 선언되었습니다.
-!!! check "확인"
- 이 기능은 함수 내에서 오류 검사, 자동완성 등의 편집기 기능을 활용할 수 있게 해줍니다.
+/// check | 확인
+
+이 기능은 함수 내에서 오류 검사, 자동완성 등의 편집기 기능을 활용할 수 있게 해줍니다.
+
+///
## 데이터 변환
@@ -35,10 +34,13 @@
{"item_id":3}
```
-!!! check "확인"
- 함수가 받은(반환도 하는) 값은 문자열 `"3"`이 아니라 파이썬 `int` 형인 `3`입니다.
+/// check | 확인
- 즉, 타입 선언을 하면 **FastAPI**는 자동으로 요청을 "파싱"합니다.
+함수가 받은(반환도 하는) 값은 문자열 `"3"`이 아니라 파이썬 `int` 형인 `3`입니다.
+
+즉, 타입 선언을 하면 **FastAPI**는 자동으로 요청을 "파싱"합니다.
+
+///
## 데이터 검증
@@ -63,12 +65,15 @@
`int`가 아닌 `float`을 전달하는 경우에도 동일한 오류가 나타납니다: http://127.0.0.1:8000/items/4.2
-!!! check "확인"
- 즉, 파이썬 타입 선언을 하면 **FastAPI**는 데이터 검증을 합니다.
+/// check | 확인
+
+즉, 파이썬 타입 선언을 하면 **FastAPI**는 데이터 검증을 합니다.
- 오류에는 정확히 어느 지점에서 검증을 통과하지 못했는지 명시됩니다.
+오류에는 정확히 어느 지점에서 검증을 통과하지 못했는지 명시됩니다.
- 이는 API와 상호 작용하는 코드를 개발하고 디버깅하는 데 매우 유용합니다.
+이는 API와 상호 작용하는 코드를 개발하고 디버깅하는 데 매우 유용합니다.
+
+///
## 문서화
@@ -76,10 +81,13 @@
POST
에 관한MDN웹 문서 를 참고하기 바랍니다,.
+
+///
- 하지만 파일이 포함된 경우, `multipart/form-data`로 인코딩됩니다. `File`을 사용하였다면, **FastAPI**는 본문의 적합한 부분에서 파일을 가져와야 한다는 것을 인지합니다.
+/// warning | 경고
- 인코딩과 폼 필드에 대해 더 알고싶다면, POST
에 관한MDN웹 문서 를 참고하기 바랍니다,.
+다수의 `File` 과 `Form` 매개변수를 한 *경로 작동*에 선언하는 것이 가능하지만, 요청의 본문이 `application/json` 가 아닌 `multipart/form-data` 로 인코딩 되기 때문에 JSON으로 받아야하는 `Body` 필드를 함께 선언할 수는 없습니다.
-!!! warning "경고"
- 다수의 `File` 과 `Form` 매개변수를 한 *경로 작동*에 선언하는 것이 가능하지만, 요청의 본문이 `application/json` 가 아닌 `multipart/form-data` 로 인코딩 되기 때문에 JSON으로 받아야하는 `Body` 필드를 함께 선언할 수는 없습니다.
+이는 **FastAPI**의 한계가 아니라, HTTP 프로토콜에 의한 것입니다.
- 이는 **FastAPI**의 한계가 아니라, HTTP 프로토콜에 의한 것입니다.
+///
## 다중 파일 업로드
@@ -121,23 +136,27 @@ HTML의 폼들(``)이 서버에 데이터를 전송하는 방식은
이 기능을 사용하기 위해 , `bytes` 의 `List` 또는 `UploadFile` 를 선언하기 바랍니다:
-```Python hl_lines="10 15"
-{!../../../docs_src/request_files/tutorial002.py!}
-```
+{* ../../docs_src/request_files/tutorial002.py hl[10,15] *}
선언한대로, `bytes` 의 `list` 또는 `UploadFile` 들을 전송받을 것입니다.
-!!! note "참고"
- 2019년 4월 14일부터 Swagger UI가 하나의 폼 필드로 다수의 파일을 업로드하는 것을 지원하지 않습니다. 더 많은 정보를 원하면, #4276과 #3641을 참고하세요.
+/// note | 참고
+
+2019년 4월 14일부터 Swagger UI가 하나의 폼 필드로 다수의 파일을 업로드하는 것을 지원하지 않습니다. 더 많은 정보를 원하면, #4276과 #3641을 참고하세요.
+
+그럼에도, **FastAPI**는 표준 Open API를 사용해 이미 호환이 가능합니다.
+
+따라서 Swagger UI 또는 기타 그 외의 OpenAPI를 지원하는 툴이 다중 파일 업로드를 지원하는 경우, 이들은 **FastAPI**와 호환됩니다.
+
+///
- 그럼에도, **FastAPI**는 표준 Open API를 사용해 이미 호환이 가능합니다.
+/// note | 기술적 세부사항
- 따라서 Swagger UI 또는 기타 그 외의 OpenAPI를 지원하는 툴이 다중 파일 업로드를 지원하는 경우, 이들은 **FastAPI**와 호환됩니다.
+`from starlette.responses import HTMLResponse` 역시 사용할 수 있습니다.
-!!! note "기술적 세부사항"
- `from starlette.responses import HTMLResponse` 역시 사용할 수 있습니다.
+**FastAPI**는 개발자의 편의를 위해 `fastapi.responses` 와 동일한 `starlette.responses` 도 제공합니다. 하지만 대부분의 응답들은 Starlette로부터 직접 제공됩니다.
- **FastAPI**는 개발자의 편의를 위해 `fastapi.responses` 와 동일한 `starlette.responses` 도 제공합니다. 하지만 대부분의 응답들은 Starlette로부터 직접 제공됩니다.
+///
## 요약
diff --git a/docs/ko/docs/tutorial/request-form-models.md b/docs/ko/docs/tutorial/request-form-models.md
new file mode 100644
index 000000000..3316a93d5
--- /dev/null
+++ b/docs/ko/docs/tutorial/request-form-models.md
@@ -0,0 +1,78 @@
+# 폼 모델
+
+FastAPI에서 **Pydantic 모델**을 이용하여 **폼 필드**를 선언할 수 있습니다.
+
+/// info | 정보
+
+폼(Form)을 사용하려면, 먼저 `python-multipart`를 설치하세요.
+
+[가상 환경](../virtual-environments.md){.internal-link target=_blank}을 생성하고 활성화한 다음, 아래와 같이 설치할 수 있습니다:
+
+```console
+$ pip install python-multipart
+```
+
+///
+
+/// note | 참고
+
+이 기능은 FastAPI 버전 `0.113.0` 이후부터 지원됩니다. 🤓
+
+///
+
+## Pydantic 모델을 사용한 폼
+
+**폼 필드**로 받고 싶은 필드를 **Pydantic 모델**로 선언한 다음, 매개변수를 `Form`으로 선언하면 됩니다:
+
+{* ../../docs_src/request_form_models/tutorial001_an_py39.py hl[9:11,15] *}
+
+**FastAPI**는 요청에서 받은 **폼 데이터**에서 **각 필드**에 대한 데이터를 **추출**하고 정의한 Pydantic 모델을 줍니다.
+
+## 문서 확인하기
+
+문서 UI `/docs`에서 확인할 수 있습니다:
+
+POST
에 대한 MDN 웹 문서를 참조하세요.
+
+///
+
+/// warning | 경고
+
+*경로 작업*에서 여러 `Form` 매개변수를 선언할 수 있지만, JSON으로 수신할 것으로 예상되는 `Body` 필드와 함께 선언할 수 없습니다. 요청 본문은 `application/json` 대신에 `application/x-www-form-urlencoded`를 사용하여 인코딩되기 때문입니다.
+
+이는 **FastAPI**의 제한 사항이 아니며 HTTP 프로토콜의 일부입니다.
+
+///
+
+## 요약
+
+폼 데이터 입력 매개변수를 선언하려면 `Form`을 사용하세요.
diff --git a/docs/ko/docs/tutorial/response-model.md b/docs/ko/docs/tutorial/response-model.md
index feff88a42..a71d649f9 100644
--- a/docs/ko/docs/tutorial/response-model.md
+++ b/docs/ko/docs/tutorial/response-model.md
@@ -8,12 +8,13 @@
* `@app.delete()`
* 기타.
-```Python hl_lines="17"
-{!../../../docs_src/response_model/tutorial001.py!}
-```
+{* ../../docs_src/response_model/tutorial001.py hl[17] *}
+
+/// note | 참고
-!!! note "참고"
- `response_model`은 "데코레이터" 메소드(`get`, `post`, 등)의 매개변수입니다. 모든 매개변수들과 본문(body)처럼 *경로 작동 함수*가 아닙니다.
+`response_model`은 "데코레이터" 메소드(`get`, `post`, 등)의 매개변수입니다. 모든 매개변수들과 본문(body)처럼 *경로 작동 함수*가 아닙니다.
+
+///
Pydantic 모델 어트리뷰트를 선언한 것과 동일한 타입을 수신하므로 Pydantic 모델이 될 수 있지만, `List[Item]`과 같이 Pydantic 모델들의 `list`일 수도 있습니다.
@@ -28,22 +29,21 @@ FastAPI는 이 `response_model`를 사용하여:
* 해당 모델의 출력 데이터 제한. 이것이 얼마나 중요한지 아래에서 볼 것입니다.
-!!! note "기술 세부사항"
- 응답 모델은 함수의 타입 어노테이션 대신 이 매개변수로 선언하는데, 경로 함수가 실제 응답 모델을 반환하지 않고 `dict`, 데이터베이스 객체나 기타 다른 모델을 `response_model`을 사용하여 필드 제한과 직렬화를 수행하고 반환할 수 있기 때문입니다
+/// note | 기술 세부사항
+
+응답 모델은 함수의 타입 어노테이션 대신 이 매개변수로 선언하는데, 경로 함수가 실제 응답 모델을 반환하지 않고 `dict`, 데이터베이스 객체나 기타 다른 모델을 `response_model`을 사용하여 필드 제한과 직렬화를 수행하고 반환할 수 있기 때문입니다
+
+///
## 동일한 입력 데이터 반환
여기서 우리는 평문 비밀번호를 포함하는 `UserIn` 모델을 선언합니다:
-```Python hl_lines="9 11"
-{!../../../docs_src/response_model/tutorial002.py!}
-```
+{* ../../docs_src/response_model/tutorial002.py hl[9,11] *}
그리고 이 모델을 사용하여 입력을 선언하고 같은 모델로 출력을 선언합니다:
-```Python hl_lines="17-18"
-{!../../../docs_src/response_model/tutorial002.py!}
-```
+{* ../../docs_src/response_model/tutorial002.py hl[17:18] *}
이제 브라우저가 비밀번호로 사용자를 만들 때마다 API는 응답으로 동일한 비밀번호를 반환합니다.
@@ -51,28 +51,25 @@ FastAPI는 이 `response_model`를 사용하여:
그러나 동일한 모델을 다른 *경로 작동*에서 사용할 경우, 모든 클라이언트에게 사용자의 비밀번호를 발신할 수 있습니다.
-!!! danger "위험"
- 절대로 사용자의 평문 비밀번호를 저장하거나 응답으로 발신하지 마십시오.
+/// danger | 위험
+
+절대로 사용자의 평문 비밀번호를 저장하거나 응답으로 발신하지 마십시오.
+
+///
## 출력 모델 추가
대신 평문 비밀번호로 입력 모델을 만들고 해당 비밀번호 없이 출력 모델을 만들 수 있습니다:
-```Python hl_lines="9 11 16"
-{!../../../docs_src/response_model/tutorial003.py!}
-```
+{* ../../docs_src/response_model/tutorial003.py hl[9,11,16] *}
여기서 *경로 작동 함수*가 비밀번호를 포함하는 동일한 입력 사용자를 반환할지라도:
-```Python hl_lines="24"
-{!../../../docs_src/response_model/tutorial003.py!}
-```
+{* ../../docs_src/response_model/tutorial003.py hl[24] *}
...`response_model`을 `UserOut` 모델로 선언했기 때문에 비밀번호를 포함하지 않습니다:
-```Python hl_lines="22"
-{!../../../docs_src/response_model/tutorial003.py!}
-```
+{* ../../docs_src/response_model/tutorial003.py hl[22] *}
따라서 **FastAPI**는 출력 모델에서 선언하지 않은 모든 데이터를 (Pydantic을 사용하여) 필터링합니다.
@@ -90,9 +87,7 @@ FastAPI는 이 `response_model`를 사용하여:
응답 모델은 아래와 같이 기본값을 가질 수 있습니다:
-```Python hl_lines="11 13-14"
-{!../../../docs_src/response_model/tutorial004.py!}
-```
+{* ../../docs_src/response_model/tutorial004.py hl[11,13:14] *}
* `description: Optional[str] = None`은 기본값으로 `None`을 갖습니다.
* `tax: float = 10.5`는 기본값으로 `10.5`를 갖습니다.
@@ -106,9 +101,7 @@ FastAPI는 이 `response_model`를 사용하여:
*경로 작동 데코레이터* 매개변수를 `response_model_exclude_unset=True`로 설정 할 수 있습니다:
-```Python hl_lines="24"
-{!../../../docs_src/response_model/tutorial004.py!}
-```
+{* ../../docs_src/response_model/tutorial004.py hl[24] *}
이러한 기본값은 응답에 포함되지 않고 실제로 설정된 값만 포함됩니다.
@@ -121,16 +114,22 @@ FastAPI는 이 `response_model`를 사용하여:
}
```
-!!! info "정보"
- FastAPI는 이를 위해 Pydantic 모델의 `.dict()`의 `exclude_unset` 매개변수를 사용합니다.
+/// info | 정보
+
+FastAPI는 이를 위해 Pydantic 모델의 `.dict()`의 `exclude_unset` 매개변수를 사용합니다.
+
+///
+
+/// info | 정보
-!!! info "정보"
- 아래 또한 사용할 수 있습니다:
+아래 또한 사용할 수 있습니다:
- * `response_model_exclude_defaults=True`
- * `response_model_exclude_none=True`
+* `response_model_exclude_defaults=True`
+* `response_model_exclude_none=True`
- Pydantic 문서에서 `exclude_defaults` 및 `exclude_none`에 대해 설명한 대로 사용할 수 있습니다.
+Pydantic 문서에서 `exclude_defaults` 및 `exclude_none`에 대해 설명한 대로 사용할 수 있습니다.
+
+///
#### 기본값이 있는 필드를 갖는 값의 데이터
@@ -166,10 +165,13 @@ ID가 `baz`인 항목(items)처럼 기본값과 동일한 값을 갖는다면:
따라서 JSON 스키마에 포함됩니다.
-!!! tip "팁"
- `None` 뿐만 아니라 다른 어떤 것도 기본값이 될 수 있습니다.
+/// tip | 팁
+
+`None` 뿐만 아니라 다른 어떤 것도 기본값이 될 수 있습니다.
+
+리스트(`[]`), `float`인 `10.5` 등이 될 수 있습니다.
- 리스트(`[]`), `float`인 `10.5` 등이 될 수 있습니다.
+///
### `response_model_include` 및 `response_model_exclude`
@@ -179,29 +181,31 @@ 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 스키마가 여전히 전체 모델에 대한 스키마이기 때문입니다.
-```Python hl_lines="31 37"
-{!../../../docs_src/response_model/tutorial005.py!}
-```
+비슷하게 작동하는 `response_model_by_alias` 역시 마찬가지로 적용됩니다.
+
+///
+
+{* ../../docs_src/response_model/tutorial005.py hl[31,37] *}
-!!! tip "팁"
- 문법 `{"name", "description"}`은 두 값을 갖는 `set`을 만듭니다.
+/// tip | 팁
- 이는 `set(["name", "description"])`과 동일합니다.
+문법 `{"name", "description"}`은 두 값을 갖는 `set`을 만듭니다.
+
+이는 `set(["name", "description"])`과 동일합니다.
+
+///
#### `set` 대신 `list` 사용하기
`list` 또는 `tuple` 대신 `set`을 사용하는 법을 잊었더라도, FastAPI는 `set`으로 변환하고 정상적으로 작동합니다:
-```Python hl_lines="31 37"
-{!../../../docs_src/response_model/tutorial006.py!}
-```
+{* ../../docs_src/response_model/tutorial006.py hl[31,37] *}
## 요약
diff --git a/docs/ko/docs/tutorial/response-status-code.md b/docs/ko/docs/tutorial/response-status-code.md
index e6eed5120..bcaf7843b 100644
--- a/docs/ko/docs/tutorial/response-status-code.md
+++ b/docs/ko/docs/tutorial/response-status-code.md
@@ -8,17 +8,21 @@
* `@app.delete()`
* 기타
-```Python hl_lines="6"
-{!../../../docs_src/response_status_code/tutorial001.py!}
-```
+{* ../../docs_src/response_status_code/tutorial001.py hl[6] *}
-!!! 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 +31,21 @@
+ FastAPI framework, zeer goede prestaties, eenvoudig te leren, snel te programmeren, klaar voor productie +
+ + +--- + +**Documentatie**: https://fastapi.tiangolo.com + +**Broncode**: https://github.com/tiangolo/fastapi + +--- + +FastAPI is een modern, snel (zeer goede prestaties), web framework voor het bouwen van API's in Python, gebruikmakend van standaard Python type-hints. + +De belangrijkste kenmerken zijn: + +* **Snel**: Zeer goede prestaties, vergelijkbaar met **NodeJS** en **Go** (dankzij Starlette en Pydantic). [Een van de snelste beschikbare Python frameworks](#prestaties). +* **Snel te programmeren**: Verhoog de snelheid om functionaliteit te ontwikkelen met ongeveer 200% tot 300%. * +* **Minder bugs**: Verminder ongeveer 40% van de door mensen (ontwikkelaars) veroorzaakte fouten. * +* **Intuïtief**: Buitengewoon goede ondersteuning voor editors. Overal automische code aanvulling. Minder tijd kwijt aan debuggen. +* **Eenvoudig**: Ontworpen om gemakkelijk te gebruiken en te leren. Minder tijd nodig om documentatie te lezen. +* **Kort**: Minimaliseer codeduplicatie. Elke parameterdeclaratie ondersteunt meerdere functionaliteiten. Minder bugs. +* **Robust**: Code gereed voor productie. Met automatische interactieve documentatie. +* **Standards-based**: Gebaseerd op (en volledig verenigbaar met) open standaarden voor API's: OpenAPI (voorheen bekend als Swagger) en JSON Schema. + +* schatting op basis van testen met een intern ontwikkelteam en bouwen van productieapplicaties. + +## Sponsors + + + +{% if sponsors %} +{% for sponsor in sponsors.gold -%} +async def
...fastapi dev main.py
...email_validator
- voor email validatie.
+
+Gebruikt door Starlette:
+
+* httpx
- Vereist indien je de `TestClient` wil gebruiken.
+* jinja2
- Vereist als je de standaard templateconfiguratie wil gebruiken.
+* python-multipart
- Vereist indien je "parsen" van formulieren wil ondersteunen met `requests.form()`.
+
+Gebruikt door FastAPI / Starlette:
+
+* uvicorn
- voor de server die jouw applicatie laadt en bedient.
+* `fastapi-cli` - om het `fastapi` commando te voorzien.
+
+### Zonder `standard` Afhankelijkheden
+
+Indien je de optionele `standard` afhankelijkheden niet wenst te installeren, kan je installeren met `pip install fastapi` in plaats van `pip install "fastapi[standard]"`.
+
+### Bijkomende Optionele Afhankelijkheden
+
+Er zijn nog een aantal bijkomende afhankelijkheden die je eventueel kan installeren.
+
+Bijkomende optionele afhankelijkheden voor Pydantic:
+
+* pydantic-settings
- voor het beheren van settings.
+* pydantic-extra-types
- voor extra data types die gebruikt kunnen worden met Pydantic.
+
+Bijkomende optionele afhankelijkheden voor FastAPI:
+
+* orjson
- Vereist indien je `ORJSONResponse` wil gebruiken.
+* ujson
- Vereist indien je `UJSONResponse` wil gebruiken.
+
+## Licentie
+
+Dit project is gelicenseerd onder de voorwaarden van de MIT licentie.
diff --git a/docs/nl/docs/python-types.md b/docs/nl/docs/python-types.md
new file mode 100644
index 000000000..fb8b1e5fd
--- /dev/null
+++ b/docs/nl/docs/python-types.md
@@ -0,0 +1,587 @@
+# Introductie tot Python Types
+
+Python biedt ondersteuning voor optionele "type hints" (ook wel "type annotaties" genoemd).
+
+Deze **"type hints"** of annotaties zijn een speciale syntax waarmee het type van een variabele kan worden gedeclareerd.
+
+Door types voor je variabelen te declareren, kunnen editors en hulpmiddelen je beter ondersteunen.
+
+Dit is slechts een **korte tutorial/opfrisser** over Python type hints. Het behandelt enkel het minimum dat nodig is om ze te gebruiken met **FastAPI**... en dat is relatief weinig.
+
+**FastAPI** is helemaal gebaseerd op deze type hints, ze geven veel voordelen.
+
+Maar zelfs als je **FastAPI** nooit gebruikt, heb je er baat bij om er iets over te leren.
+
+/// note
+
+Als je een Python expert bent en alles al weet over type hints, sla dan dit hoofdstuk over.
+
+///
+
+## Motivatie
+
+Laten we beginnen met een eenvoudig voorbeeld:
+
+{* ../../docs_src/python_types/tutorial001.py *}
+
+
+Het aanroepen van dit programma leidt tot het volgende resultaat:
+
+```
+John Doe
+```
+
+De functie voert het volgende uit:
+
+* Neem een `first_name` en een `last_name`
+* Converteer de eerste letter van elk naar een hoofdletter met `title()`.
+``
+* Voeg samen met een spatie in het midden.
+
+{* ../../docs_src/python_types/tutorial001.py hl[2] *}
+
+
+### Bewerk het
+
+Dit is een heel eenvoudig programma.
+
+Maar stel je nu voor dat je het vanaf nul zou moeten maken.
+
+Op een gegeven moment zou je aan de definitie van de functie zijn begonnen, je had de parameters klaar...
+
+Maar dan moet je “die methode die de eerste letter naar hoofdletters converteert” aanroepen.
+
+Was het `upper`? Was het `uppercase`? `first_uppercase`? `capitalize`?
+
+Dan roep je de hulp in van je oude programmeursvriend, (automatische) code aanvulling in je editor.
+
+Je typt de eerste parameter van de functie, `first_name`, dan een punt (`.`) en drukt dan op `Ctrl+Spatie` om de aanvulling te activeren.
+
+Maar helaas krijg je niets bruikbaars:
+
+email_validator
- dla walidacji adresów email.
+* email-validator
- dla walidacji adresów email.
Używane przez Starlette:
diff --git a/docs/pl/docs/tutorial/first-steps.md b/docs/pl/docs/tutorial/first-steps.md
index ce71f8b83..8fa4c75ad 100644
--- a/docs/pl/docs/tutorial/first-steps.md
+++ b/docs/pl/docs/tutorial/first-steps.md
@@ -2,9 +2,7 @@
Najprostszy plik FastAPI może wyglądać tak:
-```Python
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py *}
Skopiuj to do pliku `main.py`.
@@ -24,12 +22,15 @@ $ uvicorn main:app --reload
-!!! note
- Polecenie `uvicorn main:app` odnosi się do:
+/// note
+
+Polecenie `uvicorn main:app` odnosi się do:
+
+* `main`: plik `main.py` ("moduł" Python).
+* `app`: obiekt utworzony w pliku `main.py` w lini `app = FastAPI()`.
+* `--reload`: sprawia, że serwer uruchamia się ponownie po zmianie kodu. Używany tylko w trakcie tworzenia oprogramowania.
- * `main`: plik `main.py` ("moduł" Python).
- * `app`: obiekt utworzony w pliku `main.py` w lini `app = FastAPI()`.
- * `--reload`: sprawia, że serwer uruchamia się ponownie po zmianie kodu. Używany tylko w trakcie tworzenia oprogramowania.
+///
Na wyjściu znajduje się linia z czymś w rodzaju:
@@ -130,23 +131,21 @@ Możesz go również użyć do automatycznego generowania kodu dla klientów, kt
### Krok 1: zaimportuj `FastAPI`
-```Python hl_lines="1"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[1] *}
`FastAPI` jest klasą, która zapewnia wszystkie funkcjonalności Twojego API.
-!!! note "Szczegóły techniczne"
- `FastAPI` jest klasą, która dziedziczy bezpośrednio z `Starlette`.
+/// note | Szczegóły techniczne
+
+`FastAPI` jest klasą, która dziedziczy bezpośrednio z `Starlette`.
- Oznacza to, że możesz korzystać ze wszystkich funkcjonalności Starlette również w `FastAPI`.
+Oznacza to, że możesz korzystać ze wszystkich funkcjonalności Starlette również w `FastAPI`.
+///
### Krok 2: utwórz instancję `FastAPI`
-```Python hl_lines="3"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{*../../docs_src/first_steps/tutorial001.py hl[3] *}
Zmienna `app` będzie tutaj "instancją" klasy `FastAPI`.
@@ -166,9 +165,7 @@ $ uvicorn main:app --reload
Jeśli stworzysz swoją aplikację, np.:
-```Python hl_lines="3"
-{!../../../docs_src/first_steps/tutorial002.py!}
-```
+{* ../../docs_src/first_steps/tutorial002.py hl[3] *}
I umieścisz to w pliku `main.py`, to będziesz mógł tak wywołać `uvicorn`:
@@ -200,8 +197,11 @@ https://example.com/items/foo
/items/foo
```
-!!! info
- "Ścieżka" jest zazwyczaj nazywana "path", "endpoint" lub "route'.
+/// info
+
+"Ścieżka" jest zazwyczaj nazywana "path", "endpoint" lub "route'.
+
+///
Podczas budowania API, "ścieżka" jest głównym sposobem na oddzielenie "odpowiedzialności" i „zasobów”.
@@ -242,25 +242,26 @@ Będziemy je również nazywali "**operacjami**".
#### Zdefiniuj *dekorator operacji na ścieżce*
-```Python hl_lines="6"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[6] *}
`@app.get("/")` mówi **FastAPI** że funkcja poniżej odpowiada za obsługę żądań, które trafiają do:
* ścieżki `/`
* używając operacji 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 +276,17 @@ Oraz tych bardziej egzotycznych:
* `@app.patch()`
* `@app.trace()`
-!!! tip
- Możesz dowolnie używać każdej operacji (metody HTTP).
+/// tip
+
+Możesz dowolnie używać każdej operacji (metody HTTP).
- **FastAPI** nie narzuca żadnego konkretnego znaczenia.
+**FastAPI** nie narzuca żadnego konkretnego znaczenia.
- Informacje tutaj są przedstawione jako wskazówka, a nie wymóg.
+Informacje tutaj są przedstawione jako wskazówka, a nie wymóg.
- Na przykład, używając GraphQL, normalnie wykonujesz wszystkie akcje używając tylko operacji `POST`.
+Na przykład, używając GraphQL, normalnie wykonujesz wszystkie akcje używając tylko operacji `POST`.
+
+///
### Krok 4: zdefiniuj **funkcję obsługującą ścieżkę**
@@ -292,9 +296,7 @@ To jest nasza "**funkcja obsługująca ścieżkę**":
* **operacja**: to `get`.
* **funkcja**: to funkcja poniżej "dekoratora" (poniżej `@app.get("/")`).
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[7] *}
Jest to funkcja Python.
@@ -306,18 +308,17 @@ W tym przypadku jest to funkcja "asynchroniczna".
Możesz również zdefiniować to jako normalną funkcję zamiast `async def`:
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial003.py!}
-```
+{* ../../docs_src/first_steps/tutorial003.py hl[7] *}
+
+/// note
-!!! note
- Jeśli nie znasz różnicy, sprawdź [Async: *"In a hurry?"*](../async.md#in-a-hurry){.internal-link target=_blank}.
+Jeśli nie znasz różnicy, sprawdź [Async: *"In a hurry?"*](../async.md#in-a-hurry){.internal-link target=_blank}.
+
+///
### Krok 5: zwróć zawartość
-```Python hl_lines="8"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[8] *}
Możesz zwrócić `dict`, `list`, pojedynczą wartość jako `str`, `int`, itp.
diff --git a/docs/pl/docs/tutorial/index.md b/docs/pl/docs/tutorial/index.md
index f8c5c6022..66f7c6d62 100644
--- a/docs/pl/docs/tutorial/index.md
+++ b/docs/pl/docs/tutorial/index.md
@@ -52,22 +52,25 @@ $ pip install "fastapi[all]"
...wliczając w to `uvicorn`, który będzie służył jako serwer wykonujacy Twój kod.
-!!! note
- Możesz również wykonać instalację "krok po kroku".
+/// note
- Prawdopodobnie zechcesz to zrobić, kiedy będziesz wdrażać swoją aplikację w środowisku produkcyjnym:
+Możesz również wykonać instalację "krok po kroku".
- ```
- pip install fastapi
- ```
+Prawdopodobnie zechcesz to zrobić, kiedy będziesz wdrażać swoją aplikację w środowisku produkcyjnym:
- Zainstaluj też `uvicorn`, który będzie służył jako serwer:
+```
+pip install fastapi
+```
+
+Zainstaluj też `uvicorn`, który będzie służył jako serwer:
+
+```
+pip install "uvicorn[standard]"
+```
- ```
- pip install "uvicorn[standard]"
- ```
+Tak samo możesz zainstalować wszystkie dodatkowe biblioteki, których chcesz użyć.
- Tak samo możesz zainstalować wszystkie dodatkowe biblioteki, których chcesz użyć.
+///
## Zaawansowany poradnik
diff --git a/docs/pt/docs/advanced/additional-responses.md b/docs/pt/docs/advanced/additional-responses.md
index 7c7d22611..1060d18af 100644
--- a/docs/pt/docs/advanced/additional-responses.md
+++ b/docs/pt/docs/advanced/additional-responses.md
@@ -1,9 +1,12 @@
# Retornos Adicionais no OpenAPI
-!!! warning "Aviso"
- Este é um tema bem avançado.
+/// warning | Aviso
- Se você está começando com o **FastAPI**, provavelmente você não precisa disso.
+Este é um tema bem avançado.
+
+Se você está começando com o **FastAPI**, provavelmente você não precisa disso.
+
+///
Você pode declarar retornos adicionais, com códigos de status adicionais, media types, descrições, etc.
@@ -23,24 +26,28 @@ O **FastAPI** pegará este modelo, gerará o esquema JSON dele e incluirá no lo
Por exemplo, para declarar um outro retorno com o status code `404` e um modelo do Pydantic chamado `Message`, você pode escrever:
-```Python hl_lines="18 22"
-{!../../../docs_src/additional_responses/tutorial001.py!}
-```
+{* ../../docs_src/additional_responses/tutorial001.py hl[18,22] *}
+
+/// note | Nota
+
+Lembre-se que você deve retornar o `JSONResponse` diretamente.
+
+///
+
+/// info | Informação
-!!! note "Nota"
- Lembre-se que você deve retornar o `JSONResponse` diretamente.
+A chave `model` não é parte do OpenAPI.
-!!! 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 **FastAPI** pegará o modelo do Pydantic, gerará o `JSON Schema`, e adicionará no local correto.
+O local correto é:
- O local correto é:
+* Na chave `content`, que tem como valor um outro objeto JSON (`dict`) que contém:
+ * Uma chave com o media type, como por exemplo `application/json`, que contém como valor um outro objeto JSON, contendo::
+ * Uma chave `schema`, que contém como valor o JSON Schema do modelo, sendo este o local correto.
+ * O **FastAPI** adiciona aqui a referência dos esquemas JSON globais que estão localizados em outro lugar, ao invés de incluí-lo diretamente. Deste modo, outras aplicações e clientes podem utilizar estes esquemas JSON diretamente, fornecer melhores ferramentas de geração de código, etc.
- * Na chave `content`, que tem como valor um outro objeto JSON (`dict`) que contém:
- * Uma chave com o media type, como por exemplo `application/json`, que contém como valor um outro objeto JSON, contendo::
- * Uma chave `schema`, que contém como valor o JSON Schema do modelo, sendo este o local correto.
- * O **FastAPI** adiciona aqui a referência dos esquemas JSON globais que estão localizados em outro lugar, ao invés de incluí-lo diretamente. Deste modo, outras aplicações e clientes podem utilizar estes esquemas JSON diretamente, fornecer melhores ferramentas de geração de código, etc.
+///
O retorno gerado no OpenAI para esta *operação de caminho* será:
@@ -168,17 +175,21 @@ Você pode utilizar o mesmo parâmetro `responses` para adicionar diferentes med
Por exemplo, você pode adicionar um media type adicional de `image/png`, declarando que a sua *operação de caminho* pode retornar um objeto JSON (com o media type `application/json`) ou uma imagem PNG:
-```Python hl_lines="19-24 28"
-{!../../../docs_src/additional_responses/tutorial002.py!}
-```
+{* ../../docs_src/additional_responses/tutorial002.py hl[19:24,28] *}
+
+/// note | Nota
+
+Note que você deve retornar a imagem utilizando um `FileResponse` diretamente.
+
+///
-!!! note "Nota"
- Note que você deve retornar a imagem utilizando um `FileResponse` diretamente.
+/// info | Informação
-!!! 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`).
+A menos que você especifique um media type diferente explicitamente em seu parâmetro `responses`, o FastAPI assumirá que o retorno possui o mesmo media type contido na classe principal de retorno (padrão `application/json`).
- Porém se você especificou uma classe de retorno com o valor `None` como media type, o FastAPI utilizará `application/json` para qualquer retorno adicional que possui um modelo associado.
+Porém se você especificou uma classe de retorno com o valor `None` como media type, o FastAPI utilizará `application/json` para qualquer retorno adicional que possui um modelo associado.
+
+///
## Combinando informações
@@ -192,9 +203,7 @@ Por exemplo, você pode declarar um retorno com o código de status `404` que ut
E um retorno com o código de status `200` que utiliza o seu `response_model`, porém inclui um `example` customizado:
-```Python hl_lines="20-31"
-{!../../../docs_src/additional_responses/tutorial003.py!}
-```
+{* ../../docs_src/additional_responses/tutorial003.py hl[20:31] *}
Isso será combinado e incluído em seu OpenAPI, e disponibilizado na documentação da sua API:
@@ -228,9 +237,7 @@ Você pode utilizar essa técnica para reutilizar alguns retornos predefinidos n
Por exemplo:
-```Python hl_lines="13-17 26"
-{!../../../docs_src/additional_responses/tutorial004.py!}
-```
+{* ../../docs_src/additional_responses/tutorial004.py hl[13:17,26] *}
## Mais informações sobre retornos OpenAPI
diff --git a/docs/pt/docs/advanced/additional-status-codes.md b/docs/pt/docs/advanced/additional-status-codes.md
index a7699b324..06d619151 100644
--- a/docs/pt/docs/advanced/additional-status-codes.md
+++ b/docs/pt/docs/advanced/additional-status-codes.md
@@ -14,53 +14,25 @@ Mas você também deseja aceitar novos itens. E quando os itens não existiam, e
Para conseguir isso, importe `JSONResponse` e retorne o seu conteúdo diretamente, definindo o `status_code` que você deseja:
-=== "Python 3.10+"
+{* ../../docs_src/additional_status_codes/tutorial001_an_py310.py hl[4,25] *}
- ```Python hl_lines="4 25"
- {!> ../../../docs_src/additional_status_codes/tutorial001_an_py310.py!}
- ```
+/// warning | Aviso
-=== "Python 3.9+"
+Quando você retorna um `Response` diretamente, como no exemplo acima, ele será retornado diretamente.
- ```Python hl_lines="4 25"
- {!> ../../../docs_src/additional_status_codes/tutorial001_an_py39.py!}
- ```
+Ele não será serializado com um modelo, etc.
-=== "Python 3.8+"
+Garanta que ele tenha toda informação que você deseja, e que os valores sejam um JSON válido (caso você esteja usando `JSONResponse`).
- ```Python hl_lines="4 26"
- {!> ../../../docs_src/additional_status_codes/tutorial001_an.py!}
- ```
+///
-=== "Python 3.10+ non-Annotated"
+/// note | Detalhes técnicos
- !!! tip "Dica"
- Faça uso da versão `Annotated` quando possível.
+Você também pode utilizar `from starlette.responses import JSONResponse`.
- ```Python hl_lines="2 23"
- {!> ../../../docs_src/additional_status_codes/tutorial001_py310.py!}
- ```
+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`.
-=== "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
diff --git a/docs/pt/docs/advanced/advanced-dependencies.md b/docs/pt/docs/advanced/advanced-dependencies.md
index 58887f9c8..f57abba61 100644
--- a/docs/pt/docs/advanced/advanced-dependencies.md
+++ b/docs/pt/docs/advanced/advanced-dependencies.md
@@ -18,26 +18,7 @@ Não propriamente a classe (que já é um chamável), mas a instância desta cla
Para fazer isso, nós declaramos o método `__call__`:
-=== "Python 3.9+"
-
- ```Python hl_lines="12"
- {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="11"
- {!> ../../../docs_src/dependencies/tutorial011_an.py!}
- ```
-
-=== "Python 3.8+ non-Annotated"
-
- !!! tip "Dica"
- Prefira utilizar a versão `Annotated` se possível.
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/dependencies/tutorial011.py!}
- ```
+{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[12] *}
Neste caso, o `__call__` é o que o **FastAPI** utilizará para verificar parâmetros adicionais e sub dependências, e isso é o que será chamado para passar o valor ao parâmetro na sua *função de operação de rota* posteriormente.
@@ -45,26 +26,7 @@ Neste caso, o `__call__` é o que o **FastAPI** utilizará para verificar parâm
E agora, nós podemos utilizar o `__init__` para declarar os parâmetros da instância que podemos utilizar para "parametrizar" a dependência:
-=== "Python 3.9+"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="8"
- {!> ../../../docs_src/dependencies/tutorial011_an.py!}
- ```
-
-=== "Python 3.8+ non-Annotated"
-
- !!! tip "Dica"
- Prefira utilizar a versão `Annotated` se possível.
-
- ```Python hl_lines="7"
- {!> ../../../docs_src/dependencies/tutorial011.py!}
- ```
+{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[9] *}
Neste caso, o **FastAPI** nunca tocará ou se importará com o `__init__`, nós vamos utilizar diretamente em nosso código.
@@ -72,26 +34,7 @@ Neste caso, o **FastAPI** nunca tocará ou se importará com o `__init__`, nós
Nós poderíamos criar uma instância desta classe com:
-=== "Python 3.9+"
-
- ```Python hl_lines="18"
- {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial011_an.py!}
- ```
-
-=== "Python 3.8+ non-Annotated"
-
- !!! tip "Dica"
- Prefira utilizar a versão `Annotated` se possível.
-
- ```Python hl_lines="16"
- {!> ../../../docs_src/dependencies/tutorial011.py!}
- ```
+{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[18] *}
E deste modo nós podemos "parametrizar" a nossa dependência, que agora possui `"bar"` dentro dele, como o atributo `checker.fixed_content`.
@@ -107,32 +50,16 @@ checker(q="somequery")
...e passar o que quer que isso retorne como valor da dependência em nossa *função de operação de rota* como o parâmetro `fixed_content_included`:
-=== "Python 3.9+"
-
- ```Python hl_lines="22"
- {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="21"
- {!> ../../../docs_src/dependencies/tutorial011_an.py!}
- ```
-
-=== "Python 3.8+ non-Annotated"
+{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[22] *}
- !!! tip "Dica"
- Prefira utilizar a versão `Annotated` se possível.
+/// tip | Dica
- ```Python hl_lines="20"
- {!> ../../../docs_src/dependencies/tutorial011.py!}
- ```
+Tudo isso parece não ser natural. E pode não estar muito claro ou aparentar ser útil ainda.
-!!! tip "Dica"
- Tudo isso parece não ser natural. E pode não estar muito claro ou aparentar ser útil ainda.
+Estes exemplos são intencionalmente simples, porém mostram como tudo funciona.
- Estes exemplos são intencionalmente simples, porém mostram como tudo funciona.
+Nos capítulos sobre segurança, existem funções utilitárias que são implementadas desta maneira.
- Nos capítulos sobre segurança, existem funções utilitárias que são implementadas desta maneira.
+Se você entendeu tudo isso, você já sabe como essas funções utilitárias para segurança funcionam por debaixo dos panos.
- Se você entendeu tudo isso, você já sabe como essas funções utilitárias para segurança funcionam por debaixo dos panos.
+///
diff --git a/docs/pt/docs/advanced/async-tests.md b/docs/pt/docs/advanced/async-tests.md
index 4ccc0c452..a2b79426c 100644
--- a/docs/pt/docs/advanced/async-tests.md
+++ b/docs/pt/docs/advanced/async-tests.md
@@ -32,15 +32,11 @@ Para um exemplos simples, vamos considerar uma estrutura de arquivos semelhante
O arquivo `main.py` teria:
-```Python
-{!../../../docs_src/async_tests/main.py!}
-```
+{* ../../docs_src/async_tests/main.py *}
O arquivo `test_main.py` teria os testes para para o arquivo `main.py`, ele poderia ficar assim:
-```Python
-{!../../../docs_src/async_tests/test_main.py!}
-```
+{* ../../docs_src/async_tests/test_main.py *}
## Executá-lo
@@ -60,18 +56,17 @@ $ pytest
O marcador `@pytest.mark.anyio` informa ao pytest que esta função de teste deve ser invocada de maneira assíncrona:
-```Python hl_lines="7"
-{!../../../docs_src/async_tests/test_main.py!}
-```
+{* ../../docs_src/async_tests/test_main.py hl[7] *}
+
+/// tip | Dica
+
+Note que a função de teste é `async def` agora, no lugar de apenas `def` como quando estávamos utilizando o `TestClient` anteriormente.
-!!! tip "Dica"
- Note que a função de teste é `async def` agora, no lugar de apenas `def` como quando estávamos utilizando o `TestClient` anteriormente.
+///
Então podemos criar um `AsyncClient` com a aplicação, e enviar requisições assíncronas para ela utilizando `await`.
-```Python hl_lines="9-10"
-{!../../../docs_src/async_tests/test_main.py!}
-```
+{* ../../docs_src/async_tests/test_main.py hl[9:12] *}
Isso é equivalente a:
@@ -81,15 +76,24 @@ response = client.get('/')
...que nós utilizamos para fazer as nossas requisições utilizando o `TestClient`.
-!!! tip "Dica"
- Note que nós estamos utilizando async/await com o novo `AsyncClient` - a requisição é assíncrona.
+/// tip | Dica
+
+Note que nós estamos utilizando async/await com o novo `AsyncClient` - a requisição é assíncrona.
+
+///
+
+/// warning | Aviso
-!!! warning "Aviso"
- Se a sua aplicação depende dos eventos de vida útil (*lifespan*), o `AsyncClient` não acionará estes eventos. Para garantir que eles são acionados, utilize o `LifespanManager` do florimondmanca/asgi-lifespan.
+Se a sua aplicação depende dos eventos de vida útil (*lifespan*), o `AsyncClient` não acionará estes eventos. Para garantir que eles são acionados, utilize o `LifespanManager` do florimondmanca/asgi-lifespan.
+
+///
## Outras Chamadas de Funções Assíncronas
Como a função de teste agora é assíncrona, você pode chamar (e `esperar`) outras funções `async` além de enviar requisições para a sua aplicação FastAPI em seus testes, exatamente como você as chamaria em qualquer outro lugar do seu código.
-!!! tip "Dica"
- Se você se deparar com um `RuntimeError: Task attached to a different loop` ao integrar funções assíncronas em seus testes (e.g. ao utilizar o MotorClient do MongoDB) Lembre-se de instanciar objetos que precisam de um loop de eventos (*event loop*) apenas em funções assíncronas, e.g. um *"callback"* `'@app.on_event("startup")`.
+/// tip | Dica
+
+Se você se deparar com um `RuntimeError: Task attached to a different loop` ao integrar funções assíncronas em seus testes (e.g. ao utilizar o MotorClient do MongoDB) Lembre-se de instanciar objetos que precisam de um loop de eventos (*event loop*) apenas em funções assíncronas, e.g. um *"callback"* `'@app.on_event("startup")`.
+
+///
diff --git a/docs/pt/docs/advanced/behind-a-proxy.md b/docs/pt/docs/advanced/behind-a-proxy.md
new file mode 100644
index 000000000..6837c9542
--- /dev/null
+++ b/docs/pt/docs/advanced/behind-a-proxy.md
@@ -0,0 +1,361 @@
+# Atrás de um Proxy
+
+Em algumas situações, você pode precisar usar um servidor **proxy** como Traefik ou Nginx com uma configuração que adiciona um prefixo de caminho extra que não é visto pela sua aplicação.
+
+Nesses casos, você pode usar `root_path` para configurar sua aplicação.
+
+O `root_path` é um mecanismo fornecido pela especificação ASGI (que o FastAPI utiliza, através do Starlette).
+
+O `root_path` é usado para lidar com esses casos específicos.
+
+E também é usado internamente ao montar sub-aplicações.
+
+## Proxy com um prefixo de caminho removido
+
+Ter um proxy com um prefixo de caminho removido, nesse caso, significa que você poderia declarar um caminho em `/app` no seu código, mas então, você adiciona uma camada no topo (o proxy) que colocaria sua aplicação **FastAPI** sob um caminho como `/api/v1`.
+
+Nesse caso, o caminho original `/app` seria servido em `/api/v1/app`.
+
+Embora todo o seu código esteja escrito assumindo que existe apenas `/app`.
+
+{* ../../docs_src/behind_a_proxy/tutorial001.py hl[6] *}
+
+E o proxy estaria **"removendo"** o **prefixo do caminho** dinamicamente antes de transmitir a solicitação para o servidor da aplicação (provavelmente Uvicorn via CLI do FastAPI), mantendo sua aplicação convencida de que está sendo servida em `/app`, para que você não precise atualizar todo o seu código para incluir o prefixo `/api/v1`.
+
+Até aqui, tudo funcionaria normalmente.
+
+Mas então, quando você abre a interface de documentação integrada (o frontend), ele esperaria obter o OpenAPI schema em `/openapi.json`, em vez de `/api/v1/openapi.json`.
+
+Então, o frontend (que roda no navegador) tentaria acessar `/openapi.json` e não conseguiria obter o OpenAPI schema.
+
+Como temos um proxy com um prefixo de caminho de `/api/v1` para nossa aplicação, o frontend precisa buscar o OpenAPI schema em `/api/v1/openapi.json`.
+
+```mermaid
+graph LR
+
+browser("Browser")
+proxy["Proxy on http://0.0.0.0:9999/api/v1/app"]
+server["Server on http://127.0.0.1:8000/app"]
+
+browser --> proxy
+proxy --> server
+```
+
+/// tip | Dica
+
+O IP `0.0.0.0` é comumente usado para significar que o programa escuta em todos os IPs disponíveis naquela máquina/servidor.
+
+///
+
+A interface de documentação também precisaria do OpenAPI schema para declarar que API `server` está localizado em `/api/v1` (atrás do proxy). Por exemplo:
+
+```JSON hl_lines="4-8"
+{
+ "openapi": "3.1.0",
+ // Mais coisas aqui
+ "servers": [
+ {
+ "url": "/api/v1"
+ }
+ ],
+ "paths": {
+ // Mais coisas aqui
+ }
+}
+```
+
+Neste exemplo, o "Proxy" poderia ser algo como **Traefik**. E o servidor seria algo como CLI do FastAPI com **Uvicorn**, executando sua aplicação FastAPI.
+
+### Fornecendo o `root_path`
+
+Para conseguir isso, você pode usar a opção de linha de comando `--root-path` assim:
+
+uvicorn main:app --reload
...fastapi dev main.py
...email-validator
- para validação de email.
+
+Utilizado pelo Starlette:
+
+* httpx
- Obrigatório caso você queira utilizar o `TestClient`.
+* jinja2
- Obrigatório se você quer utilizar a configuração padrão de templates.
+* python-multipart
- Obrigatório se você deseja suporte a "parsing" de formulário, com `request.form()`.
+
+Utilizado pelo FastAPI / Starlette:
+
+* uvicorn
- para o servidor que carrega e serve a sua aplicação. Isto inclui `uvicorn[standard]`, que inclui algumas dependências (e.g. `uvloop`) necessárias para servir em alta performance.
+* `fastapi-cli` - que disponibiliza o comando `fastapi`.
-## Dependências opcionais
+### Sem as dependências `standard`
-Usados por Pydantic:
+Se você não deseja incluir as dependências opcionais `standard`, você pode instalar utilizando `pip install fastapi` ao invés de `pip install "fastapi[standard]"`.
-* email_validator
- para validação de email.
+### Dpendências opcionais adicionais
-Usados por Starlette:
+Existem algumas dependências adicionais que você pode querer instalar.
-* httpx
- Necessário se você quiser utilizar o `TestClient`.
-* jinja2
- Necessário se você quiser utilizar a configuração padrão de templates.
-* python-multipart
- Necessário se você quiser suporte com "parsing" de formulário, com `request.form()`.
-* itsdangerous
- Necessário para suporte a `SessionMiddleware`.
-* pyyaml
- Necessário para suporte a `SchemaGenerator` da Starlette (você provavelmente não precisará disso com o FastAPI).
-* graphene
- Necessário para suporte a `GraphQLApp`.
+Dependências opcionais adicionais do Pydantic:
-Usados por FastAPI / Starlette:
+* pydantic-settings
- para gerenciamento de configurações.
+* pydantic-extra-types
- tipos extras para serem utilizados com o Pydantic.
-* uvicorn
- para o servidor que carrega e serve sua aplicação.
-* orjson
- Necessário se você quer utilizar `ORJSONResponse`.
-* ujson
- Necessário se você quer utilizar `UJSONResponse`.
+Dependências opcionais adicionais do FastAPI:
-Você pode instalar todas essas dependências com `pip install fastapi[all]`.
+* orjson
- Obrigatório se você deseja utilizar o `ORJSONResponse`.
+* ujson
- Obrigatório se você deseja utilizar o `UJSONResponse`.
## Licença
diff --git a/docs/pt/docs/python-types.md b/docs/pt/docs/python-types.md
index 52b2dad8e..90a361f40 100644
--- a/docs/pt/docs/python-types.md
+++ b/docs/pt/docs/python-types.md
@@ -1,28 +1,28 @@
# Introdução aos tipos Python
-**Python 3.6 +** tem suporte para "type hints" opcionais.
+O Python possui suporte para "dicas de tipo" ou "type hints" (também chamado de "anotações de tipo" ou "type annotations")
-Esses **"type hints"** são uma nova sintaxe (desde Python 3.6+) que permite declarar o tipo de uma variável.
+Esses **"type hints"** são uma sintaxe especial que permite declarar o tipo de uma variável.
Ao declarar tipos para suas variáveis, editores e ferramentas podem oferecer um melhor suporte.
-Este é apenas um **tutorial rápido / atualização** sobre type hints Python. Ele cobre apenas o mínimo necessário para usá-los com o **FastAPI** ... que é realmente muito pouco.
+Este é apenas um **tutorial rápido / atualização** sobre type hints do Python. Ele cobre apenas o mínimo necessário para usá-los com o **FastAPI**... que é realmente muito pouco.
O **FastAPI** é baseado nesses type hints, eles oferecem muitas vantagens e benefícios.
Mas mesmo que você nunca use o **FastAPI**, você se beneficiaria de aprender um pouco sobre eles.
-!!! note "Nota"
- 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
Vamos começar com um exemplo simples:
-```Python
-{!../../../docs_src/python_types/tutorial001.py!}
-```
+{* ../../docs_src/python_types/tutorial001.py *}
A chamada deste programa gera:
@@ -33,12 +33,10 @@ John Doe
A função faz o seguinte:
* Pega um `first_name` e `last_name`.
-* Converte a primeira letra de cada uma em maiúsculas com `title ()`.
-* Concatena com um espaço no meio.
+* Converte a primeira letra de cada uma em maiúsculas com `title()`.
+* Concatena com um espaço no meio.
-```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial001.py!}
-```
+{* ../../docs_src/python_types/tutorial001.py hl[2] *}
### Edite-o
@@ -46,7 +44,7 @@ A função faz o seguinte:
Mas agora imagine que você estava escrevendo do zero.
-Em algum momento você teria iniciado a definição da função, já tinha os parâmetros prontos ...
+Em algum momento você teria iniciado a definição da função, já tinha os parâmetros prontos...
Mas então você deve chamar "esse método que converte a primeira letra em maiúscula".
@@ -80,9 +78,7 @@ para:
Esses são os "type hints":
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial002.py!}
-```
+{* ../../docs_src/python_types/tutorial002.py hl[1] *}
Isso não é o mesmo que declarar valores padrão como seria com:
@@ -94,37 +90,33 @@ Isso não é o mesmo que declarar valores padrão como seria com:
Estamos usando dois pontos (`:`), não é igual a (`=`).
-E adicionar type hints normalmente não muda o que acontece do que aconteceria sem elas.
+E adicionar type hints normalmente não muda o que acontece do que aconteceria sem eles.
Mas agora, imagine que você está novamente no meio da criação dessa função, mas com type hints.
-No mesmo ponto, você tenta acionar o preenchimento automático com o `Ctrl Space` e vê:
+No mesmo ponto, você tenta acionar o preenchimento automático com o `Ctrl+Space` e vê:
kwargs
. Mesmo que eles não possuam um valor padrão.
-```Python hl_lines="7"
-{!../../../docs_src/path_params_numeric_validations/tutorial003.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *}
## Validações numéricas: maior que ou igual
@@ -81,9 +60,7 @@ Com `Query` e `Path` (e outras que você verá mais tarde) você pode declarar r
Aqui, com `ge=1`, `item_id` precisará ser um número inteiro maior que ("`g`reater than") ou igual ("`e`qual") a 1.
-```Python hl_lines="8"
-{!../../../docs_src/path_params_numeric_validations/tutorial004.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial004.py hl[8] *}
## Validações numéricas: maior que e menor que ou igual
@@ -92,9 +69,7 @@ O mesmo se aplica para:
* `gt`: maior que (`g`reater `t`han)
* `le`: menor que ou igual (`l`ess than or `e`qual)
-```Python hl_lines="9"
-{!../../../docs_src/path_params_numeric_validations/tutorial005.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial005.py hl[9] *}
## Validações numéricas: valores do tipo float, maior que e menor que
@@ -106,9 +81,7 @@ Assim, `0.5` seria um valor válido. Mas `0.0` ou `0` não seria.
E o mesmo para lt
.
-```Python hl_lines="11"
-{!../../../docs_src/path_params_numeric_validations/tutorial006.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial006.py hl[11] *}
## Recapitulando
@@ -121,18 +94,24 @@ E você também pode declarar validações numéricas:
* `lt`: menor que (`l`ess `t`han)
* `le`: menor que ou igual (`l`ess than or `e`qual)
-!!! info "Informação"
- `Query`, `Path` e outras classes que você verá a frente são subclasses de uma classe comum `Param`.
+/// info | Informação
+
+`Query`, `Path` e outras classes que você verá a frente são subclasses de uma classe comum `Param`.
+
+Todas elas compartilham os mesmos parâmetros para validação adicional e metadados que você viu.
+
+///
+
+/// note | Detalhes Técnicos
- Todas elas compartilham os mesmos parâmetros para validação adicional e metadados que você viu.
+Quando você importa `Query`, `Path` e outras de `fastapi`, elas são na verdade funções.
-!!! note "Detalhes Técnicos"
- Quando você importa `Query`, `Path` e outras de `fastapi`, elas são na verdade funções.
+Que quando chamadas, retornam instâncias de classes de mesmo nome.
- Que quando chamadas, retornam instâncias de classes de mesmo nome.
+Então, você importa `Query`, que é uma função. E quando você a chama, ela retorna uma instância de uma classe também chamada `Query`.
- Então, você importa `Query`, que é uma função. E quando você a chama, ela retorna uma instância de uma classe também chamada `Query`.
+Estas funções são assim (ao invés de apenas usar as classes diretamente) para que seu editor não acuse erros sobre seus tipos.
- Estas funções são assim (ao invés de apenas usar as classes diretamente) para que seu editor não acuse erros sobre seus tipos.
+Dessa maneira você pode user seu editor e ferramentas de desenvolvimento sem precisar adicionar configurações customizadas para ignorar estes erros.
- Dessa maneira você pode user seu editor e ferramentas de desenvolvimento sem precisar adicionar configurações customizadas para ignorar estes erros.
+///
diff --git a/docs/pt/docs/tutorial/path-params.md b/docs/pt/docs/tutorial/path-params.md
index 27aa9dfcf..ecf77d676 100644
--- a/docs/pt/docs/tutorial/path-params.md
+++ b/docs/pt/docs/tutorial/path-params.md
@@ -2,9 +2,7 @@
Você pode declarar os "parâmetros" ou "variáveis" com a mesma sintaxe utilizada pelo formato de strings do Python:
-```Python hl_lines="6-7"
-{!../../../docs_src/path_params/tutorial001.py!}
-```
+{* ../../docs_src/path_params/tutorial001.py hl[6:7] *}
O valor do parâmetro que foi passado à `item_id` será passado para a sua função como o argumento `item_id`.
@@ -18,13 +16,16 @@ Então, se você rodar este exemplo e for até dados
@@ -35,7 +36,12 @@ Se você rodar esse exemplo e abrir o seu navegador em "parsing" automático no request .
@@ -63,7 +69,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
-!!! check "Verifique"
+/// check | Verifique
+
+
+
+///
+
Então, com a mesma declaração de tipo do Python, o **FastAPI** dá pra você validação de dados.
Observe que o erro também mostra claramente o ponto exato onde a validação não passou.
@@ -76,7 +87,12 @@ Quando você abrir o seu navegador em
-!!! check "Verifique"
+/// check | Verifique
+
+
+
+///
+
Novamente, apenas com a mesma declaração de tipo do Python, o **FastAPI** te dá de forma automática e interativa a documentação (integrada com o Swagger UI).
Veja que o parâmetro de rota está declarado como sendo um inteiro (int).
@@ -109,9 +125,7 @@ E então você pode ter também uma rota `/users/{user_id}` para pegar dados sob
Porque as operações de rota são avaliadas em ordem, você precisa ter certeza que a rota para `/users/me` está sendo declarado antes da rota `/users/{user_id}`:
-```Python hl_lines="6 11"
-{!../../../docs_src/path_params/tutorial003.py!}
-```
+{* ../../docs_src/path_params/tutorial003.py hl[6,11] *}
Caso contrário, a rota para `/users/{user_id}` coincidiria também para `/users/me`, "pensando" que estaria recebendo o parâmetro `user_id` com o valor de `"me"`.
@@ -127,23 +141,27 @@ Por herdar de `str` a documentação da API vai ser capaz de saber que os valore
Assim, crie atributos de classe com valores fixos, que serão os valores válidos disponíveis.
-```Python hl_lines="1 6-9"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial005.py hl[1,6:9] *}
-!!! info "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
+
+
+
+///
-!!! tip "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*
Logo, crie um *parâmetro de rota* com anotações de tipo usando a classe enum que você criou (`ModelName`):
-```Python hl_lines="16"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial005.py hl[16] *}
### Revise a documentação
@@ -159,19 +177,20 @@ O valor do *parâmetro da rota* será um *membro de enumeration*.
Você pode comparar eles com o *membro de enumeration* no enum `ModelName` que você criou:
-```Python hl_lines="17"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial005.py hl[17] *}
#### Obtenha o *valor de enumerate*
Você pode ter o valor exato de enumerate (um `str` nesse caso) usando `model_name.value`, ou em geral, `your_enum_member.value`:
-```Python hl_lines="20"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial005.py hl[20] *}
+
+/// tip | Dica
+
+
+
+///
-!!! tip "Dica"
Você também poderia acessar o valor `"lenet"` com `ModelName.lenet.value`
#### Retorne *membros de enumeration*
@@ -180,9 +199,7 @@ Você pode retornar *membros de enum* da sua *rota de operação*, em um corpo J
Eles serão convertidos para o seus valores correspondentes (strings nesse caso) antes de serem retornados ao cliente:
-```Python hl_lines="18 21 23"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial005.py hl[18,21,23] *}
No seu cliente você vai obter uma resposta JSON como:
@@ -221,11 +238,14 @@ Nesse caso, o nome do parâmetro é `file_path`, e a última parte, `:path`, diz
Então, você poderia usar ele com:
-```Python hl_lines="6"
-{!../../../docs_src/path_params/tutorial004.py!}
-```
+{* ../../docs_src/path_params/tutorial004.py hl[6] *}
+
+/// tip | Dica
+
+
+
+///
-!!! tip "Dica"
Você poderia precisar que o parâmetro contivesse `/home/johndoe/myfile.txt`, com uma barra no inicio (`/`).
Neste caso, a URL deveria ser: `/files//home/johndoe/myfile.txt`, com barra dupla (`//`) entre `files` e `home`.
diff --git a/docs/pt/docs/tutorial/query-param-models.md b/docs/pt/docs/tutorial/query-param-models.md
new file mode 100644
index 000000000..01a6e462f
--- /dev/null
+++ b/docs/pt/docs/tutorial/query-param-models.md
@@ -0,0 +1,69 @@
+# Modelos de Parâmetros de Consulta
+
+Se você possui um grupo de **parâmetros de consultas** que são relacionados, você pode criar um **modelo Pydantic** para declará-los.
+
+Isso permitiria que você **reutilizasse o modelo** em **diversos lugares**, e também declarasse validações e metadados de todos os parâmetros de uma única vez. 😎
+
+/// note | Nota
+
+Isso é suportado desde o FastAPI versão `0.115.0`. 🤓
+
+///
+
+## Parâmetros de Consulta com um Modelo Pydantic
+
+Declare os **parâmetros de consulta** que você precisa em um **modelo Pydantic**, e então declare o parâmetro como `Query`:
+
+{* ../../docs_src/query_param_models/tutorial001_an_py310.py hl[9:13,17] *}
+
+O **FastAPI** **extrairá** os dados para **cada campo** dos **parâmetros de consulta** presentes na requisição, e fornecerá o modelo Pydantic que você definiu.
+
+
+## Verifique os Documentos
+
+Você pode ver os parâmetros de consulta nos documentos de IU em `/docs`:
+
+POST
.
+
+///
+
+/// warning | Aviso
+
+Você pode declarar múltiplos parâmetros `File` e `Form` em uma *operação de rota*, mas você não pode declarar campos `Body` que você espera receber como JSON, pois a requisição terá o corpo codificado usando `multipart/form-data` ao invés de `application/json`.
+
+Isso não é uma limitação do **FastAPI**, é parte do protocolo HTTP.
+
+///
+
+## Upload de Arquivo Opcional
+
+Você pode tornar um arquivo opcional usando anotações de tipo padrão e definindo um valor padrão de `None`:
+
+{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *}
+
+## `UploadFile` com Metadados Adicionais
+
+Você também pode usar `File()` com `UploadFile`, por exemplo, para definir metadados adicionais:
+
+{* ../../docs_src/request_files/tutorial001_03_an_py39.py hl[9,15] *}
+
+## Uploads de Múltiplos Arquivos
+
+É possível realizar o upload de vários arquivos ao mesmo tempo.
+
+Eles serão associados ao mesmo "campo de formulário" enviado usando "dados de formulário".
+
+Para usar isso, declare uma lista de `bytes` ou `UploadFile`:
+
+{* ../../docs_src/request_files/tutorial002_an_py39.py hl[10,15] *}
+
+Você receberá, tal como declarado, uma `list` de `bytes` ou `UploadFile`.
+
+/// note | Detalhes Técnicos
+
+Você pode também pode usar `from starlette.responses import HTMLResponse`.
+
+**FastAPI** providencia o mesmo `starlette.responses` que `fastapi.responses` apenas como uma conveniência para você, o desenvolvedor. Mas a maioria das respostas disponíveis vem diretamente do Starlette.
+
+///
+
+### Uploads de Múltiplos Arquivos com Metadados Adicionais
+
+Da mesma forma de antes, você pode usar `File()` para definir parâmetros adicionais, mesmo para `UploadFile`:
+
+{* ../../docs_src/request_files/tutorial003_an_py39.py hl[11,18:20] *}
+
+## Recapitulando
+
+Utilize `File`, `bytes` e `UploadFile` para declarar arquivos a serem enviados na requisição, enviados como dados de formulário.
diff --git a/docs/pt/docs/tutorial/request-form-models.md b/docs/pt/docs/tutorial/request-form-models.md
new file mode 100644
index 000000000..ea0e63d38
--- /dev/null
+++ b/docs/pt/docs/tutorial/request-form-models.md
@@ -0,0 +1,78 @@
+# Modelos de Formulários
+
+Você pode utilizar **Modelos Pydantic** para declarar **campos de formulários** no FastAPI.
+
+/// info | Informação
+
+Para utilizar formulários, instale primeiramente o `python-multipart`.
+
+Certifique-se de criar um [ambiente virtual](../virtual-environments.md){.internal-link target=_blank}, ativá-lo, e então instalar. Por exemplo:
+
+```console
+$ pip install python-multipart
+```
+
+///
+
+/// note | Nota
+
+Isto é suportado desde a versão `0.113.0` do FastAPI. 🤓
+
+///
+
+## Modelos Pydantic para Formulários
+
+Você precisa apenas declarar um **modelo Pydantic** com os campos que deseja receber como **campos de formulários**, e então declarar o parâmetro como um `Form`:
+
+{* ../../docs_src/request_form_models/tutorial001_an_py39.py hl[9:11,15] *}
+
+O **FastAPI** irá **extrair** as informações para **cada campo** dos **dados do formulário** na requisição e dar para você o modelo Pydantic que você definiu.
+
+## Confira os Documentos
+
+Você pode verificar na UI de documentação em `/docs`:
+
+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
- Se você quiser ler mais sobre essas codificações e campos de formulário, vá para o MDN web docs para POST
.
+Você pode declarar vários parâmetros `Form` em uma *operação de caminho*, mas não pode declarar campos `Body` que espera receber como JSON, pois a solicitação terá o corpo codificado usando `application/x-www- form-urlencoded` em vez de `application/json`.
-!!! warning "Aviso"
- Você pode declarar vários parâmetros `Form` em uma *operação de caminho*, mas não pode declarar campos `Body` que espera receber como JSON, pois a solicitação terá o corpo codificado usando `application/x-www- form-urlencoded` em vez de `application/json`.
+Esta não é uma limitação do **FastAPI**, é parte do protocolo HTTP.
- Esta não é uma limitação do **FastAPI**, é parte do protocolo HTTP.
+///
## Recapitulando
diff --git a/docs/pt/docs/tutorial/request_files.md b/docs/pt/docs/tutorial/request_files.md
new file mode 100644
index 000000000..15c1ad825
--- /dev/null
+++ b/docs/pt/docs/tutorial/request_files.md
@@ -0,0 +1,172 @@
+# 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`:
+
+{* ../../docs_src/request_files/tutorial001_an_py39.py hl[3] *}
+
+## Defina os parâmetros de `File`
+
+Cria os parâmetros do arquivo da mesma forma que você faria para `Body` ou `Form`:
+
+{* ../../docs_src/request_files/tutorial001_an_py39.py hl[9] *}
+
+/// info | Informação
+
+`File` é uma classe que herda diretamente de `Form`.
+
+Mas lembre-se que quando você importa `Query`,`Path`, `File`, 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`
+
+{* ../../docs_src/request_files/tutorial001_an_py39.py hl[14] *}
+
+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`:
+
+{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *}
+
+## `UploadFile` com Metadados Adicionais
+
+Você também pode utilizar `File()` com `UploadFile`, por exemplo, para definir metadados adicionais:
+
+{* ../../docs_src/request_files/tutorial001_03_an_py39.py hl[9,15] *}
+
+## 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`:
+
+{* ../../docs_src/request_files/tutorial002_an_py39.py hl[10,15] *}
+
+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`:
+
+{* ../../docs_src/request_files/tutorial003_an_py39.py hl[11,18:20] *}
+
+## 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-model.md b/docs/pt/docs/tutorial/response-model.md
new file mode 100644
index 000000000..6726a20a7
--- /dev/null
+++ b/docs/pt/docs/tutorial/response-model.md
@@ -0,0 +1,357 @@
+# Modelo de resposta - Tipo de retorno
+
+Você pode declarar o tipo usado para a resposta anotando o **tipo de retorno** *da função de operação de rota*.
+
+Você pode usar **anotações de tipo** da mesma forma que usaria para dados de entrada em **parâmetros** de função, você pode usar modelos Pydantic, listas, dicionários, valores escalares como inteiros, booleanos, etc.
+
+{* ../../docs_src/response_model/tutorial001_01_py310.py hl[16,21] *}
+
+O FastAPI usará este tipo de retorno para:
+
+* **Validar** os dados retornados.
+ * Se os dados forem inválidos (por exemplo, se estiver faltando um campo), significa que o código do *seu* aplicativo está quebrado, não retornando o que deveria, e retornará um erro de servidor em vez de retornar dados incorretos. Dessa forma, você e seus clientes podem ter certeza de que receberão os dados e o formato de dados esperados.
+* Adicionar um **Esquema JSON** para a resposta, na *operação de rota* do OpenAPI.
+ * Isso será usado pela **documentação automática**.
+ * Também será usado por ferramentas de geração automática de código do cliente.
+
+Mas o mais importante:
+
+* Ele **limitará e filtrará** os dados de saída para o que está definido no tipo de retorno.
+ * Isso é particularmente importante para a **segurança**, veremos mais sobre isso abaixo.
+
+## Parâmetro `response_model`
+
+Existem alguns casos em que você precisa ou deseja retornar alguns dados que não são exatamente o que o tipo declara.
+
+Por exemplo, você pode querer **retornar um dicionário** ou um objeto de banco de dados, mas **declará-lo como um modelo Pydantic**. Dessa forma, o modelo Pydantic faria toda a documentação de dados, validação, etc. para o objeto que você retornou (por exemplo, um dicionário ou objeto de banco de dados).
+
+Se você adicionasse a anotação do tipo de retorno, ferramentas e editores reclamariam com um erro (correto) informando que sua função está retornando um tipo (por exemplo, um dict) diferente do que você declarou (por exemplo, um modelo Pydantic).
+
+Nesses casos, você pode usar o parâmetro `response_model` do *decorador de operação de rota* em vez do tipo de retorno.
+
+Você pode usar o parâmetro `response_model` em qualquer uma das *operações de rota*:
+
+* `@app.get()`
+* `@app.post()`
+* `@app.put()`
+* `@app.delete()`
+* etc.
+
+{* ../../docs_src/response_model/tutorial001_py310.py hl[17,22,24:27] *}
+
+/// note | Nota
+
+Observe que `response_model` é um parâmetro do método "decorator" (`get`, `post`, etc). Não da sua *função de operação de rota*, como todos os parâmetros e corpo.
+
+///
+
+`response_model` recebe o mesmo tipo que você declararia para um campo de modelo Pydantic, então, pode ser um modelo Pydantic, mas também pode ser, por exemplo, uma `lista` de modelos Pydantic, como `List[Item]`.
+
+O FastAPI usará este `response_model` para fazer toda a documentação de dados, validação, etc. e também para **converter e filtrar os dados de saída** para sua declaração de tipo.
+
+/// tip | Dica
+
+Se você tiver verificações de tipo rigorosas em seu editor, mypy, etc, você pode declarar o tipo de retorno da função como `Any`.
+
+Dessa forma, você diz ao editor que está retornando qualquer coisa intencionalmente. Mas o FastAPI ainda fará a documentação de dados, validação, filtragem, etc. com o `response_model`.
+
+///
+
+### Prioridade `response_model`
+
+Se você declarar tanto um tipo de retorno quanto um `response_model`, o `response_model` terá prioridade e será usado pelo FastAPI.
+
+Dessa forma, você pode adicionar anotações de tipo corretas às suas funções, mesmo quando estiver retornando um tipo diferente do modelo de resposta, para ser usado pelo editor e ferramentas como mypy. E ainda assim você pode fazer com que o FastAPI faça a validação de dados, documentação, etc. usando o `response_model`.
+
+Você também pode usar `response_model=None` para desabilitar a criação de um modelo de resposta para essa *operação de rota*, você pode precisar fazer isso se estiver adicionando anotações de tipo para coisas que não são campos Pydantic válidos, você verá um exemplo disso em uma das seções abaixo.
+
+## Retorna os mesmos dados de entrada
+
+Aqui estamos declarando um modelo `UserIn`, ele conterá uma senha em texto simples:
+
+{* ../../docs_src/response_model/tutorial002_py310.py hl[7,9] *}
+
+/// info | Informação
+
+Para usar `EmailStr`, primeiro instale `email-validator`.
+
+Certifique-se de criar um [ambiente virtual](../virtual-environments.md){.internal-link target=_blank}, ative-o e instale-o, por exemplo:
+
+```console
+$ pip install email-validator
+```
+
+ou com:
+
+```console
+$ pip install "pydantic[email]"
+```
+
+///
+
+E estamos usando este modelo para declarar nossa entrada e o mesmo modelo para declarar nossa saída:
+
+{* ../../docs_src/response_model/tutorial002_py310.py hl[16] *}
+
+Agora, sempre que um navegador estiver criando um usuário com uma senha, a API retornará a mesma senha na resposta.
+
+Neste caso, pode não ser um problema, porque é o mesmo usuário enviando a senha.
+
+Mas se usarmos o mesmo modelo para outra *operação de rota*, poderíamos estar enviando as senhas dos nossos usuários para todos os clientes.
+
+/// danger | Perigo
+
+Nunca armazene a senha simples de um usuário ou envie-a em uma resposta como esta, a menos que você saiba todas as ressalvas e saiba o que está fazendo.
+
+///
+
+## Adicionar um modelo de saída
+
+Podemos, em vez disso, criar um modelo de entrada com a senha em texto simples e um modelo de saída sem ela:
+
+{* ../../docs_src/response_model/tutorial003_py310.py hl[9,11,16] *}
+
+Aqui, embora nossa *função de operação de rota* esteja retornando o mesmo usuário de entrada que contém a senha:
+
+{* ../../docs_src/response_model/tutorial003_py310.py hl[24] *}
+
+...declaramos o `response_model` como nosso modelo `UserOut`, que não inclui a senha:
+
+{* ../../docs_src/response_model/tutorial003_py310.py hl[22] *}
+
+Então, **FastAPI** cuidará de filtrar todos os dados que não são declarados no modelo de saída (usando Pydantic).
+
+### `response_model` ou Tipo de Retorno
+
+Neste caso, como os dois modelos são diferentes, se anotássemos o tipo de retorno da função como `UserOut`, o editor e as ferramentas reclamariam que estamos retornando um tipo inválido, pois são classes diferentes.
+
+É por isso que neste exemplo temos que declará-lo no parâmetro `response_model`.
+
+...mas continue lendo abaixo para ver como superar isso.
+
+## Tipo de Retorno e Filtragem de Dados
+
+Vamos continuar do exemplo anterior. Queríamos **anotar a função com um tipo**, mas queríamos poder retornar da função algo que realmente incluísse **mais dados**.
+
+Queremos que o FastAPI continue **filtrando** os dados usando o modelo de resposta. Para que, embora a função retorne mais dados, a resposta inclua apenas os campos declarados no modelo de resposta.
+
+No exemplo anterior, como as classes eram diferentes, tivemos que usar o parâmetro `response_model`. Mas isso também significa que não temos suporte do editor e das ferramentas verificando o tipo de retorno da função.
+
+Mas na maioria dos casos em que precisamos fazer algo assim, queremos que o modelo apenas **filtre/remova** alguns dados como neste exemplo.
+
+E nesses casos, podemos usar classes e herança para aproveitar as **anotações de tipo** de função para obter melhor suporte no editor e nas ferramentas, e ainda obter a **filtragem de dados** FastAPI.
+
+{* ../../docs_src/response_model/tutorial003_01_py310.py hl[7:10,13:14,18] *}
+
+Com isso, temos suporte de ferramentas, de editores e mypy, pois este código está correto em termos de tipos, mas também obtemos a filtragem de dados do FastAPI.
+
+Como isso funciona? Vamos verificar. 🤓
+
+### Anotações de tipo e ferramentas
+
+Primeiro, vamos ver como editores, mypy e outras ferramentas veriam isso.
+
+`BaseUser` tem os campos base. Então `UserIn` herda de `BaseUser` e adiciona o campo `password`, então, ele incluirá todos os campos de ambos os modelos.
+
+Anotamos o tipo de retorno da função como `BaseUser`, mas na verdade estamos retornando uma instância `UserIn`.
+
+O editor, mypy e outras ferramentas não reclamarão disso porque, em termos de digitação, `UserIn` é uma subclasse de `BaseUser`, o que significa que é um tipo *válido* quando o que é esperado é qualquer coisa que seja um `BaseUser`.
+
+### Filtragem de dados FastAPI
+
+Agora, para FastAPI, ele verá o tipo de retorno e garantirá que o que você retornar inclua **apenas** os campos que são declarados no tipo.
+
+O FastAPI faz várias coisas internamente com o Pydantic para garantir que essas mesmas regras de herança de classe não sejam usadas para a filtragem de dados retornados, caso contrário, você pode acabar retornando muito mais dados do que o esperado.
+
+Dessa forma, você pode obter o melhor dos dois mundos: anotações de tipo com **suporte a ferramentas** e **filtragem de dados**.
+
+## Veja na documentação
+
+Quando você vê a documentação automática, pode verificar se o modelo de entrada e o modelo de saída terão seus próprios esquemas JSON:
+
+
-
+
-
-
+
+
@@ -93,7 +93,7 @@ FastAPI — это современный, быстрый (высокопрои
"_Честно говоря, то, что вы создали, выглядит очень солидно и отполировано. Во многих смыслах я хотел, чтобы **Hug** был именно таким — это действительно вдохновляет, когда кто-то создаёт такое._"
-
+
---
@@ -443,7 +443,7 @@ item: Item
Используется Pydantic:
-*
email_validator
- для проверки электронной почты.
+* email-validator
- для проверки электронной почты.
Используется Starlette:
diff --git a/docs/ru/docs/python-types.md b/docs/ru/docs/python-types.md
index 3c8492c67..b1d4715fd 100644
--- a/docs/ru/docs/python-types.md
+++ b/docs/ru/docs/python-types.md
@@ -12,16 +12,18 @@ Python имеет поддержку необязательных аннотац
Но даже если вы никогда не используете **FastAPI**, вам будет полезно немного узнать о них.
-!!! note
- Если вы являетесь экспертом в Python и уже знаете всё об аннотациях типов, переходите к следующему разделу.
+/// note
+
+Если вы являетесь экспертом в Python и уже знаете всё об аннотациях типов, переходите к следующему разделу.
+
+///
## Мотивация
Давайте начнем с простого примера:
-```Python
-{!../../../docs_src/python_types/tutorial001.py!}
-```
+{* ../../docs_src/python_types/tutorial001.py *}
+
Вызов этой программы выводит:
@@ -35,9 +37,8 @@ John Doe
* Преобразует первую букву содержимого каждой переменной в верхний регистр с `title()`.
* Соединяет их через пробел.
-```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial001.py!}
-```
+{* ../../docs_src/python_types/tutorial001.py hl[2] *}
+
### Отредактируем пример
@@ -79,9 +80,8 @@ John Doe
Это аннотации типов:
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial002.py!}
-```
+{* ../../docs_src/python_types/tutorial002.py hl[1] *}
+
Это не то же самое, что объявление значений по умолчанию, например:
@@ -109,9 +109,8 @@ John Doe
Проверьте эту функцию, она уже имеет аннотации типов:
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial003.py!}
-```
+{* ../../docs_src/python_types/tutorial003.py hl[1] *}
+
Поскольку редактор знает типы переменных, вы получаете не только дополнение, но и проверки ошибок:
@@ -119,9 +118,8 @@ John Doe
Теперь вы знаете, что вам нужно исправить, преобразовав `age` в строку с `str(age)`:
-```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial004.py!}
-```
+{* ../../docs_src/python_types/tutorial004.py hl[2] *}
+
## Объявление типов
@@ -140,9 +138,8 @@ John Doe
* `bool`
* `bytes`
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial005.py!}
-```
+{* ../../docs_src/python_types/tutorial005.py hl[1] *}
+
### Generic-типы с параметрами типов
@@ -158,9 +155,8 @@ John Doe
Импортируйте `List` из `typing` (с заглавной `L`):
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial006.py!}
-```
+{* ../../docs_src/python_types/tutorial006.py hl[1] *}
+
Объявите переменную с тем же синтаксисом двоеточия (`:`).
@@ -168,14 +164,16 @@ John Doe
Поскольку список является типом, содержащим некоторые внутренние типы, вы помещаете их в квадратные скобки:
-```Python hl_lines="4"
-{!../../../docs_src/python_types/tutorial006.py!}
-```
+{* ../../docs_src/python_types/tutorial006.py hl[4] *}
+
-!!! tip
- Эти внутренние типы в квадратных скобках называются «параметрами типов».
+/// tip
- В этом случае `str` является параметром типа, передаваемым в `List`.
+Эти внутренние типы в квадратных скобках называются «параметрами типов».
+
+В этом случае `str` является параметром типа, передаваемым в `List`.
+
+///
Это означает: "переменная `items` является `list`, и каждый из элементов этого списка является `str`".
@@ -193,9 +191,8 @@ John Doe
Вы бы сделали то же самое, чтобы объявить `tuple` и `set`:
-```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial007.py!}
-```
+{* ../../docs_src/python_types/tutorial007.py hl[1,4] *}
+
Это означает:
@@ -210,9 +207,8 @@ John Doe
Второй параметр типа предназначен для значений `dict`:
-```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial008.py!}
-```
+{* ../../docs_src/python_types/tutorial008.py hl[1,4] *}
+
Это означает:
@@ -225,7 +221,7 @@ John Doe
Вы также можете использовать `Optional`, чтобы объявить, что переменная имеет тип, например, `str`, но это является «необязательным», что означает, что она также может быть `None`:
```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009.py!}
+{!../../docs_src/python_types/tutorial009.py!}
```
Использование `Optional[str]` вместо просто `str` позволит редактору помочь вам в обнаружении ошибок, в которых вы могли бы предположить, что значение всегда является `str`, хотя на самом деле это может быть и `None`.
@@ -249,15 +245,13 @@ John Doe
Допустим, у вас есть класс `Person` с полем `name`:
-```Python hl_lines="1-3"
-{!../../../docs_src/python_types/tutorial010.py!}
-```
+{* ../../docs_src/python_types/tutorial010.py hl[1:3] *}
+
Тогда вы можете объявить переменную типа `Person`:
-```Python hl_lines="6"
-{!../../../docs_src/python_types/tutorial010.py!}
-```
+{* ../../docs_src/python_types/tutorial010.py hl[6] *}
+
И снова вы получаете полную поддержку редактора:
@@ -277,12 +271,14 @@ John Doe
Взято из официальной документации Pydantic:
-```Python
-{!../../../docs_src/python_types/tutorial011.py!}
-```
+{* ../../docs_src/python_types/tutorial011.py *}
+
-!!! info
- Чтобы узнать больше о Pydantic, читайте его документацию.
+/// info
+
+Чтобы узнать больше о Pydantic, читайте его документацию.
+
+///
**FastAPI** целиком основан на Pydantic.
@@ -310,5 +306,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..bf2e9dec3 100644
--- a/docs/ru/docs/tutorial/background-tasks.md
+++ b/docs/ru/docs/tutorial/background-tasks.md
@@ -15,9 +15,7 @@
Сначала импортируйте `BackgroundTasks`, потом добавьте в функцию параметр с типом `BackgroundTasks`:
-```Python hl_lines="1 13"
-{!../../../docs_src/background_tasks/tutorial001.py!}
-```
+{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *}
**FastAPI** создаст объект класса `BackgroundTasks` для вас и запишет его в параметр.
@@ -33,17 +31,13 @@
Так как операция записи не использует `async` и `await`, мы определим ее как обычную `def`:
-```Python hl_lines="6-9"
-{!../../../docs_src/background_tasks/tutorial001.py!}
-```
+{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *}
## Добавление фоновой задачи
Внутри функции вызовите метод `.add_task()` у объекта *background tasks* и передайте ему функцию, которую хотите выполнить в фоне:
-```Python hl_lines="14"
-{!../../../docs_src/background_tasks/tutorial001.py!}
-```
+{* ../../docs_src/background_tasks/tutorial001.py hl[14] *}
`.add_task()` принимает следующие аргументы:
@@ -57,17 +51,7 @@
**FastAPI** знает, что нужно сделать в каждом случае и как переиспользовать тот же объект `BackgroundTasks`, так чтобы все фоновые задачи собрались и запустились вместе в фоне:
-=== "Python 3.10+"
-
- ```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!}
- ```
+{* ../../docs_src/background_tasks/tutorial002_py310.py hl[11,13,20,23] *}
В этом примере сообщения будут записаны в `log.txt` *после* того, как ответ сервера был отправлен.
@@ -93,8 +77,6 @@
Их тяжелее настраивать, также им нужен брокер сообщений наподобие RabbitMQ или Redis, но зато они позволяют вам запускать фоновые задачи в нескольких процессах и даже на нескольких серверах.
-Для примера, посмотрите [Project Generators](../project-generation.md){.internal-link target=_blank}, там есть проект с уже настроенным Celery.
-
Но если вам нужен доступ к общим переменным и объектам вашего **FastAPI** приложения или вам нужно выполнять простые фоновые задачи (наподобие отправки письма из примера) вы можете просто использовать `BackgroundTasks`.
## Резюме
diff --git a/docs/ru/docs/tutorial/bigger-applications.md b/docs/ru/docs/tutorial/bigger-applications.md
new file mode 100644
index 000000000..8b9080d39
--- /dev/null
+++ b/docs/ru/docs/tutorial/bigger-applications.md
@@ -0,0 +1,556 @@
+# Большие приложения, в которых много файлов
+
+При построении приложения или веб-API нам редко удается поместить всё в один файл.
+
+**FastAPI** предоставляет удобный инструментарий, который позволяет нам структурировать приложение, сохраняя при этом всю необходимую гибкость.
+
+/// info | Примечание
+
+Если вы раньше использовали Flask, то это аналог шаблонов Flask (Flask's Blueprints).
+
+///
+
+## Пример структуры приложения
+
+Давайте предположим, что наше приложение имеет следующую структуру:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+│ ├── dependencies.py
+│ └── routers
+│ │ ├── __init__.py
+│ │ ├── items.py
+│ │ └── users.py
+│ └── internal
+│ ├── __init__.py
+│ └── admin.py
+```
+
+/// tip | Подсказка
+
+Обратите внимание, что в каждом каталоге и подкаталоге имеется файл `__init__.py`
+
+Это как раз то, что позволяет импортировать код из одного файла в другой.
+
+Например, в файле `app/main.py` может быть следующая строка:
+
+```
+from app.routers import items
+```
+
+///
+
+* Всё помещается в каталоге `app`. В нём также находится пустой файл `app/__init__.py`. Таким образом, `app` является "Python-пакетом" (коллекцией модулей Python).
+* Он содержит файл `app/main.py`. Данный файл является частью пакета (т.е. находится внутри каталога, содержащего файл `__init__.py`), и, соответственно, он является модулем пакета: `app.main`.
+* Он также содержит файл `app/dependencies.py`, который также, как и `app/main.py`, является модулем: `app.dependencies`.
+* Здесь также находится подкаталог `app/routers/`, содержащий `__init__.py`. Он является суб-пакетом: `app.routers`.
+* Файл `app/routers/items.py` находится внутри пакета `app/routers/`. Таким образом, он является суб-модулем: `app.routers.items`.
+* Точно также `app/routers/users.py` является ещё одним суб-модулем: `app.routers.users`.
+* Подкаталог `app/internal/`, содержащий файл `__init__.py`, является ещё одним суб-пакетом: `app.internal`.
+* А файл `app/internal/admin.py` является ещё одним суб-модулем: `app.internal.admin`.
+
+
+
+Та же самая файловая структура приложения, но с комментариями:
+
+```
+.
+├── app # "app" пакет
+│ ├── __init__.py # этот файл превращает "app" в "Python-пакет"
+│ ├── main.py # модуль "main", напр.: import app.main
+│ ├── dependencies.py # модуль "dependencies", напр.: import app.dependencies
+│ └── routers # суб-пакет "routers"
+│ │ ├── __init__.py # превращает "routers" в суб-пакет
+│ │ ├── items.py # суб-модуль "items", напр.: import app.routers.items
+│ │ └── users.py # суб-модуль "users", напр.: import app.routers.users
+│ └── internal # суб-пакет "internal"
+│ ├── __init__.py # превращает "internal" в суб-пакет
+│ └── admin.py # суб-модуль "admin", напр.: import app.internal.admin
+```
+
+## `APIRouter`
+
+Давайте предположим, что для работы с пользователями используется отдельный файл (суб-модуль) `/app/routers/users.py`.
+
+Для лучшей организации приложения, вы хотите отделить операции пути, связанные с пользователями, от остального кода.
+
+Но так, чтобы эти операции по-прежнему оставались частью **FastAPI** приложения/веб-API (частью одного пакета)
+
+С помощью `APIRouter` вы можете создать *операции пути* (*эндпоинты*) для данного модуля.
+
+
+### Импорт `APIRouter`
+
+Точно также, как и в случае с классом `FastAPI`, вам нужно импортировать и создать объект класса `APIRouter`.
+
+```Python hl_lines="1 3" title="app/routers/users.py"
+{!../../docs_src/bigger_applications/app/routers/users.py!}
+```
+
+### Создание *эндпоинтов* с помощью `APIRouter`
+
+В дальнейшем используйте `APIRouter` для объявления *эндпоинтов*, точно также, как вы используете класс `FastAPI`:
+
+```Python hl_lines="6 11 16" title="app/routers/users.py"
+{!../../docs_src/bigger_applications/app/routers/users.py!}
+```
+
+Вы можете думать об `APIRouter` как об "уменьшенной версии" класса FastAPI`.
+
+`APIRouter` поддерживает все те же самые опции.
+
+`APIRouter` поддерживает все те же самые параметры, такие как `parameters`, `responses`, `dependencies`, `tags`, и т. д.
+
+/// tip | Подсказка
+
+В данном примере, в качестве названия переменной используется `router`, но вы можете использовать любое другое имя.
+
+///
+
+Мы собираемся подключить данный `APIRouter` к нашему основному приложению на `FastAPI`, но сначала давайте проверим зависимости и создадим ещё один модуль с `APIRouter`.
+
+## Зависимости
+
+Нам понадобятся некоторые зависимости, которые мы будем использовать в разных местах нашего приложения.
+
+Мы поместим их в отдельный модуль `dependencies` (`app/dependencies.py`).
+
+Теперь мы воспользуемся простой зависимостью, чтобы прочитать кастомизированный `X-Token` из заголовка:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="3 6-8" title="app/dependencies.py"
+{!> ../../docs_src/bigger_applications/app_an_py39/dependencies.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="1 5-7" title="app/dependencies.py"
+{!> ../../docs_src/bigger_applications/app_an/dependencies.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | Подсказка
+
+Мы рекомендуем использовать версию `Annotated`, когда это возможно.
+
+///
+
+```Python hl_lines="1 4-6" title="app/dependencies.py"
+{!> ../../docs_src/bigger_applications/app/dependencies.py!}
+```
+
+////
+
+/// tip | Подсказка
+
+Для простоты мы воспользовались неким воображаемым заголовоком.
+
+В реальных случаях для получения наилучших результатов используйте интегрированные утилиты обеспечения безопасности [Security utilities](security/index.md){.internal-link target=_blank}.
+
+///
+
+## Ещё один модуль с `APIRouter`
+
+Давайте также предположим, что у вас есть *эндпоинты*, отвечающие за обработку "items", и они находятся в модуле `app/routers/items.py`.
+
+У вас определены следующие *операции пути* (*эндпоинты*):
+
+* `/items/`
+* `/items/{item_id}`
+
+Тут всё точно также, как и в ситуации с `app/routers/users.py`.
+
+Но теперь мы хотим поступить немного умнее и слегка упростить код.
+
+Мы знаем, что все *эндпоинты* данного модуля имеют некоторые общие свойства:
+
+* Префикс пути: `/items`.
+* Теги: (один единственный тег: `items`).
+* Дополнительные ответы (responses)
+* Зависимости: использование созданной нами зависимости `X-token`
+
+Таким образом, вместо того чтобы добавлять все эти свойства в функцию каждого отдельного *эндпоинта*,
+мы добавим их в `APIRouter`.
+
+```Python hl_lines="5-10 16 21" title="app/routers/items.py"
+{!../../docs_src/bigger_applications/app/routers/items.py!}
+```
+
+Так как каждый *эндпоинт* начинается с символа `/`:
+
+```Python hl_lines="1"
+@router.get("/{item_id}")
+async def read_item(item_id: str):
+ ...
+```
+
+...то префикс не должен заканчиваться символом `/`.
+
+В нашем случае префиксом является `/items`.
+
+Мы также можем добавить в наш маршрутизатор (router) список `тегов` (`tags`) и дополнительных `ответов` (`responses`), которые являются общими для каждого *эндпоинта*.
+
+И ещё мы можем добавить в наш маршрутизатор список `зависимостей`, которые должны вызываться при каждом обращении к *эндпоинтам*.
+
+/// tip | Подсказка
+
+Обратите внимание, что также, как и в случае с зависимостями в декораторах *эндпоинтов* ([dependencies in *path operation decorators*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}), никакого значения в *функцию эндпоинта* передано не будет.
+
+///
+
+В результате мы получим следующие эндпоинты:
+
+* `/items/`
+* `/items/{item_id}`
+
+...как мы и планировали.
+
+* Они будут помечены тегами из заданного списка, в нашем случае это `"items"`.
+ * Эти теги особенно полезны для системы автоматической интерактивной документации (с использованием OpenAPI).
+* Каждый из них будет включать предопределенные ответы `responses`.
+* Каждый *эндпоинт* будет иметь список зависимостей (`dependencies`), исполняемых перед вызовом *эндпоинта*.
+ * Если вы определили зависимости в самой операции пути, **то она также будет выполнена**.
+ * Сначала выполняются зависимости маршрутизатора, затем вызываются зависимости, определенные в декораторе *эндпоинта* ([`dependencies` in the decorator](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}), и, наконец, обычные параметрические зависимости.
+ * Вы также можете добавить зависимости безопасности с областями видимости (`scopes`) [`Security` dependencies with `scopes`](../advanced/security/oauth2-scopes.md){.internal-link target=_blank}.
+
+/// tip | Подсказка
+
+Например, с помощью зависимостей в `APIRouter` мы можем потребовать аутентификации для доступа ко всей группе *эндпоинтов*, не указывая зависимости для каждой отдельной функции *эндпоинта*.
+
+///
+
+/// check | Заметка
+
+Параметры `prefix`, `tags`, `responses` и `dependencies` относятся к функционалу **FastAPI**, помогающему избежать дублирования кода.
+
+///
+
+### Импорт зависимостей
+
+Наш код находится в модуле `app.routers.items` (файл `app/routers/items.py`).
+
+И нам нужно вызвать функцию зависимости из модуля `app.dependencies` (файл `app/dependencies.py`).
+
+Мы используем операцию относительного импорта `..` для импорта зависимости:
+
+```Python hl_lines="3" title="app/routers/items.py"
+{!../../docs_src/bigger_applications/app/routers/items.py!}
+```
+
+#### Как работает относительный импорт?
+
+/// tip | Подсказка
+
+Если вы прекрасно знаете, как работает импорт в Python, то переходите к следующему разделу.
+
+///
+
+Одна точка `.`, как в данном примере:
+
+```Python
+from .dependencies import get_token_header
+```
+означает:
+
+* Начните с пакета, в котором находится данный модуль (файл `app/routers/items.py` расположен в каталоге `app/routers/`)...
+* ... найдите модуль `dependencies` (файл `app/routers/dependencies.py`)...
+* ... и импортируйте из него функцию `get_token_header`.
+
+К сожалению, такого файла не существует, и наши зависимости находятся в файле `app/dependencies.py`.
+
+Вспомните, как выглядит файловая структура нашего приложения:
+
+
+
+---
+
+Две точки `..`, как в данном примере:
+
+```Python
+from ..dependencies import get_token_header
+```
+
+означают:
+
+* Начните с пакета, в котором находится данный модуль (файл `app/routers/items.py` находится в каталоге `app/routers/`)...
+* ... перейдите в родительский пакет (каталог `app/`)...
+* ... найдите в нём модуль `dependencies` (файл `app/dependencies.py`)...
+* ... и импортируйте из него функцию `get_token_header`.
+
+Это работает верно! 🎉
+
+---
+
+Аналогично, если бы мы использовали три точки `...`, как здесь:
+
+```Python
+from ...dependencies import get_token_header
+```
+
+то это бы означало:
+
+* Начните с пакета, в котором находится данный модуль (файл `app/routers/items.py` находится в каталоге `app/routers/`)...
+* ... перейдите в родительский пакет (каталог `app/`)...
+* ... затем перейдите в родительский пакет текущего пакета (такого пакета не существует, `app` находится на самом верхнем уровне 😱)...
+* ... найдите в нём модуль `dependencies` (файл `app/dependencies.py`)...
+* ... и импортируйте из него функцию `get_token_header`.
+
+Это будет относиться к некоторому пакету, находящемуся на один уровень выше чем `app/` и содержащему свой собственный файл `__init__.py`. Но ничего такого у нас нет. Поэтому это приведет к ошибке в нашем примере. 🚨
+
+Теперь вы знаете, как работает импорт в Python, и сможете использовать относительное импортирование в своих собственных приложениях любого уровня сложности. 🤓
+
+### Добавление пользовательских тегов (`tags`), ответов (`responses`) и зависимостей (`dependencies`)
+
+Мы не будем добавлять префикс `/items` и список тегов `tags=["items"]` для каждого *эндпоинта*, т.к. мы уже их добавили с помощью `APIRouter`.
+
+Но помимо этого мы можем добавить новые теги для каждого отдельного *эндпоинта*, а также некоторые дополнительные ответы (`responses`), характерные для данного *эндпоинта*:
+
+```Python hl_lines="30-31" title="app/routers/items.py"
+{!../../docs_src/bigger_applications/app/routers/items.py!}
+```
+
+/// tip | Подсказка
+
+Последний *эндпоинт* будет иметь следующую комбинацию тегов: `["items", "custom"]`.
+
+А также в его документации будут содержаться оба ответа: один для `404` и другой для `403`.
+
+///
+
+## Модуль main в `FastAPI`
+
+Теперь давайте посмотрим на модуль `app/main.py`.
+
+Именно сюда вы импортируете и именно здесь вы используете класс `FastAPI`.
+
+Это основной файл вашего приложения, который объединяет всё в одно целое.
+
+И теперь, когда большая часть логики приложения разделена на отдельные модули, основной файл `app/main.py` будет достаточно простым.
+
+### Импорт `FastAPI`
+
+Вы импортируете и создаете класс `FastAPI` как обычно.
+
+Мы даже можем объявить глобальные зависимости [global dependencies](dependencies/global-dependencies.md){.internal-link target=_blank}, которые будут объединены с зависимостями для каждого отдельного маршрутизатора:
+
+```Python hl_lines="1 3 7" title="app/main.py"
+{!../../docs_src/bigger_applications/app/main.py!}
+```
+
+### Импорт `APIRouter`
+
+Теперь мы импортируем другие суб-модули, содержащие `APIRouter`:
+
+```Python hl_lines="4-5" title="app/main.py"
+{!../../docs_src/bigger_applications/app/main.py!}
+```
+
+Так как файлы `app/routers/users.py` и `app/routers/items.py` являются суб-модулями одного и того же Python-пакета `app`, то мы сможем их импортировать, воспользовавшись операцией относительного импорта `.`.
+
+### Как работает импорт?
+
+Данная строка кода:
+
+```Python
+from .routers import items, users
+```
+
+означает:
+
+* Начните с пакета, в котором содержится данный модуль (файл `app/main.py` содержится в каталоге `app/`)...
+* ... найдите суб-пакет `routers` (каталог `app/routers/`)...
+* ... и из него импортируйте суб-модули `items` (файл `app/routers/items.py`) и `users` (файл `app/routers/users.py`)...
+
+В модуле `items` содержится переменная `router` (`items.router`), та самая, которую мы создали в файле `app/routers/items.py`, она является объектом класса `APIRouter`.
+
+И затем мы сделаем то же самое для модуля `users`.
+
+Мы также могли бы импортировать и другим методом:
+
+```Python
+from app.routers import items, users
+```
+
+/// info | Примечание
+
+Первая версия является примером относительного импорта:
+
+```Python
+from .routers import items, users
+```
+
+Вторая версия является примером абсолютного импорта:
+
+```Python
+from app.routers import items, users
+```
+
+Узнать больше о пакетах и модулях в Python вы можете из официальной документации Python о модулях
+
+///
+
+### Избегайте конфликтов имен
+
+Вместо того чтобы импортировать только переменную `router`, мы импортируем непосредственно суб-модуль `items`.
+
+Мы делаем это потому, что у нас есть ещё одна переменная `router` в суб-модуле `users`.
+
+Если бы мы импортировали их одну за другой, как показано в примере:
+
+```Python
+from .routers.items import router
+from .routers.users import router
+```
+
+то переменная `router` из `users` переписал бы переменную `router` из `items`, и у нас не было бы возможности использовать их одновременно.
+
+Поэтому, для того чтобы использовать обе эти переменные в одном файле, мы импортировали соответствующие суб-модули:
+
+```Python hl_lines="5" title="app/main.py"
+{!../../docs_src/bigger_applications/app/main.py!}
+```
+
+### Подключение маршрутизаторов (`APIRouter`) для `users` и для `items`
+
+Давайте подключим маршрутизаторы (`router`) из суб-модулей `users` и `items`:
+
+```Python hl_lines="10-11" title="app/main.py"
+{!../../docs_src/bigger_applications/app/main.py!}
+```
+
+/// info | Примечание
+
+`users.router` содержит `APIRouter` из файла `app/routers/users.py`.
+
+А `items.router` содержит `APIRouter` из файла `app/routers/items.py`.
+
+///
+
+С помощью `app.include_router()` мы можем добавить каждый из маршрутизаторов (`APIRouter`) в основное приложение `FastAPI`.
+
+Он подключит все маршруты заданного маршрутизатора к нашему приложению.
+
+/// note | Технические детали
+
+Фактически, внутри он создаст все *операции пути* для каждой операции пути объявленной в `APIRouter`.
+
+И под капотом всё будет работать так, как будто бы мы имеем дело с одним файлом приложения.
+
+///
+
+/// check | Заметка
+
+При подключении маршрутизаторов не стоит беспокоиться о производительности.
+
+Операция подключения займёт микросекунды и понадобится только при запуске приложения.
+
+Таким образом, это не повлияет на производительность. ⚡
+
+///
+
+### Подключение `APIRouter` с пользовательскими префиксом (`prefix`), тегами (`tags`), ответами (`responses`), и зависимостями (`dependencies`)
+
+Теперь давайте представим, что ваша организация передала вам файл `app/internal/admin.py`.
+
+Он содержит `APIRouter` с некоторыми *эндпоитами* администрирования, которые ваша организация использует для нескольких проектов.
+
+В данном примере это сделать очень просто. Но давайте предположим, что поскольку файл используется для нескольких проектов,
+то мы не можем модифицировать его, добавляя префиксы (`prefix`), зависимости (`dependencies`), теги (`tags`), и т.д. непосредственно в `APIRouter`:
+
+```Python hl_lines="3" title="app/internal/admin.py"
+{!../../docs_src/bigger_applications/app/internal/admin.py!}
+```
+
+Но, несмотря на это, мы хотим использовать кастомный префикс (`prefix`) для подключенного маршрутизатора (`APIRouter`), в результате чего, каждая *операция пути* будет начинаться с `/admin`. Также мы хотим защитить наш маршрутизатор с помощью зависимостей, созданных для нашего проекта. И ещё мы хотим включить теги (`tags`) и ответы (`responses`).
+
+Мы можем применить все вышеперечисленные настройки, не изменяя начальный `APIRouter`. Нам всего лишь нужно передать нужные параметры в `app.include_router()`.
+
+```Python hl_lines="14-17" title="app/main.py"
+{!../../docs_src/bigger_applications/app/main.py!}
+```
+
+Таким образом, оригинальный `APIRouter` не будет модифицирован, и мы сможем использовать файл `app/internal/admin.py` сразу в нескольких проектах организации.
+
+В результате, в нашем приложении каждый *эндпоинт* модуля `admin` будет иметь:
+
+* Префикс `/admin`.
+* Тег `admin`.
+* Зависимость `get_token_header`.
+* Ответ `418`. 🍵
+
+Это будет иметь место исключительно для `APIRouter` в нашем приложении, и не затронет любой другой код, использующий его.
+
+Например, другие проекты, могут использовать тот же самый `APIRouter` с другими методами аутентификации.
+
+### Подключение отдельного *эндпоинта*
+
+Мы также можем добавить *эндпоинт* непосредственно в основное приложение `FastAPI`.
+
+Здесь мы это делаем ... просто, чтобы показать, что это возможно 🤷:
+
+```Python hl_lines="21-23" title="app/main.py"
+{!../../docs_src/bigger_applications/app/main.py!}
+```
+
+и это будет работать корректно вместе с другими *эндпоинтами*, добавленными с помощью `app.include_router()`.
+
+/// info | Сложные технические детали
+
+**Примечание**: это сложная техническая деталь, которую, скорее всего, **вы можете пропустить**.
+
+---
+
+Маршрутизаторы (`APIRouter`) не "монтируются" по-отдельности и не изолируются от остального приложения.
+
+Это происходит потому, что нужно включить их *эндпоинты* в OpenAPI схему и в интерфейс пользователя.
+
+В силу того, что мы не можем их изолировать и "примонтировать" независимо от остальных, *эндпоинты* клонируются (пересоздаются) и не подключаются напрямую.
+
+///
+
+## Проверка автоматической документации API
+
+Теперь запустите приложение:
+
+
get
операцию
-!!! info "`@decorator` Дополнительная информация"
- Синтаксис `@something` в Python называется "декоратор".
+/// info | `@decorator` Дополнительная информация
+
+Синтаксис `@something` в Python называется "декоратор".
+
+Вы помещаете его над функцией. Как красивую декоративную шляпу (думаю, что оттуда и происходит этот термин).
- Вы помещаете его над функцией. Как красивую декоративную шляпу (думаю, что оттуда и происходит этот термин).
+"Декоратор" принимает функцию ниже и выполняет с ней какое-то действие.
- "Декоратор" принимает функцию ниже и выполняет с ней какое-то действие.
+В нашем случае, этот декоратор сообщает **FastAPI**, что функция ниже соответствует **пути** `/` и **операции** `get`.
- В нашем случае, этот декоратор сообщает **FastAPI**, что функция ниже соответствует **пути** `/` и **операции** `get`.
+Это и есть "**декоратор операции пути**".
- Это и есть "**декоратор операции пути**".
+///
Можно также использовать операции:
@@ -274,14 +276,17 @@ https://example.com/items/foo
* `@app.patch()`
* `@app.trace()`
-!!! tip "Подсказка"
- Вы можете использовать каждую операцию (HTTP-метод) по своему усмотрению.
+/// tip | Подсказка
+
+Вы можете использовать каждую операцию (HTTP-метод) по своему усмотрению.
+
+**FastAPI** не навязывает определенного значения для каждого метода.
- **FastAPI** не навязывает определенного значения для каждого метода.
+Информация здесь представлена как рекомендация, а не требование.
- Информация здесь представлена как рекомендация, а не требование.
+Например, при использовании GraphQL обычно все действия выполняются только с помощью POST операций.
- Например, при использовании GraphQL обычно все действия выполняются только с помощью POST операций.
+///
### Шаг 4: определите **функцию операции пути**
@@ -291,9 +296,7 @@ https://example.com/items/foo
* **операция**: `get`.
* **функция**: функция ниже "декоратора" (ниже `@app.get("/")`).
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[7] *}
Это обычная Python функция.
@@ -305,18 +308,17 @@ https://example.com/items/foo
Вы также можете определить ее как обычную функцию вместо `async def`:
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial003.py!}
-```
+{* ../../docs_src/first_steps/tutorial003.py hl[7] *}
+
+/// note | Технические детали
-!!! note "Технические детали"
- Если не знаете в чём разница, посмотрите [Конкурентность: *"Нет времени?"*](../async.md#_1){.internal-link target=_blank}.
+Если не знаете в чём разница, посмотрите [Конкурентность: *"Нет времени?"*](../async.md#_1){.internal-link target=_blank}.
+
+///
### Шаг 5: верните результат
-```Python hl_lines="8"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[8] *}
Вы можете вернуть `dict`, `list`, отдельные значения `str`, `int` и т.д.
diff --git a/docs/ru/docs/tutorial/handling-errors.md b/docs/ru/docs/tutorial/handling-errors.md
index 40b6f9bc4..c596abe1f 100644
--- a/docs/ru/docs/tutorial/handling-errors.md
+++ b/docs/ru/docs/tutorial/handling-errors.md
@@ -25,9 +25,7 @@
### Импортируйте `HTTPException`
-```Python hl_lines="1"
-{!../../../docs_src/handling_errors/tutorial001.py!}
-```
+{* ../../docs_src/handling_errors/tutorial001.py hl[1] *}
### Вызовите `HTTPException` в своем коде
@@ -41,9 +39,7 @@
В данном примере, когда клиент запрашивает элемент по несуществующему ID, возникает исключение со статус-кодом `404`:
-```Python hl_lines="11"
-{!../../../docs_src/handling_errors/tutorial001.py!}
-```
+{* ../../docs_src/handling_errors/tutorial001.py hl[11] *}
### Возвращаемый ответ
@@ -63,12 +59,15 @@
}
```
-!!! tip "Подсказка"
- При вызове `HTTPException` в качестве параметра `detail` можно передавать любое значение, которое может быть преобразовано в JSON, а не только `str`.
+/// tip | Подсказка
+
+При вызове `HTTPException` в качестве параметра `detail` можно передавать любое значение, которое может быть преобразовано в JSON, а не только `str`.
+
+Вы можете передать `dict`, `list` и т.д.
- Вы можете передать `dict`, `list` и т.д.
+Они автоматически обрабатываются **FastAPI** и преобразуются в JSON.
- Они автоматически обрабатываются **FastAPI** и преобразуются в JSON.
+///
## Добавление пользовательских заголовков
@@ -78,9 +77,7 @@
Но в случае, если это необходимо для продвинутого сценария, можно добавить пользовательские заголовки:
-```Python hl_lines="14"
-{!../../../docs_src/handling_errors/tutorial002.py!}
-```
+{* ../../docs_src/handling_errors/tutorial002.py hl[14] *}
## Установка пользовательских обработчиков исключений
@@ -92,9 +89,7 @@
Можно добавить собственный обработчик исключений с помощью `@app.exception_handler()`:
-```Python hl_lines="5-7 13-18 24"
-{!../../../docs_src/handling_errors/tutorial003.py!}
-```
+{* ../../docs_src/handling_errors/tutorial003.py hl[5:7,13:18,24] *}
Здесь, если запросить `/unicorns/yolo`, то *операция пути* вызовет `UnicornException`.
@@ -106,10 +101,13 @@
{"message": "Oops! yolo did something. There goes a rainbow..."}
```
-!!! note "Технические детали"
- Также можно использовать `from starlette.requests import Request` и `from starlette.responses import JSONResponse`.
+/// note | Технические детали
+
+Также можно использовать `from starlette.requests import Request` и `from starlette.responses import JSONResponse`.
+
+**FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette. То же самое касается и `Request`.
- **FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette. То же самое касается и `Request`.
+///
## Переопределение стандартных обработчиков исключений
@@ -129,9 +127,7 @@
Обработчик исключения получит объект `Request` и исключение.
-```Python hl_lines="2 14-16"
-{!../../../docs_src/handling_errors/tutorial004.py!}
-```
+{* ../../docs_src/handling_errors/tutorial004.py hl[2,14:16] *}
Теперь, если перейти к `/items/foo`, то вместо стандартной JSON-ошибки с:
@@ -160,8 +156,11 @@ path -> item_id
#### `RequestValidationError` или `ValidationError`
-!!! warning "Внимание"
- Это технические детали, которые можно пропустить, если они не важны для вас сейчас.
+/// warning | Внимание
+
+Это технические детали, которые можно пропустить, если они не важны для вас сейчас.
+
+///
`RequestValidationError` является подклассом Pydantic `ValidationError`.
@@ -179,14 +178,15 @@ path -> item_id
Например, для этих ошибок можно вернуть обычный текстовый ответ вместо JSON:
-```Python hl_lines="3-4 9-11 22"
-{!../../../docs_src/handling_errors/tutorial004.py!}
-```
+{* ../../docs_src/handling_errors/tutorial004.py hl[3:4,9:11,22] *}
-!!! note "Технические детали"
- Можно также использовать `from starlette.responses import PlainTextResponse`.
+/// note | Технические детали
- **FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette.
+Можно также использовать `from starlette.responses import PlainTextResponse`.
+
+**FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette.
+
+///
### Используйте тело `RequestValidationError`
@@ -194,9 +194,7 @@ path -> item_id
Вы можете использовать его при разработке приложения для регистрации тела и его отладки, возврата пользователю и т.д.
-```Python hl_lines="14"
-{!../../../docs_src/handling_errors/tutorial005.py!}
-```
+{* ../../docs_src/handling_errors/tutorial005.py hl[14] *}
Теперь попробуйте отправить недействительный элемент, например:
@@ -254,8 +252,6 @@ from starlette.exceptions import HTTPException as StarletteHTTPException
Если вы хотите использовать исключение вместе с теми же обработчиками исключений по умолчанию из **FastAPI**, вы можете импортировать и повторно использовать обработчики исключений по умолчанию из `fastapi.exception_handlers`:
-```Python hl_lines="2-5 15 21"
-{!../../../docs_src/handling_errors/tutorial006.py!}
-```
+{* ../../docs_src/handling_errors/tutorial006.py hl[2:5,15,21] *}
В этом примере вы просто `выводите в терминал` ошибку с очень выразительным сообщением, но идея вам понятна. Вы можете использовать исключение, а затем просто повторно использовать стандартные обработчики исключений.
diff --git a/docs/ru/docs/tutorial/header-param-models.md b/docs/ru/docs/tutorial/header-param-models.md
new file mode 100644
index 000000000..4f54e3e15
--- /dev/null
+++ b/docs/ru/docs/tutorial/header-param-models.md
@@ -0,0 +1,72 @@
+# Модели Header-параметров
+
+Если у вас есть группа связанных **header-параметров**, то вы можете объединить их в одну **Pydantic-модель**.
+
+Это позволит вам **переиспользовать модель** в **разных местах**, а также задать валидацию и метаданные сразу для всех параметров. 😎
+
+/// note | Заметка
+
+Этот функционал доступен в FastAPI начиная с версии `0.115.0`. 🤓
+
+///
+
+## Header-параметры в виде Pydantic-модели
+
+Объявите нужные **header-параметры** в **Pydantic-модели** и затем аннотируйте параметр как `Header`:
+
+{* ../../docs_src/header_param_models/tutorial001_an_py310.py hl[9:14,18] *}
+
+**FastAPI** **извлечёт** данные для **каждого поля** из **заголовков** запроса и выдаст заданную вами Pydantic-модель.
+
+## Проверьте документацию
+
+Вы можете посмотреть нужные header-параметры в графическом интерфейсе сгенерированной документации по пути `/docs`:
+
+kwargs
, даже если у них нет значений по умолчанию.
-```Python hl_lines="7"
-{!../../../docs_src/path_params_numeric_validations/tutorial003.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *}
### Лучше с `Annotated`
Имейте в виду, что если вы используете `Annotated`, то, поскольку вы не используете значений по умолчанию для параметров функции, то у вас не возникнет подобной проблемы и вам не придётся использовать `*`.
-=== "Python 3.9+"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!}
- ```
+{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py hl[10] *}
## Валидация числовых данных: больше или равно
@@ -186,26 +113,7 @@ Python не будет ничего делать с `*`, но он будет з
В этом примере при указании `ge=1`, параметр `item_id` должен быть больше или равен `1` ("`g`reater than or `e`qual").
-=== "Python 3.9+"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!}
- ```
-
-=== "Python 3.8+ без Annotated"
-
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
-
- ```Python hl_lines="8"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!}
- ```
+{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py hl[10] *}
## Валидация числовых данных: больше и меньше или равно
@@ -214,26 +122,7 @@ Python не будет ничего делать с `*`, но он будет з
* `gt`: больше (`g`reater `t`han)
* `le`: меньше или равно (`l`ess than or `e`qual)
-=== "Python 3.9+"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!}
- ```
-
-=== "Python 3.8+ без Annotated"
-
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!}
- ```
+{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py hl[10] *}
## Валидация числовых данных: числа с плавающей точкой, больше и меньше
@@ -245,26 +134,7 @@ Python не будет ничего делать с `*`, но он будет з
То же самое справедливо и для lt
.
-=== "Python 3.9+"
-
- ```Python hl_lines="13"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="12"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!}
- ```
-
-=== "Python 3.8+ без Annotated"
-
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
-
- ```Python hl_lines="11"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!}
- ```
+{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py hl[13] *}
## Резюме
@@ -277,16 +147,22 @@ Python не будет ничего делать с `*`, но он будет з
* `lt`: меньше (`l`ess `t`han)
* `le`: меньше или равно (`l`ess than or `e`qual)
-!!! info "Информация"
- `Query`, `Path` и другие классы, которые мы разберём позже, являются наследниками общего класса `Param`.
+/// info | Информация
+
+`Query`, `Path` и другие классы, которые мы разберём позже, являются наследниками общего класса `Param`.
+
+Все они используют те же параметры для дополнительной валидации и метаданных, которые вы видели ранее.
+
+///
+
+/// note | Технические детали
- Все они используют те же параметры для дополнительной валидации и метаданных, которые вы видели ранее.
+`Query`, `Path` и другие "классы", которые вы импортируете из `fastapi`, на самом деле являются функциями, которые при вызове возвращают экземпляры одноимённых классов.
-!!! note "Технические детали"
- `Query`, `Path` и другие "классы", которые вы импортируете из `fastapi`, на самом деле являются функциями, которые при вызове возвращают экземпляры одноимённых классов.
+Объект `Query`, который вы импортируете, является функцией. И при вызове она возвращает экземпляр одноимённого класса `Query`.
- Объект `Query`, который вы импортируете, является функцией. И при вызове она возвращает экземпляр одноимённого класса `Query`.
+Использование функций (вместо использования классов напрямую) нужно для того, чтобы ваш редактор не подсвечивал ошибки, связанные с их типами.
- Использование функций (вместо использования классов напрямую) нужно для того, чтобы ваш редактор не подсвечивал ошибки, связанные с их типами.
+Таким образом вы можете использовать привычный вам редактор и инструменты разработки, не добавляя дополнительных конфигураций для игнорирования подобных ошибок.
- Таким образом вы можете использовать привычный вам редактор и инструменты разработки, не добавляя дополнительных конфигураций для игнорирования подобных ошибок.
+///
diff --git a/docs/ru/docs/tutorial/path-params.md b/docs/ru/docs/tutorial/path-params.md
index 1241e0919..5c2d82a65 100644
--- a/docs/ru/docs/tutorial/path-params.md
+++ b/docs/ru/docs/tutorial/path-params.md
@@ -2,9 +2,7 @@
Вы можете определить "параметры" или "переменные" пути, используя синтаксис форматированных строк Python:
-```Python hl_lines="6-7"
-{!../../../docs_src/path_params/tutorial001.py!}
-```
+{* ../../docs_src/path_params/tutorial001.py hl[6:7] *}
Значение параметра пути `item_id` будет передано в функцию в качестве аргумента `item_id`.
@@ -18,14 +16,15 @@
Вы можете объявить тип параметра пути в функции, используя стандартные аннотации типов Python.
-```Python hl_lines="7"
-{!../../../docs_src/path_params/tutorial002.py!}
-```
+{* ../../docs_src/path_params/tutorial002.py hl[7] *}
Здесь, `item_id` объявлен типом `int`.
-!!! check "Заметка"
- Это обеспечит поддержку редактора внутри функции (проверка ошибок, автодополнение и т.п.).
+/// check | Заметка
+
+Это обеспечит поддержку редактора внутри функции (проверка ошибок, автодополнение и т.п.).
+
+///
## Преобразование данных
@@ -35,10 +34,13 @@
{"item_id":3}
```
-!!! check "Заметка"
- Обратите внимание на значение `3`, которое получила (и вернула) функция. Это целочисленный Python `int`, а не строка `"3"`.
+/// check | Заметка
- Используя определения типов, **FastAPI** выполняет автоматический "парсинг" запросов.
+Обратите внимание на значение `3`, которое получила (и вернула) функция. Это целочисленный Python `int`, а не строка `"3"`.
+
+Используя определения типов, **FastAPI** выполняет автоматический "парсинг" запросов.
+
+///
## Проверка данных
@@ -63,12 +65,15 @@
Та же ошибка возникнет, если вместо `int` передать `float` , например: http://127.0.0.1:8000/items/4.2
-!!! check "Заметка"
- **FastAPI** обеспечивает проверку типов, используя всё те же определения типов.
+/// check | Заметка
+
+**FastAPI** обеспечивает проверку типов, используя всё те же определения типов.
- Обратите внимание, что в тексте ошибки явно указано место не прошедшее проверку.
+Обратите внимание, что в тексте ошибки явно указано место не прошедшее проверку.
- Это очень полезно при разработке и отладке кода, который взаимодействует с API.
+Это очень полезно при разработке и отладке кода, который взаимодействует с API.
+
+///
## Документация
@@ -76,10 +81,13 @@
POST
.
+///
-!!! warning "Внимание"
- В операции *функции операции пути* можно объявить несколько параметров `File` и `Form`, но нельзя также объявлять поля `Body`, которые предполагается получить в виде JSON, поскольку тело запроса будет закодировано с помощью `multipart/form-data`, а не `application/json`.
-
- Это не является ограничением **FastAPI**, это часть протокола HTTP.
+## Про данные формы ("Form Data")
-## Необязательная загрузка файлов
+Способ, которым HTML-формы (``) отправляют данные на сервер, обычно использует "специальную" кодировку для этих данных, отличную от JSON.
-Вы можете сделать загрузку файла необязательной, используя стандартные аннотации типов и установив значение по умолчанию `None`:
+**FastAPI** позаботится о том, чтобы считать эти данные из нужного места, а не из JSON.
-=== "Python 3.10+"
+/// note | Технические детали
- ```Python hl_lines="9 17"
- {!> ../../../docs_src/request_files/tutorial001_02_an_py310.py!}
- ```
+Данные из форм обычно кодируются с использованием "media type" `application/x-www-form-urlencoded` когда он не включает файлы.
-=== "Python 3.9+"
+Но когда форма включает файлы, она кодируется как multipart/form-data. Если вы используете `File`, **FastAPI** будет знать, что ему нужно получить файлы из нужной части тела.
- ```Python hl_lines="9 17"
- {!> ../../../docs_src/request_files/tutorial001_02_an_py39.py!}
- ```
+Если вы хотите узнать больше об этих кодировках и полях форм, перейдите по ссылке MDN web docs for POST
.
-=== "Python 3.6+"
+///
- ```Python hl_lines="10 18"
- {!> ../../../docs_src/request_files/tutorial001_02_an.py!}
- ```
+/// warning | Внимание
-=== "Python 3.10+ без Annotated"
+В операции *функции операции пути* можно объявить несколько параметров `File` и `Form`, но нельзя также объявлять поля `Body`, которые предполагается получить в виде JSON, поскольку тело запроса будет закодировано с помощью `multipart/form-data`, а не `application/json`.
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+Это не является ограничением **FastAPI**, это часть протокола HTTP.
- ```Python hl_lines="7 15"
- {!> ../../../docs_src/request_files/tutorial001_02_py310.py!}
- ```
+///
-=== "Python 3.6+ без Annotated"
+## Необязательная загрузка файлов
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+Вы можете сделать загрузку файла необязательной, используя стандартные аннотации типов и установив значение по умолчанию `None`:
- ```Python hl_lines="9 17"
- {!> ../../../docs_src/request_files/tutorial001_02.py!}
- ```
+{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *}
## `UploadFile` с дополнительными метаданными
Вы также можете использовать `File()` вместе с `UploadFile`, например, для установки дополнительных метаданных:
-=== "Python 3.9+"
-
- ```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!}
- ```
-
-=== "Python 3.6+ без Annotated"
-
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
-
- ```Python hl_lines="7 13"
- {!> ../../../docs_src/request_files/tutorial001_03.py!}
- ```
+{* ../../docs_src/request_files/tutorial001_03_an_py39.py hl[9,15] *}
## Загрузка нескольких файлов
@@ -238,76 +149,23 @@ contents = myfile.file.read()
Для этого необходимо объявить список `bytes` или `UploadFile`:
-=== "Python 3.9+"
-
- ```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!}
- ```
-
-=== "Python 3.9+ без Annotated"
-
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+{* ../../docs_src/request_files/tutorial002_an_py39.py hl[10,15] *}
- ```Python hl_lines="8 13"
- {!> ../../../docs_src/request_files/tutorial002_py39.py!}
- ```
-
-=== "Python 3.6+ без Annotated"
-
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+Вы получите, как и было объявлено, список `list` из `bytes` или `UploadFile`.
- ```Python hl_lines="10 15"
- {!> ../../../docs_src/request_files/tutorial002.py!}
- ```
+/// note | Technical Details
-Вы получите, как и было объявлено, список `list` из `bytes` или `UploadFile`.
+Можно также использовать `from starlette.responses import HTMLResponse`.
-!!! note "Technical Details"
- Можно также использовать `from starlette.responses import HTMLResponse`.
+**FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette.
- **FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette.
+///
### Загрузка нескольких файлов с дополнительными метаданными
Так же, как и раньше, вы можете использовать `File()` для задания дополнительных параметров, даже для `UploadFile`:
-=== "Python 3.9+"
-
- ```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!}
- ```
-
-=== "Python 3.9+ без Annotated"
-
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
-
- ```Python hl_lines="9 16"
- {!> ../../../docs_src/request_files/tutorial003_py39.py!}
- ```
-
-=== "Python 3.6+ без Annotated"
-
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
-
- ```Python hl_lines="11 18"
- {!> ../../../docs_src/request_files/tutorial003.py!}
- ```
+{* ../../docs_src/request_files/tutorial003_an_py39.py hl[11,18:20] *}
## Резюме
diff --git a/docs/ru/docs/tutorial/request-form-models.md b/docs/ru/docs/tutorial/request-form-models.md
new file mode 100644
index 000000000..1034ed27f
--- /dev/null
+++ b/docs/ru/docs/tutorial/request-form-models.md
@@ -0,0 +1,78 @@
+# Модели форм
+
+Вы можете использовать **Pydantic-модели** для объявления **полей форм** в FastAPI.
+
+/// info | Дополнительная информация
+
+Чтобы использовать формы, сначала установите `python-multipart`.
+
+Убедитесь, что вы создали и активировали [виртуальное окружение](../virtual-environments.md){.internal-link target=_blank}, а затем установите пакет, например:
+
+```console
+$ pip install python-multipart
+```
+
+///
+
+/// note | Заметка
+
+Этот функционал доступен с версии `0.113.0`. 🤓
+
+///
+
+## Pydantic-модель для формы
+
+Вам просто нужно объявить **Pydantic-модель** с полями, которые вы хотите получить как **поля формы**, а затем объявить параметр как `Form`:
+
+{* ../../docs_src/request_form_models/tutorial001_an_py39.py hl[9:11,15] *}
+
+**FastAPI** **извлечёт** данные для **каждого поля** из **данных формы** в запросе и выдаст вам объявленную Pydantic-модель.
+
+## Проверка сгенерированной документации
+
+Вы можете посмотреть поля формы в графическом интерфейсе Документации по пути `/docs`:
+
+
-
+
@@ -449,7 +449,7 @@ Daha fazla bilgi için, bu bölüme bir göz at
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.
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/python-types.md b/docs/tr/docs/python-types.md
index ac3111136..b44aa3b9d 100644
--- a/docs/tr/docs/python-types.md
+++ b/docs/tr/docs/python-types.md
@@ -12,16 +12,18 @@ Bu pythonda tip belirteçleri için **hızlı bir başlangıç / bilgi tazeleme
**FastAPI** kullanmayacak olsanız bile tür belirteçleri hakkında bilgi edinmenizde fayda var.
-!!! note "Not"
- Python uzmanıysanız ve tip belirteçleri ilgili her şeyi zaten biliyorsanız, sonraki bölüme geçin.
+/// note | Not
+
+Python uzmanıysanız ve tip belirteçleri ilgili her şeyi zaten biliyorsanız, sonraki bölüme geçin.
+
+///
## Motivasyon
Basit bir örnek ile başlayalım:
-```Python
-{!../../../docs_src/python_types/tutorial001.py!}
-```
+{* ../../docs_src/python_types/tutorial001.py *}
+
Programın çıktısı:
@@ -35,9 +37,8 @@ Fonksiyon sırayla şunları yapar:
* `title()` ile değişkenlerin ilk karakterlerini büyütür.
* Değişkenleri aralarında bir boşlukla beraber Birleştirir.
-```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial001.py!}
-```
+{* ../../docs_src/python_types/tutorial001.py hl[2] *}
+
### Düzenle
@@ -79,9 +80,8 @@ Bu kadar.
İşte bunlar "tip belirteçleri":
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial002.py!}
-```
+{* ../../docs_src/python_types/tutorial002.py hl[1] *}
+
Bu, aşağıdaki gibi varsayılan değerleri bildirmekle aynı şey değildir:
@@ -109,9 +109,8 @@ Aradığınızı bulana kadar seçenekleri kaydırabilirsiniz:
Bu fonksiyon, zaten tür belirteçlerine sahip:
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial003.py!}
-```
+{* ../../docs_src/python_types/tutorial003.py hl[1] *}
+
Editör değişkenlerin tiplerini bildiğinden, yalnızca otomatik tamamlama değil, hata kontrolleri de sağlar:
@@ -119,9 +118,8 @@ Editör değişkenlerin tiplerini bildiğinden, yalnızca otomatik tamamlama de
Artık `age` değişkenini `str(age)` olarak kullanmanız gerektiğini biliyorsunuz:
-```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial004.py!}
-```
+{* ../../docs_src/python_types/tutorial004.py hl[2] *}
+
## Tip bildirme
@@ -140,9 +138,8 @@ Yalnızca `str` değil, tüm standart Python tiplerinin bildirebilirsiniz.
* `bool`
* `bytes`
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial005.py!}
-```
+{* ../../docs_src/python_types/tutorial005.py hl[1] *}
+
### Tip parametreleri ile Generic tipler
@@ -158,9 +155,8 @@ Bu tür tip belirteçlerini desteklemek için özel olarak mevcuttur.
From `typing`, import `List` (büyük harf olan `L` ile):
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial006.py!}
-```
+{* ../../docs_src/python_types/tutorial006.py hl[1] *}
+
Değişkenin tipini yine iki nokta üstüste (`:`) ile belirleyin.
@@ -168,14 +164,16 @@ tip olarak `List` kullanın.
Liste, bazı dahili tipleri içeren bir tür olduğundan, bunları köşeli parantez içine alırsınız:
-```Python hl_lines="4"
-{!../../../docs_src/python_types/tutorial006.py!}
-```
+{* ../../docs_src/python_types/tutorial006.py hl[4] *}
+
-!!! tip "Ipucu"
- 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".
@@ -193,9 +191,8 @@ Ve yine, editör bunun bir `str` olduğunu biliyor ve bunun için destek s
`Tuple` ve `set`lerin tiplerini bildirmek için de aynısını yapıyoruz:
-```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial007.py!}
-```
+{* ../../docs_src/python_types/tutorial007.py hl[1,4] *}
+
Bu şu anlama geliyor:
@@ -210,9 +207,8 @@ Bir `dict` tanımlamak için virgülle ayrılmış iki parametre verebilirsiniz.
İkinci parametre ise `dict` değerinin `value` değeri içindir:
-```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial008.py!}
-```
+{* ../../docs_src/python_types/tutorial008.py hl[1,4] *}
+
Bu şu anlama gelir:
@@ -225,7 +221,7 @@ Bu şu anlama gelir:
`Optional` bir değişkenin `str`gibi bir tipi olabileceğini ama isteğe bağlı olarak tipinin `None` olabileceğini belirtir:
```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009.py!}
+{!../../docs_src/python_types/tutorial009.py!}
```
`str` yerine `Optional[str]` kullanmak editorün bu değerin her zaman `str` tipinde değil bazen `None` tipinde de olabileceğini belirtir ve hataları tespit etmemizde yardımcı olur.
@@ -249,15 +245,13 @@ Bir değişkenin tipini bir sınıf ile bildirebilirsiniz.
Diyelim ki `name` değerine sahip `Person` sınıfınız var:
-```Python hl_lines="1-3"
-{!../../../docs_src/python_types/tutorial010.py!}
-```
+{* ../../docs_src/python_types/tutorial010.py hl[1:3] *}
+
Sonra bir değişkeni 'Person' tipinde tanımlayabilirsiniz:
-```Python hl_lines="6"
-{!../../../docs_src/python_types/tutorial010.py!}
-```
+{* ../../docs_src/python_types/tutorial010.py hl[6] *}
+
Ve yine bütün editör desteğini alırsınız:
@@ -277,12 +271,14 @@ Ve ortaya çıkan nesne üzerindeki bütün editör desteğini alırsınız.
Resmi Pydantic dokümanlarından alınmıştır:
-```Python
-{!../../../docs_src/python_types/tutorial011.py!}
-```
+{* ../../docs_src/python_types/tutorial011.py *}
+
-!!! info
- 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 +306,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
index 4a66f26eb..f07508c2f 100644
--- a/docs/tr/docs/tutorial/cookie-params.md
+++ b/docs/tr/docs/tutorial/cookie-params.md
@@ -6,41 +6,7 @@
Öncelikle, `Cookie`'yi projenize dahil edin:
-=== "Python 3.10+"
-
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001_an.py!}
- ```
-
-=== "Python 3.10+ non-Annotated"
-
- !!! tip "İpucu"
- Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın.
-
- ```Python hl_lines="1"
- {!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
- ```
-
-=== "Python 3.8+ non-Annotated"
-
- !!! tip "İpucu"
- Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın.
-
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001.py!}
- ```
+{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[3] *}
## `Cookie` Parametrelerini Tanımlayın
@@ -48,49 +14,21 @@
İlk değer varsayılan değerdir; tüm ekstra doğrulama veya belirteç parametrelerini kullanabilirsiniz:
-=== "Python 3.10+"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/cookie_params/tutorial001_an.py!}
- ```
-
-=== "Python 3.10+ non-Annotated"
-
- !!! tip "İpucu"
- Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın.
+{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[9] *}
- ```Python hl_lines="7"
- {!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
- ```
+/// note | Teknik Detaylar
-=== "Python 3.8+ non-Annotated"
+`Cookie` sınıfı `Path` ve `Query` sınıflarının kardeşidir. Diğerleri gibi `Param` sınıfını miras alan bir sınıftır.
- !!! tip "İpucu"
- Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın.
+Ancak `fastapi`'dan projenize dahil ettiğiniz `Query`, `Path`, `Cookie` ve diğerleri aslında özel sınıflar döndüren birer fonksiyondur.
- ```Python hl_lines="9"
- {!> ../../../docs_src/cookie_params/tutorial001.py!}
- ```
+///
-!!! note "Teknik Detaylar"
- `Cookie` sınıfı `Path` ve `Query` sınıflarının kardeşidir. Diğerleri gibi `Param` sınıfını miras alan bir sınıftır.
+/// info | Bilgi
- Ancak `fastapi`'dan projenize dahil ettiğiniz `Query`, `Path`, `Cookie` ve diğerleri aslında özel sınıflar döndüren birer fonksiyondur.
+Çerez tanımlamak için `Cookie` sınıfını kullanmanız gerekmektedir, aksi taktirde parametreler sorgu parametreleri olarak yorumlanır.
-!!! info "Bilgi"
- Çerez tanımlamak için `Cookie` sınıfını kullanmanız gerekmektedir, aksi taktirde parametreler sorgu parametreleri olarak yorumlanır.
+///
## Özet
diff --git a/docs/tr/docs/tutorial/first-steps.md b/docs/tr/docs/tutorial/first-steps.md
index e66f73034..2d2949b50 100644
--- a/docs/tr/docs/tutorial/first-steps.md
+++ b/docs/tr/docs/tutorial/first-steps.md
@@ -2,9 +2,7 @@
En sade FastAPI dosyası şu şekilde görünür:
-```Python
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py *}
Yukarıdaki içeriği bir `main.py` dosyasına kopyalayalım.
@@ -24,12 +22,15 @@ $ uvicorn main:app --reload
-!!! note "Not"
- `uvicorn main:app` komutunu şu şekilde açıklayabiliriz:
+/// note | Not
+
+`uvicorn main:app` komutunu şu şekilde açıklayabiliriz:
+
+* `main`: dosya olan `main.py` (yani Python "modülü").
+* `app`: ise `main.py` dosyasının içerisinde `app = FastAPI()` satırında oluşturduğumuz `FastAPI` nesnesi.
+* `--reload`: kod değişikliklerinin ardından sunucuyu otomatik olarak yeniden başlatır. Bu parameteyi sadece geliştirme aşamasında kullanmalıyız.
- * `main`: dosya olan `main.py` (yani Python "modülü").
- * `app`: ise `main.py` dosyasının içerisinde `app = FastAPI()` satırında oluşturduğumuz `FastAPI` nesnesi.
- * `--reload`: kod değişikliklerinin ardından sunucuyu otomatik olarak yeniden başlatır. Bu parameteyi sadece geliştirme aşamasında kullanmalıyız.
+///
Çıktı olarak şöyle bir satır ile karşılaşacaksınız:
@@ -130,22 +131,21 @@ Ayrıca, API'ınızla iletişim kuracak önyüz, mobil veya IoT uygulamaları gi
### Adım 1: `FastAPI`yı Projemize Dahil Edelim
-```Python hl_lines="1"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[1] *}
`FastAPI`, API'niz için tüm işlevselliği sağlayan bir Python sınıfıdır.
-!!! note "Teknik Detaylar"
- `FastAPI` doğrudan `Starlette`'i miras alan bir sınıftır.
+/// note | Teknik Detaylar
+
+`FastAPI` doğrudan `Starlette`'i miras alan bir sınıftır.
- Starlette'in tüm işlevselliğini `FastAPI` ile de kullanabilirsiniz.
+Starlette'in tüm işlevselliğini `FastAPI` ile de kullanabilirsiniz.
+
+///
### Adım 2: Bir `FastAPI` "Örneği" Oluşturalım
-```Python hl_lines="3"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[3] *}
Burada `app` değişkeni `FastAPI` sınıfının bir örneği olacaktır.
@@ -165,9 +165,7 @@ $ uvicorn main:app --reload
Uygulamanızı aşağıdaki gibi oluşturursanız:
-```Python hl_lines="3"
-{!../../../docs_src/first_steps/tutorial002.py!}
-```
+{* ../../docs_src/first_steps/tutorial002.py hl[3] *}
Ve bunu `main.py` dosyasına yerleştirirseniz eğer `uvicorn` komutunu şu şekilde çalıştırabilirsiniz:
@@ -199,8 +197,11 @@ https://example.com/items/foo
/items/foo
```
-!!! info "Bilgi"
- "Yol" genellikle "endpoint" veya "route" olarak adlandırılır.
+/// info | Bilgi
+
+"Yol" genellikle "endpoint" veya "route" olarak adlandırılır.
+
+///
Bir API oluştururken, "yol", "kaynaklar" ile "endişeleri" ayırmanın ana yöntemidir.
@@ -241,25 +242,26 @@ Biz de onları "**operasyonlar**" olarak adlandıracağız.
#### Bir *Yol Operasyonu Dekoratörü* Tanımlayalım
-```Python hl_lines="6"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[6] *}
`@app.get("/")` dekoratörü, **FastAPI**'a hemen altındaki fonksiyonun aşağıdaki durumlardan sorumlu olduğunu söyler:
* get
operasyonu ile
* `/` yoluna gelen istekler
-!!! info "`@decorator` Bilgisi"
- Python'da `@something` sözdizimi "dekoratör" olarak adlandırılır.
+/// info | `@decorator` Bilgisi
+
+Python'da `@something` sözdizimi "dekoratör" olarak adlandırılır.
+
+Dekoratörler, dekoratif bir şapka gibi (sanırım terim buradan geliyor) fonksiyonların üzerlerine yerleştirilirler.
- Dekoratörler, dekoratif bir şapka gibi (sanırım terim buradan geliyor) fonksiyonların üzerlerine yerleştirilirler.
+Bir "dekoratör" hemen altında bulunan fonksiyonu alır ve o fonksiyon ile bazı işlemler gerçekleştirir.
- Bir "dekoratör" hemen altında bulunan fonksiyonu alır ve o fonksiyon ile bazı işlemler gerçekleştirir.
+Bizim durumumuzda, kullandığımız dekoratör, **FastAPI**'a altındaki fonksiyonun `/` yoluna gelen `get` metodlu isteklerden sorumlu olduğunu söyler.
- 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**.
- Bu bir **yol operasyonu dekoratörüdür**.
+///
Ayrıca diğer operasyonları da kullanabilirsiniz:
@@ -274,14 +276,17 @@ Daha az kullanılanları da kullanabilirsiniz:
* `@app.patch()`
* `@app.trace()`
-!!! tip "İpucu"
- Her işlemi (HTTP metod) istediğiniz gibi kullanmakta özgürsünüz.
+/// tip | İpucu
+
+Her işlemi (HTTP metod) istediğiniz gibi kullanmakta özgürsünüz.
+
+**FastAPI** herhangi bir özel amacı veya anlamı olması konusunda ısrarcı olmaz.
- **FastAPI** herhangi bir özel amacı veya anlamı olması konusunda ısrarcı olmaz.
+Buradaki bilgiler bir gereklilik değil, bir kılavuz olarak sunulmaktadır.
- Buradaki bilgiler bir gereklilik değil, bir kılavuz olarak sunulmaktadır.
+Mesela GraphQL kullanırkan genelde tüm işlemleri yalnızca `POST` operasyonunu kullanarak gerçekleştirirsiniz.
- Mesela GraphQL kullanırkan genelde tüm işlemleri yalnızca `POST` operasyonunu kullanarak gerçekleştirirsiniz.
+///
### Adım 4: **Yol Operasyonu Fonksiyonunu** Tanımlayın
@@ -291,9 +296,7 @@ Aşağıdaki, bizim **yol operasyonu fonksiyonumuzdur**:
* **operasyon**: `get`
* **fonksiyon**: "dekoratör"ün (`@app.get("/")`'in) altındaki fonksiyondur.
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[7] *}
Bu bir Python fonksiyonudur.
@@ -305,18 +308,17 @@ Bu durumda bu fonksiyon bir `async` fonksiyondur.
Bu fonksiyonu `async def` yerine normal bir fonksiyon olarak da tanımlayabilirsiniz.
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial003.py!}
-```
+{* ../../docs_src/first_steps/tutorial003.py hl[7] *}
+
+/// note | Not
-!!! note "Not"
- Eğer farkı bilmiyorsanız, [Async: *"Aceleniz mi var?"*](../async.md#in-a-hurry){.internal-link target=_blank} sayfasını kontrol edebilirsiniz.
+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
-```Python hl_lines="8"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[8] *}
Bir `dict`, `list` veya `str`, `int` gibi tekil değerler döndürebilirsiniz.
diff --git a/docs/tr/docs/tutorial/path-params.md b/docs/tr/docs/tutorial/path-params.md
index c19023645..e1707a5d9 100644
--- a/docs/tr/docs/tutorial/path-params.md
+++ b/docs/tr/docs/tutorial/path-params.md
@@ -2,9 +2,7 @@
Yol "parametrelerini" veya "değişkenlerini" Python string biçimlemede kullanılan sözdizimi ile tanımlayabilirsiniz.
-```Python hl_lines="6-7"
-{!../../../docs_src/path_params/tutorial001.py!}
-```
+{* ../../docs_src/path_params/tutorial001.py hl[6:7] *}
Yol parametresi olan `item_id`'nin değeri, fonksiyonunuza `item_id` argümanı olarak aktarılacaktır.
@@ -18,14 +16,15 @@ Eğer bu örneği çalıştırıp Dönüşümü
POST
sayfasını ziyaret edebilirsiniz.
+
+///
- Ancak form içerisinde dosyalar yer aldığında `multipart/form-data` olarak kodlanır. Bir sonraki bölümde dosyaların işlenmesi hakkında bilgi edineceksiniz.
+/// warning | Uyarı
- Form kodlama türleri ve form alanları hakkında daha fazla bilgi edinmek istiyorsanız MDN web docs for POST
sayfasını ziyaret edebilirsiniz.
+*Yol operasyonları* içerisinde birden fazla `Form` parametresi tanımlayabilirsiniz ancak bunlarla birlikte JSON verisi kabul eden `Body` alanları tanımlayamazsınız çünkü bu durumda istek gövdesi `application/json` yerine `application/x-www-form-urlencoded` ile kodlanmış olur.
-!!! warning "Uyarı"
- *Yol operasyonları* içerisinde birden fazla `Form` parametresi tanımlayabilirsiniz ancak bunlarla birlikte JSON verisi kabul eden `Body` alanları tanımlayamazsınız çünkü bu durumda istek gövdesi `application/json` yerine `application/x-www-form-urlencoded` ile kodlanmış olur.
+Bu **FastAPI**'ın getirdiği bir kısıtlama değildir, HTTP protokolünün bir parçasıdır.
- Bu **FastAPI**'ın getirdiği bir kısıtlama değildir, HTTP protokolünün bir parçasıdır.
+///
## Özet
diff --git a/docs/tr/docs/tutorial/static-files.md b/docs/tr/docs/tutorial/static-files.md
index 00c833686..db30f13bc 100644
--- a/docs/tr/docs/tutorial/static-files.md
+++ b/docs/tr/docs/tutorial/static-files.md
@@ -7,14 +7,15 @@
* `StaticFiles` sınıfını projenize dahil edin.
* Bir `StaticFiles()` örneğini belirli bir yola bağlayın.
-```Python hl_lines="2 6"
-{!../../../docs_src/static_files/tutorial001.py!}
-```
+{* ../../docs_src/static_files/tutorial001.py hl[2,6] *}
-!!! note "Teknik Detaylar"
- Projenize dahil etmek için `from starlette.staticfiles import StaticFiles` kullanabilirsiniz.
+/// note | Teknik Detaylar
- **FastAPI**, geliştiricilere kolaylık sağlamak amacıyla `starlette.staticfiles`'ı `fastapi.staticfiles` olarak sağlar. Ancak `StaticFiles` sınıfı aslında doğrudan Starlette'den gelir.
+Projenize dahil etmek için `from starlette.staticfiles import StaticFiles` kullanabilirsiniz.
+
+**FastAPI**, geliştiricilere kolaylık sağlamak amacıyla `starlette.staticfiles`'ı `fastapi.staticfiles` olarak sağlar. Ancak `StaticFiles` sınıfı aslında doğrudan Starlette'den gelir.
+
+///
### Bağlama (Mounting) Nedir?
diff --git a/docs/uk/docs/alternatives.md b/docs/uk/docs/alternatives.md
index 16cc0d875..1acbe237a 100644
--- a/docs/uk/docs/alternatives.md
+++ b/docs/uk/docs/alternatives.md
@@ -30,12 +30,17 @@
Це був один із перших прикладів **автоматичної документації API**, і саме це була одна з перших ідей, яка надихнула на «пошук» **FastAPI**.
-!!! note "Примітка"
- Django REST Framework створив Том Крісті. Той самий творець Starlette і Uvicorn, на яких базується **FastAPI**.
+/// note | Примітка
+Django REST Framework створив Том Крісті. Той самий творець Starlette і Uvicorn, на яких базується **FastAPI**.
-!!! check "Надихнуло **FastAPI** на"
- Мати автоматичний веб-інтерфейс документації API.
+///
+
+/// check | Надихнуло **FastAPI** на
+
+Мати автоматичний веб-інтерфейс документації API.
+
+///
### Flask
@@ -51,11 +56,13 @@ Flask — це «мікрофреймворк», він не включає ін
Враховуючи простоту Flask, він здавався хорошим підходом для створення API. Наступним, що знайшов, був «Django REST Framework» для Flask.
-!!! check "Надихнуло **FastAPI** на"
- Бути мікрофреймоворком. Зробити легким комбінування та поєднання необхідних інструментів та частин.
+/// check | Надихнуло **FastAPI** на
- Мати просту та легку у використанні систему маршрутизації.
+Бути мікрофреймоворком. Зробити легким комбінування та поєднання необхідних інструментів та частин.
+ Мати просту та легку у використанні систему маршрутизації.
+
+///
### Requests
@@ -91,11 +98,13 @@ def read_url():
Зверніть увагу на схожість у `requests.get(...)` і `@app.get(...)`.
-!!! check "Надихнуло **FastAPI** на"
- * Майте простий та інтуїтивно зрозумілий API.
- * Використовуйте імена (операції) методів HTTP безпосередньо, простим та інтуїтивно зрозумілим способом.
- * Розумні параметри за замовчуванням, але потужні налаштування.
+/// check | Надихнуло **FastAPI** на
+
+* Майте простий та інтуїтивно зрозумілий API.
+ * Використовуйте імена (операції) методів HTTP безпосередньо, простим та інтуїтивно зрозумілим способом.
+ * Розумні параметри за замовчуванням, але потужні налаштування.
+///
### Swagger / OpenAPI
@@ -109,15 +118,18 @@ def read_url():
Тому, коли говорять про версію 2.0, прийнято говорити «Swagger», а про версію 3+ «OpenAPI».
-!!! check "Надихнуло **FastAPI** на"
- Прийняти і використовувати відкритий стандарт для специфікацій API замість спеціальної схеми.
+/// check | Надихнуло **FastAPI** на
+
+Прийняти і використовувати відкритий стандарт для специфікацій API замість спеціальної схеми.
- Інтегрувати інструменти інтерфейсу на основі стандартів:
+ Інтегрувати інструменти інтерфейсу на основі стандартів:
- * Інтерфейс Swagger
- * ReDoc
+ * Інтерфейс Swagger
+ * ReDoc
- Ці два було обрано через те, що вони досить популярні та стабільні, але, виконавши швидкий пошук, ви можете знайти десятки додаткових альтернативних інтерфейсів для OpenAPI (які можна використовувати з **FastAPI**).
+ Ці два було обрано через те, що вони досить популярні та стабільні, але, виконавши швидкий пошук, ви можете знайти десятки додаткових альтернативних інтерфейсів для OpenAPI (які можна використовувати з **FastAPI**).
+
+///
### Фреймворки REST для Flask
@@ -135,8 +147,11 @@ Marshmallow створено для забезпечення цих функці
Але він був створений до того, як існували підказки типу Python. Отже, щоб визначити кожну схему, вам потрібно використовувати спеціальні утиліти та класи, надані Marshmallow.
-!!! check "Надихнуло **FastAPI** на"
- Використовувати код для автоматичного визначення "схем", які надають типи даних і перевірку.
+/// check | Надихнуло **FastAPI** на
+
+Використовувати код для автоматичного визначення "схем", які надають типи даних і перевірку.
+
+///
### Webargs
@@ -148,11 +163,17 @@ Webargs — це інструмент, створений, щоб забезпе
Це чудовий інструмент, і я також часто використовував його, перш ніж створити **FastAPI**.
-!!! info "Інформація"
- Webargs був створений тими ж розробниками Marshmallow.
+/// info | Інформація
+
+Webargs був створений тими ж розробниками Marshmallow.
+
+///
+
+/// check | Надихнуло **FastAPI** на
-!!! check "Надихнуло **FastAPI** на"
- Мати автоматичну перевірку даних вхідного запиту.
+Мати автоматичну перевірку даних вхідного запиту.
+
+///
### APISpec
@@ -172,12 +193,17 @@ Marshmallow і Webargs забезпечують перевірку, аналіз
Редактор тут нічим не може допомогти. І якщо ми змінимо параметри чи схеми Marshmallow і забудемо також змінити цю строку документа YAML, згенерована схема буде застарілою.
-!!! info "Інформація"
- APISpec був створений тими ж розробниками Marshmallow.
+/// info | Інформація
+
+APISpec був створений тими ж розробниками Marshmallow.
+
+///
+/// check | Надихнуло **FastAPI** на
-!!! check "Надихнуло **FastAPI** на"
- Підтримувати відкритий стандарт API, OpenAPI.
+Підтримувати відкритий стандарт API, OpenAPI.
+
+///
### Flask-apispec
@@ -199,11 +225,17 @@ Marshmallow і Webargs забезпечують перевірку, аналіз
І ці самі генератори повного стеку були основою [**FastAPI** генераторів проектів](project-generation.md){.internal-link target=_blank}.
-!!! info "Інформація"
- Flask-apispec був створений тими ж розробниками Marshmallow.
+/// info | Інформація
+
+Flask-apispec був створений тими ж розробниками Marshmallow.
+
+///
-!!! check "Надихнуло **FastAPI** на"
- Створення схеми OpenAPI автоматично з того самого коду, який визначає серіалізацію та перевірку.
+/// check | Надихнуло **FastAPI** на
+
+Створення схеми OpenAPI автоматично з того самого коду, який визначає серіалізацію та перевірку.
+
+///
### NestJS (та Angular)
@@ -219,24 +251,33 @@ Marshmallow і Webargs забезпечують перевірку, аналіз
Він не дуже добре обробляє вкладені моделі. Отже, якщо тіло JSON у запиті є об’єктом JSON із внутрішніми полями, які, у свою чергу, є вкладеними об’єктами JSON, його неможливо належним чином задокументувати та перевірити.
-!!! check "Надихнуло **FastAPI** на"
- Використовувати типи Python, щоб мати чудову підтримку редактора.
+/// check | Надихнуло **FastAPI** на
+
+Використовувати типи Python, щоб мати чудову підтримку редактора.
- Мати потужну систему впровадження залежностей. Знайдіть спосіб звести до мінімуму повторення коду.
+ Мати потужну систему впровадження залежностей. Знайдіть спосіб звести до мінімуму повторення коду.
+
+///
### Sanic
Це був один із перших надзвичайно швидких фреймворків Python на основі `asyncio`. Він був дуже схожий на Flask.
-!!! note "Технічні деталі"
- Він використовував `uvloop` замість стандартного циклу Python `asyncio`. Ось що зробило його таким швидким.
+/// note | Технічні деталі
+
+Він використовував `uvloop` замість стандартного циклу Python `asyncio`. Ось що зробило його таким швидким.
- Це явно надихнуло Uvicorn і Starlette, які зараз швидші за Sanic у відкритих тестах.
+ Це явно надихнуло Uvicorn і Starlette, які зараз швидші за Sanic у відкритих тестах.
-!!! check "Надихнуло **FastAPI** на"
- Знайти спосіб отримати божевільну продуктивність.
+///
- Ось чому **FastAPI** базується на Starlette, оскільки це найшвидша доступна структура (перевірена тестами сторонніх розробників).
+/// check | Надихнуло **FastAPI** на
+
+Знайти спосіб отримати божевільну продуктивність.
+
+ Ось чому **FastAPI** базується на Starlette, оскільки це найшвидша доступна структура (перевірена тестами сторонніх розробників).
+
+///
### Falcon
@@ -246,12 +287,15 @@ Falcon — ще один високопродуктивний фреймворк
Таким чином, перевірка даних, серіалізація та документація повинні виконуватися в коді, а не автоматично. Або вони повинні бути реалізовані як фреймворк поверх Falcon, як Hug. Така сама відмінність спостерігається в інших фреймворках, натхненних дизайном Falcon, що мають один об’єкт запиту та один об’єкт відповіді як параметри.
-!!! check "Надихнуло **FastAPI** на"
- Знайти способи отримати чудову продуктивність.
+/// check | Надихнуло **FastAPI** на
- Разом із Hug (оскільки Hug базується на Falcon) надихнув **FastAPI** оголосити параметр `response` у функціях.
+Знайти способи отримати чудову продуктивність.
- Хоча у FastAPI це необов’язково, і використовується в основному для встановлення заголовків, файлів cookie та альтернативних кодів стану.
+ Разом із Hug (оскільки Hug базується на Falcon) надихнув **FastAPI** оголосити параметр `response` у функціях.
+
+ Хоча у FastAPI це необов’язково, і використовується в основному для встановлення заголовків, файлів cookie та альтернативних кодів стану.
+
+///
### Molten
@@ -269,12 +313,15 @@ Falcon — ще один високопродуктивний фреймворк
Маршрути оголошуються в одному місці з використанням функцій, оголошених в інших місцях (замість використання декораторів, які можна розмістити безпосередньо поверх функції, яка обробляє кінцеву точку). Це ближче до того, як це робить Django, ніж до Flask (і Starlette). Він розділяє в коді речі, які відносно тісно пов’язані.
-!!! check "Надихнуло **FastAPI** на"
- Визначити додаткові перевірки для типів даних, використовуючи значення "за замовчуванням" атрибутів моделі. Це покращує підтримку редактора, а раніше вона була недоступна в Pydantic.
+/// check | Надихнуло **FastAPI** на
+
+Визначити додаткові перевірки для типів даних, використовуючи значення "за замовчуванням" атрибутів моделі. Це покращує підтримку редактора, а раніше вона була недоступна в Pydantic.
- Це фактично надихнуло оновити частини Pydantic, щоб підтримувати той самий стиль оголошення перевірки (всі ці функції вже доступні в Pydantic).
+ Це фактично надихнуло оновити частини Pydantic, щоб підтримувати той самий стиль оголошення перевірки (всі ці функції вже доступні в Pydantic).
-### Hug
+///
+
+### Hug
Hug був одним із перших фреймворків, який реалізував оголошення типів параметрів API за допомогою підказок типу Python. Це була чудова ідея, яка надихнула інші інструменти зробити те саме.
@@ -288,15 +335,21 @@ Hug був одним із перших фреймворків, який реа
Оскільки він заснований на попередньому стандарті для синхронних веб-фреймворків Python (WSGI), він не може працювати з Websockets та іншими речами, хоча він також має високу продуктивність.
-!!! info "Інформація"
- Hug створив Тімоті Крослі, той самий творець `isort`, чудовий інструмент для автоматичного сортування імпорту у файлах Python.
+/// info | Інформація
+
+Hug створив Тімоті Крослі, той самий творець `isort`, чудовий інструмент для автоматичного сортування імпорту у файлах Python.
+
+///
-!!! check "Надихнуло **FastAPI** на"
- Hug надихнув частину APIStar і був одним із найбільш перспективних інструментів, поряд із APIStar.
+/// check | Надихнуло **FastAPI** на
- Hug надихнув **FastAPI** на використання підказок типу Python для оголошення параметрів і автоматичного створення схеми, що визначає API.
+Hug надихнув частину APIStar і був одним із найбільш перспективних інструментів, поряд із APIStar.
- Hug надихнув **FastAPI** оголосити параметр `response` у функціях для встановлення заголовків і файлів cookie.
+ Hug надихнув **FastAPI** на використання підказок типу Python для оголошення параметрів і автоматичного створення схеми, що визначає API.
+
+ Hug надихнув **FastAPI** оголосити параметр `response` у функціях для встановлення заголовків і файлів cookie.
+
+///
### APIStar (<= 0,5)
@@ -322,21 +375,27 @@ Hug був одним із перших фреймворків, який реа
Тепер APIStar — це набір інструментів для перевірки специфікацій OpenAPI, а не веб-фреймворк.
-!!! info "Інформація"
- APIStar створив Том Крісті. Той самий хлопець, який створив:
+/// info | Інформація
+
+APIStar створив Том Крісті. Той самий хлопець, який створив:
- * Django REST Framework
- * Starlette (на якому базується **FastAPI**)
- * Uvicorn (використовується Starlette і **FastAPI**)
+ * Django REST Framework
+ * Starlette (на якому базується **FastAPI**)
+ * Uvicorn (використовується Starlette і **FastAPI**)
-!!! check "Надихнуло **FastAPI** на"
- Існувати.
+///
- Ідею оголошення кількох речей (перевірки даних, серіалізації та документації) за допомогою тих самих типів Python, які в той же час забезпечували чудову підтримку редактора, я вважав геніальною ідеєю.
+/// check | Надихнуло **FastAPI** на
- І після тривалого пошуку подібної структури та тестування багатьох різних альтернатив, APIStar став найкращим доступним варіантом.
+Існувати.
- Потім APIStar перестав існувати як сервер, і було створено Starlette, який став новою кращою основою для такої системи. Це стало останнім джерелом натхнення для створення **FastAPI**. Я вважаю **FastAPI** «духовним спадкоємцем» APIStar, удосконалюючи та розширюючи функції, систему введення тексту та інші частини на основі досвіду, отриманого від усіх цих попередніх інструментів.
+ Ідею оголошення кількох речей (перевірки даних, серіалізації та документації) за допомогою тих самих типів Python, які в той же час забезпечували чудову підтримку редактора, я вважав геніальною ідеєю.
+
+ І після тривалого пошуку подібної структури та тестування багатьох різних альтернатив, APIStar став найкращим доступним варіантом.
+
+ Потім APIStar перестав існувати як сервер, і було створено Starlette, який став новою кращою основою для такої системи. Це стало останнім джерелом натхнення для створення **FastAPI**. Я вважаю **FastAPI** «духовним спадкоємцем» APIStar, удосконалюючи та розширюючи функції, систему введення тексту та інші частини на основі досвіду, отриманого від усіх цих попередніх інструментів.
+
+///
## Використовується **FastAPI**
@@ -348,10 +407,13 @@ Pydantic — це бібліотека для визначення переві
Його можна порівняти з Marshmallow. Хоча він швидший за Marshmallow у тестах. Оскільки він базується на тих самих підказках типу Python, підтримка редактора чудова.
-!!! check "**FastAPI** використовує його для"
- Виконання перевірки всіх даних, серіалізації даних і автоматичної документацію моделі (на основі схеми JSON).
+/// check | **FastAPI** використовує його для
- Потім **FastAPI** бере ці дані схеми JSON і розміщує їх у OpenAPI, окремо від усіх інших речей, які він робить.
+Виконання перевірки всіх даних, серіалізації даних і автоматичної документацію моделі (на основі схеми JSON).
+
+ Потім **FastAPI** бере ці дані схеми JSON і розміщує їх у OpenAPI, окремо від усіх інших речей, які він робить.
+
+///
### Starlette
@@ -380,17 +442,23 @@ Starlette надає всі основні функції веб-мікрофр
Це одна з головних речей, які **FastAPI** додає зверху, все на основі підказок типу Python (з використанням Pydantic). Це, а також система впровадження залежностей, утиліти безпеки, створення схеми OpenAPI тощо.
-!!! note "Технічні деталі"
- ASGI — це новий «стандарт», який розробляється членами основної команди Django. Це ще не «стандарт Python» (PEP), хоча вони в процесі цього.
+/// note | Технічні деталі
+
+ASGI — це новий «стандарт», який розробляється членами основної команди Django. Це ще не «стандарт Python» (PEP), хоча вони в процесі цього.
- Тим не менш, він уже використовується як «стандарт» кількома інструментами. Це значно покращує сумісність, оскільки ви можете переключити Uvicorn на будь-який інший сервер ASGI (наприклад, Daphne або Hypercorn), або ви можете додати інструменти, сумісні з ASGI, як-от `python-socketio`.
+ Тим не менш, він уже використовується як «стандарт» кількома інструментами. Це значно покращує сумісність, оскільки ви можете переключити Uvicorn на будь-який інший сервер ASGI (наприклад, Daphne або Hypercorn), або ви можете додати інструменти, сумісні з ASGI, як-от `python-socketio`.
-!!! check "**FastAPI** використовує його для"
- Керування всіма основними веб-частинами. Додавання функцій зверху.
+///
- Сам клас `FastAPI` безпосередньо успадковує клас `Starlette`.
+/// check | **FastAPI** використовує його для
- Отже, усе, що ви можете робити зі Starlette, ви можете робити це безпосередньо за допомогою **FastAPI**, оскільки це, по суті, Starlette на стероїдах.
+Керування всіма основними веб-частинами. Додавання функцій зверху.
+
+ Сам клас `FastAPI` безпосередньо успадковує клас `Starlette`.
+
+ Отже, усе, що ви можете робити зі Starlette, ви можете робити це безпосередньо за допомогою **FastAPI**, оскільки це, по суті, Starlette на стероїдах.
+
+///
### Uvicorn
@@ -400,12 +468,15 @@ Uvicorn — це блискавичний сервер ASGI, побудован
Це рекомендований сервер для Starlette і **FastAPI**.
-!!! check "**FastAPI** рекомендує це як"
- Основний веб-сервер для запуску програм **FastAPI**.
+/// check | **FastAPI** рекомендує це як
+
+Основний веб-сервер для запуску програм **FastAPI**.
+
+ Ви можете поєднати його з Gunicorn, щоб мати асинхронний багатопроцесний сервер.
- Ви можете поєднати його з Gunicorn, щоб мати асинхронний багатопроцесний сервер.
+ Додаткову інформацію див. у розділі [Розгортання](deployment/index.md){.internal-link target=_blank}.
- Додаткову інформацію див. у розділі [Розгортання](deployment/index.md){.internal-link target=_blank}.
+///
## Орієнтири та швидкість
diff --git a/docs/uk/docs/fastapi-cli.md b/docs/uk/docs/fastapi-cli.md
new file mode 100644
index 000000000..6bbbbc326
--- /dev/null
+++ b/docs/uk/docs/fastapi-cli.md
@@ -0,0 +1,83 @@
+# FastAPI CLI
+
+**FastAPI CLI** це програма командного рядка, яку Ви можете використовувати, щоб обслуговувати Ваш додаток FastAPI, керувати Вашими FastApi проектами, тощо.
+
+Коли Ви встановлюєте FastApi (тобто виконуєте `pip install "fastapi[standard]"`), Ви також встановлюєте пакунок `fastapi-cli`, цей пакунок надає команду `fastapi` в терміналі.
+
+Для запуску Вашого FastAPI проекту для розробки, Ви можете скористатись командою `fastapi dev`:
+
+
-
+
@@ -88,7 +88,7 @@ FastAPI - це сучасний, швидкий (високопродуктив
"_Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted **Hug** to be - it's really inspiring to see someone build that._"
-
+
---
@@ -437,7 +437,7 @@ item: Item
Pydantic використовує:
-*
email_validator
- для валідації електронної пошти.
+* email-validator
- для валідації електронної пошти.
* pydantic-settings
- для управління налаштуваннями.
* pydantic-extra-types
- для додаткових типів, що можуть бути використані з Pydantic.
diff --git a/docs/uk/docs/learn/index.md b/docs/uk/docs/learn/index.md
new file mode 100644
index 000000000..7f9f21e57
--- /dev/null
+++ b/docs/uk/docs/learn/index.md
@@ -0,0 +1,5 @@
+# Навчання
+
+У цьому розділі надані вступні та навчальні матеріали для вивчення FastAPI.
+
+Це можна розглядати як **книгу**, **курс**, або **офіційний** та рекомендований спосіб освоїти FastAPI. 😎
diff --git a/docs/uk/docs/python-types.md b/docs/uk/docs/python-types.md
index d0adadff3..676bafb15 100644
--- a/docs/uk/docs/python-types.md
+++ b/docs/uk/docs/python-types.md
@@ -12,16 +12,18 @@ Python підтримує додаткові "підказки типу" ("type
Але навіть якщо ви ніколи не використаєте **FastAPI**, вам буде корисно дізнатись трохи про них.
-!!! note
- Якщо ви експерт у Python і ви вже знаєте усе про анотації типів - перейдіть до наступного розділу.
+/// note
+
+Якщо ви експерт у Python і ви вже знаєте усе про анотації типів - перейдіть до наступного розділу.
+
+///
## Мотивація
Давайте почнемо з простого прикладу:
-```Python
-{!../../../docs_src/python_types/tutorial001.py!}
-```
+{* ../../docs_src/python_types/tutorial001.py *}
+
Виклик цієї програми виводить:
@@ -35,9 +37,8 @@ John Doe
* Конвертує кожну літеру кожного слова у верхній регістр за допомогою `title()`.
* Конкатенує їх разом із пробілом по середині.
-```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial001.py!}
-```
+{* ../../docs_src/python_types/tutorial001.py hl[2] *}
+
### Редагуйте це
@@ -79,9 +80,8 @@ John Doe
Це "type hints":
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial002.py!}
-```
+{* ../../docs_src/python_types/tutorial002.py hl[1] *}
+
Це не те саме, що оголошення значень за замовчуванням, як це було б з:
@@ -109,9 +109,8 @@ John Doe
Перевірте цю функцію, вона вже має анотацію типу:
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial003.py!}
-```
+{* ../../docs_src/python_types/tutorial003.py hl[1] *}
+
Оскільки редактор знає типи змінних, ви не тільки отримаєте автозаповнення, ви також отримаєте перевірку помилок:
@@ -119,9 +118,8 @@ John Doe
Тепер ви знаєте, щоб виправити це, вам потрібно перетворити `age` у строку з допомогою `str(age)`:
-```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial004.py!}
-```
+{* ../../docs_src/python_types/tutorial004.py hl[2] *}
+
## Оголошення типів
@@ -140,9 +138,8 @@ John Doe
* `bool`
* `bytes`
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial005.py!}
-```
+{* ../../docs_src/python_types/tutorial005.py hl[1] *}
+
### Generic-типи з параметрами типів
@@ -164,45 +161,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!}
+```
+
+Оголосимо змінну з тим самим синтаксисом двокрапки (`:`).
+
+Як тип вкажемо `List`, який ви імпортували з `typing`.
+
+Оскільки список є типом, який містить деякі внутрішні типи, ви поміщаєте їх у квадратні дужки:
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial006.py!}
- ```
+```Python hl_lines="4"
+{!> ../../docs_src/python_types/tutorial006.py!}
+```
- Оголосимо змінну з тим самим синтаксисом двокрапки (`:`).
+////
- Як тип вкажемо `List`, який ви імпортували з `typing`.
+//// tab | Python 3.9 і вище
- Оскільки список є типом, який містить деякі внутрішні типи, ви поміщаєте їх у квадратні дужки:
+Оголосимо змінну з тим самим синтаксисом двокрапки (`:`).
- ```Python hl_lines="4"
- {!> ../../../docs_src/python_types/tutorial006.py!}
- ```
+Як тип вкажемо `list`.
-=== "Python 3.9 і вище"
+Оскільки список є типом, який містить деякі внутрішні типи, ви поміщаєте їх у квадратні дужки:
- Оголосимо змінну з тим самим синтаксисом двокрапки (`:`).
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial006_py39.py!}
+```
- Як тип вкажемо `list`.
+////
- Оскільки список є типом, який містить деякі внутрішні типи, ви поміщаєте їх у квадратні дужки:
+/// info
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial006_py39.py!}
- ```
+Ці внутрішні типи в квадратних дужках називаються "параметрами типу".
-!!! info
- Ці внутрішні типи в квадратних дужках називаються "параметрами типу".
+У цьому випадку, `str` це параметр типу переданий у `List` (або `list` у Python 3.9 і вище).
- У цьому випадку, `str` це параметр типу переданий у `List` (або `list` у Python 3.9 і вище).
+///
Це означає: "змінна `items` це `list`, і кожен з елементів у цьому списку - `str`".
-!!! tip
- Якщо ви використовуєте Python 3.9 і вище, вам не потрібно імпортувати `List` з `typing`, ви можете використовувати натомість тип `list`.
+/// tip
+
+Якщо ви використовуєте Python 3.9 і вище, вам не потрібно імпортувати `List` з `typing`, ви можете використовувати натомість тип `list`.
+
+///
Зробивши це, ваш редактор може надати підтримку навіть під час обробки елементів зі списку:
@@ -218,17 +225,21 @@ John Doe
Ви повинні зробити те ж саме, щоб оголосити `tuple` і `set`:
-=== "Python 3.8 і вище"
+//// tab | Python 3.8 і вище
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial007.py!}
- ```
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial007.py!}
+```
+
+////
-=== "Python 3.9 і вище"
+//// tab | Python 3.9 і вище
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial007_py39.py!}
- ```
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial007_py39.py!}
+```
+
+////
Це означає:
@@ -243,17 +254,21 @@ John Doe
Другий параметр типу для значення у `dict`:
-=== "Python 3.8 і вище"
+//// tab | Python 3.8 і вище
+
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial008.py!}
+```
+
+////
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial008.py!}
- ```
+//// tab | Python 3.9 і вище
-=== "Python 3.9 і вище"
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial008_py39.py!}
+```
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial008_py39.py!}
- ```
+////
Це означає:
@@ -269,17 +284,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!}
- ```
+//// tab | Python 3.10 і вище
-=== "Python 3.10 і вище"
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial008b_py310.py!}
+```
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial008b_py310.py!}
- ```
+////
В обох випадках це означає, що `item` може бути `int` або `str`.
@@ -290,7 +309,7 @@ John Doe
У Python 3.6 і вище (включаючи Python 3.10) ви можете оголосити його, імпортувавши та використовуючи `Optional` з модуля `typing`.
```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009.py!}
+{!../../docs_src/python_types/tutorial009.py!}
```
Використання `Optional[str]` замість просто `str` дозволить редактору допомогти вам виявити помилки, коли ви могли б вважати, що значенням завжди є `str`, хоча насправді воно також може бути `None`.
@@ -299,69 +318,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 і вище"
+//// tab | Python 3.9 і вище
- Ви можете використовувати ті самі вбудовані типи, як generic (з квадратними дужками та типами всередині):
+Ви можете використовувати ті самі вбудовані типи, як generic (з квадратними дужками та типами всередині):
- * `list`
- * `tuple`
- * `set`
- * `dict`
+* `list`
+* `tuple`
+* `set`
+* `dict`
- І те саме, що й у Python 3.8, із модуля `typing`:
+І те саме, що й у Python 3.8, із модуля `typing`:
- * `Union`
- * `Optional`
- * ...та інші.
+* `Union`
+* `Optional`
+* ...та інші.
-=== "Python 3.10 і вище"
+////
- Ви можете використовувати ті самі вбудовані типи, як generic (з квадратними дужками та типами всередині):
+//// tab | Python 3.10 і вище
- * `list`
- * `tuple`
- * `set`
- * `dict`
+Ви можете використовувати ті самі вбудовані типи, як generic (з квадратними дужками та типами всередині):
- І те саме, що й у Python 3.8, із модуля `typing`:
+* `list`
+* `tuple`
+* `set`
+* `dict`
- * `Union`
- * `Optional` (так само як у Python 3.8)
- * ...та інші.
+І те саме, що й у Python 3.8, із модуля `typing`:
- У Python 3.10, як альтернатива використанню `Union` та `Optional`, ви можете використовувати вертикальну смугу (`|`) щоб оголосити об'єднання типів.
+* `Union`
+* `Optional` (так само як у Python 3.8)
+* ...та інші.
+
+У Python 3.10, як альтернатива використанню `Union` та `Optional`, ви можете використовувати вертикальну смугу (`|`) щоб оголосити об'єднання типів.
+
+////
### Класи як типи
@@ -369,15 +400,13 @@ John Doe
Скажімо, у вас є клас `Person` з імʼям:
-```Python hl_lines="1-3"
-{!../../../docs_src/python_types/tutorial010.py!}
-```
+{* ../../docs_src/python_types/tutorial010.py hl[1:3] *}
+
Потім ви можете оголосити змінну типу `Person`:
-```Python hl_lines="6"
-{!../../../docs_src/python_types/tutorial010.py!}
-```
+{* ../../docs_src/python_types/tutorial010.py hl[6] *}
+
І знову ж таки, ви отримуєте всю підтримку редактора:
@@ -397,26 +426,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 +482,8 @@ John Doe
Важливо те, що за допомогою стандартних типів Python в одному місці (замість того, щоб додавати більше класів, декораторів тощо), **FastAPI** зробить багато роботи за вас.
-!!! info
- Якщо ви вже пройшли весь навчальний посібник і повернулися, щоб дізнатися більше про типи, ось хороший ресурс "шпаргалка" від `mypy`.
+/// info
+
+Якщо ви вже пройшли весь навчальний посібник і повернулися, щоб дізнатися більше про типи, ось хороший ресурс "шпаргалка" від `mypy`.
+
+///
diff --git a/docs/uk/docs/tutorial/background-tasks.md b/docs/uk/docs/tutorial/background-tasks.md
new file mode 100644
index 000000000..912ba8c2a
--- /dev/null
+++ b/docs/uk/docs/tutorial/background-tasks.md
@@ -0,0 +1,85 @@
+# Фонові задачі
+
+Ви можете створювати фонові задачі, які будуть виконуватися *після* повернення відповіді.
+
+Це корисно для операцій, які потрібно виконати після обробки запиту, але клієнту не обов’язково чекати завершення цієї операції перед отриманням відповіді.
+
+Приклади використання:
+
+* Надсилання email-сповіщень після виконання певної дії:
+ * Підключення до поштового сервера та надсилання листа може займати кілька секунд. Ви можете відразу повернути відповідь, а email відправити у фоні.
+* Обробка даних:
+ * Наприклад, якщо отримано файл, який потрібно обробити довготривалим процесом, можна повернути відповідь "Accepted" ("Прийнято", HTTP 202) і виконати обробку файлу у фоні.
+
+## Використання `BackgroundTasks`
+
+Спочатку імпортуйте `BackgroundTasks` і додайте його як параметр у Вашу *функцію операції шляху* (path operation function) до `BackgroundTasks`:
+
+{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *}
+
+**FastAPI** автоматично створить об'єкт `BackgroundTasks` і передасть його у цей параметр.
+
+
+## Створення функції задачі
+
+Створіть функцію, яка буде виконувати фонову задачу.
+
+Це звичайна функція, яка може отримувати параметри.
+
+Вона може бути асинхронною `async def` або звичайною `def` функцією – **FastAPI** обробить її правильно.
+
+У нашому випадку функція записує у файл (імітуючи надсилання email).
+
+І оскільки операція запису не використовує `async` та `await`, ми визначаємо функцію як звичайну `def`:
+
+{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *}
+
+## Додавання фонової задачі
+
+Усередині Вашої *функції обробки шляху*, передайте функцію задачі в об'єкт *background tasks*, використовуючи метод `.add_task()`:
+
+{* ../../docs_src/background_tasks/tutorial001.py hl[14] *}
+
+`.add_task()` приймає аргументи:
+
+* Функція задача, яка буде виконуватися у фоновому режимі (`write_notification`). Зверніть увагу, що передається обʼєкт без дужок.
+* Будь-яка послідовність аргументів, які потрібно передати у функцію завдання у відповідному порядку (`email`).
+* Будь-які іменовані аргументи, які потрібно передати у функцію задачу (`message="some notification"`).
+
+## Впровадження залежностей
+
+Використання `BackgroundTasks` також працює з системою впровадження залежностей. Ви можете оголосити параметр типу `BackgroundTasks` на різних рівнях: у *функції операції шляху*, у залежності (dependable), у під залежності тощо.
+
+**FastAPI** знає, як діяти в кожному випадку і як повторно використовувати один і той самий об'єкт, щоб усі фонові задачі були об’єднані та виконувалися у фоновому режимі після завершення основного запиту.
+
+{* ../../docs_src/background_tasks/tutorial002_an_py310.py hl[13,15,22,25] *}
+
+У цьому прикладі повідомлення будуть записані у файл `log.txt` *після* того, як відповідь буде надіслана.
+
+Якщо у запиті був переданий query-параметр, він буде записаний у лог у фоновій задачі.
+
+А потім інша фонова задача, яка створюється у *функції операції шляху*, запише повідомлення з використанням path параметра `email`.
+
+## Технічні деталі
+
+Клас `BackgroundTasks` походить безпосередньо з `starlette.background`.
+
+Він імпортується безпосередньо у FastAPI, щоб Ви могли використовувати його з `fastapi` і випадково не імпортували `BackgroundTask` (без s в кінці) з `starlette.background`.
+
+Якщо використовувати лише `BackgroundTasks` (а не `BackgroundTask`), то його можна передавати як параметр у *функції операції шляху*, і **FastAPI** подбає про все інше, так само як і про використання об'єкта `Request`.
+
+Також можна використовувати `BackgroundTask` окремо в FastAPI, але для цього Вам доведеться створити об'єкт у коді та повернути Starlette `Response`, включаючи його.
+
+Детальніше можна почитати в офіційній документації Starlette про фонові задачі .
+
+## Застереження
+
+Якщо Вам потрібно виконувати складні фонові обчислення, і при цьому нема потреби запускати їх у тому ж процесі (наприклад, не потрібно спільного доступу до пам’яті чи змінних), можливо, варто скористатися більш потужними інструментами, такими як Celery.
+
+Такі інструменти зазвичай потребують складнішої конфігурації та менеджера черги повідомлень/завдань, наприклад, RabbitMQ або Redis. Однак вони дозволяють виконувати фонові задачі в кількох процесах і навіть на кількох серверах.
+
+Якщо ж Вам потрібно отримати доступ до змінних і об’єктів із тієї ж **FastAPI** - програми або виконувати невеликі фонові завдання (наприклад, надсилати сповіщення електронною поштою), достатньо просто використовувати `BackgroundTasks`.
+
+## Підсумок
+
+Імпортуйте та використовуйте `BackgroundTasks` як параметр у *функціях операції шляху* та залежностях, щоб додавати фонові задачі.
diff --git a/docs/uk/docs/tutorial/body-fields.md b/docs/uk/docs/tutorial/body-fields.md
index eee993cbe..7ddd9d104 100644
--- a/docs/uk/docs/tutorial/body-fields.md
+++ b/docs/uk/docs/tutorial/body-fields.md
@@ -6,98 +6,39 @@
Спочатку вам потрібно імпортувати це:
-=== "Python 3.10+"
+{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[4] *}
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!}
- ```
+/// warning
-=== "Python 3.9+"
+Зверніть увагу, що `Field` імпортується прямо з `pydantic`, а не з `fastapi`, як всі інші (`Query`, `Path`, `Body` тощо).
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001_an.py!}
- ```
-
-=== "Python 3.10+ non-Annotated"
-
- !!! tip
- Варто користуватись `Annotated` версією, якщо це можливо.
-
- ```Python hl_lines="2"
- {!> ../../../docs_src/body_fields/tutorial001_py310.py!}
- ```
-
-=== "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+"
-
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!}
- ```
+{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[11:14] *}
-=== "Python 3.9+"
-
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="12-15"
- {!> ../../../docs_src/body_fields/tutorial001_an.py!}
- ```
-
-=== "Python 3.10+ non-Annotated"
-
- !!! tip
- Варто користуватись `Annotated` версією, якщо це можливо..
-
- ```Python hl_lines="9-12"
- {!> ../../../docs_src/body_fields/tutorial001_py310.py!}
- ```
+`Field` працює так само, як `Query`, `Path` і `Body`, у нього такі самі параметри тощо.
-=== "Python 3.8+ non-Annotated"
+/// note | Технічні деталі
- !!! tip
- Варто користуватись `Annotated` версією, якщо це можливо..
+Насправді, `Query`, `Path` та інші, що ви побачите далі, створюють об'єкти підкласів загального класу `Param`, котрий сам є підкласом класу `FieldInfo` з Pydantic.
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001.py!}
- ```
+І `Field` від Pydantic також повертає екземпляр `FieldInfo`.
-`Field` працює так само, як `Query`, `Path` і `Body`, у нього такі самі параметри тощо.
+`Body` також безпосередньо повертає об'єкти підкласу `FieldInfo`. І є інші підкласи, які ви побачите пізніше, що є підкласами класу Body.
-!!! note "Технічні деталі"
- Насправді, `Query`, `Path` та інші, що ви побачите далі, створюють об'єкти підкласів загального класу `Param`, котрий сам є підкласом класу `FieldInfo` з Pydantic.
+Пам'ятайте, що коли ви імпортуєте 'Query', 'Path' та інше з 'fastapi', вони фактично є функціями, які повертають спеціальні класи.
- І `Field` від Pydantic також повертає екземпляр `FieldInfo`.
+///
- `Body` також безпосередньо повертає об'єкти підкласу `FieldInfo`. І є інші підкласи, які ви побачите пізніше, що є підкласами класу Body.
+/// tip
- Пам'ятайте, що коли ви імпортуєте 'Query', 'Path' та інше з 'fastapi', вони фактично є функціями, які повертають спеціальні класи.
+Зверніть увагу, що кожен атрибут моделі із типом, значенням за замовчуванням та `Field` має ту саму структуру, що й параметр *функції обробки шляху*, з `Field` замість `Path`, `Query` і `Body`.
-!!! tip
- Зверніть увагу, що кожен атрибут моделі із типом, значенням за замовчуванням та `Field` має ту саму структуру, що й параметр *функції обробки шляху*, з `Field` замість `Path`, `Query` і `Body`.
+///
## Додавання додаткової інформації
@@ -105,9 +46,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-multiple-params.md b/docs/uk/docs/tutorial/body-multiple-params.md
new file mode 100644
index 000000000..e2acf8a70
--- /dev/null
+++ b/docs/uk/docs/tutorial/body-multiple-params.md
@@ -0,0 +1,170 @@
+# Тіло запиту - Декілька параметрів
+
+Тепер, коли ми розглянули використання `Path` та `Query`, розгляньмо більш просунуті способи оголошення тіла запиту в **FastAPI**.
+
+## Змішування `Path`, `Query` та параметрів тіла запиту
+
+По-перше, звісно, Ви можете вільно змішувати оголошення параметрів `Path`, `Query` та тіла запиту, і **FastAPI** правильно їх обробить.
+
+Також Ви можете оголосити параметри тіла як необов’язкові, встановивши для них значення за замовчуванням `None`:
+
+{* ../../docs_src/body_multiple_params/tutorial001_an_py310.py hl[18:20] *}
+
+/// note | Примітка
+
+Зверніть увагу, що в цьому випадку параметр `item`, який береться з тіла запиту, є необов'язковим, оскільки має значення за замовчуванням `None`.
+
+///
+
+## Декілька параметрів тіла запиту
+
+У попередньому прикладі *операція шляху* очікувала JSON з атрибутами `Item`, наприклад:
+
+```JSON
+{
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2
+}
+```
+Але Ви також можете оголосити декілька параметрів тіла, наприклад `item` та `user`:
+
+{* ../../docs_src/body_multiple_params/tutorial002_py310.py hl[20] *}
+
+У цьому випадку **FastAPI** розпізнає, що є кілька параметрів тіла (два параметри є моделями Pydantic).
+
+Тому він використає назви параметрів як ключі (назви полів) у тілі запиту, очікуючи:
+
+```JSON
+{
+ "item": {
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2
+ },
+ "user": {
+ "username": "dave",
+ "full_name": "Dave Grohl"
+ }
+}
+```
+
+/// note | Примітка
+
+Зверніть увагу, що хоча `item` оголошено, так само як і раніше, тепер він очікується в тілі під ключем `item`.
+
+///
+
+**FastAPI** автоматично конвертує дані із запиту таким чином, щоб параметр `item` отримав свій вміст, і те ж саме стосується `user`.
+
+Він виконає валідацію складених даних і задокументує їх відповідним чином у схемі OpenAPI та в автоматичній документації.
+
+## Одиничні значення в тілі запиту
+
+Так само як є `Query` і `Path` для визначення додаткових даних для параметрів запиту та шляху, **FastAPI** надає еквівалентний `Body`.
+
+Наприклад, розширюючи попередню модель, Ви можете вирішити додати ще один ключ `importance` в те ж саме тіло запиту разом із `item` і `user`.
+
+Якщо Ви оголосите його як є, то, оскільки це одиничне значення, **FastAPI** припускатиме, що це параметр запиту (query parameter).
+
+Але Ви можете вказати **FastAPI** обробляти його як інший ключ тіла (body key), використовуючи `Body`:
+
+{* ../../docs_src/body_multiple_params/tutorial003_an_py310.py hl[23] *}
+
+У цьому випадку **FastAPI** очікуватиме тіло запиту у такому вигляді:
+
+```JSON
+{
+ "item": {
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2
+ },
+ "user": {
+ "username": "dave",
+ "full_name": "Dave Grohl"
+ },
+ "importance": 5
+}
+```
+Знову ж таки, **FastAPI** конвертуватиме типи даних, перевірятиме їх, створюватиме документацію тощо.
+
+## Декілька body та query параметрів
+
+Звісно, Ви можете оголошувати додаткові query параметри запиту, коли це необхідно, на додаток до будь-яких параметрів тіла запиту.
+
+Оскільки за замовчуванням окремі значення інтерпретуються як параметри запиту, Вам не потрібно явно додавати `Query`, можна просто використати:
+
+```Python
+q: Union[str, None] = None
+```
+
+Або в Python 3.10 та вище:
+
+```Python
+q: str | None = None
+```
+
+Наприклад:
+
+{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[28] *}
+
+
+/// info | Інформація
+
+`Body` також має ті самі додаткові параметри валідації та метаданих, що й `Query`, `Path` та інші, які Ви побачите пізніше.
+
+///
+
+## Вкладений поодинокий параметр тіла запиту
+
+Припустимо, у вас є лише один параметр тіла запиту `item` з моделі Pydantic `Item`.
+
+За замовчуванням **FastAPI** очікуватиме, що тіло запиту міститиме вміст безпосередньо.
+
+Але якщо Ви хочете, щоб він очікував JSON з ключем `item`, а всередині — вміст моделі (так, як це відбувається при оголошенні додаткових параметрів тіла), Ви можете використати спеціальний параметр `Body` — `embed`:
+
+```Python
+item: Item = Body(embed=True)
+```
+
+як у прикладі:
+
+{* ../../docs_src/body_multiple_params/tutorial005_an_py310.py hl[17] *}
+
+У цьому випадку **FastAPI** очікуватиме тіло запиту такого вигляду:
+
+```JSON hl_lines="2"
+{
+ "item": {
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2
+ }
+}
+```
+
+замість:
+
+```JSON
+{
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2
+}
+```
+
+## Підсумок
+
+Ви можете додавати кілька параметрів тіла до Вашої *функції операції шляху* (*path operation function*), навіть якщо запит може мати лише одне тіло.
+
+Але **FastAPI** обробить це, надасть Вам потрібні дані у функції, перевірить їх та задокументує коректну схему в *операції шляху*.
+
+Також Ви можете оголошувати окремі значення, які будуть отримані як частина тіла запиту.
+
+Крім того, Ви можете вказати **FastAPI** вбудовувати тіло в ключ, навіть якщо оголошено лише один параметр.
diff --git a/docs/uk/docs/tutorial/body-nested-models.md b/docs/uk/docs/tutorial/body-nested-models.md
new file mode 100644
index 000000000..abc33f2eb
--- /dev/null
+++ b/docs/uk/docs/tutorial/body-nested-models.md
@@ -0,0 +1,245 @@
+# Тіло запиту - Вкладені моделі
+
+З **FastAPI** Ви можете визначати, перевіряти, документувати та використовувати моделі, які можуть бути вкладені на будь-яку глибину (завдяки Pydantic).
+
+## Поля списку
+
+Ви можете визначити атрибут як підтип. Наприклад, Python-список (`list`):
+
+{* ../../docs_src/body_nested_models/tutorial001_py310.py hl[12] *}
+
+Це зробить `tags` списком, хоча не визначається тип елементів списку.
+
+## Поля списку з параметром типу
+
+Але Python має специфічний спосіб оголошення списків з внутрішніми типами або "параметрами типу":
+### Імпортуємо `List` з модуля typing
+
+У Python 3.9 і вище можна використовувати стандартний `list` для оголошення таких типів, як ми побачимо нижче. 💡
+
+Але в Python версії до 3.9 (від 3.6 і вище) спочатку потрібно імпортувати `List` з модуля стандартної бібліотеки Python `typing`:
+
+{* ../../docs_src/body_nested_models/tutorial002.py hl[1] *}
+
+### Оголошення `list` з параметром типу
+
+Щоб оголосити типи з параметрами типу (внутрішніми типами), такими як `list`, `dict`, `tuple`:
+
+* Якщо Ви використовуєте версію Python до 3.9, імпортуйте їх відповідну версію з модуля `typing`.
+* Передайте внутрішні типи як "параметри типу", використовуючи квадратні дужки: `[` and `]`.
+
+У Python 3.9 це буде виглядати так:
+
+```Python
+my_list: list[str]
+```
+
+У версіях Python до 3.9 це виглядає так:
+
+```Python
+from typing import List
+
+my_list: List[str]
+```
+
+Це стандартний синтаксис Python для оголошення типів.
+
+Використовуйте той самий стандартний синтаксис для атрибутів моделей з внутрішніми типами.
+
+Отже, у нашому прикладі, ми можемо зробити `tags` саме "списком рядків":
+
+{* ../../docs_src/body_nested_models/tutorial002_py310.py hl[12] *}
+
+## Типи множин
+
+Але потім ми подумали, що теги не повинні повторюватися, вони, ймовірно, повинні бути унікальними рядками.
+
+І Python має спеціальний тип даних для множин унікальних елементів — це `set`.
+
+Тому ми можемо оголосити `tags` як множину рядків:
+
+{* ../../docs_src/body_nested_models/tutorial003_py310.py hl[12] *}
+
+Навіть якщо Ви отримаєте запит з дубльованими даними, він буде перетворений у множину унікальних елементів.
+
+І коли Ви будете виводити ці дані, навіть якщо джерело містить дублікати, вони будуть виведені як множина унікальних елементів.
+
+І це буде анотовано/документовано відповідно.
+
+## Вкладені моделі
+
+Кожен атрибут моделі Pydantic має тип.
+
+Але цей тип сам може бути іншою моделлю Pydantic.
+
+Отже, Ви можете оголосити глибоко вкладені JSON "об'єкти" з конкретними іменами атрибутів, типами та перевірками.
+
+Усе це, вкладене без обмежень.
+
+### Визначення підмоделі
+
+Наприклад, ми можемо визначити модель `Image`:
+
+{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[7:9] *}
+
+### Використання підмоделі як типу
+
+А потім ми можемо використовувати її як тип атрибута:
+
+{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[18] *}
+
+Це означатиме, що **FastAPI** очікуватиме тіло запиту такого вигляду:
+
+```JSON
+{
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2,
+ "tags": ["rock", "metal", "bar"],
+ "image": {
+ "url": "http://example.com/baz.jpg",
+ "name": "The Foo live"
+ }
+}
+```
+
+Завдяки такій декларації у **FastAPI** Ви отримуєте:
+
+* Підтримку в редакторі (автозавершення тощо), навіть для вкладених моделей
+* Конвертацію даних
+* Валідацію даних
+* Автоматичну документацію
+
+## Спеціальні типи та валідація
+
+Окрім звичайних типів, таких як `str`, `int`, `float`, та ін. Ви можете використовувати складніші типи, які наслідують `str`.
+
+Щоб побачити всі доступні варіанти, ознайомтеся з оглядом типів у Pydantic. Деякі приклади будуть у наступних розділах.
+
+Наприклад, у моделі `Image` є поле `url`, тому ми можемо оголосити його як `HttpUrl` від Pydantic замість `str`:
+
+{* ../../docs_src/body_nested_models/tutorial005_py310.py hl[2,8] *}
+
+Рядок буде перевірено як дійсну URL-адресу і задокументовано в JSON Schema / OpenAPI як URL.
+
+## Атрибути зі списками підмоделей
+
+У Pydantic Ви можете використовувати моделі як підтипи для `list`, `set` тощо:
+
+{* ../../docs_src/body_nested_models/tutorial006_py310.py hl[18] *}
+
+Це означає, що **FastAPI** буде очікувати (конвертувати, валідувати, документувати тощо) JSON тіло запиту у вигляді:
+
+```JSON hl_lines="11"
+{
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2,
+ "tags": [
+ "rock",
+ "metal",
+ "bar"
+ ],
+ "images": [
+ {
+ "url": "http://example.com/baz.jpg",
+ "name": "The Foo live"
+ },
+ {
+ "url": "http://example.com/dave.jpg",
+ "name": "The Baz"
+ }
+ ]
+}
+```
+
+/// info | Інформація
+
+Зверніть увагу, що тепер ключ `images` містить список об'єктів зображень.
+
+///
+
+## Глибоко вкладені моделі
+
+Ви можете визначати вкладені моделі довільної глибини:
+
+{* ../../docs_src/body_nested_models/tutorial007_py310.py hl[7,12,18,21,25] *}
+
+/// info | Інформація
+
+Зверніть увагу, що в моделі `Offer` є список `Item`ів, які, своєю чергою, можуть мати необов'язковий список `Image`ів.
+
+///
+
+## Тіла запитів, що складаються зі списків
+
+Якщо верхній рівень JSON тіла, яке Ви очікуєте, є JSON `масивом` (у Python — `list`), Ви можете оголосити тип у параметрі функції, як і в моделях Pydantic:
+
+```Python
+images: List[Image]
+```
+або в Python 3.9 і вище:
+
+```Python
+images: list[Image]
+```
+
+наприклад:
+
+{* ../../docs_src/body_nested_models/tutorial008_py39.py hl[13] *}
+
+## Підтримка в редакторі всюди
+
+Ви отримаєте підтримку в редакторі всюди.
+
+Навіть для елементів у списках:
+
+
+
+Ви не змогли б отримати таку підтримку в редакторі, якби працювали напряму зі `dict`, а не з моделями Pydantic.
+
+Але Вам не потрібно турбуватися про це: вхідні dict'и автоматично конвертуються, а вихідні дані автоматично перетворюються в JSON.
+
+## Тіла з довільними `dict`
+
+Ви також можете оголосити тіло як `dict` з ключами одного типу та значеннями іншого типу.
+
+Це корисно, якщо Ви не знаєте наперед, які імена полів будуть дійсними (як у випадку з моделями Pydantic).
+
+Це буде корисно, якщо Ви хочете приймати ключі, які заздалегідь невідомі.
+
+---
+
+Це також зручно, якщо Ви хочете мати ключі іншого типу (наприклад, `int`).
+
+Ось що ми розглянемо далі.
+
+У цьому випадку Ви можете приймати будь-який `dict`, якщо його ключі — це `int`, а значення — `float`:
+
+{* ../../docs_src/body_nested_models/tutorial009_py39.py hl[7] *}
+
+/// tip | Порада
+
+Майте на увазі, що в JSON тілі ключі можуть бути лише рядками (`str`).
+
+Але Pydantic автоматично конвертує дані.
+
+Це означає, що навіть якщо клієнти вашого API надсилатимуть ключі у вигляді рядків, якщо вони містять цілі числа, Pydantic конвертує їх і проведе валідацію.
+
+Тобто `dict`, який Ви отримаєте як `weights`, матиме ключі типу `int` та значення типу `float`.
+
+///
+
+## Підсумок
+
+З **FastAPI** Ви маєте максимальну гнучкість завдяки моделям Pydantic, зберігаючи при цьому код простим, коротким та елегантним.
+
+А також отримуєте всі переваги:
+
+* Підтримка в редакторі (автодоповнення всюди!)
+* Конвертація даних (парсинг/сериалізація)
+* Валідація даних
+* Документація схем
+* Автоматичне створення документації
diff --git a/docs/uk/docs/tutorial/body.md b/docs/uk/docs/tutorial/body.md
index 11e94e929..38fed7bb8 100644
--- a/docs/uk/docs/tutorial/body.md
+++ b/docs/uk/docs/tutorial/body.md
@@ -8,28 +8,21 @@
Щоб оголосити тіло **запиту**, ви використовуєте Pydantic моделі з усією їх потужністю та перевагами.
-!!! info
- Щоб надіслати дані, ви повинні використовувати один із: `POST` (більш поширений), `PUT`, `DELETE` або `PATCH`.
+/// info
- Надсилання тіла із запитом `GET` має невизначену поведінку в специфікаціях, проте воно підтримується FastAPI лише для дуже складних/екстремальних випадків використання.
+Щоб надіслати дані, ви повинні використовувати один із: `POST` (більш поширений), `PUT`, `DELETE` або `PATCH`.
- Оскільки це не рекомендується, інтерактивна документація з Swagger UI не відображатиме документацію для тіла запиту під час використання `GET`, і проксі-сервери в середині можуть не підтримувати її.
+Надсилання тіла із запитом `GET` має невизначену поведінку в специфікаціях, проте воно підтримується FastAPI лише для дуже складних/екстремальних випадків використання.
-## Імпортуйте `BaseModel` від Pydantic
-
-Спочатку вам потрібно імпортувати `BaseModel` з `pydantic`:
+Оскільки це не рекомендується, інтерактивна документація з Swagger UI не відображатиме документацію для тіла запиту під час використання `GET`, і проксі-сервери в середині можуть не підтримувати її.
-=== "Python 3.8 і вище"
+///
- ```Python hl_lines="4"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
+## Імпортуйте `BaseModel` від Pydantic
-=== "Python 3.10 і вище"
+Спочатку вам потрібно імпортувати `BaseModel` з `pydantic`:
- ```Python hl_lines="2"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
+{* ../../docs_src/body/tutorial001.py hl[4] *}
## Створіть свою модель даних
@@ -37,17 +30,7 @@
Використовуйте стандартні типи Python для всіх атрибутів:
-=== "Python 3.8 і вище"
-
- ```Python hl_lines="7-11"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
-
-=== "Python 3.10 і вище"
-
- ```Python hl_lines="5-9"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
+{* ../../docs_src/body/tutorial001.py hl[7:11] *}
Так само, як і при оголошенні параметрів запиту, коли атрибут моделі має значення за замовчуванням, він не є обов’язковим. В іншому випадку це потрібно. Використовуйте `None`, щоб зробити його необов'язковим.
@@ -75,17 +58,7 @@
Щоб додати модель даних до вашої *операції шляху*, оголосіть її так само, як ви оголосили параметри шляху та запиту:
-=== "Python 3.8 і вище"
-
- ```Python hl_lines="18"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
-
-=== "Python 3.10 і вище"
-
- ```Python hl_lines="16"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
+{* ../../docs_src/body/tutorial001.py hl[18] *}
...і вкажіть її тип як модель, яку ви створили, `Item`.
@@ -134,32 +107,25 @@
-!!! tip
- Якщо ви використовуєте PyCharm як ваш редактор, ви можете використати Pydantic PyCharm Plugin.
-
- Він покращує підтримку редакторів для моделей Pydantic за допомогою:
+/// tip
- * автозаповнення
- * перевірки типу
- * рефакторингу
- * пошуку
- * інспекції
+Якщо ви використовуєте PyCharm як ваш редактор, ви можете використати Pydantic PyCharm Plugin.
-## Використовуйте модель
+Він покращує підтримку редакторів для моделей Pydantic за допомогою:
-Усередині функції ви можете отримати прямий доступ до всіх атрибутів об’єкта моделі:
+* автозаповнення
+* перевірки типу
+* рефакторингу
+* пошуку
+* інспекції
-=== "Python 3.8 і вище"
+///
- ```Python hl_lines="21"
- {!> ../../../docs_src/body/tutorial002.py!}
- ```
+## Використовуйте модель
-=== "Python 3.10 і вище"
+Усередині функції ви можете отримати прямий доступ до всіх атрибутів об’єкта моделі:
- ```Python hl_lines="19"
- {!> ../../../docs_src/body/tutorial002_py310.py!}
- ```
+{* ../../docs_src/body/tutorial002.py hl[21] *}
## Тіло запиту + параметри шляху
@@ -167,17 +133,7 @@
**FastAPI** розпізнає, що параметри функції, які відповідають параметрам шляху, мають бути **взяті з шляху**, а параметри функції, які оголошуються як моделі Pydantic, **взяті з тіла запиту**.
-=== "Python 3.8 і вище"
-
- ```Python hl_lines="17-18"
- {!> ../../../docs_src/body/tutorial003.py!}
- ```
-
-=== "Python 3.10 і вище"
-
- ```Python hl_lines="15-16"
- {!> ../../../docs_src/body/tutorial003_py310.py!}
- ```
+{* ../../docs_src/body/tutorial003.py hl[17:18] *}
## Тіло запиту + шлях + параметри запиту
@@ -185,17 +141,7 @@
**FastAPI** розпізнає кожен з них і візьме дані з потрібного місця.
-=== "Python 3.8 і вище"
-
- ```Python hl_lines="18"
- {!> ../../../docs_src/body/tutorial004.py!}
- ```
-
-=== "Python 3.10 і вище"
-
- ```Python hl_lines="16"
- {!> ../../../docs_src/body/tutorial004_py310.py!}
- ```
+{* ../../docs_src/body/tutorial004.py hl[18] *}
Параметри функції будуть розпізнаватися наступним чином:
@@ -203,10 +149,13 @@
* Якщо параметр має **сингулярний тип** (наприклад, `int`, `float`, `str`, `bool` тощо), він буде інтерпретуватися як параметр **запиту**.
* Якщо параметр оголошується як тип **Pydantic моделі**, він інтерпретується як **тіло** запиту.
-!!! note
- FastAPI буде знати, що значення "q" не є обов'язковим через значення за замовчуванням "= None".
+/// note
+
+FastAPI буде знати, що значення "q" не є обов'язковим через значення за замовчуванням "= None".
+
+`Optional` у `Optional[str]` не використовується FastAPI, але дозволить вашому редактору надати вам кращу підтримку та виявляти помилки.
- `Optional` у `Optional[str]` не використовується FastAPI, але дозволить вашому редактору надати вам кращу підтримку та виявляти помилки.
+///
## Без Pydantic
diff --git a/docs/uk/docs/tutorial/cookie-param-models.md b/docs/uk/docs/tutorial/cookie-param-models.md
new file mode 100644
index 000000000..f070b6ac8
--- /dev/null
+++ b/docs/uk/docs/tutorial/cookie-param-models.md
@@ -0,0 +1,76 @@
+# Моделі для Cookie-параметрів
+
+Якщо у Вас є група **cookies** параметрів, які пов'язані між собою, Ви можете створити **Pydantic-модель**, щоб оголосити їх. 🍪
+
+Це дозволить Вам повторно **використовувати модель** у **різних місцях**, а також оголосити валідацію та метадані для всіх параметрів одночасно. 😎
+
+/// note | Нотатки
+
+Це підтримується з версії FastAPI `0.115.0`. 🤓
+
+///
+
+/// tip | Порада
+
+Ця ж техніка застосовується до `Query`, `Cookie`, та `Header`. 😎
+
+///
+
+## Cookie з Pydantic-моделлю
+
+Оголосіть **cookie-параметри**, які Вам потрібні, у **Pydantic-моделі**, а потім оголосіть параметр як `Cookie`:
+
+{* ../../docs_src/cookie_param_models/tutorial001_an_py310.py hl[9:12,16] *}
+
+**FastAPI** буде **витягувати** дані для **кожного поля** з **cookie** параметрів, отриманих у запиті, і передавати Вам Pydantic-модель, яку Ви визначили.
+
+## Перевірка у документації
+
+Ви можете побачити визначені cookie в інтерфейсі документації за адресою `/docs`:
+
+
get
операцію
-!!! info "`@decorator` Додаткова інформація"
- Синтаксис `@something` у Python називається "декоратором".
+/// info | `@decorator` Додаткова інформація
- Ви розташовуєте його над функцією. Як гарний декоративний капелюх (мабуть, звідти походить термін).
+Синтаксис `@something` у Python називається "декоратором".
- "Декоратор" приймає функцію нижче і виконує з нею якусь дію.
+Ви розташовуєте його над функцією. Як гарний декоративний капелюх (мабуть, звідти походить термін).
- У нашому випадку, цей декоратор повідомляє **FastAPI**, що функція нижче відповідає **шляху** `/` і **операції** `get`.
+"Декоратор" приймає функцію нижче і виконує з нею якусь дію.
- Це і є "декоратор операції шляху (path operation decorator)".
+У нашому випадку, цей декоратор повідомляє **FastAPI**, що функція нижче відповідає **шляху** `/` і **операції** `get`.
+
+Це і є "декоратор операції шляху (path operation decorator)".
+
+///
Можна також використовувати операції:
@@ -268,15 +269,17 @@ https://example.com/items/foo
* `@app.patch()`
* `@app.trace()`
-!!! tip "Порада"
- Ви можете використовувати кожну операцію (HTTP-метод) на свій розсуд.
+/// tip | Порада
- **FastAPI** не нав'язує жодного певного значення для кожного методу.
+Ви можете використовувати кожну операцію (HTTP-метод) на свій розсуд.
- Наведена тут інформація є рекомендацією, а не обов'язковою вимогою.
+**FastAPI** не нав'язує жодного певного значення для кожного методу.
- Наприклад, під час використання GraphQL зазвичай усі дії виконуються тільки за допомогою `POST` операцій.
+Наведена тут інформація є рекомендацією, а не обов'язковою вимогою.
+Наприклад, під час використання GraphQL зазвичай усі дії виконуються тільки за допомогою `POST` операцій.
+
+///
### Крок 4: визначте **функцію операції шляху (path operation function)**
@@ -286,9 +289,7 @@ https://example.com/items/foo
* **операція**: це `get`.
* **функція**: це функція, яка знаходиться нижче "декоратора" (нижче `@app.get("/")`).
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[7] *}
Це звичайна функція Python.
@@ -300,18 +301,17 @@ FastAPI викликатиме її щоразу, коли отримає зап
Ви також можете визначити її як звичайну функцію замість `async def`:
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial003.py!}
-```
+{* ../../docs_src/first_steps/tutorial003.py hl[7] *}
+
+/// note | Примітка
-!!! note "Примітка"
- Якщо не знаєте в чому різниця, подивіться [Конкурентність: *"Поспішаєш?"*](../async.md#in-a-hurry){.internal-link target=_blank}.
+Якщо не знаєте в чому різниця, подивіться [Конкурентність: *"Поспішаєш?"*](../async.md#in-a-hurry){.internal-link target=_blank}.
+
+///
### Крок 5: поверніть результат
-```Python hl_lines="8"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[8] *}
Ви можете повернути `dict`, `list`, а також окремі значення `str`, `int`, ітд.
diff --git a/docs/uk/docs/tutorial/handling-errors.md b/docs/uk/docs/tutorial/handling-errors.md
new file mode 100644
index 000000000..12a356cd0
--- /dev/null
+++ b/docs/uk/docs/tutorial/handling-errors.md
@@ -0,0 +1,255 @@
+# Обробка Помилок
+
+Є багато ситуацій, коли потрібно повідомити клієнта, який використовує Ваш API, про помилку.
+
+Цим клієнтом може бути браузер із фронтендом, код іншого розробника, IoT-пристрій тощо.
+
+Можливо, Вам потрібно повідомити клієнта, що:
+
+* У нього недостатньо прав для виконання цієї операції.
+* Він не має доступу до цього ресурсу.
+* Елемент, до якого він намагається отримати доступ, не існує.
+* тощо.
+
+У таких випадках зазвичай повертається **HTTP статус-код** в діапазоні **400** (від 400 до 499).
+
+Це схоже на HTTP статус-коди 200 (від 200 до 299). Ці "200" статус-коди означають, що запит пройшов успішно.
+
+Статус-коди в діапазоні 400 означають, що сталася помилка з боку клієнта.
+
+Пам'ятаєте всі ці помилки **404 Not Found** (і жарти про них)?
+
+## Використання `HTTPException`
+
+Щоб повернути HTTP-відповіді з помилками клієнту, використовуйте `HTTPException`.
+
+### Імпорт `HTTPException`
+
+{* ../../docs_src/handling_errors/tutorial001.py hl[1] *}
+
+### Використання `HTTPException` у коді
+
+`HTTPException` — це звичайна помилка Python із додатковими даними, які стосуються API.
+
+Оскільки це помилка Python, Ви не `повертаєте` його, а `генеруєте` (генеруєте помилку).
+
+Це також означає, що якщо Ви перебуваєте всередині допоміжної функції, яку викликаєте всередині своєї *функції операції шляху*, і там генеруєте `HTTPException`, всередині цієї допоміжної функції, то решта коду в *функції операції шляху* не буде виконана. Запит одразу завершиться, і HTTP-помилка з `HTTPException` буде надіслана клієнту.
+
+Перевага використання `генерації` (raise) помилки замість `повернення` значення (return) стане більш очевидним в розділі про Залежності та Безпеку.
+
+У цьому прикладі, якщо клієнт запитує елемент за ID, якого не існує, буде згенеровано помилку зі статус-кодом `404`:
+
+{* ../../docs_src/handling_errors/tutorial001.py hl[11] *}
+
+### Отримана відповідь
+
+Якщо клієнт робить запит за шляхом `http://example.com/items/foo` (де `item_id` `"foo"`), він отримає статус-код 200 і JSON відповідь:
+
+```JSON
+{
+ "item": "The Foo Wrestlers"
+}
+```
+
+Але якщо клієнт робить запит на `http://example.com/items/bar` (де `item_id` має не існуюче значення `"bar"`), то отримає статус-код 404 (помилка "не знайдено") та відповідь:
+
+```JSON
+{
+ "detail": "Item not found"
+}
+```
+
+/// tip | Порада
+
+Під час виклику `HTTPException` Ви можете передати будь-яке значення, яке може бути перетворене в JSON, як параметр `detail`, а не лише рядок (`str`).
+
+Ви можете передати `dict`, `list` тощо.
+
+Вони обробляються автоматично за допомогою **FastAPI** та перетворюються в JSON.
+
+///
+
+## Додавання власних заголовків
+
+Іноді потрібно додати власні заголовки до HTTP-помилки, наприклад, для певних типів безпеки.
+
+Ймовірно, Вам не доведеться використовувати це безпосередньо у своєму коді.
+
+Але якщо Вам знадобиться це для складного сценарію, Ви можете додати власні заголовки:
+
+{* ../../docs_src/handling_errors/tutorial002.py hl[14] *}
+
+## Встановлення власних обробників помилок
+
+Ви можете додати власні обробники помилок за допомогою тих самих утиліт обробки помилок зі Starlette.
+
+Припустимо, у Вас є власний обʼєкт помилки `UnicornException`, яке Ви (або бібліотека, яку Ви використовуєте) може `згенерувати` (`raise`).
+
+І Ви хочете обробляти це виключення глобально за допомогою FastAPI.
+
+Ви можете додати власний обробник виключень за допомогою `@app.exception_handler()`:
+
+{* ../../docs_src/handling_errors/tutorial003.py hl[5:7,13:18,24] *}
+
+Тут, якщо Ви звернетеся до `/unicorns/yolo`, то згенерується помилка `UnicornException`.
+
+Але вона буде оброблена функцією-обробником `unicorn_exception_handler`.
+
+Отже, Ви отримаєте зрозумілу помилку зі HTTP-статусом `418` і JSON-відповіддю:
+
+```JSON
+{"message": "Oops! yolo did something. There goes a rainbow..."}
+```
+
+/// note | Технічні деталі
+
+Ви також можете використовувати `from starlette.requests import Request` і `from starlette.responses import JSONResponse`.
+
+**FastAPI** надає ті самі `starlette.responses`, що й `fastapi.responses`, просто для зручності розробника. Але більшість доступних відповідей надходять безпосередньо зі Starlette. Те ж саме стосується і `Request`.
+
+///
+
+## Перевизначення обробників помилок за замовчуванням
+
+**FastAPI** має кілька обробників помилок за замовчуванням.
+
+Ці обробники відповідають за повернення стандартних JSON-відповідей, коли Ви `генеруєте` (`raise`) `HTTPException`, а також коли запит містить некоректні дані.
+
+Ви можете перевизначити ці обробники, створивши власні.
+
+### Перевизначення помилок валідації запиту
+
+Коли запит містить некоректні дані, **FastAPI** генерує `RequestValidationError`.
+
+І також включає обробник помилок за замовчуванням для нього.
+
+Щоб перевизначити його, імпортуйте `RequestValidationError` і використовуйте його з `@app.exception_handler(RequestValidationError)` для декорування обробника помилок.
+
+Обробник помилок отримує `Request` і саму помилку.
+
+{* ../../docs_src/handling_errors/tutorial004.py hl[2,14:16] *}
+
+Тепер, якщо Ви перейдете за посиланням `/items/foo`, замість того, щоб отримати стандартну JSON-помилку:
+
+```JSON
+{
+ "detail": [
+ {
+ "loc": [
+ "path",
+ "item_id"
+ ],
+ "msg": "value is not a valid integer",
+ "type": "type_error.integer"
+ }
+ ]
+}
+```
+
+Ви отримаєте текстову версію:
+
+```
+1 validation error
+path -> item_id
+ value is not a valid integer (type=type_error.integer)
+```
+
+#### `RequestValidationError` проти `ValidationError`
+
+/// warning | Увага
+
+Це технічні деталі, які Ви можете пропустити, якщо вони зараз не важливі для Вас.
+
+///
+
+`RequestValidationError` є підкласом Pydantic `ValidationError`.
+
+**FastAPI** використовує його для того, якщо Ви використовуєте модель Pydantic у `response_model` і у ваших даних є помилка, Ви побачили помилку у своєму журналі.
+
+Але клієнт/користувач не побачить її. Натомість клієнт отримає "Internal Server Error" зі статусом HTTP `500`.
+
+Так має бути, якщо у Вас виникла `ValidationError` Pydantic у *відповіді* або деінде у вашому коді (не у *запиті* клієнта), це насправді є помилкою у Вашому коді.
+
+І поки Ви її виправляєте, клієнти/користувачі не повинні мати доступу до внутрішньої інформації про помилку, оскільки це може призвести до вразливості безпеки.
+
+### Перевизначення обробника помилок `HTTPException`
+
+Аналогічно, Ви можете перевизначити обробник `HTTPException`.
+
+Наприклад, Ви можете захотіти повернути текстову відповідь замість JSON для цих помилок:
+
+{* ../../docs_src/handling_errors/tutorial004.py hl[3:4,9:11,22] *}
+
+/// note | Технічні деталі
+
+Ви також можете використовувати `from starlette.responses import PlainTextResponse`.
+
+**FastAPI** надає ті самі `starlette.responses`, що й `fastapi.responses`, просто для зручності розробника. Але більшість доступних відповідей надходять безпосередньо зі Starlette.
+
+///
+
+### Використання тіла `RequestValidationError`
+
+`RequestValidationError` містить `body`, який він отримав із некоректними даними.
+
+Ви можете використовувати це під час розробки свого додатка, щоб логувати тіло запиту та налагоджувати його, повертати користувачеві тощо.
+
+{* ../../docs_src/handling_errors/tutorial005.py hl[14] *}
+
+Тепер спробуйте надіслати некоректний елемент, наприклад:
+
+```JSON
+{
+ "title": "towel",
+ "size": "XL"
+}
+```
+Ви отримаєте відповідь, яка повідомить Вам, які саме дані є некоректні у вашому тілі запиту:
+
+
+```JSON hl_lines="12-15"
+{
+ "detail": [
+ {
+ "loc": [
+ "body",
+ "size"
+ ],
+ "msg": "value is not a valid integer",
+ "type": "type_error.integer"
+ }
+ ],
+ "body": {
+ "title": "towel",
+ "size": "XL"
+ }
+}
+```
+
+#### `HTTPException` FastAPI проти `HTTPException` Starlette
+
+**FastAPI** має власний `HTTPException`.
+
+І клас помилки `HTTPException` в **FastAPI** успадковується від класу помилки `HTTPException` в Starlette.
+
+Єдина різниця полягає в тому, що `HTTPException` в **FastAPI** приймає будь-які дані, які можна перетворити на JSON, для поля `detail`, тоді як `HTTPException` у Starlette приймає тільки рядки.
+
+Отже, Ви можете продовжувати використовувати `HTTPException` в **FastAPI** як зазвичай у своєму коді.
+
+Але коли Ви реєструєте обробник виключень, слід реєструвати його для `HTTPException` зі Starlette.
+
+Таким чином, якщо будь-яка частина внутрішнього коду Starlette або розширення чи плагін Starlette згенерує (raise) `HTTPException`, Ваш обробник зможе перехопити та обробити її.
+
+У цьому прикладі, щоб мати можливість використовувати обидва `HTTPException` в одному коді, помилка Starlette перейменовується на `StarletteHTTPException`:
+
+```Python
+from starlette.exceptions import HTTPException as StarletteHTTPException
+```
+
+### Повторне використання обробників помилок **FastAPI**
+
+Якщо Ви хочете використовувати помилки разом із такими ж обробниками помилок за замовчуванням, як у **FastAPI**, Ви можете імпортувати та повторно використовувати їх із `fastapi.exception_handlers`:
+
+{* ../../docs_src/handling_errors/tutorial006.py hl[2:5,15,21] *}
+
+У цьому прикладі Ви просто використовуєте `print` для виведення дуже інформативного повідомлення, але Ви зрозуміли основну ідею. Ви можете обробити помилку та повторно використовувати обробники помилок за замовчуванням.
diff --git a/docs/uk/docs/tutorial/header-param-models.md b/docs/uk/docs/tutorial/header-param-models.md
new file mode 100644
index 000000000..6f7b0bdae
--- /dev/null
+++ b/docs/uk/docs/tutorial/header-param-models.md
@@ -0,0 +1,58 @@
+# Моделі Параметрів Заголовків
+
+Якщо у Вас є група пов’язаних параметрів заголовків, Ви можете створити **Pydantic модель** для їх оголошення.
+
+Це дозволить Вам повторно **використовувати модель** в **різних місцях**, а також оголосити валідації та метадані для всіх параметрів одночасно. 😎
+
+/// note | Нотатки
+
+Ця можливість підтримується починаючи з версії FastAPI `0.115.0`. 🤓
+
+///
+
+## Параметри Заголовків з Використанням Pydantic Model
+
+Оголосіть потрібні **параметри заголовків** у **Pydantic моделі**, а потім оголосіть параметр як `Header`:
+
+{* ../../docs_src/header_param_models/tutorial001_an_py310.py hl[9:14,18] *}
+
+FastAPI буде витягувати дані для кожного поля з заголовків у запиті та передавати їх у створену Вами Pydantic модель.
+
+**FastAPI** буде **витягувати** дані для **кожного поля** з **заголовків** у запиті та передавати їх у створену Вами Pydantic модель.
+
+## Перевірка в Документації
+
+Ви можете побачити необхідні заголовки в інтерфейсі документації за адресою `/docs`:
+
+contact
поляПараметр | Тип | Опис |
---|---|---|
name | str | Ім'я контактної особи або організації. |
url | str | URL з інформацією для контакту. Повинен бути у форматі URL. |
email | str | Email контактної особи або організації. Повинен бути у форматі електронної пошти. |
license_info
поляПараметр | Тип | Опис |
---|---|---|
name | str | ОБОВ'ЯЗКОВО (якщо встановлено license_info ). Назва ліцензії для API. |
identifier | str | Ліцензійний вираз за SPDX для API. Поле identifier взаємовиключне з полем url . Доступно з OpenAPI 3.1.0, FastAPI 0.99.0. |
url | str | URL до ліцензії, яка використовується для API. Повинен бути у форматі URL. |
kwargs
. Навіть якщо вони не мають значення за замовчуванням.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *}
+
+### Краще з `Annotated`
+
+Майте на увазі, якщо Ви використовуєте `Annotated`, оскільки Ви не використовуєте значення за замовчуванням для параметрів функції, цієї проблеми не виникне, і, швидше за все, Вам не потрібно буде використовувати `*`.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py hl[10] *}
+
+## Валідація числових даних: більше або дорівнює
+
+За допомогою `Query` і `Path` (та інших, які Ви побачите пізніше) можна оголошувати числові обмеження.
+
+Тут, завдяки `ge=1`, `item_id` має бути цілим числом, яке "`g`reater than or `e`qual" (більше або дорівнює) `1`.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py hl[10] *}
+
+## Валідація числових даних: більше ніж і менше або дорівнює
+
+Те саме застосовується до:
+
+* `gt`: `g`reater `t`han (більше ніж)
+* `le`: `l`ess than or `e`qual (менше або дорівнює)
+
+{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py hl[10] *}
+
+## Валідація числових даних: float, більше ніж і менше ніж
+
+Валідація чисел також працює для значень типу `float`.
+
+Ось де стає важливо мати можливість оголошувати gt
, а не тільки ge
. Це дозволяє, наприклад, вимагати, щоб значення було більше `0`, навіть якщо воно менше `1`.
+
+Таким чином, значення `0.5` буде допустимим. Але `0.0` або `0` — ні.
+
+Те саме стосується lt
.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py hl[13] *}
+
+## Підсумок
+
+За допомогою `Query`, `Path` (і інших параметрів, які Ви ще не бачили) можна оголошувати метадані та перевірки рядків, так само як у [Query параметри та валідація рядків](query-params-str-validations.md){.internal-link target=_blank}.
+
+Також можна оголошувати числові перевірки:
+
+* `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` та інші класи, які Ви побачите пізніше, є підкласами спільного класу `Param`.
+
+Всі вони мають однакові параметри для додаткових перевірок і метаданих, які Ви вже бачили.
+
+///
+
+/// note | Технічні деталі
+
+Коли Ви імпортуєте `Query`, `Path` та інші з `fastapi`, насправді це функції.
+
+При виклику вони повертають екземпляри класів з такими ж іменами.
+
+Тобто Ви імпортуєте `Query`, яка є функцією. А коли Ви її викликаєте, вона повертає екземпляр класу, який теж називається `Query`.
+
+Ці функції створені таким чином (замість використання класів напряму), щоб Ваш редактор не відзначав їхні типи як помилки.
+
+Таким чином, Ви можете користуватися своїм звичайним редактором і інструментами для програмування без додаткових налаштувань для ігнорування таких помилок.
+
+///
diff --git a/docs/uk/docs/tutorial/path-params.md b/docs/uk/docs/tutorial/path-params.md
new file mode 100644
index 000000000..e7df1f19a
--- /dev/null
+++ b/docs/uk/docs/tutorial/path-params.md
@@ -0,0 +1,261 @@
+# Path Параметри
+
+Ви можете визначити "параметри" або "змінні" шляху, використовуючи синтаксис форматованих рядків:
+
+{* ../../docs_src/path_params/tutorial001.py hl[6:7] *}
+
+Значення параметра шляху `item_id` передається у функцію як аргумент `item_id`.
+
+Якщо запустити цей приклад та перейти за посиланням http://127.0.0.1:8000/items/foo, то отримаємо таку відповідь:
+
+```JSON
+{"item_id":"foo"}
+```
+
+## Path параметри з типами
+
+Ви можете визначити тип параметра шляху у функції, використовуючи стандартні анотації типів Python:
+
+{* ../../docs_src/path_params/tutorial002.py hl[7] *}
+
+У такому випадку `item_id` визначається як `int`.
+
+/// check | Примітка
+
+Це дасть можливість підтримки редактора всередині функції з перевірками помилок, автодоповнення тощо.
+
+///
+
+## Перетворення даних
+
+Якщо запустити цей приклад і перейти за посиланням http://127.0.0.1:8000/items/3, то отримаєте таку відповідь:
+
+```JSON
+{"item_id":3}
+```
+
+/// check | Примітка
+
+Зверніть увагу, що значення, яке отримала (і повернула) ваша функція, — це `3`. Це Python `int`, а не рядок `"3"`.
+
+Отже, з таким оголошенням типу **FastAPI** автоматично виконує "парсинг" запитів.
+
+///
+
+## Перевірка даних
+
+Якщо ж відкрити у браузері посилання http://127.0.0.1:8000/items/foo, то побачимо цікаву HTTP-помилку:
+
+```JSON
+{
+ "detail": [
+ {
+ "type": "int_parsing",
+ "loc": [
+ "path",
+ "item_id"
+ ],
+ "msg": "Input should be a valid integer, unable to parse string as an integer",
+ "input": "foo",
+ "url": "https://errors.pydantic.dev/2.1/v/int_parsing"
+ }
+ ]
+}
+```
+тому що параметр шляху має значення `"foo"`, яке не є типом `int`.
+
+Таку саму помилку отримаємо, якщо передати `float` замість `int`, як бачимо, у цьому прикладі: http://127.0.0.1:8000/items/4.2
+
+/// check | Примітка
+
+Отже, **FastAPI** надає перевірку типів з таким самим оголошенням типу в Python.
+
+Зверніть увагу, що помилка також чітко вказує саме на те місце, де валідація не пройшла.
+
+Це неймовірно корисно під час розробки та дебагінгу коду, що взаємодіє з вашим API.
+
+///
+
+## Документація
+
+Тепер коли відкриєте свій браузер за посиланням http://127.0.0.1:8000/docs, то побачите автоматично згенеровану, інтерактивну API-документацію:
+
+POST
.
+
+///
+
+/// warning | Увага
+
+Ви можете оголосити кілька параметрів `File` і `Form` в *операції шляху*, але Ви не можете одночасно оголошувати поля `Body`, які мають надходити у форматі JSON, оскільки тіло запиту буде закодоване у форматі `multipart/form-data`, а не `application/json`.
+
+Це не обмеження **FastAPI**, а особливість протоколу HTTP.
+
+///
+
+## Опціональне Завантаження Файлів
+
+Файл можна зробити необов’язковим, використовуючи стандартні анотації типів і встановлюючи значення за замовчуванням `None`:
+
+{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *}
+
+## `UploadFile` із Додатковими Мета Даними
+
+Ви також можете використовувати `File()` разом із `UploadFile`, наприклад, для встановлення додаткових метаданих:
+
+{* ../../docs_src/request_files/tutorial001_03_an_py39.py hl[9,15] *}
+
+## Завантаження Кількох Файлів
+
+Можна завантажувати кілька файлів одночасно.
+
+Вони будуть пов’язані з одним і тим самим "form field", який передається у вигляді "form data".
+
+Щоб це реалізувати, потрібно оголосити список `bytes` або `UploadFile`:
+
+{* ../../docs_src/request_files/tutorial002_an_py39.py hl[10,15] *}
+
+Ви отримаєте, як і було оголошено, `list` із `bytes` або `UploadFile`.
+
+/// note | Технічні деталі
+
+Ви також можете використати `from starlette.responses import HTMLResponse`.
+
+**FastAPI** надає ті ж самі `starlette.responses`, що й `fastapi.responses`, для зручності розробників. Однак більшість доступних відповідей надходять безпосередньо від Starlette.
+
+///
+
+### Завантаження декількох файлів із додатковими метаданими
+
+Так само як і раніше, Ви можете використовувати `File()`, щоб встановити додаткові параметри навіть для `UploadFile`:
+
+{* ../../docs_src/request_files/tutorial003_an_py39.py hl[11,18:20] *}
+
+## Підсумок
+
+Використовуйте `File`, `bytes`та `UploadFile`, щоб оголошувати файли для завантаження у запитах, які надсилаються у вигляді form data.
diff --git a/docs/uk/docs/tutorial/request-form-models.md b/docs/uk/docs/tutorial/request-form-models.md
new file mode 100644
index 000000000..7f5759e79
--- /dev/null
+++ b/docs/uk/docs/tutorial/request-form-models.md
@@ -0,0 +1,78 @@
+# Моделі форм (Form Models)
+
+У FastAPI Ви можете використовувати **Pydantic-моделі** для оголошення **полів форми**.
+
+/// info | Інформація
+
+Щоб використовувати форми, спочатку встановіть python-multipart.
+
+Переконайтеся, що Ви створили [віртуальне середовище](../virtual-environments.md){.internal-link target=_blank}, активували його, а потім встановили бібліотеку, наприклад:
+
+```console
+$ pip install python-multipart
+```
+
+///
+
+/// note | Підказка
+
+Ця функція підтримується, починаючи з FastAPI версії `0.113.0`. 🤓
+
+///
+
+## Використання Pydantic-моделей для форм
+
+Вам просто потрібно оголосити **Pydantic-модель** з полями, які Ви хочете отримати як **поля форми**, а потім оголосити параметр як `Form`:
+
+{* ../../docs_src/request_form_models/tutorial001_an_py39.py hl[9:11,15] *}
+
+**FastAPI** **витягне** дані для **кожного поля** з **формових даних** у запиті та надасть вам Pydantic-модель, яку Ви визначили.
+
+## Перевірка документації
+
+Ви можете перевірити це в UI документації за `/docs`:
+
+POST
.
+
+///
+
+/// warning | Попередження
+
+Ви можете оголосити кілька параметрів `Form` в *операції шляху*, але не можете одночасно оголосити поля `Body`, які Ви очікуєте отримати у форматі JSON, оскільки тіло запиту буде закодовано у форматі `application/x-www-form-urlencoded`, а не `application/json`.
+
+Це не обмеження **FastAPI**, а частина HTTP-протоколу.
+
+///
+
+## Підсумок
+
+Використовуйте `Form` для оголошення вхідних параметрів у вигляді даних форми.
diff --git a/docs/uk/docs/tutorial/response-status-code.md b/docs/uk/docs/tutorial/response-status-code.md
new file mode 100644
index 000000000..1ed69d6f2
--- /dev/null
+++ b/docs/uk/docs/tutorial/response-status-code.md
@@ -0,0 +1,100 @@
+# Статус коди Відповідей
+
+Так само як Ви можете вказати модель відповіді, Ви також можете оголосити HTTP код статусу для відповіді за допомогою параметра `status_code` в будь-якій з *операцій шляху*:
+
+* `@app.get()`
+* `@app.post()`
+* `@app.put()`
+* `@app.delete()`
+* тощо.
+
+{* ../../docs_src/response_status_code/tutorial001.py hl[6] *}
+
+/// note | Нотатка
+
+Зверніть увагу, що `status_code` є параметром методу "декоратора" (`get`, `post` і т.д.), а не Вашої *функції операції шляху*, як усі інші параметри та тіло запиту.
+
+///
+
+Параметр `status_code` приймає число, яке відповідає HTTP коду статусу.
+
+/// info | Інформація
+`status_code` також може отримувати значення з `IntEnum`, наприклад, з Python `http.HTTPStatus`.
+
+///
+
+Він буде:
+
+* Повертати вказаний код статусу у відповіді.
+* Документувати його як такий у схемі OpenAPI (і, таким чином, в інтерфейсі користувача):
+
+
-
+
@@ -93,7 +93,7 @@ Những tính năng như:
"_Thành thật, những gì bạn đã xây dựng nhìn siêu chắc chắn và bóng bẩy. Theo nhiều cách, nó là những gì tôi đã muốn Hug trở thành - thật sự truyền cảm hứng để thấy ai đó xây dựng nó._"
-
+
---
@@ -452,7 +452,7 @@ Independent TechEmpower benchmarks cho thấy các ứng dụng **FastAPI** ch
Sử dụng bởi Pydantic:
-*
email_validator
- cho email validation.
+* email-validator
- cho email validation.
Sử dụng Starlette:
diff --git a/docs/vi/docs/python-types.md b/docs/vi/docs/python-types.md
index 84d14de55..403e89930 100644
--- a/docs/vi/docs/python-types.md
+++ b/docs/vi/docs/python-types.md
@@ -12,16 +12,18 @@ 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
Hãy bắt đầu với một ví dụ đơn giản:
-```Python
-{!../../../docs_src/python_types/tutorial001.py!}
-```
+{* ../../docs_src/python_types/tutorial001.py *}
+
Kết quả khi gọi chương trình này:
@@ -35,9 +37,8 @@ Hàm thực hiện như sau:
* Chuyển đổi kí tự đầu tiên của mỗi biến sang kiểu chữ hoa với `title()`.
* Nối chúng lại với nhau bằng một kí tự trắng ở giữa.
-```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial001.py!}
-```
+{* ../../docs_src/python_types/tutorial001.py hl[2] *}
+
### Sửa đổi
@@ -79,9 +80,8 @@ Chính là nó.
Những thứ đó là "type hints":
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial002.py!}
-```
+{* ../../docs_src/python_types/tutorial002.py hl[1] *}
+
Đó không giống như khai báo những giá trị mặc định giống như:
@@ -109,9 +109,8 @@ Với cái đó, bạn có thể cuộn, nhìn thấy các lựa chọn, cho đ
Kiểm tra hàm này, nó đã có gợi ý kiểu dữ liệu:
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial003.py!}
-```
+{* ../../docs_src/python_types/tutorial003.py hl[1] *}
+
Bởi vì trình soạn thảo biết kiểu dữ liệu của các biến, bạn không chỉ có được completion, bạn cũng được kiểm tra lỗi:
@@ -119,9 +118,8 @@ Bởi vì trình soạn thảo biết kiểu dữ liệu của các biến, bạ
Bây giờ bạn biết rằng bạn phải sửa nó, chuyển `age` sang một xâu với `str(age)`:
-```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial004.py!}
-```
+{* ../../docs_src/python_types/tutorial004.py hl[2] *}
+
## Khai báo các kiểu dữ liệu
@@ -140,9 +138,8 @@ Bạn có thể sử dụng, ví dụ:
* `bool`
* `bytes`
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial005.py!}
-```
+{* ../../docs_src/python_types/tutorial005.py hl[1] *}
+
### Các kiểu dữ liệu tổng quát với tham số kiểu dữ liệu
@@ -170,45 +167,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 (`:`).
+
+Tương tự kiểu dữ liệu `list`.
+
+Như danh sách là một kiểu dữ liệu chứa một vài kiểu dữ liệu có sẵn, bạn đặt chúng trong các dấu ngoặc vuông:
+
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial006_py39.py!}
+```
- Khai báo biến với cùng dấu hai chấm (`:`).
+////
- Tương tự kiểu dữ liệu `list`.
+//// tab | Python 3.8+
- 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:
+Từ `typing`, import `List` (với chữ cái `L` viết hoa):
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial006_py39.py!}
- ```
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial006.py!}
+```
-=== "Python 3.8+"
+Khai báo biến với cùng dấu hai chấm (`:`).
- Từ `typing`, import `List` (với chữ cái `L` viết hoa):
+Tương tự như kiểu dữ liệu, `List` bạn import từ `typing`.
- ```Python hl_lines="1"
- {!> ../../../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:
- Khai báo biến với cùng dấu hai chấm (`:`).
+```Python hl_lines="4"
+{!> ../../docs_src/python_types/tutorial006.py!}
+```
- Tương tự như kiểu dữ liệu, `List` bạn import từ `typing`.
+////
- Như danh sách là một kiểu dữ liệu chứa các kiểu dữ liệu có sẵn, bạn đặt chúng bên trong dấu ngoặc vuông:
+/// info
- ```Python hl_lines="4"
- {!> ../../../docs_src/python_types/tutorial006.py!}
- ```
+Các kiểu dữ liệu có sẵn bên trong dấu ngoặc vuông được gọi là "tham số kiểu dữ liệu".
-!!! info
- 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).
- 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 +231,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+"
+//// 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!}
- ```
+////
Điều này có nghĩa là:
@@ -249,17 +260,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+"
+//// 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!}
- ```
+////
Điều này có nghĩa là:
@@ -278,17 +293,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+"
+//// 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!}
+```
+
+////
Trong cả hai trường hợp có nghĩa là `item` có thể là một `int` hoặc `str`.
@@ -299,7 +318,7 @@ Bạn có thể khai báo một giá trị có thể có một kiểu dữ liệ
Trong Python 3.6 hoặc lớn hơn (bao gồm Python 3.10) bạn có thể khai báo nó bằng các import và sử dụng `Optional` từ mô đun `typing`.
```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009.py!}
+{!../../docs_src/python_types/tutorial009.py!}
```
Sử dụng `Optional[str]` thay cho `str` sẽ cho phép trình soạn thảo giúp bạn phát hiện các lỗi mà bạn có thể gặp như một giá trị luôn là một `str`, trong khi thực tế nó rất có thể là `None`.
@@ -308,23 +327,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!}
+```
+
+////
+
+//// tab | Python 3.8+
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial009_py310.py!}
- ```
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial009.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial009.py!}
- ```
+//// tab | Python 3.8+ alternative
-=== "Python 3.8+ alternative"
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial009b.py!}
+```
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial009b.py!}
- ```
+////
#### Sử dụng `Union` hay `Optional`
@@ -343,9 +368,8 @@ Nó chỉ là về các từ và tên. Nhưng những từ đó có thể ảnh
Cho một ví dụ, hãy để ý hàm này:
-```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009c.py!}
-```
+{* ../../docs_src/python_types/tutorial009c.py hl[1,4] *}
+
Tham số `name` được định nghĩa là `Optional[str]`, nhưng nó **không phải là tùy chọn**, bạn không thể gọi hàm mà không có tham số:
@@ -361,9 +385,8 @@ say_hi(name=None) # This works, None is valid 🎉
Tin tốt là, khi bạn sử dụng Python 3.10, bạn sẽ không phải lo lắng về điều đó, bạn sẽ có thể sử dụng `|` để định nghĩa hợp của các kiểu dữ liệu một cách đơn giản:
-```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009c_py310.py!}
-```
+{* ../../docs_src/python_types/tutorial009c_py310.py hl[1,4] *}
+
Và sau đó, bạn sẽ không phải lo rằng những cái tên như `Optional` và `Union`. 😎
@@ -372,47 +395,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):
+
+* `list`
+* `tuple`
+* `set`
+* `dict`
- 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):
+Và tương tự với Python 3.6, từ mô đun `typing`:
- * `list`
- * `tuple`
- * `set`
- * `dict`
+* `Union`
+* `Optional` (tương tự như Python 3.6)
+* ...và các kiểu dữ liệu khác.
- Và tương tự với Python 3.6, từ mô đun `typing`:
+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.
- * `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.
+//// tab | Python 3.9+
-=== "Python 3.9+"
+Bạn có thể sử dụng các kiểu dữ liệu có sẵn tương tự như (với ngoặc vuông và kiểu dữ liệu bên trong):
- Bạn có thể sử dụng các kiểu dữ liệu có sẵn tương tự như (với ngoặc vuông và kiểu dữ liệu bên trong):
+* `list`
+* `tuple`
+* `set`
+* `dict`
- * `list`
- * `tuple`
- * `set`
- * `dict`
+Và tương tự với Python 3.6, từ mô đun `typing`:
- Và tương tự với Python 3.6, từ mô đun `typing`:
+* `Union`
+* `Optional`
+* ...and others.
- * `Union`
- * `Optional`
- * ...and others.
+////
-=== "Python 3.8+"
+//// tab | Python 3.8+
- * `List`
- * `Tuple`
- * `Set`
- * `Dict`
- * `Union`
- * `Optional`
- * ...và các kiểu khác.
+* `List`
+* `Tuple`
+* `Set`
+* `Dict`
+* `Union`
+* `Optional`
+* ...và các kiểu khác.
+
+////
### Lớp như kiểu dữ liệu
@@ -420,15 +449,13 @@ Bạn cũng có thể khai báo một lớp như là kiểu dữ liệu của m
Hãy nói rằng bạn muốn có một lớp `Person` với một tên:
-```Python hl_lines="1-3"
-{!../../../docs_src/python_types/tutorial010.py!}
-```
+{* ../../docs_src/python_types/tutorial010.py hl[1:3] *}
+
Sau đó bạn có thể khai báo một biến có kiểu là `Person`:
-```Python hl_lines="6"
-{!../../../docs_src/python_types/tutorial010.py!}
-```
+{* ../../docs_src/python_types/tutorial010.py hl[6] *}
+
Và lại một lần nữa, bạn có được tất cả sự hỗ trợ từ trình soạn thảo:
@@ -452,56 +479,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+"
+//// tab | Python 3.9+
+
+```Python
+{!> ../../docs_src/python_types/tutorial011_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python
+{!> ../../docs_src/python_types/tutorial011.py!}
+```
- ```Python
- {!> ../../../docs_src/python_types/tutorial011_py39.py!}
- ```
+////
-=== "Python 3.8+"
+/// info
- ```Python
- {!> ../../../docs_src/python_types/tutorial011.py!}
- ```
+Để học nhiều hơn về Pydantic, tham khảo tài liệu của nó.
-!!! 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+"
+//// tab | Python 3.8+
- Ở phiên bản dưới Python 3.9, bạn import `Annotated` từ `typing_extensions`.
+Ở phiên bản dưới Python 3.9, bạn import `Annotated` từ `typing_extensions`.
- Nó đã được cài đặt sẵng cùng với **FastAPI**.
+Nó đã được cài đặt sẵng cùng với **FastAPI**.
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial013.py!}
- ```
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial013.py!}
+```
+
+////
Python bản thân nó không làm bất kì điều gì với `Annotated`. Với các trình soạn thảo và các công cụ khác, kiểu dữ liệu vẫn là `str`.
@@ -514,10 +556,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
+
+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. 🚀
- 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 +586,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..901c8fd59 100644
--- a/docs/vi/docs/tutorial/first-steps.md
+++ b/docs/vi/docs/tutorial/first-steps.md
@@ -2,9 +2,7 @@
Tệp tin FastAPI đơn giản nhất có thể trông như này:
-```Python
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py *}
Sao chép sang một tệp tin `main.py`.
@@ -24,12 +22,15 @@ $ uvicorn main:app --reload
-!!! note
- Câu lệnh `uvicorn main:app` được giải thích như sau:
+/// note
+
+Câu lệnh `uvicorn main:app` được giải thích như sau:
+
+* `main`: tệp tin `main.py` (một Python "mô đun").
+* `app`: một object được tạo ra bên trong `main.py` với dòng `app = FastAPI()`.
+* `--reload`: làm server khởi động lại sau mỗi lần thay đổi. Chỉ sử dụng trong môi trường phát triển.
- * `main`: tệp tin `main.py` (một Python "mô đun").
- * `app`: một object được tạo ra bên trong `main.py` với dòng `app = FastAPI()`.
- * `--reload`: làm server khởi động lại sau mỗi lần thay đổi. Chỉ sử dụng trong môi trường phát triển.
+///
Trong output, có một dòng giống như:
@@ -130,22 +131,21 @@ Bạn cũng có thể sử dụng nó để sinh code tự động, với các c
### Bước 1: import `FastAPI`
-```Python hl_lines="1"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[1] *}
`FastAPI` là một Python class cung cấp tất cả chức năng cho API của bạn.
-!!! note "Chi tiết kĩ thuật"
- `FastAPI` là một class kế thừa trực tiếp `Starlette`.
+/// note | Chi tiết kĩ thuật
+
+`FastAPI` là một class kế thừa trực tiếp `Starlette`.
- Bạn cũng có thể sử dụng tất cả Starlette chức năng với `FastAPI`.
+Bạn cũng có thể sử dụng tất cả Starlette chức năng với `FastAPI`.
+
+///
### Bước 2: Tạo một `FastAPI` "instance"
-```Python hl_lines="3"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[3] *}
Biến `app` này là một "instance" của class `FastAPI`.
@@ -165,9 +165,7 @@ $ uvicorn main:app --reload
Nếu bạn tạo ứng dụng của bạn giống như:
-```Python hl_lines="3"
-{!../../../docs_src/first_steps/tutorial002.py!}
-```
+{* ../../docs_src/first_steps/tutorial002.py hl[3] *}
Và đặt nó trong một tệp tin `main.py`, sau đó bạn sẽ gọi `uvicorn` giống như:
@@ -199,8 +197,11 @@ https://example.com/items/foo
/items/foo
```
-!!! info
- Một đường dẫn cũng là một cách gọi chung cho một "endpoint" hoặc một "route".
+/// info
+
+Một đường dẫn cũng là một cách gọi chung cho một "endpoint" hoặc một "route".
+
+///
Trong khi xây dựng một API, "đường dẫn" là các chính để phân tách "mối quan hệ" và "tài nguyên".
@@ -241,25 +242,26 @@ Chúng ta cũng sẽ gọi chúng là "**các toán tử**".
#### Định nghĩa moojt *decorator cho đường dẫn toán tử*
-```Python hl_lines="6"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[6] *}
`@app.get("/")` nói **FastAPI** rằng hàm bên dưới có trách nhiệm xử lí request tới:
* đường dẫn `/`
* sử dụng một toán tử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`"
+
+Cú pháp `@something` trong Python được gọi là một "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).
- 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).
+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ó.
- 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ó.
+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`.
- 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ử**".
- 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 +276,17 @@ Và nhiều hơn với các toán tử còn lại:
* `@app.patch()`
* `@app.trace()`
-!!! tip
- Bạn thoải mái sử dụng mỗi toán tử (phương thức HTTP) như bạn mơ ước.
+/// tip
+
+Bạn thoải mái sử dụng mỗi toán tử (phương thức HTTP) như bạn mơ ước.
+
+**FastAPI** không bắt buộc bất kì ý nghĩa cụ thể nào.
- **FastAPI** không bắt buộc bất kì ý nghĩa cụ thể nào.
+Thông tin ở đây được biểu thị như là một chỉ dẫn, không phải là một yêu cầu bắt buộc.
- Thông tin ở đây được biểu thị như là một chỉ dẫn, không phải là một yêu cầu bắt buộc.
+Ví dụ, khi sử dụng GraphQL bạn thông thường thực hiện tất cả các hành động chỉ bằng việc sử dụng các toán tử `POST`.
- Ví dụ, khi sử dụng GraphQL bạn thông thường thực hiện tất cả các hành động chỉ bằng việc sử dụng các toán tử `POST`.
+///
### Step 4: Định nghĩa **hàm cho đường dẫn toán tử**
@@ -291,9 +296,7 @@ Và nhiều hơn với các toán tử còn lại:
* **toán tử**: là `get`.
* **hàm**: là hàm bên dưới "decorator" (bên dưới `@app.get("/")`).
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[7] *}
Đây là một hàm Python.
@@ -305,18 +308,17 @@ Trong trường hợp này, nó là một hàm `async`.
Bạn cũng có thể định nghĩa nó như là một hàm thông thường thay cho `async def`:
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial003.py!}
-```
+{* ../../docs_src/first_steps/tutorial003.py hl[7] *}
+
+/// note
-!!! 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}.
+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ề
-```Python hl_lines="8"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[8] *}
Bạn có thể trả về một `dict`, `list`, một trong những giá trị đơn như `str`, `int`,...
diff --git a/docs/vi/docs/tutorial/index.md b/docs/vi/docs/tutorial/index.md
index e8a93fe40..dfeeed8c5 100644
--- a/docs/vi/docs/tutorial/index.md
+++ b/docs/vi/docs/tutorial/index.md
@@ -52,22 +52,25 @@ $ pip install "fastapi[all]"
...dó cũng bao gồm `uvicorn`, bạn có thể sử dụng như một server để chạy code của bạn.
-!!! note
- Bạn cũng có thể cài đặt nó từng phần.
+/// note
- Đây là những gì bạn có thể sẽ làm một lần duy nhất bạn muốn triển khai ứng dụng của bạn lên production:
+Bạn cũng có thể cài đặt nó từng phần.
- ```
- pip install fastapi
- ```
+Đây là những gì bạn có thể sẽ làm một lần duy nhất bạn muốn triển khai ứng dụng của bạn lên production:
- Cũng cài đặt `uvicorn` để làm việc như một server:
+```
+pip install fastapi
+```
+
+Cũng cài đặt `uvicorn` để làm việc như một server:
+
+```
+pip install "uvicorn[standard]"
+```
- ```
- pip install "uvicorn[standard]"
- ```
+Và tương tự với từng phụ thuộc tùy chọn mà bạn muốn sử dụng.
- Và tương tự với từng phụ thuộc tùy chọn mà bạn muốn sử dụng.
+///
## Hướng dẫn nâng cao
diff --git a/docs/vi/docs/tutorial/static-files.md b/docs/vi/docs/tutorial/static-files.md
new file mode 100644
index 000000000..ecf8c2485
--- /dev/null
+++ b/docs/vi/docs/tutorial/static-files.md
@@ -0,0 +1,40 @@
+# Tệp tĩnh (Static Files)
+
+Bạn có thể triển khai tệp tĩnh tự động từ một thư mục bằng cách sử dụng StaticFiles.
+
+## Sử dụng `Tệp tĩnh`
+
+- Nhập `StaticFiles`.
+- "Mount" a `StaticFiles()` instance in a specific path.
+
+{* ../../docs_src/static_files/tutorial001.py hl[2,6] *}
+
+/// note | Chi tiết kỹ thuật
+
+Bạn cũng có thể sử dụng `from starlette.staticfiles import StaticFiles`.
+
+**FastAPI** cung cấp cùng `starlette.staticfiles` như `fastapi.staticfiles` giúp đơn giản hóa việc sử dụng, nhưng nó thực sự đến từ Starlette.
+
+///
+
+### "Mounting" là gì
+
+"Mounting" có nghĩa là thêm một ứng dụng "độc lập" hoàn chỉnh vào một đường dẫn cụ thể, sau đó ứng dụng đó sẽ chịu trách nhiệm xử lý tất cả các đường dẫn con.
+
+Điều này khác với việc sử dụng `APIRouter` vì một ứng dụng được gắn kết là hoàn toàn độc lập. OpenAPI và tài liệu từ ứng dụng chính của bạn sẽ không bao gồm bất kỳ thứ gì từ ứng dụng được gắn kết, v.v.
+
+Bạn có thể đọc thêm về điều này trong [Hướng dẫn Người dùng Nâng cao](../advanced/index.md){.internal-link target=\_blank}.
+
+## Chi tiết
+
+Đường dẫn đầu tiên `"/static"` là đường dẫn con mà "ứng dụng con" này sẽ được "gắn" vào. Vì vậy, bất kỳ đường dẫn nào bắt đầu bằng `"/static"` sẽ được xử lý bởi nó.
+
+Đường dẫn `directory="static"` là tên của thư mục chứa tệp tĩnh của bạn.
+
+Tham số `name="static"` đặt tên cho nó để có thể được sử dụng bên trong **FastAPI**.
+
+Tất cả các tham số này có thể khác với `static`, điều chỉnh chúng với phù hợp với ứng dụng của bạn.
+
+## Thông tin thêm
+
+Để biết thêm chi tiết và tùy chọn, hãy xem Starlette's docs about Static Files.
diff --git a/docs/vi/docs/virtual-environments.md b/docs/vi/docs/virtual-environments.md
new file mode 100644
index 000000000..22d8e153e
--- /dev/null
+++ b/docs/vi/docs/virtual-environments.md
@@ -0,0 +1,842 @@
+# Môi trường ảo (Virtual Environments)
+
+Khi bạn làm việc trong các dự án Python, bạn có thể sử dụng một **môi trường ảo** (hoặc một cơ chế tương tự) để cách ly các gói bạn cài đặt cho mỗi dự án.
+
+/// info
+Nếu bạn đã biết về các môi trường ảo, cách tạo chúng và sử dụng chúng, bạn có thể bỏ qua phần này. 🤓
+
+///
+
+/// tip
+
+Một **môi trường ảo** khác với một **biến môi trường (environment variable)**.
+
+Một **biến môi trường** là một biến trong hệ thống có thể được sử dụng bởi các chương trình.
+
+Một **môi trường ảo** là một thư mục với một số tệp trong đó.
+
+///
+
+/// info
+
+Trang này sẽ hướng dẫn bạn cách sử dụng các **môi trường ảo** và cách chúng hoạt động.
+
+Nếu bạn đã sẵn sàng sử dụng một **công cụ có thể quản lý tất cả mọi thứ** cho bạn (bao gồm cả việc cài đặt Python), hãy thử uv.
+
+///
+
+## Tạo một Dự án
+
+Đầu tiên, tạo một thư mục cho dự án của bạn.
+
+Cách tôi thường làm là tạo một thư mục có tên `code` trong thư mục `home/user`.
+
+Và trong thư mục đó, tôi tạo một thư mục cho mỗi dự án.
+
+
-
+
@@ -93,7 +93,7 @@ FastAPI jẹ́ ìgbàlódé, tí ó yára (iṣẹ-giga), ìlànà wẹ́ẹ́b
"_Ní tòótọ́, ohun tí o kọ dára ó sì tún dán. Ní ọ̀pọ̀lọpọ̀ ọ̀nà, ohun tí mo fẹ́ kí **Hug** jẹ́ nìyẹn - ó wúni lórí gan-an láti rí ẹnìkan tí ó kọ́ nǹkan bí èyí._"
-
+
---
@@ -449,7 +449,7 @@ Láti ní òye síi nípa rẹ̀, wo abala àwọn
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.
diff --git a/docs/zh-hant/docs/about/index.md b/docs/zh-hant/docs/about/index.md
new file mode 100644
index 000000000..5dcee68f2
--- /dev/null
+++ b/docs/zh-hant/docs/about/index.md
@@ -0,0 +1,3 @@
+# 關於 FastAPI
+
+關於 FastAPI、其設計、靈感來源等更多資訊。 🤓
diff --git a/docs/zh-hant/docs/async.md b/docs/zh-hant/docs/async.md
new file mode 100644
index 000000000..6ab75d2ab
--- /dev/null
+++ b/docs/zh-hant/docs/async.md
@@ -0,0 +1,442 @@
+# 並行與 async / await
+
+有關*路徑操作函式*的 `async def` 語法的細節與非同步 (asynchronous) 程式碼、並行 (concurrency) 與平行 (parallelism) 的一些背景知識。
+
+## 趕時間嗎?
+
+TL;DR:
+
+如果你正在使用要求你以 `await` 語法呼叫的第三方函式庫,例如:
+
+```Python
+results = await some_library()
+```
+
+然後,使用 `async def` 宣告你的*路徑操作函式*:
+
+
+```Python hl_lines="2"
+@app.get('/')
+async def read_results():
+ results = await some_library()
+ return results
+```
+
+/// note | 注意
+
+你只能在 `async def` 建立的函式內使用 `await`。
+
+///
+
+---
+
+如果你使用的是第三方函式庫並且它需要與某些外部資源(例如資料庫、API、檔案系統等)進行通訊,但不支援 `await`(目前大多數資料庫函式庫都是這樣),在這種情況下,你可以像平常一樣使用 `def` 宣告*路徑操作函式*,如下所示:
+
+```Python hl_lines="2"
+@app.get('/')
+def results():
+ results = some_library()
+ return results
+```
+
+---
+
+如果你的應用程式不需要與外部資源進行任何通訊並等待其回應,請使用 `async def`。
+
+---
+
+如果你不確定該用哪個,直接用 `def` 就好。
+
+---
+
+**注意**:你可以在*路徑操作函式*中混合使用 `def` 和 `async def` ,並使用最適合你需求的方式來定義每個函式。FastAPI 會幫你做正確的處理。
+
+無論如何,在上述哪種情況下,FastAPI 仍將以非同步方式運行,並且速度非常快。
+
+但透過遵循上述步驟,它將能進行一些效能最佳化。
+
+## 技術細節
+
+現代版本的 Python 支援使用 **「協程」** 的 **`async` 和 `await`** 語法來寫 **「非同步程式碼」**。
+
+接下來我們逐一介紹:
+
+* **非同步程式碼**
+* **`async` 和 `await`**
+* **協程**
+
+## 非同步程式碼
+
+非同步程式碼僅意味著程式語言 💬 有辦法告訴電腦/程式 🤖 在程式碼中的某個點,它 🤖 需要等待某些事情完成。讓我們假設這些事情被稱為「慢速檔案」📝。
+
+因此,在等待「慢速檔案」📝 完成的這段時間,電腦可以去處理一些其他工作。
+
+接著程式 🤖 會在有空檔時回來查看是否有等待的工作已經完成,並執行必要的後續操作。
+
+接下來,它 🤖 完成第一個工作(例如我們的「慢速檔案」📝)並繼續執行相關的所有操作。
+這個「等待其他事情」通常指的是一些相對較慢的(與處理器和 RAM 記憶體的速度相比)的 I/O 操作,比如說:
+
+* 透過網路傳送來自用戶端的資料
+* 從網路接收來自用戶端的資料
+* 從磁碟讀取檔案內容
+* 將內容寫入磁碟
+* 遠端 API 操作
+* 資料庫操作
+* 資料庫查詢
+* 等等
+
+由於大部分的執行時間都消耗在等待 I/O 操作上,因此這些操作被稱為 "I/O 密集型" 操作。
+
+之所以稱為「非同步」,是因為電腦/程式不需要與那些耗時的任務「同步」,等待任務完成的精確時間,然後才能取得結果並繼續工作。
+
+相反地,非同步系統在任務完成後,可以讓任務稍微等一下(幾微秒),等待電腦/程式完成手頭上的其他工作,然後再回來取得結果繼續進行。
+
+相對於「非同步」(asynchronous),「同步」(synchronous)也常被稱作「順序性」(sequential),因為電腦/程式會依序執行所有步驟,即便這些步驟涉及等待,才會切換到其他任務。
+
+### 並行與漢堡
+
+上述非同步程式碼的概念有時也被稱為「並行」,它不同於「平行」。
+
+並行和平行都與 "不同的事情或多或少同時發生" 有關。
+
+但並行和平行之間的細節是完全不同的。
+
+為了理解差異,請想像以下有關漢堡的故事:
+
+### 並行漢堡
+
+你和你的戀人去速食店,排隊等候時,收銀員正在幫排在你前面的人點餐。😍
+
+
+
+輪到你了,你給你與你的戀人點了兩個豪華漢堡。🍔🍔
+
+
+
+收銀員通知廚房準備你的漢堡(儘管他們還在為前面其他顧客準備食物)。
+
+
+
+之後你完成付款。💸
+
+收銀員給你一個號碼牌。
+
+
+
+在等待漢堡的同時,你可以與戀人選一張桌子,然後坐下來聊很長一段時間(因為漢堡十分豪華,準備特別費工。)
+
+這段時間,你還能欣賞你的戀人有多麼的可愛、聰明與迷人。✨😍✨
+
+
+
+當你和戀人邊聊天邊等待時,你會不時地查看櫃檯上的顯示的號碼,確認是否已經輪到你了。
+
+然後在某個時刻,終於輪到你了。你走到櫃檯,拿了漢堡,然後回到桌子上。
+
+
+
+你和戀人享用這頓大餐,整個過程十分開心✨
+
+
+
+/// info
+
+漂亮的插畫來自 Ketrina Thompson. 🎨
+
+///
+
+---
+
+想像你是故事中的電腦或程式 🤖。
+
+當你排隊時,你在放空😴,等待輪到你,沒有做任何「生產性」的事情。但這沒關係,因為收銀員只是接單(而不是準備食物),所以排隊速度很快。
+
+然後,當輪到你時,你開始做真正「有生產力」的工作,處理菜單,決定你想要什麼,替戀人選擇餐點,付款,確認你給了正確的帳單或信用卡,檢查你是否被正確收費,確認訂單中的項目是否正確等等。
+
+但是,即使你還沒有拿到漢堡,你與收銀員的工作已經「暫停」了 ⏸,因為你必須等待 🕙 漢堡準備好。
+
+但當你離開櫃檯,坐到桌子旁,拿著屬於你的號碼等待時,你可以把注意力 🔀 轉移到戀人身上,並開始「工作」⏯ 🤓——也就是和戀人調情 😍。這時你又開始做一些非常「有生產力」的事情。
+
+接著,收銀員 💁 將你的號碼顯示在櫃檯螢幕上,並告訴你「漢堡已經做好了」。但你不會瘋狂地立刻跳起來,因為顯示的號碼變成了你的。你知道沒有人會搶走你的漢堡,因為你有自己的號碼,他們也有他們的號碼。
+
+所以你會等戀人講完故事(完成當前的工作 ⏯/正在進行的任務 🤓),然後微笑著溫柔地說你要去拿漢堡了 ⏸。
+
+然後你走向櫃檯 🔀,回到已經完成的最初任務 ⏯,拿起漢堡,說聲謝謝,並帶回桌上。這就結束了與櫃檯的互動步驟/任務 ⏹,接下來會產生一個新的任務,「吃漢堡」 🔀 ⏯,而先前的「拿漢堡」任務已經完成了 ⏹。
+
+### 平行漢堡
+
+現在,讓我們來想像這裡不是「並行漢堡」,而是「平行漢堡」。
+
+你和戀人一起去吃平行的速食餐。
+
+你們站在隊伍中,前面有幾位(假設有 8 位)既是收銀員又是廚師的員工,他們同時接單並準備餐點。
+
+所有排在你前面的人都在等著他們的漢堡準備好後才會離開櫃檯,因為每位收銀員在接完單後,馬上會去準備漢堡,然後才回來處理下一個訂單。
+
+
+
+終於輪到你了,你為你和你的戀人點了兩個非常豪華的漢堡。
+
+你付款了 💸。
+
+
+
+收銀員走進廚房準備食物。
+
+你站在櫃檯前等待 🕙,以免其他人先拿走你的漢堡,因為這裡沒有號碼牌系統。
+
+
+
+由於你和戀人都忙著不讓別人搶走你的漢堡,等漢堡準備好時,你根本無法專心和戀人互動。😞
+
+這是「同步」(synchronous)工作,你和收銀員/廚師 👨🍳 是「同步化」的。你必須等到 🕙 收銀員/廚師 👨🍳 完成漢堡並交給你的那一刻,否則別人可能會拿走你的餐點。
+
+
+
+最終,經過長時間的等待 🕙,收銀員/廚師 👨🍳 拿著漢堡回來了。
+
+
+
+你拿著漢堡,和你的戀人回到餐桌。
+
+你們僅僅是吃完漢堡,然後就結束了。⏹
+
+
+
+整個過程中沒有太多的談情說愛,因為大部分時間 🕙 都花在櫃檯前等待。😞
+
+/// info
+
+漂亮的插畫來自 Ketrina Thompson. 🎨
+
+///
+
+---
+
+在這個平行漢堡的情境下,你是一個程式 🤖 且有兩個處理器(你和戀人),兩者都在等待 🕙 並專注於等待櫃檯上的餐點 🕙,等待的時間非常長。
+
+這家速食店有 8 個處理器(收銀員/廚師)。而並行漢堡店可能只有 2 個處理器(一位收銀員和一位廚師)。
+
+儘管如此,最終的體驗並不是最理想的。😞
+
+---
+
+這是與漢堡類似的故事。🍔
+
+一個更「現實」的例子,想像一間銀行。
+
+直到最近,大多數銀行都有多位出納員 👨💼👨💼👨💼👨💼,以及一條長長的隊伍 🕙🕙🕙🕙🕙🕙🕙🕙。
+
+所有的出納員都在一個接一個地滿足每位客戶的所有需求 👨💼⏯。
+
+你必須長時間排隊 🕙,不然就會失去機會。
+
+所以,你不會想帶你的戀人 😍 一起去銀行辦事 🏦。
+
+### 漢堡結論
+
+在「和戀人一起吃速食漢堡」的這個場景中,由於有大量的等待 🕙,使用並行系統 ⏸🔀⏯ 更有意義。
+
+這也是大多數 Web 應用的情況。
+
+許多用戶正在使用你的應用程式,而你的伺服器則在等待 🕙 這些用戶不那麼穩定的網路來傳送請求。
+
+接著,再次等待 🕙 回應。
+
+這種「等待」 🕙 通常以微秒來衡量,但累加起來,最終還是花費了很多等待時間。
+
+這就是為什麼對於 Web API 來說,使用非同步程式碼 ⏸🔀⏯ 是非常有意義的。
+
+這種類型的非同步性正是 NodeJS 成功的原因(儘管 NodeJS 不是平行的),這也是 Go 語言作為程式語言的一個強大優勢。
+
+這與 **FastAPI** 所能提供的性能水平相同。
+
+你可以同時利用並行性和平行性,進一步提升效能,這比大多數已測試的 NodeJS 框架都更快,並且與 Go 語言相當,而 Go 是一種更接近 C 的編譯語言(感謝 Starlette)。
+
+### 並行比平行更好嗎?
+
+不是的!這不是故事的本意。
+
+並行與平行不同。並行在某些 **特定** 的需要大量等待的情境下表現更好。正因如此,並行在 Web 應用程式開發中通常比平行更有優勢。但並不是所有情境都如此。
+
+因此,為了平衡報導,想像下面這個短故事
+
+> 你需要打掃一間又大又髒的房子。
+
+*是的,這就是全部的故事。*
+
+---
+
+這裡沒有任何需要等待 🕙 的地方,只需要在房子的多個地方進行大量的工作。
+
+你可以像漢堡的例子那樣輪流進行,先打掃客廳,再打掃廚房,但由於你不需要等待 🕙 任何事情,只需要持續地打掃,輪流並不會影響任何結果。
+
+無論輪流執行與否(並行),你都需要相同的工時完成任務,同時需要執行相同工作量。
+
+但是,在這種情境下,如果你可以邀請8位前收銀員/廚師(現在是清潔工)來幫忙,每個人(加上你)負責房子的某個區域,這樣你就可以 **平行** 地更快完成工作。
+
+在這個場景中,每個清潔工(包括你)都是一個處理器,完成工作的一部分。
+
+由於大多數的執行時間都花在實際的工作上(而不是等待),而電腦中的工作由 CPU 完成,因此這些問題被稱為「CPU 密集型」。
+
+---
+
+常見的 CPU 密集型操作範例包括那些需要進行複雜數學計算的任務。
+
+例如:
+
+* **音訊**或**圖像處理**;
+* **電腦視覺**:一張圖片由數百萬個像素組成,每個像素有 3 個值/顏色,處理這些像素通常需要同時進行大量計算;
+* **機器學習**: 通常需要大量的「矩陣」和「向量」運算。想像一個包含數字的巨大電子表格,並所有的數字同時相乘;
+* **深度學習**: 這是機器學習的子領域,同樣適用。只不過這不僅僅是一張數字表格,而是大量的數據集合,並且在很多情況下,你會使用特殊的處理器來構建或使用這些模型。
+
+### 並行 + 平行: Web + 機器學習
+
+使用 **FastAPI**,你可以利用並行的優勢,這在 Web 開發中非常常見(這也是 NodeJS 的最大吸引力)。
+
+但你也可以利用平行與多行程 (multiprocessing)(讓多個行程同時運行) 的優勢來處理機器學習系統中的 **CPU 密集型**工作。
+
+這一點,再加上 Python 是 **資料科學**、機器學習,尤其是深度學習的主要語言,讓 **FastAPI** 成為資料科學/機器學習 Web API 和應用程式(以及許多其他應用程式)的絕佳選擇。
+
+想了解如何在生產環境中實現這種平行性,請參見 [部屬](deployment/index.md){.internal-link target=_blank}。
+
+## `async` 和 `await`
+
+現代 Python 版本提供一種非常直觀的方式定義非同步程式碼。這使得它看起來就像正常的「順序」程式碼,並在適當的時機「等待」。
+
+當某個操作需要等待才能回傳結果,並且支援這些新的 Python 特性時,你可以像這樣編寫程式碼:
+
+```Python
+burgers = await get_burgers(2)
+```
+
+這裡的關鍵是 `await`。它告訴 Python 必須等待 ⏸ `get_burgers(2)` 完成它的工作 🕙, 然後將結果儲存在 `burgers` 中。如此,Python 就可以在此期間去處理其他事情 🔀 ⏯ (例如接收另一個請求)。
+
+要讓 `await` 運作,它必須位於支持非同步功能的函式內。為此,只需使用 `async def` 宣告函式:
+
+```Python hl_lines="1"
+async def get_burgers(number: int):
+ # Do some asynchronous stuff to create the burgers
+ return burgers
+```
+
+...而不是 `def`:
+
+```Python hl_lines="2"
+# This is not asynchronous
+def get_sequential_burgers(number: int):
+ # Do some sequential stuff to create the burgers
+ return burgers
+```
+
+使用 `async def`,Python Python 知道在該函式內需要注意 `await`,並且它可以「暫停」 ⏸ 執行該函式,然後執行其他任務 🔀 後回來。
+
+當你想要呼叫 `async def` 函式時,必須使用「await」。因此,這樣寫將無法運行:
+
+```Python
+# This won't work, because get_burgers was defined with: async def
+burgers = get_burgers(2)
+```
+
+---
+
+如果你正在使用某個函式庫,它告訴你可以使用 `await` 呼叫它,那麼你需要用 `async def` 定義*路徑操作函式*,如:
+
+```Python hl_lines="2-3"
+@app.get('/burgers')
+async def read_burgers():
+ burgers = await get_burgers(2)
+ return burgers
+```
+
+### 更多技術細節
+
+你可能已經注意到,`await` 只能在 `async def` 定義的函式內使用。
+
+但同時,使用 `async def` 定義的函式本身也必須被「等待」。所以,帶有 `async def` 函式只能在其他使用 `async def` 定義的函式內呼叫。
+
+那麼,這就像「先有雞還是先有蛋」的問題,要如何呼叫第一個 `async` 函式呢?
+
+如果你使用 FastAPI,無需擔心這個問題,因為「第一個」函式將是你的*路徑操作函式*,FastAPI 會知道如何正確處理這個問題。
+
+但如果你想在沒有 FastAPI 的情況下使用 `async` / `await`,你也可以這樣做。
+
+### 編寫自己的非同步程式碼
+
+Starlette (和 **FastAPI**) 是基於 AnyIO 實作的,這使得它們與 Python 標準函式庫相容 asyncio 和 Trio。
+
+特別是,你可以直接使用 AnyIO 來處理更複雜的並行使用案例,這些案例需要你在自己的程式碼中使用更高階的模式。
+
+即使你不使用 **FastAPI**,你也可以使用 AnyIO 來撰寫自己的非同步應用程式,並獲得高相容性及一些好處(例如結構化並行)。
+
+### 其他形式的非同步程式碼
+
+使用 `async` 和 `await` 的風格在語言中相對較新。
+
+但它使處理異步程式碼變得更加容易。
+
+相同的語法(或幾乎相同的語法)最近也被包含在現代 JavaScript(無論是瀏覽器還是 NodeJS)中。
+
+但在此之前,處理異步程式碼要更加複雜和困難。
+
+在較舊的 Python 版本中,你可能會使用多執行緒或 Gevent。但這些程式碼要更難以理解、調試和思考。
+
+在較舊的 NodeJS / 瀏覽器 JavaScript 中,你會使用「回呼」,這可能會導致回呼地獄。
+
+## 協程
+
+**協程** 只是 `async def` 函式所回傳的非常特殊的事物名稱。Python 知道它是一個類似函式的東西,可以啟動它,並且在某個時刻它會結束,但它也可能在內部暫停 ⏸,只要遇到 `await`。
+
+這種使用 `async` 和 `await` 的非同步程式碼功能通常被概括為「協程」。這與 Go 語言的主要特性「Goroutines」相似。
+
+## 結論
+
+讓我們再次回顧之前的句子:
+
+> 現代版本的 Python 支持使用 **"協程"** 的 **`async` 和 `await`** 語法來寫 **"非同步程式碼"**。
+
+現在應該能明白其含意了。✨
+
+這些就是驅動 FastAPI(通過 Starlette)運作的原理,也讓它擁有如此驚人的效能。
+
+## 非常技術性的細節
+
+/// warning
+
+你大概可以跳過這段。
+
+這裡是有關 FastAPI 內部技術細節。
+
+如果你有相當多的技術背景(例如協程、執行緒、阻塞等),並且對 FastAPI 如何處理 `async def` 與常規 `def` 感到好奇,請繼續閱讀。
+
+///
+
+### 路徑操作函数
+
+當你使用 `def` 而不是 `async def` 宣告*路徑操作函式*時,該函式會在外部的執行緒池(threadpool)中執行,然後等待結果,而不是直接呼叫(因為這樣會阻塞伺服器)。
+
+如果你來自於其他不以這種方式運作的非同步框架,而且你習慣於使用普通的 `def` 定義僅進行簡單計算的*路徑操作函式*,目的是獲得微小的性能增益(大約 100 奈秒),請注意,在 FastAPI 中,效果會完全相反。在這些情況下,最好使用 `async def`除非你的*路徑操作函式*執行阻塞的 I/O 的程式碼。
+
+不過,在這兩種情況下,**FastAPI** [仍然很快](index.md#_11){.internal-link target=_blank}至少與你之前的框架相當(或者更快)。
+
+### 依賴項(Dependencies)
+
+同樣適用於[依賴項](tutorial/dependencies/index.md){.internal-link target=_blank}。如果依賴項是一個標準的 `def` 函式,而不是 `async def`,那麼它在外部的執行緒池被運行。
+
+### 子依賴項
+
+你可以擁有多個相互依賴的依賴項和[子依賴項](tutorial/dependencies/sub-dependencies.md){.internal-link target=_blank} (作為函式定義的參數),其中一些可能是用 `async def` 宣告,也可能是用 `def` 宣告。它們仍然可以正常運作,用 `def` 定義的那些將會在外部的執行緒中呼叫(來自執行緒池),而不是被「等待」。
+
+### 其他輔助函式
+
+你可以直接呼叫任何使用 `def` 或 `async def` 建立的其他輔助函式,FastAPI 不會影響你呼叫它們的方式。
+
+這與 FastAPI 為你呼叫*路徑操作函式*和依賴項的邏輯有所不同。
+
+如果你的輔助函式是用 `def` 宣告的,它將會被直接呼叫(按照你在程式碼中撰寫的方式),而不是在執行緒池中。如果該函式是用 `async def` 宣告,那麼你在呼叫時應該使用 `await` 等待其結果。
+
+---
+
+再一次強調,這些都是非常技術性的細節,如果你特地在尋找這些資訊,這些內容可能會對你有幫助。
+
+否則,只需遵循上面提到的指引即可:趕時間嗎?.
diff --git a/docs/zh-hant/docs/benchmarks.md b/docs/zh-hant/docs/benchmarks.md
index cbd5a6cde..c59e8e71c 100644
--- a/docs/zh-hant/docs/benchmarks.md
+++ b/docs/zh-hant/docs/benchmarks.md
@@ -1,34 +1,34 @@
-# 基準測試
-
-由第三方機構 TechEmpower 的基準測試表明在 Uvicorn 下運行的 **FastAPI** 應用程式是 最快的 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 等框架。
+# 基準測試
+
+由第三方機構 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/deployment/cloud.md b/docs/zh-hant/docs/deployment/cloud.md
new file mode 100644
index 000000000..29ebe3ff5
--- /dev/null
+++ b/docs/zh-hant/docs/deployment/cloud.md
@@ -0,0 +1,17 @@
+# 在雲端部署 FastAPI
+
+你幾乎可以使用**任何雲端供應商**來部署你的 FastAPI 應用程式。
+
+在大多數情況下,主要的雲端供應商都有部署 FastAPI 的指南。
+
+## 雲端供應商 - 贊助商
+
+一些雲端供應商 ✨ [**贊助 FastAPI**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨,這確保了 FastAPI 及其**生態系統**持續健康地**發展**。
+
+這也展現了他們對 FastAPI 和其**社群**(包括你)的真正承諾,他們不僅希望為你提供**優質的服務**,還希望確保你擁有一個**良好且健康的框架**:FastAPI。🙇
+
+你可能會想嘗試他們的服務,以下有他們的指南:
+
+* Platform.sh
+* Porter
+* Coherence
diff --git a/docs/zh-hant/docs/deployment/index.md b/docs/zh-hant/docs/deployment/index.md
new file mode 100644
index 000000000..1726562b4
--- /dev/null
+++ b/docs/zh-hant/docs/deployment/index.md
@@ -0,0 +1,21 @@
+# 部署
+
+部署 **FastAPI** 應用程式相對容易。
+
+## 部署是什麼意思
+
+**部署**應用程式指的是執行一系列必要的步驟,使其能夠**讓使用者存取和使用**。
+
+對於一個 **Web API**,部署通常涉及將其放置在**遠端伺服器**上,並使用性能優良且穩定的**伺服器程式**,確保使用者能夠高效、無中斷地存取應用程式,且不會遇到問題。
+
+這與**開發**階段形成鮮明對比,在**開發**階段,你會不斷更改程式碼、破壞程式碼、修復程式碼,然後停止和重新啟動伺服器等。
+
+## 部署策略
+
+根據你的使用場景和使用工具,有多種方法可以實現此目的。
+
+你可以使用一些工具自行**部署伺服器**,你也可以使用能為你完成部分工作的**雲端服務**,或其他可能的選項。
+
+我將向你展示在部署 **FastAPI** 應用程式時你可能應該記住的一些主要概念(儘管其中大部分適用於任何其他類型的 Web 應用程式)。
+
+在接下來的部分中,你將看到更多需要記住的細節以及一些技巧。 ✨
diff --git a/docs/zh-hant/docs/environment-variables.md b/docs/zh-hant/docs/environment-variables.md
new file mode 100644
index 000000000..a1598fc01
--- /dev/null
+++ b/docs/zh-hant/docs/environment-variables.md
@@ -0,0 +1,298 @@
+# 環境變數
+
+/// tip
+
+如果你已經知道什麼是「環境變數」並且知道如何使用它們,你可以放心跳過這一部分。
+
+///
+
+環境變數(也稱為「**env var**」)是一個獨立於 Python 程式碼**之外**的變數,它存在於**作業系統**中,可以被你的 Python 程式碼(或其他程式)讀取。
+
+環境變數對於處理應用程式**設定**(作為 Python **安裝**的一部分等方面)非常有用。
+
+## 建立和使用環境變數
+
+你在 **shell(終端機)**中就可以**建立**和使用環境變數,並不需要用到 Python:
+
+//// tab | Linux, macOS, Windows Bash
+
+
-
+
@@ -87,7 +87,7 @@ FastAPI 是一個現代、快速(高效能)的 web 框架,用於 Python
"_老實說,你建造的東西看起來非常堅固和精緻。在很多方面,這就是我想要的,看到有人建造它真的很鼓舞人心。_"
-
+
---
@@ -443,7 +443,7 @@ item: Item
用於 Pydantic:
--
email_validator
- 用於電子郵件驗證。
+- email-validator
- 用於電子郵件驗證。
- pydantic-settings
- 用於設定管理。
- pydantic-extra-types
- 用於與 Pydantic 一起使用的額外型別。
diff --git a/docs/zh-hant/docs/resources/index.md b/docs/zh-hant/docs/resources/index.md
new file mode 100644
index 000000000..f4c70a3a0
--- /dev/null
+++ b/docs/zh-hant/docs/resources/index.md
@@ -0,0 +1,3 @@
+# 資源
+
+額外的資源、外部連結、文章等。 ✈️
diff --git a/docs/zh-hant/docs/tutorial/first-steps.md b/docs/zh-hant/docs/tutorial/first-steps.md
new file mode 100644
index 000000000..a557fa369
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/first-steps.md
@@ -0,0 +1,331 @@
+# 第一步
+
+最簡單的 FastAPI 檔案可能看起來像這樣:
+
+{* ../../docs_src/first_steps/tutorial001.py *}
+
+將其複製到一個名為 `main.py` 的文件中。
+
+執行即時重新載入伺服器(live server):
+
+
get
操作
+
+/// info | `@decorator` Info
+
+Python 中的 `@something` 語法被稱為「裝飾器」。
+
+你把它放在一個函式上面。像一個漂亮的裝飾帽子(我猜這是術語的來源)。
+
+一個「裝飾器」會對下面的函式做一些事情。
+
+在這種情況下,這個裝飾器告訴 **FastAPI** 那個函式對應於 **路徑** `/` 和 **操作** `get`.
+
+這就是「**路徑操作裝飾器**」。
+
+///
+
+你也可以使用其他的操作:
+
+* `@app.post()`
+* `@app.put()`
+* `@app.delete()`
+
+以及更少見的:
+
+* `@app.options()`
+* `@app.head()`
+* `@app.patch()`
+* `@app.trace()`
+
+/// tip
+
+你可以自由地使用每個操作(HTTP 方法)。
+
+**FastAPI** 不強制任何特定的意義。
+
+這裡的資訊作為一個指南,而不是要求。
+
+例如,當使用 GraphQL 時,你通常只使用 `POST` 操作。
+
+///
+
+### 第四步:定義 **路徑操作函式**
+
+這是我們的「**路徑操作函式**」:
+
+* **path**: 是 `/`.
+* **operation**: 是 `get`.
+* **function**: 是裝飾器下面的函式(在 `@app.get("/")` 下面)。
+
+{* ../../docs_src/first_steps/tutorial001.py h1[7] *}
+
+這就是一個 Python 函式。
+
+它將會在 **FastAPI** 收到一個請求時被呼叫,使用 `GET` 操作。
+
+在這種情況下,它是一個 `async` 函式。
+
+---
+
+你可以將它定義為一個正常的函式,而不是 `async def`:
+
+{* ../../docs_src/first_steps/tutorial003.py h1[7] *}
+
+/// note
+
+如果你不知道差別,請查看 [Async: *"In a hurry?"*](../async.md#in-a-hurry){.internal-link target=_blank}.
+
+///
+
+### 第五步:回傳內容
+
+{* ../../docs_src/first_steps/tutorial001.py h1[8] *}
+
+你可以返回一個 `dict`、`list`、單個值作為 `str`、`int` 等。
+
+你也可以返回 Pydantic 模型(稍後你會看到更多關於這方面的內容)。
+
+有很多其他物件和模型會自動轉換為 JSON(包括 ORMs,等等)。試用你最喜歡的,很有可能它們已經有支援。
+
+## 回顧
+
+* 引入 `FastAPI`.
+* 建立一個 `app` 實例。
+* 寫一個 **路徑操作裝飾器** 使用裝飾器像 `@app.get("/")`。
+* 定義一個 **路徑操作函式**;例如,`def root(): ...`。
+* 使用命令 `fastapi dev` 執行開發伺服器。
diff --git a/docs/zh-hant/docs/tutorial/index.md b/docs/zh-hant/docs/tutorial/index.md
new file mode 100644
index 000000000..ae0056f52
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/index.md
@@ -0,0 +1,102 @@
+# 教學 - 使用者指南
+
+本教學將一步一步展示如何使用 **FastAPI** 及其大多數功能。
+
+每個部分都是在前一部分的基礎上逐步建置的,但內容結構是按主題分開的,因此你可以直接跳到任何特定的部分,解決你具體的 API 需求。
+
+它也被設計成可作為未來的參考,讓你隨時回來查看所需的內容。
+
+## 運行程式碼
+
+所有程式碼區塊都可以直接複製和使用(它們實際上是經過測試的 Python 檔案)。
+
+要運行任何範例,請將程式碼複製到 `main.py` 檔案,並使用以下命令啟動 `fastapi dev`:
+
+
-
-
+
+
-
-
+
+
@@ -94,7 +94,7 @@ FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框
「_老实说,你的作品看起来非常可靠和优美。在很多方面,这就是我想让 **Hug** 成为的样子 - 看到有人实现了它真的很鼓舞人心。_」
-
+
---
@@ -446,7 +446,7 @@ item: Item
用于 Pydantic:
-*
email_validator
- 用于 email 校验。
+* email-validator
- 用于 email 校验。
用于 Starlette:
diff --git a/docs/zh/docs/project-generation.md b/docs/zh/docs/project-generation.md
index 0655cb0a9..48eb990df 100644
--- a/docs/zh/docs/project-generation.md
+++ b/docs/zh/docs/project-generation.md
@@ -1,84 +1,28 @@
-# 项目生成 - 模板
-
-项目生成器一般都会提供很多初始设置、安全措施、数据库,甚至还准备好了第一个 API 端点,能帮助您快速上手。
-
-项目生成器的设置通常都很主观,您可以按需更新或修改,但对于您的项目来说,它是非常好的起点。
-
-## 全栈 FastAPI + PostgreSQL
-
-GitHub:https://github.com/tiangolo/full-stack-fastapi-postgresql
-
-### 全栈 FastAPI + PostgreSQL - 功能
-
-* 完整的 **Docker** 集成(基于 Docker)
-* Docker Swarm 开发模式
-* **Docker Compose** 本地开发集成与优化
-* **生产可用**的 Python 网络服务器,使用 Uvicorn 或 Gunicorn
-* Python **FastAPI** 后端:
-* * **速度快**:可与 **NodeJS** 和 **Go** 比肩的极高性能(归功于 Starlette 和 Pydantic)
- * **直观**:强大的编辑器支持,处处皆可自动补全,减少调试时间
- * **简单**:易学、易用,阅读文档所需时间更短
- * **简短**:代码重复最小化,每次参数声明都可以实现多个功能
- * **健壮**: 生产级别的代码,还有自动交互文档
- * **基于标准**:完全兼容并基于 API 开放标准:OpenAPI 和 JSON Schema
- * **更多功能**包括自动验证、序列化、交互文档、OAuth2 JWT 令牌身份验证等
-* **安全密码**,默认使用密码哈希
-* **JWT 令牌**身份验证
-* **SQLAlchemy** 模型(独立于 Flask 扩展,可直接用于 Celery Worker)
-* 基础的用户模型(可按需修改或删除)
-* **Alembic** 迁移
-* **CORS**(跨域资源共享)
-* **Celery** Worker 可从后端其它部分有选择地导入并使用模型和代码
-* REST 后端测试基于 Pytest,并与 Docker 集成,可独立于数据库实现完整的 API 交互测试。因为是在 Docker 中运行,每次都可从头构建新的数据存储(使用 ElasticSearch、MongoDB、CouchDB 等数据库,仅测试 API 运行)
-* Python 与 **Jupyter Kernels** 集成,用于远程或 Docker 容器内部开发,使用 Atom Hydrogen 或 Visual Studio Code 的 Jupyter 插件
-* **Vue** 前端:
- * 由 Vue CLI 生成
- * **JWT 身份验证**处理
- * 登录视图
- * 登录后显示主仪表盘视图
- * 主仪表盘支持用户创建与编辑
- * 用户信息编辑
- * **Vuex**
- * **Vue-router**
- * **Vuetify** 美化组件
- * **TypeScript**
- * 基于 **Nginx** 的 Docker 服务器(优化了 Vue-router 配置)
- * Docker 多阶段构建,无需保存或提交编译的代码
- * 在构建时运行前端测试(可禁用)
- * 尽量模块化,开箱即用,但仍可使用 Vue CLI 重新生成或创建所需项目,或复用所需内容
-* 使用 **PGAdmin** 管理 PostgreSQL 数据库,可轻松替换为 PHPMyAdmin 或 MySQL
-* 使用 **Flower** 监控 Celery 任务
-* 使用 **Traefik** 处理前后端负载平衡,可把前后端放在同一个域下,按路径分隔,但在不同容器中提供服务
-* Traefik 集成,包括自动生成 Let's Encrypt **HTTPS** 凭证
-* GitLab **CI**(持续集成),包括前后端测试
-
-## 全栈 FastAPI + Couchbase
-
-GitHub:https://github.com/tiangolo/full-stack-fastapi-couchbase
-
-⚠️ **警告** ⚠️
-
-如果您想从头开始创建新项目,建议使用以下备选方案。
-
-例如,项目生成器全栈 FastAPI + PostgreSQL 会更适用,这个项目的维护积极,用的人也多,还包括了所有新功能和改进内容。
-
-当然,您也可以放心使用这个基于 Couchbase 的生成器,它也能正常使用。就算用它生成项目也没有任何问题(为了更好地满足需求,您可以自行更新这个项目)。
-
-详见资源仓库中的文档。
-
-## 全栈 FastAPI + MongoDB
-
-……敬请期待,得看我有没有时间做这个项目。😅 🎉
-
-## FastAPI + spaCy 机器学习模型
-
-GitHub:https://github.com/microsoft/cookiecutter-spacy-fastapi
-
-### FastAPI + spaCy 机器学习模型 - 功能
-
-* 集成 **spaCy** NER 模型
-* 内置 **Azure 认知搜索**请求格式
-* **生产可用**的 Python 网络服务器,使用 Uvicorn 与 Gunicorn
-* 内置 **Azure DevOps** Kubernetes (AKS) CI/CD 开发
-* **多语**支持,可在项目设置时选择 spaCy 内置的语言
-* 不仅局限于 spaCy,可**轻松扩展**至其它模型框架(Pytorch、TensorFlow)
+# FastAPI全栈模板
+
+模板通常带有特定的设置,而且被设计为灵活和可定制的。这允许您根据项目的需求修改和调整它们,使它们成为一个很好的起点。🏁
+
+您可以使用此模板开始,因为它包含了许多已经为您完成的初始设置、安全性、数据库和一些API端点。
+
+代码仓: Full Stack FastAPI Template
+
+## FastAPI全栈模板 - 技术栈和特性
+
+- ⚡ [**FastAPI**](https://fastapi.tiangolo.com) 用于Python后端API.
+ - 🧰 [SQLModel](https://sqlmodel.tiangolo.com) 用于Python和SQL数据库的集成(ORM)。
+ - 🔍 [Pydantic](https://docs.pydantic.dev) FastAPI的依赖项之一,用于数据验证和配置管理。
+ - 💾 [PostgreSQL](https://www.postgresql.org) 作为SQL数据库。
+- 🚀 [React](https://react.dev) 用于前端。
+ - 💃 使用了TypeScript、hooks、[Vite](https://vitejs.dev)和其他一些现代化的前端技术栈。
+ - 🎨 [Chakra UI](https://chakra-ui.com) 用于前端组件。
+ - 🤖 一个自动化生成的前端客户端。
+ - 🧪 [Playwright](https://playwright.dev)用于端到端测试。
+ - 🦇 支持暗黑主题(Dark mode)。
+- 🐋 [Docker Compose](https://www.docker.com) 用于开发环境和生产环境。
+- 🔒 默认使用密码哈希来保证安全。
+- 🔑 JWT令牌用于权限验证。
+- 📫 使用邮箱来进行密码恢复。
+- ✅ 单元测试用了[Pytest](https://pytest.org).
+- 📞 [Traefik](https://traefik.io) 用于反向代理和负载均衡。
+- 🚢 部署指南(Docker Compose)包含了如何起一个Traefik前端代理来自动化HTTPS认证。
+- 🏭 CI(持续集成)和 CD(持续部署)基于GitHub Actions。
diff --git a/docs/zh/docs/python-types.md b/docs/zh/docs/python-types.md
index 214b47611..ba767da87 100644
--- a/docs/zh/docs/python-types.md
+++ b/docs/zh/docs/python-types.md
@@ -12,16 +12,18 @@
但即使你不会用到 **FastAPI**,了解一下类型提示也会让你从中受益。
-!!! note
- 如果你已经精通 Python,并且了解关于类型提示的一切知识,直接跳到下一章节吧。
+/// note
+
+如果你已经精通 Python,并且了解关于类型提示的一切知识,直接跳到下一章节吧。
+
+///
## 动机
让我们从一个简单的例子开始:
-```Python
-{!../../../docs_src/python_types/tutorial001.py!}
-```
+{* ../../docs_src/python_types/tutorial001.py *}
+
运行这段程序将输出:
@@ -35,9 +37,8 @@ John Doe
* 通过 `title()` 将每个参数的第一个字母转换为大写形式。
* 中间用一个空格来拼接它们。
-```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial001.py!}
-```
+{* ../../docs_src/python_types/tutorial001.py hl[2] *}
+
### 修改示例
@@ -79,9 +80,8 @@ John Doe
这些就是"类型提示":
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial002.py!}
-```
+{* ../../docs_src/python_types/tutorial002.py hl[1] *}
+
这和声明默认值是不同的,例如:
@@ -109,9 +109,8 @@ John Doe
下面是一个已经有类型提示的函数:
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial003.py!}
-```
+{* ../../docs_src/python_types/tutorial003.py hl[1] *}
+
因为编辑器已经知道了这些变量的类型,所以不仅能对代码进行补全,还能检查其中的错误:
@@ -119,9 +118,8 @@ John Doe
现在你知道了必须先修复这个问题,通过 `str(age)` 把 `age` 转换成字符串:
-```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial004.py!}
-```
+{* ../../docs_src/python_types/tutorial004.py hl[2] *}
+
## 声明类型
@@ -140,9 +138,8 @@ John Doe
* `bool`
* `bytes`
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial005.py!}
-```
+{* ../../docs_src/python_types/tutorial005.py hl[1] *}
+
### 嵌套类型
@@ -158,9 +155,8 @@ John Doe
从 `typing` 模块导入 `List`(注意是大写的 `L`):
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial006.py!}
-```
+{* ../../docs_src/python_types/tutorial006.py hl[1] *}
+
同样以冒号(`:`)来声明这个变量。
@@ -168,9 +164,8 @@ John Doe
由于列表是带有"子类型"的类型,所以我们把子类型放在方括号中:
-```Python hl_lines="4"
-{!../../../docs_src/python_types/tutorial006.py!}
-```
+{* ../../docs_src/python_types/tutorial006.py hl[4] *}
+
这表示:"变量 `items` 是一个 `list`,并且这个列表里的每一个元素都是 `str`"。
@@ -188,9 +183,8 @@ John Doe
声明 `tuple` 和 `set` 的方法也是一样的:
-```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial007.py!}
-```
+{* ../../docs_src/python_types/tutorial007.py hl[1,4] *}
+
这表示:
@@ -205,9 +199,8 @@ John Doe
第二个子类型声明 `dict` 的所有值:
-```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial008.py!}
-```
+{* ../../docs_src/python_types/tutorial008.py hl[1,4] *}
+
这表示:
@@ -221,15 +214,13 @@ John Doe
假设你有一个名为 `Person` 的类,拥有 name 属性:
-```Python hl_lines="1-3"
-{!../../../docs_src/python_types/tutorial010.py!}
-```
+{* ../../docs_src/python_types/tutorial010.py hl[1:3] *}
+
接下来,你可以将一个变量声明为 `Person` 类型:
-```Python hl_lines="6"
-{!../../../docs_src/python_types/tutorial010.py!}
-```
+{* ../../docs_src/python_types/tutorial010.py hl[6] *}
+
然后,你将再次获得所有的编辑器支持:
@@ -237,7 +228,7 @@ John Doe
## Pydantic 模型
-Pydantic 是一个用来用来执行数据校验的 Python 库。
+Pydantic 是一个用来执行数据校验的 Python 库。
你可以将数据的"结构"声明为具有属性的类。
@@ -249,12 +240,14 @@ John Doe
下面的例子来自 Pydantic 官方文档:
-```Python
-{!../../../docs_src/python_types/tutorial010.py!}
-```
+{* ../../docs_src/python_types/tutorial010.py *}
+
-!!! info
- 想进一步了解 Pydantic,请阅读其文档.
+/// info
+
+想进一步了解 Pydantic,请阅读其文档.
+
+///
整个 **FastAPI** 建立在 Pydantic 的基础之上。
@@ -282,5 +275,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..40e61add7 100644
--- a/docs/zh/docs/tutorial/background-tasks.md
+++ b/docs/zh/docs/tutorial/background-tasks.md
@@ -15,9 +15,7 @@
首先导入 `BackgroundTasks` 并在 *路径操作函数* 中使用类型声明 `BackgroundTasks` 定义一个参数:
-```Python hl_lines="1 13"
-{!../../../docs_src/background_tasks/tutorial001.py!}
-```
+{* ../../docs_src/background_tasks/tutorial001.py hl[1, 13] *}
**FastAPI** 会创建一个 `BackgroundTasks` 类型的对象并作为该参数传入。
@@ -33,17 +31,13 @@
由于写操作不使用 `async` 和 `await`,我们用普通的 `def` 定义函数:
-```Python hl_lines="6-9"
-{!../../../docs_src/background_tasks/tutorial001.py!}
-```
+{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *}
## 添加后台任务
在你的 *路径操作函数* 里,用 `.add_task()` 方法将任务函数传到 *后台任务* 对象中:
-```Python hl_lines="14"
-{!../../../docs_src/background_tasks/tutorial001.py!}
-```
+{* ../../docs_src/background_tasks/tutorial001.py hl[14] *}
`.add_task()` 接收以下参数:
@@ -57,41 +51,47 @@
**FastAPI** 知道在每种情况下该做什么以及如何复用同一对象,因此所有后台任务被合并在一起并且随后在后台运行:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="13 15 22 25"
- {!> ../../../docs_src/background_tasks/tutorial002_an_py310.py!}
- ```
+{* ../../docs_src/background_tasks/tutorial002_an_py310.py hl[13, 15, 22, 25] *}
-=== "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+"
+{* ../../docs_src/background_tasks/tutorial002_an_py39.py hl[13, 15, 22, 25] *}
- ```Python hl_lines="14 16 23 26"
- {!> ../../../docs_src/background_tasks/tutorial002_an.py!}
- ```
+////
-=== "Python 3.10+ 没Annotated"
+//// tab | Python 3.8+
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+{* ../../docs_src/background_tasks/tutorial002_an.py hl[14, 16, 23, 26] *}
- ```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` 的版本。
+
+///
+
+{* ../../docs_src/background_tasks/tutorial002_py310.py hl[11, 13, 20, 23] *}
+
+////
+
+//// tab | Python 3.8+ 没Annotated
+
+/// tip
+
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+{* ../../docs_src/background_tasks/tutorial002.py hl[13, 15, 22, 25] *}
+
+////
该示例中,信息会在响应发出 *之后* 被写到 `log.txt` 文件。
@@ -117,8 +117,6 @@
它们往往需要更复杂的配置,即消息/作业队列管理器,如RabbitMQ或Redis,但它们允许您在多个进程中运行后台任务,甚至是在多个服务器中。
-要查看示例,查阅 [Project Generators](../project-generation.md){.internal-link target=_blank},它们都包括已经配置的Celery。
-
但是,如果您需要从同一个**FastAPI**应用程序访问变量和对象,或者您需要执行小型后台任务(如发送电子邮件通知),您只需使用 `BackgroundTasks` 即可。
## 回顾
diff --git a/docs/zh/docs/tutorial/bigger-applications.md b/docs/zh/docs/tutorial/bigger-applications.md
index 422cd7c16..554bc654f 100644
--- a/docs/zh/docs/tutorial/bigger-applications.md
+++ b/docs/zh/docs/tutorial/bigger-applications.md
@@ -4,8 +4,11 @@
**FastAPI** 提供了一个方便的工具,可以在保持所有灵活性的同时构建你的应用程序。
-!!! info
- 如果你来自 Flask,那这将相当于 Flask 的 Blueprints。
+/// info
+
+如果你来自 Flask,那这将相当于 Flask 的 Blueprints。
+
+///
## 一个文件结构示例
@@ -26,16 +29,19 @@
│ └── admin.py
```
-!!! tip
- 上面有几个 `__init__.py` 文件:每个目录或子目录中都有一个。
+/// tip
+
+上面有几个 `__init__.py` 文件:每个目录或子目录中都有一个。
- 这就是能将代码从一个文件导入到另一个文件的原因。
+这就是能将代码从一个文件导入到另一个文件的原因。
- 例如,在 `app/main.py` 中,你可以有如下一行:
+例如,在 `app/main.py` 中,你可以有如下一行:
+
+```
+from app.routers import items
+```
- ```
- from app.routers import items
- ```
+///
* `app` 目录包含了所有内容。并且它有一个空文件 `app/__init__.py`,因此它是一个「Python 包」(「Python 模块」的集合):`app`。
* 它包含一个 `app/main.py` 文件。由于它位于一个 Python 包(一个包含 `__init__.py` 文件的目录)中,因此它是该包的一个「模块」:`app.main`。
@@ -46,7 +52,7 @@
* 还有一个子目录 `app/internal/` 包含另一个 `__init__.py` 文件,因此它是又一个「Python 子包」:`app.internal`。
* `app/internal/admin.py` 是另一个子模块:`app.internal.admin`。
-
+
带有注释的同一文件结构:
@@ -80,7 +86,7 @@
你可以导入它并通过与 `FastAPI` 类相同的方式创建一个「实例」:
```Python hl_lines="1 3" title="app/routers/users.py"
-{!../../../docs_src/bigger_applications/app/routers/users.py!}
+{!../../docs_src/bigger_applications/app/routers/users.py!}
```
### 使用 `APIRouter` 的*路径操作*
@@ -90,7 +96,7 @@
使用方式与 `FastAPI` 类相同:
```Python hl_lines="6 11 16" title="app/routers/users.py"
-{!../../../docs_src/bigger_applications/app/routers/users.py!}
+{!../../docs_src/bigger_applications/app/routers/users.py!}
```
你可以将 `APIRouter` 视为一个「迷你 `FastAPI`」类。
@@ -99,8 +105,11 @@
所有相同的 `parameters`、`responses`、`dependencies`、`tags` 等等。
-!!! tip
- 在此示例中,该变量被命名为 `router`,但你可以根据你的想法自由命名。
+/// tip
+
+在此示例中,该变量被命名为 `router`,但你可以根据你的想法自由命名。
+
+///
我们将在主 `FastAPI` 应用中包含该 `APIRouter`,但首先,让我们来看看依赖项和另一个 `APIRouter`。
@@ -113,13 +122,16 @@
现在我们将使用一个简单的依赖项来读取一个自定义的 `X-Token` 请求首部:
```Python hl_lines="1 4-6" title="app/dependencies.py"
-{!../../../docs_src/bigger_applications/app/dependencies.py!}
+{!../../docs_src/bigger_applications/app/dependencies.py!}
```
-!!! tip
- 我们正在使用虚构的请求首部来简化此示例。
+/// tip
+
+我们正在使用虚构的请求首部来简化此示例。
+
+但在实际情况下,使用集成的[安全性实用工具](security/index.md){.internal-link target=_blank}会得到更好的效果。
- 但在实际情况下,使用集成的[安全性实用工具](security/index.md){.internal-link target=_blank}会得到更好的效果。
+///
## 其他使用 `APIRouter` 的模块
@@ -144,7 +156,7 @@
因此,我们可以将其添加到 `APIRouter` 中,而不是将其添加到每个路径操作中。
```Python hl_lines="5-10 16 21" title="app/routers/items.py"
-{!../../../docs_src/bigger_applications/app/routers/items.py!}
+{!../../docs_src/bigger_applications/app/routers/items.py!}
```
由于每个*路径操作*的路径都必须以 `/` 开头,例如:
@@ -163,8 +175,11 @@ async def read_item(item_id: str):
我们可以添加一个 `dependencies` 列表,这些依赖项将被添加到路由器中的所有*路径操作*中,并将针对向它们发起的每个请求执行/解决。
-!!! tip
- 请注意,和[*路径操作装饰器*中的依赖项](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}很类似,没有值会被传递给你的*路径操作函数*。
+/// tip
+
+请注意,和[*路径操作装饰器*中的依赖项](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}很类似,没有值会被传递给你的*路径操作函数*。
+
+///
最终结果是项目相关的路径现在为:
@@ -181,11 +196,17 @@ async def read_item(item_id: str):
* 路由器的依赖项最先执行,然后是[装饰器中的 `dependencies`](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank},再然后是普通的参数依赖项。
* 你还可以添加[具有 `scopes` 的 `Security` 依赖项](../advanced/security/oauth2-scopes.md){.internal-link target=_blank}。
-!!! tip
- 在 `APIRouter`中具有 `dependencies` 可以用来,例如,对一整组的*路径操作*要求身份认证。即使这些依赖项并没有分别添加到每个路径操作中。
+/// tip
+
+在 `APIRouter`中具有 `dependencies` 可以用来,例如,对一整组的*路径操作*要求身份认证。即使这些依赖项并没有分别添加到每个路径操作中。
+
+///
+
+/// check
-!!! check
- `prefix`、`tags`、`responses` 以及 `dependencies` 参数只是(和其他很多情况一样)**FastAPI** 的一个用于帮助你避免代码重复的功能。
+`prefix`、`tags`、`responses` 以及 `dependencies` 参数只是(和其他很多情况一样)**FastAPI** 的一个用于帮助你避免代码重复的功能。
+
+///
### 导入依赖项
@@ -196,13 +217,16 @@ async def read_item(item_id: str):
因此,我们通过 `..` 对依赖项使用了相对导入:
```Python hl_lines="3" title="app/routers/items.py"
-{!../../../docs_src/bigger_applications/app/routers/items.py!}
+{!../../docs_src/bigger_applications/app/routers/items.py!}
```
#### 相对导入如何工作
-!!! tip
- 如果你完全了解导入的工作原理,请从下面的下一部分继续。
+/// tip
+
+如果你完全了解导入的工作原理,请从下面的下一部分继续。
+
+///
一个单点 `.`,例如:
@@ -220,7 +244,7 @@ from .dependencies import get_token_header
请记住我们的程序/文件结构是怎样的:
-
+
---
@@ -266,13 +290,16 @@ from ...dependencies import get_token_header
但是我们仍然可以添加*更多*将会应用于特定的*路径操作*的 `tags`,以及一些特定于该*路径操作*的额外 `responses`:
```Python hl_lines="30-31" title="app/routers/items.py"
-{!../../../docs_src/bigger_applications/app/routers/items.py!}
+{!../../docs_src/bigger_applications/app/routers/items.py!}
```
-!!! tip
- 最后的这个路径操作将包含标签的组合:`["items","custom"]`。
+/// tip
+
+最后的这个路径操作将包含标签的组合:`["items","custom"]`。
- 并且在文档中也会有两个响应,一个用于 `404`,一个用于 `403`。
+并且在文档中也会有两个响应,一个用于 `404`,一个用于 `403`。
+
+///
## `FastAPI` 主体
@@ -291,7 +318,7 @@ from ...dependencies import get_token_header
我们甚至可以声明[全局依赖项](dependencies/global-dependencies.md){.internal-link target=_blank},它会和每个 `APIRouter` 的依赖项组合在一起:
```Python hl_lines="1 3 7" title="app/main.py"
-{!../../../docs_src/bigger_applications/app/main.py!}
+{!../../docs_src/bigger_applications/app/main.py!}
```
### 导入 `APIRouter`
@@ -299,7 +326,7 @@ from ...dependencies import get_token_header
现在,我们导入具有 `APIRouter` 的其他子模块:
```Python hl_lines="5" title="app/main.py"
-{!../../../docs_src/bigger_applications/app/main.py!}
+{!../../docs_src/bigger_applications/app/main.py!}
```
由于文件 `app/routers/users.py` 和 `app/routers/items.py` 是同一 Python 包 `app` 一个部分的子模块,因此我们可以使用单个点 ` .` 通过「相对导入」来导入它们。
@@ -328,20 +355,23 @@ from .routers import items, users
from app.routers import items, users
```
-!!! info
- 第一个版本是「相对导入」:
+/// info
+
+第一个版本是「相对导入」:
- ```Python
- from .routers import items, users
- ```
+```Python
+from .routers import items, users
+```
- 第二个版本是「绝对导入」:
+第二个版本是「绝对导入」:
+
+```Python
+from app.routers import items, users
+```
- ```Python
- from app.routers import items, users
- ```
+要了解有关 Python 包和模块的更多信息,请查阅关于 Modules 的 Python 官方文档。
- 要了解有关 Python 包和模块的更多信息,请查阅关于 Modules 的 Python 官方文档。
+///
### 避免名称冲突
@@ -361,7 +391,7 @@ from .routers.users import router
因此,为了能够在同一个文件中使用它们,我们直接导入子模块:
```Python hl_lines="5" title="app/main.py"
-{!../../../docs_src/bigger_applications/app/main.py!}
+{!../../docs_src/bigger_applications/app/main.py!}
```
### 包含 `users` 和 `items` 的 `APIRouter`
@@ -369,29 +399,38 @@ from .routers.users import router
现在,让我们来包含来自 `users` 和 `items` 子模块的 `router`。
```Python hl_lines="10-11" title="app/main.py"
-{!../../../docs_src/bigger_applications/app/main.py!}
+{!../../docs_src/bigger_applications/app/main.py!}
```
-!!! info
- `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`
@@ -402,7 +441,7 @@ from .routers.users import router
对于此示例,它将非常简单。但是假设由于它是与组织中的其他项目所共享的,因此我们无法对其进行修改,以及直接在 `APIRouter` 中添加 `prefix`、`dependencies`、`tags` 等:
```Python hl_lines="3" title="app/internal/admin.py"
-{!../../../docs_src/bigger_applications/app/internal/admin.py!}
+{!../../docs_src/bigger_applications/app/internal/admin.py!}
```
但是我们仍然希望在包含 `APIRouter` 时设置一个自定义的 `prefix`,以便其所有*路径操作*以 `/admin` 开头,我们希望使用本项目已经有的 `dependencies` 保护它,并且我们希望它包含自定义的 `tags` 和 `responses`。
@@ -410,7 +449,7 @@ from .routers.users import router
我们可以通过将这些参数传递给 `app.include_router()` 来完成所有的声明,而不必修改原始的 `APIRouter`:
```Python hl_lines="14-17" title="app/main.py"
-{!../../../docs_src/bigger_applications/app/main.py!}
+{!../../docs_src/bigger_applications/app/main.py!}
```
这样,原始的 `APIRouter` 将保持不变,因此我们仍然可以与组织中的其他项目共享相同的 `app/internal/admin.py` 文件。
@@ -433,21 +472,24 @@ from .routers.users import router
这里我们这样做了...只是为了表明我们可以做到🤷:
```Python hl_lines="21-23" title="app/main.py"
-{!../../../docs_src/bigger_applications/app/main.py!}
+{!../../docs_src/bigger_applications/app/main.py!}
```
它将与通过 `app.include_router()` 添加的所有其他*路径操作*一起正常运行。
-!!! info "特别的技术细节"
- **注意**:这是一个非常技术性的细节,你也许可以**直接跳过**。
+/// info | 特别的技术细节
+
+**注意**:这是一个非常技术性的细节,你也许可以**直接跳过**。
+
+---
- ---
+`APIRouter` 没有被「挂载」,它们与应用程序的其余部分没有隔离。
- `APIRouter` 没有被「挂载」,它们与应用程序的其余部分没有隔离。
+这是因为我们想要在 OpenAPI 模式和用户界面中包含它们的*路径操作*。
- 这是因为我们想要在 OpenAPI 模式和用户界面中包含它们的*路径操作*。
+由于我们不能仅仅隔离它们并独立于其余部分来「挂载」它们,因此*路径操作*是被「克隆的」(重新创建),而不是直接包含。
- 由于我们不能仅仅隔离它们并独立于其余部分来「挂载」它们,因此*路径操作*是被「克隆的」(重新创建),而不是直接包含。
+///
## 查看自动化的 API 文档
diff --git a/docs/zh/docs/tutorial/body-fields.md b/docs/zh/docs/tutorial/body-fields.md
index 6c68f1008..4cff58bfc 100644
--- a/docs/zh/docs/tutorial/body-fields.md
+++ b/docs/zh/docs/tutorial/body-fields.md
@@ -6,101 +6,39 @@
首先,从 Pydantic 中导入 `Field`:
-=== "Python 3.10+"
+{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[4] *}
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!}
- ```
+/// warning | 警告
-=== "Python 3.9+"
+注意,与从 `fastapi` 导入 `Query`,`Path`、`Body` 不同,要直接从 `pydantic` 导入 `Field` 。
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001_an.py!}
- ```
-
-=== "Python 3.10+ non-Annotated"
-
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
-
- ```Python hl_lines="2"
- {!> ../../../docs_src/body_fields/tutorial001_py310.py!}
- ```
-
-=== "Python 3.8+ non-Annotated"
-
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
-
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001.py!}
- ```
-
-!!! warning "警告"
-
- 注意,与从 `fastapi` 导入 `Query`,`Path`、`Body` 不同,要直接从 `pydantic` 导入 `Field` 。
+///
## 声明模型属性
然后,使用 `Field` 定义模型的属性:
-=== "Python 3.10+"
-
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!}
- ```
+{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[11:14] *}
-=== "Python 3.9+"
-
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="12-15"
- {!> ../../../docs_src/body_fields/tutorial001_an.py!}
- ```
-
-=== "Python 3.10+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="9-12"
- {!> ../../../docs_src/body_fields/tutorial001_py310.py!}
- ```
-
-=== "Python 3.8+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
+`Field` 的工作方式和 `Query`、`Path`、`Body` 相同,参数也相同。
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001.py!}
- ```
+/// note | 技术细节
-`Field` 的工作方式和 `Query`、`Path`、`Body` 相同,参数也相同。
+实际上,`Query`、`Path` 都是 `Params` 的子类,而 `Params` 类又是 Pydantic 中 `FieldInfo` 的子类。
-!!! note "技术细节"
+Pydantic 的 `Field` 返回也是 `FieldInfo` 的类实例。
- 实际上,`Query`、`Path` 都是 `Params` 的子类,而 `Params` 类又是 Pydantic 中 `FieldInfo` 的子类。
+`Body` 直接返回的也是 `FieldInfo` 的子类的对象。后文还会介绍一些 `Body` 的子类。
- Pydantic 的 `Field` 返回也是 `FieldInfo` 的类实例。
+注意,从 `fastapi` 导入的 `Query`、`Path` 等对象实际上都是返回特殊类的函数。
- `Body` 直接返回的也是 `FieldInfo` 的子类的对象。后文还会介绍一些 `Body` 的子类。
+///
- 注意,从 `fastapi` 导入的 `Query`、`Path` 等对象实际上都是返回特殊类的函数。
+/// tip | 提示
-!!! tip "提示"
+注意,模型属性的类型、默认值及 `Field` 的代码结构与*路径操作函数*的参数相同,只不过是用 `Field` 替换了`Path`、`Query`、`Body`。
- 注意,模型属性的类型、默认值及 `Field` 的代码结构与*路径操作函数*的参数相同,只不过是用 `Field` 替换了`Path`、`Query`、`Body`。
+///
## 添加更多信息
diff --git a/docs/zh/docs/tutorial/body-multiple-params.md b/docs/zh/docs/tutorial/body-multiple-params.md
index c93ef2f5c..b4356fdcb 100644
--- a/docs/zh/docs/tutorial/body-multiple-params.md
+++ b/docs/zh/docs/tutorial/body-multiple-params.md
@@ -8,44 +8,13 @@
你还可以通过将默认值设置为 `None` 来将请求体参数声明为可选参数:
-=== "Python 3.10+"
+{* ../../docs_src/body_multiple_params/tutorial001_an_py310.py hl[18:20] *}
- ```Python hl_lines="18-20"
- {!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!}
- ```
+/// note
-=== "Python 3.9+"
+请注意,在这种情况下,将从请求体获取的 `item` 是可选的。因为它的默认值为 `None`。
- ```Python hl_lines="18-20"
- {!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="19-21"
- {!> ../../../docs_src/body_multiple_params/tutorial001_an.py!}
- ```
-
-=== "Python 3.10+ non-Annotated"
-
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
-
- ```Python hl_lines="17-19"
- {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!}
- ```
-
-=== "Python 3.8+ non-Annotated"
-
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
-
- ```Python hl_lines="19-21"
- {!> ../../../docs_src/body_multiple_params/tutorial001.py!}
- ```
-
-!!! note
- 请注意,在这种情况下,将从请求体获取的 `item` 是可选的。因为它的默认值为 `None`。
+///
## 多个请求体参数
@@ -62,17 +31,7 @@
但是你也可以声明多个请求体参数,例如 `item` 和 `user`:
-=== "Python 3.10+"
-
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="22"
- {!> ../../../docs_src/body_multiple_params/tutorial002.py!}
- ```
+{* ../../docs_src/body_multiple_params/tutorial002_py310.py hl[20] *}
在这种情况下,**FastAPI** 将注意到该函数中有多个请求体参数(两个 Pydantic 模型参数)。
@@ -93,9 +52,11 @@
}
```
-!!! note
- 请注意,即使 `item` 的声明方式与之前相同,但现在它被期望通过 `item` 键内嵌在请求体中。
+/// note
+请注意,即使 `item` 的声明方式与之前相同,但现在它被期望通过 `item` 键内嵌在请求体中。
+
+///
**FastAPI** 将自动对请求中的数据进行转换,因此 `item` 参数将接收指定的内容,`user` 参数也是如此。
@@ -112,41 +73,7 @@
但是你可以使用 `Body` 指示 **FastAPI** 将其作为请求体的另一个键进行处理。
-=== "Python 3.10+"
-
- ```Python hl_lines="23"
- {!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="23"
- {!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="24"
- {!> ../../../docs_src/body_multiple_params/tutorial003_an.py!}
- ```
-
-=== "Python 3.10+ non-Annotated"
-
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
-
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!}
- ```
-
-=== "Python 3.8+ non-Annotated"
-
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
-
- ```Python hl_lines="22"
- {!> ../../../docs_src/body_multiple_params/tutorial003.py!}
- ```
+{* ../../docs_src/body_multiple_params/tutorial003_an_py310.py hl[23] *}
在这种情况下,**FastAPI** 将期望像这样的请求体:
@@ -181,45 +108,13 @@ q: str = None
比如:
-=== "Python 3.10+"
-
- ```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="28"
- {!> ../../../docs_src/body_multiple_params/tutorial004_an.py!}
- ```
-
-=== "Python 3.10+ non-Annotated"
-
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
-
- ```Python hl_lines="25"
- {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!}
- ```
-
-=== "Python 3.8+ non-Annotated"
-
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[27] *}
- ```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004.py!}
- ```
+/// info
-!!! info
- `Body` 同样具有与 `Query`、`Path` 以及其他后面将看到的类完全相同的额外校验和元数据参数。
+`Body` 同样具有与 `Query`、`Path` 以及其他后面将看到的类完全相同的额外校验和元数据参数。
+///
## 嵌入单个请求体参数
@@ -235,41 +130,7 @@ item: Item = Body(embed=True)
比如:
-=== "Python 3.10+"
-
- ```Python hl_lines="17"
- {!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="17"
- {!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="18"
- {!> ../../../docs_src/body_multiple_params/tutorial005_an.py!}
- ```
-
-=== "Python 3.10+ non-Annotated"
-
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
-
- ```Python hl_lines="15"
- {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!}
- ```
-
-=== "Python 3.8+ non-Annotated"
-
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
-
- ```Python hl_lines="17"
- {!> ../../../docs_src/body_multiple_params/tutorial005.py!}
- ```
+{* ../../docs_src/body_multiple_params/tutorial005_an_py310.py hl[17] *}
在这种情况下,**FastAPI** 将期望像这样的请求体:
diff --git a/docs/zh/docs/tutorial/body-nested-models.md b/docs/zh/docs/tutorial/body-nested-models.md
index 3f519ae33..df96d96b4 100644
--- a/docs/zh/docs/tutorial/body-nested-models.md
+++ b/docs/zh/docs/tutorial/body-nested-models.md
@@ -6,17 +6,7 @@
你可以将一个属性定义为拥有子元素的类型。例如 Python `list`:
-=== "Python 3.10+"
-
- ```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!}
- ```
+{* ../../docs_src/body_nested_models/tutorial001_py310.py hl[12] *}
这将使 `tags` 成为一个由元素组成的列表。不过它没有声明每个元素的类型。
@@ -28,9 +18,7 @@
首先,从 Python 的标准库 `typing` 模块中导入 `List`:
-```Python hl_lines="1"
-{!> ../../../docs_src/body_nested_models/tutorial002.py!}
-```
+{* ../../docs_src/body_nested_models/tutorial002.py hl[1] *}
### 声明具有子类型的 List
@@ -51,23 +39,7 @@ my_list: List[str]
因此,在我们的示例中,我们可以将 `tags` 明确地指定为一个「字符串列表」:
-=== "Python 3.10+"
-
- ```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!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial002.py!}
- ```
+{* ../../docs_src/body_nested_models/tutorial002_py310.py hl[12] *}
## Set 类型
@@ -77,23 +49,7 @@ Python 具有一种特殊的数据类型来保存一组唯一的元素,即 `se
然后我们可以导入 `Set` 并将 `tag` 声明为一个由 `str` 组成的 `set`:
-=== "Python 3.10+"
-
- ```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!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="1 14"
- {!> ../../../docs_src/body_nested_models/tutorial003.py!}
- ```
+{* ../../docs_src/body_nested_models/tutorial003_py310.py hl[12] *}
这样,即使你收到带有重复数据的请求,这些数据也会被转换为一组唯一项。
@@ -115,45 +71,13 @@ Pydantic 模型的每个属性都具有类型。
例如,我们可以定义一个 `Image` 模型:
-=== "Python 3.10+"
-
- ```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!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="9-11"
- {!> ../../../docs_src/body_nested_models/tutorial004.py!}
- ```
+{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[7:9] *}
### 将子模型用作类型
然后我们可以将其用作一个属性的类型:
-=== "Python 3.10+"
-
- ```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!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial004.py!}
- ```
+{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[18] *}
这意味着 **FastAPI** 将期望类似于以下内容的请求体:
@@ -186,23 +110,7 @@ Pydantic 模型的每个属性都具有类型。
例如,在 `Image` 模型中我们有一个 `url` 字段,我们可以把它声明为 Pydantic 的 `HttpUrl`,而不是 `str`:
-=== "Python 3.10+"
-
- ```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!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="4 10"
- {!> ../../../docs_src/body_nested_models/tutorial005.py!}
- ```
+{* ../../docs_src/body_nested_models/tutorial005_py310.py hl[2,8] *}
该字符串将被检查是否为有效的 URL,并在 JSON Schema / OpenAPI 文档中进行记录。
@@ -210,23 +118,7 @@ Pydantic 模型的每个属性都具有类型。
你还可以将 Pydantic 模型用作 `list`、`set` 等的子类型:
-=== "Python 3.10+"
-
- ```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!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial006.py!}
- ```
+{* ../../docs_src/body_nested_models/tutorial006_py310.py hl[18] *}
这将期望(转换,校验,记录文档等)下面这样的 JSON 请求体:
@@ -254,33 +146,23 @@ Pydantic 模型的每个属性都具有类型。
}
```
-!!! info
- 请注意 `images` 键现在具有一组 image 对象是如何发生的。
+/// info
-## 深度嵌套模型
+请注意 `images` 键现在具有一组 image 对象是如何发生的。
-你可以定义任意深度的嵌套模型:
+///
-=== "Python 3.10+"
-
- ```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!}
- ```
+{* ../../docs_src/body_nested_models/tutorial007_py310.py hl[7,12,18,21,25] *}
-=== "Python 3.8+"
+/// info
- ```Python hl_lines="9 14 20 23 27"
- {!> ../../../docs_src/body_nested_models/tutorial007.py!}
- ```
+请注意 `Offer` 拥有一组 `Item` 而反过来 `Item` 又是一个可选的 `Image` 列表是如何发生的。
-!!! info
- 请注意 `Offer` 拥有一组 `Item` 而反过来 `Item` 又是一个可选的 `Image` 列表是如何发生的。
+///
## 纯列表请求体
@@ -292,17 +174,7 @@ images: List[Image]
例如:
-=== "Python 3.9+"
-
- ```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!}
- ```
+{* ../../docs_src/body_nested_models/tutorial008_py39.py hl[13] *}
## 无处不在的编辑器支持
@@ -332,26 +204,19 @@ images: List[Image]
在下面的例子中,你将接受任意键为 `int` 类型并且值为 `float` 类型的 `dict`:
-=== "Python 3.9+"
-
- ```Python hl_lines="7"
- {!> ../../../docs_src/body_nested_models/tutorial009_py39.py!}
- ```
+{* ../../docs_src/body_nested_models/tutorial009_py39.py hl[7] *}
-=== "Python 3.8+"
+/// tip
- ```Python hl_lines="9"
- {!> ../../../docs_src/body_nested_models/tutorial009.py!}
- ```
+请记住 JSON 仅支持将 `str` 作为键。
-!!! tip
- 请记住 JSON 仅支持将 `str` 作为键。
+但是 Pydantic 具有自动转换数据的功能。
- 但是 Pydantic 具有自动转换数据的功能。
+这意味着,即使你的 API 客户端只能将字符串作为键发送,只要这些字符串内容仅包含整数,Pydantic 就会对其进行转换并校验。
- 这意味着,即使你的 API 客户端只能将字符串作为键发送,只要这些字符串内容仅包含整数,Pydantic 就会对其进行转换并校验。
+然后你接收的名为 `weights` 的 `dict` 实际上将具有 `int` 类型的键和 `float` 类型的值。
- 然后你接收的名为 `weights` 的 `dict` 实际上将具有 `int` 类型的键和 `float` 类型的值。
+///
## 总结
diff --git a/docs/zh/docs/tutorial/body-updates.md b/docs/zh/docs/tutorial/body-updates.md
index e529fc914..87f88f255 100644
--- a/docs/zh/docs/tutorial/body-updates.md
+++ b/docs/zh/docs/tutorial/body-updates.md
@@ -6,9 +6,7 @@
把输入数据转换为以 JSON 格式存储的数据(比如,使用 NoSQL 数据库时),可以使用 `jsonable_encoder`。例如,把 `datetime` 转换为 `str`。
-```Python hl_lines="30-35"
-{!../../../docs_src/body_updates/tutorial001.py!}
-```
+{* ../../docs_src/body_updates/tutorial001.py hl[30:35] *}
`PUT` 用于接收替换现有数据的数据。
@@ -34,15 +32,17 @@
即,只发送要更新的数据,其余数据保持不变。
-!!! note "笔记"
+/// note | 笔记
+
+`PATCH` 没有 `PUT` 知名,也怎么不常用。
- `PATCH` 没有 `PUT` 知名,也怎么不常用。
+很多人甚至只用 `PUT` 实现部分更新。
- 很多人甚至只用 `PUT` 实现部分更新。
+**FastAPI** 对此没有任何限制,可以**随意**互换使用这两种操作。
- **FastAPI** 对此没有任何限制,可以**随意**互换使用这两种操作。
+但本指南也会分别介绍这两种操作各自的用途。
- 但本指南也会分别介绍这两种操作各自的用途。
+///
### 使用 Pydantic 的 `exclude_unset` 参数
@@ -54,9 +54,7 @@
然后再用它生成一个只含已设置(在请求中所发送)数据,且省略了默认值的 `dict`:
-```Python hl_lines="34"
-{!../../../docs_src/body_updates/tutorial002.py!}
-```
+{* ../../docs_src/body_updates/tutorial002.py hl[34] *}
### 使用 Pydantic 的 `update` 参数
@@ -64,9 +62,7 @@
例如,`stored_item_model.copy(update=update_data)`:
-```Python hl_lines="35"
-{!../../../docs_src/body_updates/tutorial002.py!}
-```
+{* ../../docs_src/body_updates/tutorial002.py hl[35] *}
### 更新部分数据小结
@@ -83,19 +79,21 @@
* 把数据保存至数据库;
* 返回更新后的模型。
-```Python hl_lines="30-37"
-{!../../../docs_src/body_updates/tutorial002.py!}
-```
+{* ../../docs_src/body_updates/tutorial002.py hl[30:37] *}
+
+/// tip | 提示
+
+实际上,HTTP `PUT` 也可以完成相同的操作。
+但本节以 `PATCH` 为例的原因是,该操作就是为了这种用例创建的。
-!!! tip "提示"
+///
- 实际上,HTTP `PUT` 也可以完成相同的操作。
- 但本节以 `PATCH` 为例的原因是,该操作就是为了这种用例创建的。
+/// note | 笔记
-!!! note "笔记"
+注意,输入模型仍需验证。
- 注意,输入模型仍需验证。
+因此,如果希望接收的部分更新数据可以省略其他所有属性,则要把模型中所有的属性标记为可选(使用默认值或 `None`)。
- 因此,如果希望接收的部分更新数据可以省略其他所有属性,则要把模型中所有的属性标记为可选(使用默认值或 `None`)。
+为了区分用于**更新**所有可选值的模型与用于**创建**包含必选值的模型,请参照[更多模型](extra-models.md){.internal-link target=_blank} 一节中的思路。
- 为了区分用于**更新**所有可选值的模型与用于**创建**包含必选值的模型,请参照[更多模型](extra-models.md){.internal-link target=_blank} 一节中的思路。
+///
diff --git a/docs/zh/docs/tutorial/body.md b/docs/zh/docs/tutorial/body.md
index 65d459cd1..3820fc747 100644
--- a/docs/zh/docs/tutorial/body.md
+++ b/docs/zh/docs/tutorial/body.md
@@ -8,29 +8,21 @@ API 基本上肯定要发送**响应体**,但是客户端不一定发送**请
使用 Pydantic 模型声明**请求体**,能充分利用它的功能和优点。
-!!! info "说明"
+/// info | 说明
- 发送数据使用 `POST`(最常用)、`PUT`、`DELETE`、`PATCH` 等操作。
+发送数据使用 `POST`(最常用)、`PUT`、`DELETE`、`PATCH` 等操作。
- 规范中没有定义使用 `GET` 发送请求体的操作,但不管怎样,FastAPI 也支持这种方式,只不过仅用于非常复杂或极端的用例。
+规范中没有定义使用 `GET` 发送请求体的操作,但不管怎样,FastAPI 也支持这种方式,只不过仅用于非常复杂或极端的用例。
- 我们不建议使用 `GET`,因此,在 Swagger UI 交互文档中不会显示有关 `GET` 的内容,而且代理协议也不一定支持 `GET`。
+我们不建议使用 `GET`,因此,在 Swagger UI 交互文档中不会显示有关 `GET` 的内容,而且代理协议也不一定支持 `GET`。
+
+///
## 导入 Pydantic 的 `BaseModel`
从 `pydantic` 中导入 `BaseModel`:
-=== "Python 3.10+"
-
- ```Python hl_lines="2"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="4"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
+{* ../../docs_src/body/tutorial001_py310.py hl[2] *}
## 创建数据模型
@@ -38,17 +30,7 @@ API 基本上肯定要发送**响应体**,但是客户端不一定发送**请
使用 Python 标准类型声明所有属性:
-=== "Python 3.10+"
-
- ```Python hl_lines="5-9"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="7-11"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
+{* ../../docs_src/body/tutorial001_py310.py hl[5:9] *}
与声明查询参数一样,包含默认值的模型属性是可选的,否则就是必选的。默认值为 `None` 的模型属性也是可选的。
@@ -76,17 +58,7 @@ API 基本上肯定要发送**响应体**,但是客户端不一定发送**请
使用与声明路径和查询参数相同的方式声明请求体,把请求体添加至*路径操作*:
-=== "Python 3.10+"
-
- ```Python hl_lines="16"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="18"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
+{* ../../docs_src/body/tutorial001_py310.py hl[16] *}
……此处,请求体参数的类型为 `Item` 模型。
@@ -135,33 +107,25 @@ Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文
-!!! tip "提示"
+/// tip | 提示
+
+使用 PyCharm 编辑器时,推荐安装 Pydantic PyCharm 插件。
- 使用 PyCharm 编辑器时,推荐安装 Pydantic PyCharm 插件。
+该插件用于完善 PyCharm 对 Pydantic 模型的支持,优化的功能如下:
- 该插件用于完善 PyCharm 对 Pydantic 模型的支持,优化的功能如下:
+* 自动补全
+* 类型检查
+* 代码重构
+* 查找
+* 代码审查
- * 自动补全
- * 类型检查
- * 代码重构
- * 查找
- * 代码审查
+///
## 使用模型
在*路径操作*函数内部直接访问模型对象的属性:
-=== "Python 3.10+"
-
- ```Python hl_lines="19"
- {!> ../../../docs_src/body/tutorial002_py310.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="21"
- {!> ../../../docs_src/body/tutorial002.py!}
- ```
+{* ../../docs_src/body/tutorial002_py310.py hl[19] *}
## 请求体 + 路径参数
@@ -169,17 +133,7 @@ Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文
**FastAPI** 能识别与**路径参数**匹配的函数参数,还能识别从**请求体**中获取的类型为 Pydantic 模型的函数参数。
-=== "Python 3.10+"
-
- ```Python hl_lines="15-16"
- {!> ../../../docs_src/body/tutorial003_py310.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="17-18"
- {!> ../../../docs_src/body/tutorial003.py!}
- ```
+{* ../../docs_src/body/tutorial003_py310.py hl[15:16] *}
## 请求体 + 路径参数 + 查询参数
@@ -187,17 +141,7 @@ Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文
**FastAPI** 能够正确识别这三种参数,并从正确的位置获取数据。
-=== "Python 3.10+"
-
- ```Python hl_lines="16"
- {!> ../../../docs_src/body/tutorial004_py310.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="18"
- {!> ../../../docs_src/body/tutorial004.py!}
- ```
+{* ../../docs_src/body/tutorial004_py310.py hl[16] *}
函数参数按如下规则进行识别:
@@ -205,11 +149,13 @@ Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文
- 类型是(`int`、`float`、`str`、`bool` 等)**单类型**的参数,是**查询**参数
- 类型是 **Pydantic 模型**的参数,是**请求体**
-!!! note "笔记"
+/// note | 笔记
+
+因为默认值是 `None`, FastAPI 会把 `q` 当作可选参数。
- 因为默认值是 `None`, FastAPI 会把 `q` 当作可选参数。
+FastAPI 不使用 `Optional[str]` 中的 `Optional`, 但 `Optional` 可以让编辑器提供更好的支持,并检测错误。
- FastAPI 不使用 `Optional[str]` 中的 `Optional`, 但 `Optional` 可以让编辑器提供更好的支持,并检测错误。
+///
## 不使用 Pydantic
diff --git a/docs/zh/docs/tutorial/cookie-param-models.md b/docs/zh/docs/tutorial/cookie-param-models.md
new file mode 100644
index 000000000..6a7b09e25
--- /dev/null
+++ b/docs/zh/docs/tutorial/cookie-param-models.md
@@ -0,0 +1,76 @@
+# Cookie 参数模型
+
+如果您有一组相关的 **cookie**,您可以创建一个 **Pydantic 模型**来声明它们。🍪
+
+这将允许您在**多个地方**能够**重用模型**,并且可以一次性声明所有参数的验证方式和元数据。😎
+
+/// note
+
+自 FastAPI 版本 `0.115.0` 起支持此功能。🤓
+
+///
+
+/// tip
+
+此技术同样适用于 `Query` 、 `Cookie` 和 `Header` 。😎
+
+///
+
+## 带有 Pydantic 模型的 Cookie
+
+在 **Pydantic** 模型中声明所需的 **cookie** 参数,然后将参数声明为 `Cookie` :
+
+{* ../../docs_src/cookie_param_models/tutorial001_an_py310.py hl[9:12,16] *}
+
+**FastAPI** 将从请求中接收到的 **cookie** 中**提取**出**每个字段**的数据,并提供您定义的 Pydantic 模型。
+
+## 查看文档
+
+您可以在文档 UI 的 `/docs` 中查看定义的 cookie:
+
+
get
操作
-!!! info "`@decorator` Info"
- `@something` 语法在 Python 中被称为「装饰器」。
+/// info | `@decorator` Info
- 像一顶漂亮的装饰帽一样,将它放在一个函数的上方(我猜测这个术语的命名就是这么来的)。
+`@something` 语法在 Python 中被称为「装饰器」。
- 装饰器接收位于其下方的函数并且用它完成一些工作。
+像一顶漂亮的装饰帽一样,将它放在一个函数的上方(我猜测这个术语的命名就是这么来的)。
- 在我们的例子中,这个装饰器告诉 **FastAPI** 位于其下方的函数对应着**路径** `/` 加上 `get` **操作**。
+装饰器接收位于其下方的函数并且用它完成一些工作。
- 它是一个「**路径操作装饰器**」。
+在我们的例子中,这个装饰器告诉 **FastAPI** 位于其下方的函数对应着**路径** `/` 加上 `get` **操作**。
+
+它是一个「**路径操作装饰器**」。
+
+///
你也可以使用其他的操作:
@@ -276,14 +264,17 @@ https://example.com/items/foo
* `@app.patch()`
* `@app.trace()`
-!!! tip
- 您可以随意使用任何一个操作(HTTP方法)。
+/// tip
+
+你可以随意使用任何一个操作(HTTP方法)。
- **FastAPI** 没有强制要求操作有任何特定的含义。
+**FastAPI** 没有强制要求操作有任何特定的含义。
- 此处提供的信息仅作为指导,而不是要求。
+此处提供的信息仅作为指导,而不是要求。
- 比如,当使用 GraphQL 时通常你所有的动作都通过 `post` 一种方法执行。
+比如,当使用 GraphQL 时通常你所有的动作都通过 `POST` 一种方法执行。
+
+///
### 步骤 4:定义**路径操作函数**
@@ -293,9 +284,7 @@ https://example.com/items/foo
* **操作**:是 `get`。
* **函数**:是位于「装饰器」下方的函数(位于 `@app.get("/")` 下方)。
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[7] *}
这是一个 Python 函数。
@@ -307,18 +296,17 @@ https://example.com/items/foo
你也可以将其定义为常规函数而不使用 `async def`:
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial003.py!}
-```
+{* ../../docs_src/first_steps/tutorial003.py hl[7] *}
-!!! note
- 如果你不知道两者的区别,请查阅 [Async: *"In a hurry?"*](https://fastapi.tiangolo.com/async/#in-a-hurry){.internal-link target=_blank}。
+/// note
+
+如果你不知道两者的区别,请查阅 [并发: *赶时间吗?*](../async.md#_1){.internal-link target=_blank}。
+
+///
### 步骤 5:返回内容
-```Python hl_lines="8"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001.py hl[8] *}
你可以返回一个 `dict`、`list`,像 `str`、`int` 一样的单个值,等等。
@@ -330,6 +318,6 @@ https://example.com/items/foo
* 导入 `FastAPI`。
* 创建一个 `app` 实例。
-* 编写一个**路径操作装饰器**(如 `@app.get("/")`)。
-* 编写一个**路径操作函数**(如上面的 `def root(): ...`)。
-* 运行开发服务器(如 `uvicorn main:app --reload`)。
+* 编写一个**路径操作装饰器**,如 `@app.get("/")`。
+* 定义一个**路径操作函数**,如 `def root(): ...`。
+* 使用命令 `fastapi dev` 运行开发服务器。
diff --git a/docs/zh/docs/tutorial/handling-errors.md b/docs/zh/docs/tutorial/handling-errors.md
index 701cd241e..0b887c292 100644
--- a/docs/zh/docs/tutorial/handling-errors.md
+++ b/docs/zh/docs/tutorial/handling-errors.md
@@ -25,10 +25,7 @@
### 导入 `HTTPException`
-```Python hl_lines="1"
-{!../../../docs_src/handling_errors/tutorial001.py!}
-
-```
+{* ../../docs_src/handling_errors/tutorial001.py hl[1] *}
### 触发 `HTTPException`
@@ -42,10 +39,7 @@
本例中,客户端用 `ID` 请求的 `item` 不存在时,触发状态码为 `404` 的异常:
-```Python hl_lines="11"
-{!../../../docs_src/handling_errors/tutorial001.py!}
-
-```
+{* ../../docs_src/handling_errors/tutorial001.py hl[11] *}
### 响应结果
@@ -67,14 +61,15 @@
```
-!!! tip "提示"
+/// tip | 提示
- 触发 `HTTPException` 时,可以用参数 `detail` 传递任何能转换为 JSON 的值,不仅限于 `str`。
+触发 `HTTPException` 时,可以用参数 `detail` 传递任何能转换为 JSON 的值,不仅限于 `str`。
- 还支持传递 `dict`、`list` 等数据结构。
+还支持传递 `dict`、`list` 等数据结构。
- **FastAPI** 能自动处理这些数据,并将之转换为 JSON。
+**FastAPI** 能自动处理这些数据,并将之转换为 JSON。
+///
## 添加自定义响应头
@@ -84,10 +79,7 @@
但对于某些高级应用场景,还是需要添加自定义响应头:
-```Python hl_lines="14"
-{!../../../docs_src/handling_errors/tutorial002.py!}
-
-```
+{* ../../docs_src/handling_errors/tutorial002.py hl[14] *}
## 安装自定义异常处理器
@@ -99,10 +91,7 @@
此时,可以用 `@app.exception_handler()` 添加自定义异常控制器:
-```Python hl_lines="5-7 13-18 24"
-{!../../../docs_src/handling_errors/tutorial003.py!}
-
-```
+{* ../../docs_src/handling_errors/tutorial003.py hl[5:7,13:18,24] *}
请求 `/unicorns/yolo` 时,路径操作会触发 `UnicornException`。
@@ -115,12 +104,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` 也是如此。
+///
## 覆盖默认异常处理器
@@ -140,10 +130,7 @@
这样,异常处理器就可以接收 `Request` 与异常。
-```Python hl_lines="2 14-16"
-{!../../../docs_src/handling_errors/tutorial004.py!}
-
-```
+{* ../../docs_src/handling_errors/tutorial004.py hl[2,14:16] *}
访问 `/items/foo`,可以看到默认的 JSON 错误信息:
@@ -174,10 +161,11 @@ path -> item_id
### `RequestValidationError` vs `ValidationError`
-!!! warning "警告"
+/// warning | 警告
- 如果您觉得现在还用不到以下技术细节,可以先跳过下面的内容。
+如果您觉得现在还用不到以下技术细节,可以先跳过下面的内容。
+///
`RequestValidationError` 是 Pydantic 的 `ValidationError` 的子类。
@@ -195,17 +183,15 @@ path -> item_id
例如,只为错误返回纯文本响应,而不是返回 JSON 格式的内容:
-```Python hl_lines="3-4 9-11 22"
-{!../../../docs_src/handling_errors/tutorial004.py!}
-
-```
+{* ../../docs_src/handling_errors/tutorial004.py hl[3:4,9:11,22] *}
-!!! note "技术细节"
+/// note | 技术细节
- 还可以使用 `from starlette.responses import PlainTextResponse`。
+还可以使用 `from starlette.responses import PlainTextResponse`。
- **FastAPI** 提供了与 `starlette.responses` 相同的 `fastapi.responses` 作为快捷方式,但大部分响应都可以直接从 Starlette 导入。
+**FastAPI** 提供了与 `starlette.responses` 相同的 `fastapi.responses` 作为快捷方式,但大部分响应都可以直接从 Starlette 导入。
+///
### 使用 `RequestValidationError` 的请求体
@@ -213,10 +199,7 @@ path -> item_id
开发时,可以用这个请求体生成日志、调试错误,并返回给用户。
-```Python hl_lines="14"
-{!../../../docs_src/handling_errors/tutorial005.py!}
-
-```
+{* ../../docs_src/handling_errors/tutorial005.py hl[14] *}
现在试着发送一个无效的 `item`,例如:
@@ -279,10 +262,7 @@ FastAPI 支持先对异常进行某些处理,然后再使用 **FastAPI** 中
从 `fastapi.exception_handlers` 中导入要复用的默认异常处理器:
-```Python hl_lines="2-5 15 21"
-{!../../../docs_src/handling_errors/tutorial006.py!}
-
-```
+{* ../../docs_src/handling_errors/tutorial006.py hl[2:5,15,21] *}
虽然,本例只是输出了夸大其词的错误信息。
diff --git a/docs/zh/docs/tutorial/header-param-models.md b/docs/zh/docs/tutorial/header-param-models.md
new file mode 100644
index 000000000..13366aebc
--- /dev/null
+++ b/docs/zh/docs/tutorial/header-param-models.md
@@ -0,0 +1,56 @@
+# Header 参数模型
+
+如果您有一组相关的 **header 参数**,您可以创建一个 **Pydantic 模型**来声明它们。
+
+这将允许您在**多个地方**能够**重用模型**,并且可以一次性声明所有参数的验证和元数据。😎
+
+/// note
+
+自 FastAPI 版本 `0.115.0` 起支持此功能。🤓
+
+///
+
+## 使用 Pydantic 模型的 Header 参数
+
+在 **Pydantic 模型**中声明所需的 **header 参数**,然后将参数声明为 `Header` :
+
+{* ../../docs_src/header_param_models/tutorial001_an_py310.py hl[9:14,18] *}
+
+**FastAPI** 将从请求中接收到的 **headers** 中**提取**出**每个字段**的数据,并提供您定义的 Pydantic 模型。
+
+## 查看文档
+
+您可以在文档 UI 的 `/docs` 中查看所需的 headers:
+
+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 格式。 |
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 格式。 |
kwargs
,来调用。即使它们没有默认值。
-```Python hl_lines="7"
-{!../../../docs_src/path_params_numeric_validations/tutorial003.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *}
## 数值校验:大于等于
@@ -134,9 +60,7 @@ Python 不会对该 `*` 做任何事情,但是它将知道之后的所有参
像下面这样,添加 `ge=1` 后,`item_id` 将必须是一个大于(`g`reater than)或等于(`e`qual)`1` 的整数。
-```Python hl_lines="8"
-{!../../../docs_src/path_params_numeric_validations/tutorial004.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial004.py hl[8] *}
## 数值校验:大于和小于等于
@@ -145,9 +69,7 @@ Python 不会对该 `*` 做任何事情,但是它将知道之后的所有参
* `gt`:大于(`g`reater `t`han)
* `le`:小于等于(`l`ess than or `e`qual)
-```Python hl_lines="9"
-{!../../../docs_src/path_params_numeric_validations/tutorial005.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial005.py hl[9] *}
## 数值校验:浮点数、大于和小于
@@ -159,9 +81,7 @@ Python 不会对该 `*` 做任何事情,但是它将知道之后的所有参
对于 lt
也是一样的。
-```Python hl_lines="11"
-{!../../../docs_src/path_params_numeric_validations/tutorial006.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial006.py hl[11] *}
## 总结
@@ -174,18 +94,24 @@ Python 不会对该 `*` 做任何事情,但是它将知道之后的所有参
* `lt`:小于(`l`ess `t`han)
* `le`:小于等于(`l`ess than or `e`qual)
-!!! info
- `Query`、`Path` 以及你后面会看到的其他类继承自一个共同的 `Param` 类(不需要直接使用它)。
+/// info
+
+`Query`、`Path` 以及你后面会看到的其他类继承自一个共同的 `Param` 类(不需要直接使用它)。
+
+而且它们都共享相同的所有你已看到并用于添加额外校验和元数据的参数。
+
+///
+
+/// note | 技术细节
- 而且它们都共享相同的所有你已看到并用于添加额外校验和元数据的参数。
+当你从 `fastapi` 导入 `Query`、`Path` 和其他同类对象时,它们实际上是函数。
-!!! note "技术细节"
- 当你从 `fastapi` 导入 `Query`、`Path` 和其他同类对象时,它们实际上是函数。
+当被调用时,它们返回同名类的实例。
- 当被调用时,它们返回同名类的实例。
+如此,你导入 `Query` 这个函数。当你调用它时,它将返回一个同样命名为 `Query` 的类的实例。
- 如此,你导入 `Query` 这个函数。当你调用它时,它将返回一个同样命名为 `Query` 的类的实例。
+因为使用了这些函数(而不是直接使用类),所以你的编辑器不会标记有关其类型的错误。
- 因为使用了这些函数(而不是直接使用类),所以你的编辑器不会标记有关其类型的错误。
+这样,你可以使用常规的编辑器和编码工具,而不必添加自定义配置来忽略这些错误。
- 这样,你可以使用常规的编辑器和编码工具,而不必添加自定义配置来忽略这些错误。
+///
diff --git a/docs/zh/docs/tutorial/path-params.md b/docs/zh/docs/tutorial/path-params.md
index 12a08b4a3..ac9df0831 100644
--- a/docs/zh/docs/tutorial/path-params.md
+++ b/docs/zh/docs/tutorial/path-params.md
@@ -2,9 +2,7 @@
FastAPI 支持使用 Python 字符串格式化语法声明**路径参数**(**变量**):
-```Python hl_lines="6-7"
-{!../../../docs_src/path_params/tutorial001.py!}
-```
+{* ../../docs_src/path_params/tutorial001.py hl[6:7] *}
这段代码把路径参数 `item_id` 的值传递给路径函数的参数 `item_id`。
@@ -18,15 +16,15 @@ FastAPI 支持使用 Python 字符串格式化语法声明**路径参数**(**
使用 Python 标准类型注解,声明路径操作函数中路径参数的类型。
-```Python hl_lines="7"
-{!../../../docs_src/path_params/tutorial002.py!}
-```
+{* ../../docs_src/path_params/tutorial002.py hl[7] *}
本例把 `item_id` 的类型声明为 `int`。
-!!! check "检查"
+/// check | 检查
+
+类型声明将为函数提供错误检查、代码补全等编辑器支持。
- 类型声明将为函数提供错误检查、代码补全等编辑器支持。
+///
## 数据转换
@@ -36,11 +34,13 @@ FastAPI 支持使用 Python 字符串格式化语法声明**路径参数**(**
{"item_id":3}
```
-!!! check "检查"
+/// check | 检查
- 注意,函数接收并返回的值是 `3`( `int`),不是 `"3"`(`str`)。
+注意,函数接收并返回的值是 `3`( `int`),不是 `"3"`(`str`)。
- **FastAPI** 通过类型声明自动**解析**请求中的数据。
+**FastAPI** 通过类型声明自动**解析**请求中的数据。
+
+///
## 数据校验
@@ -65,13 +65,15 @@ FastAPI 支持使用 Python 字符串格式化语法声明**路径参数**(**
值的类型不是 `int ` 而是浮点数(`float`)时也会显示同样的错误,比如: http://127.0.0.1:8000/items/4.2。
-!!! check "检查"
+/// check | 检查
+
+**FastAPI** 使用 Python 类型声明实现了数据校验。
- **FastAPI** 使用 Python 类型声明实现了数据校验。
+注意,上面的错误清晰地指出了未通过校验的具体原因。
- 注意,上面的错误清晰地指出了未通过校验的具体原因。
+这在开发调试与 API 交互的代码时非常有用。
- 这在开发调试与 API 交互的代码时非常有用。
+///
## 查看文档
@@ -79,11 +81,13 @@ FastAPI 支持使用 Python 字符串格式化语法声明**路径参数**(**
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`。
-## 可选文件上传
-
-您可以通过使用标准类型注解并将 None 作为默认值的方式将一个文件参数设为可选:
+这不是 **FastAPI** 的问题,而是 HTTP 协议的规定。
-=== "Python 3.9+"
+///
- ```Python hl_lines="7 14"
- {!> ../../../docs_src/request_files/tutorial001_02_py310.py!}
- ```
+## 可选文件上传
-=== "Python 3.8+"
+您可以通过使用标准类型注解并将 None 作为默认值的方式将一个文件参数设为可选:
- ```Python hl_lines="9 17"
- {!> ../../../docs_src/request_files/tutorial001_02.py!}
- ```
+{* ../../docs_src/request_files/tutorial001_02_py310.py hl[7,14] *}
## 带有额外元数据的 `UploadFile`
您也可以将 `File()` 与 `UploadFile` 一起使用,例如,设置额外的元数据:
-```Python hl_lines="13"
-{!../../../docs_src/request_files/tutorial001_03.py!}
-```
+{* ../../docs_src/request_files/tutorial001_03.py hl[13] *}
## 多文件上传
@@ -152,42 +148,24 @@ FastAPI 支持同时上传多个文件。
上传多个文件时,要声明含 `bytes` 或 `UploadFile` 的列表(`List`):
-=== "Python 3.9+"
-
- ```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!}
- ```
+{* ../../docs_src/request_files/tutorial002_py39.py hl[8,13] *}
接收的也是含 `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+"
-
- ```Python hl_lines="16"
- {!> ../../../docs_src/request_files/tutorial003_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="18"
- {!> ../../../docs_src/request_files/tutorial003.py!}
- ```
+{* ../../docs_src/request_files/tutorial003_py39.py hl[16] *}
## 小结
diff --git a/docs/zh/docs/tutorial/request-form-models.md b/docs/zh/docs/tutorial/request-form-models.md
new file mode 100644
index 000000000..e639e4b9f
--- /dev/null
+++ b/docs/zh/docs/tutorial/request-form-models.md
@@ -0,0 +1,78 @@
+# 表单模型
+
+您可以使用 **Pydantic 模型**在 FastAPI 中声明**表单字段**。
+
+/// info
+
+要使用表单,需预先安装 `python-multipart` 。
+
+确保您创建、激活一个[虚拟环境](../virtual-environments.md){.internal-link target=_blank}后再安装。
+
+```console
+$ pip install python-multipart
+```
+
+///
+
+/// note
+
+自 FastAPI 版本 `0.113.0` 起支持此功能。🤓
+
+///
+
+## 表单的 Pydantic 模型
+
+您只需声明一个 **Pydantic 模型**,其中包含您希望接收的**表单字段**,然后将参数声明为 `Form` :
+
+{* ../../docs_src/request_form_models/tutorial001_an_py39.py hl[9:11,15] *}
+
+**FastAPI** 将从请求中的**表单数据**中**提取**出**每个字段**的数据,并提供您定义的 Pydantic 模型。
+
+## 检查文档
+
+您可以在文档 UI 中验证它,地址为 `/docs` :
+
+POST
小节。
- 但包含文件的表单编码为 `multipart/form-data`。文件处理详见下节。
+///
- 编码和表单字段详见 MDN Web 文档的 POST
小节。
+/// warning | 警告
-!!! warning "警告"
+可在一个*路径操作*中声明多个 `Form` 参数,但不能同时声明要接收 JSON 的 `Body` 字段。因为此时请求体的编码是 `application/x-www-form-urlencoded`,不是 `application/json`。
- 可在一个*路径操作*中声明多个 `Form` 参数,但不能同时声明要接收 JSON 的 `Body` 字段。因为此时请求体的编码是 `application/x-www-form-urlencoded`,不是 `application/json`。
+这不是 **FastAPI** 的问题,而是 HTTP 协议的规定。
- 这不是 **FastAPI** 的问题,而是 HTTP 协议的规定。
+///
## 小结
diff --git a/docs/zh/docs/tutorial/response-model.md b/docs/zh/docs/tutorial/response-model.md
index 0f1b3b4b9..049cd1223 100644
--- a/docs/zh/docs/tutorial/response-model.md
+++ b/docs/zh/docs/tutorial/response-model.md
@@ -8,26 +8,13 @@
* `@app.delete()`
* 等等。
-=== "Python 3.10+"
+{* ../../docs_src/response_model/tutorial001_py310.py hl[17,22,24:27] *}
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001_py310.py!}
- ```
+/// note
-=== "Python 3.9+"
+注意,`response_model`是「装饰器」方法(`get`,`post` 等)的一个参数。不像之前的所有参数和请求体,它不属于*路径操作函数*。
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001_py39.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001.py!}
- ```
-
-!!! note
- 注意,`response_model`是「装饰器」方法(`get`,`post` 等)的一个参数。不像之前的所有参数和请求体,它不属于*路径操作函数*。
+///
它接收的类型与你将为 Pydantic 模型属性所声明的类型相同,因此它可以是一个 Pydantic 模型,但也可以是一个由 Pydantic 模型组成的 `list`,例如 `List[Item]`。
@@ -42,22 +29,21 @@ FastAPI 将使用此 `response_model` 来:
* 会将输出数据限制在该模型定义内。下面我们会看到这一点有多重要。
-!!! note "技术细节"
- 响应模型在参数中被声明,而不是作为函数返回类型的注解,这是因为路径函数可能不会真正返回该响应模型,而是返回一个 `dict`、数据库对象或其他模型,然后再使用 `response_model` 来执行字段约束和序列化。
+/// note | 技术细节
+
+响应模型在参数中被声明,而不是作为函数返回类型的注解,这是因为路径函数可能不会真正返回该响应模型,而是返回一个 `dict`、数据库对象或其他模型,然后再使用 `response_model` 来执行字段约束和序列化。
+
+///
## 返回与输入相同的数据
现在我们声明一个 `UserIn` 模型,它将包含一个明文密码属性。
-```Python hl_lines="9 11"
-{!../../../docs_src/response_model/tutorial002.py!}
-```
+{* ../../docs_src/response_model/tutorial002.py hl[9,11] *}
我们正在使用此模型声明输入数据,并使用同一模型声明输出数据:
-```Python hl_lines="17-18"
-{!../../../docs_src/response_model/tutorial002.py!}
-```
+{* ../../docs_src/response_model/tutorial002.py hl[17:18] *}
现在,每当浏览器使用一个密码创建用户时,API 都会在响应中返回相同的密码。
@@ -65,52 +51,25 @@ FastAPI 将使用此 `response_model` 来:
但是,如果我们在其他的*路径操作*中使用相同的模型,则可能会将用户的密码发送给每个客户端。
-!!! danger
- 永远不要存储用户的明文密码,也不要在响应中发送密码。
-
-## 添加输出模型
+/// danger
-相反,我们可以创建一个有明文密码的输入模型和一个没有明文密码的输出模型:
+永远不要存储用户的明文密码,也不要在响应中发送密码。
-=== "Python 3.10+"
+///
- ```Python hl_lines="9 11 16"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
+## 添加输出模型
-=== "Python 3.8+"
+相反,我们可以创建一个有明文密码的输入模型和一个没有明文密码的输出模型:
- ```Python hl_lines="9 11 16"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+{* ../../docs_src/response_model/tutorial003_py310.py hl[9,11,16] *}
这样,即便我们的*路径操作函数*将会返回包含密码的相同输入用户:
-=== "Python 3.10+"
-
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+{* ../../docs_src/response_model/tutorial003_py310.py hl[24] *}
...我们已经将 `response_model` 声明为了不包含密码的 `UserOut` 模型:
-=== "Python 3.10+"
-
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
-
-=== "Python 3.8+"
-
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+{* ../../docs_src/response_model/tutorial003_py310.py hl[22] *}
因此,**FastAPI** 将会负责过滤掉未在输出模型中声明的所有数据(使用 Pydantic)。
@@ -128,9 +87,7 @@ FastAPI 将使用此 `response_model` 来:
你的响应模型可以具有默认值,例如:
-```Python hl_lines="11 13-14"
-{!../../../docs_src/response_model/tutorial004.py!}
-```
+{* ../../docs_src/response_model/tutorial004.py hl[11,13:14] *}
* `description: Union[str, None] = None` 具有默认值 `None`。
* `tax: float = 10.5` 具有默认值 `10.5`.
@@ -144,9 +101,7 @@ FastAPI 将使用此 `response_model` 来:
你可以设置*路径操作装饰器*的 `response_model_exclude_unset=True` 参数:
-```Python hl_lines="24"
-{!../../../docs_src/response_model/tutorial004.py!}
-```
+{* ../../docs_src/response_model/tutorial004.py hl[24] *}
然后响应中将不会包含那些默认值,而是仅有实际设置的值。
@@ -159,16 +114,22 @@ FastAPI 将使用此 `response_model` 来:
}
```
-!!! info
- FastAPI 通过 Pydantic 模型的 `.dict()` 配合 该方法的 `exclude_unset` 参数 来实现此功能。
+/// info
+
+FastAPI 通过 Pydantic 模型的 `.dict()` 配合 该方法的 `exclude_unset` 参数 来实现此功能。
+
+///
+
+/// info
+
+你还可以使用:
-!!! info
- 你还可以使用:
+* `response_model_exclude_defaults=True`
+* `response_model_exclude_none=True`
- * `response_model_exclude_defaults=True`
- * `response_model_exclude_none=True`
+参考 Pydantic 文档 中对 `exclude_defaults` 和 `exclude_none` 的描述。
- 参考 Pydantic 文档 中对 `exclude_defaults` 和 `exclude_none` 的描述。
+///
#### 默认值字段有实际值的数据
@@ -203,10 +164,13 @@ FastAPI 将使用此 `response_model` 来:
因此,它们将包含在 JSON 响应中。
-!!! tip
- 请注意默认值可以是任何值,而不仅是`None`。
+/// tip
- 它们可以是一个列表(`[]`),一个值为 `10.5`的 `float`,等等。
+请注意默认值可以是任何值,而不仅是`None`。
+
+它们可以是一个列表(`[]`),一个值为 `10.5`的 `float`,等等。
+
+///
### `response_model_include` 和 `response_model_exclude`
@@ -216,29 +180,31 @@ 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 仍将是完整的模型。
-```Python hl_lines="31 37"
-{!../../../docs_src/response_model/tutorial005.py!}
-```
+这也适用于作用类似的 `response_model_by_alias`。
+
+///
-!!! tip
- `{"name", "description"}` 语法创建一个具有这两个值的 `set`。
+{* ../../docs_src/response_model/tutorial005.py hl[31,37] *}
- 等同于 `set(["name", "description"])`。
+/// tip
+
+`{"name", "description"}` 语法创建一个具有这两个值的 `set`。
+
+等同于 `set(["name", "description"])`。
+
+///
#### 使用 `list` 而不是 `set`
如果你忘记使用 `set` 而是使用 `list` 或 `tuple`,FastAPI 仍会将其转换为 `set` 并且正常工作:
-```Python hl_lines="31 37"
-{!../../../docs_src/response_model/tutorial006.py!}
-```
+{* ../../docs_src/response_model/tutorial006.py hl[31,37] *}
## 总结
diff --git a/docs/zh/docs/tutorial/response-status-code.md b/docs/zh/docs/tutorial/response-status-code.md
index cc23231b4..aa8032ada 100644
--- a/docs/zh/docs/tutorial/response-status-code.md
+++ b/docs/zh/docs/tutorial/response-status-code.md
@@ -8,19 +8,21 @@
* `@app.delete()`
* 等……
-```Python hl_lines="6"
-{!../../../docs_src/response_status_code/tutorial001.py!}
-```
+{* ../../docs_src/response_status_code/tutorial001.py hl[6] *}
-!!! note "笔记"
+/// note | 笔记
- 注意,`status_code` 是(`get`、`post` 等)**装饰器**方法中的参数。与之前的参数和请求体不同,不是*路径操作函数*的参数。
+注意,`status_code` 是(`get`、`post` 等)**装饰器**方法中的参数。与之前的参数和请求体不同,不是*路径操作函数*的参数。
+
+///
`status_code` 参数接收表示 HTTP 状态码的数字。
-!!! info "说明"
+/// info | 说明
+
+`status_code` 还能接收 `IntEnum` 类型,比如 Python 的 `http.HTTPStatus`。
- `status_code` 还能接收 `IntEnum` 类型,比如 Python 的 `http.HTTPStatus`。
+///
它可以:
@@ -29,17 +31,21 @@