diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index e46786a53992c..387063f12c839 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -64,7 +64,7 @@ jobs: BRANCH: ${{ ( github.event.workflow_run.head_repository.full_name == github.repository && github.event.workflow_run.head_branch == 'master' && 'main' ) || ( github.event.workflow_run.head_sha ) }} # TODO: Use v3 when it's fixed, probably in v3.11 # https://github.com/cloudflare/wrangler-action/issues/307 - uses: cloudflare/wrangler-action@v3.11 + uses: cloudflare/wrangler-action@v3.12 # uses: cloudflare/wrangler-action@v3 with: apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }} diff --git a/.github/workflows/latest-changes.yml b/.github/workflows/latest-changes.yml index 16da3bc6359a6..b8b5c42ee9039 100644 --- a/.github/workflows/latest-changes.yml +++ b/.github/workflows/latest-changes.yml @@ -34,7 +34,7 @@ jobs: if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled == 'true' }} with: limit-access-to-actor: true - - uses: tiangolo/latest-changes@0.3.1 + - uses: tiangolo/latest-changes@0.3.2 with: token: ${{ secrets.GITHUB_TOKEN }} latest_changes_file: docs/en/docs/release-notes.md diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index c8ea4e18cb970..fc61c3fca6671 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -35,7 +35,7 @@ jobs: TIANGOLO_BUILD_PACKAGE: ${{ matrix.package }} run: python -m build - name: Publish - uses: pypa/gh-action-pypi-publish@v1.10.3 + uses: pypa/gh-action-pypi-publish@v1.12.2 - name: Dump GitHub context env: GITHUB_CONTEXT: ${{ toJson(github) }} diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 779018ff9633e..767ef8d9e75a2 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -14,7 +14,7 @@ repos: - id: end-of-file-fixer - id: trailing-whitespace - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.7.0 + rev: v0.7.4 hooks: - id: ruff args: diff --git a/README.md b/README.md index a12e740f72774..62eeda03b4a87 100644 --- a/README.md +++ b/README.md @@ -56,6 +56,7 @@ The key features are: + diff --git a/docs/bn/docs/python-types.md b/docs/bn/docs/python-types.md index 4a602b679d050..d98c2ec8716e4 100644 --- a/docs/bn/docs/python-types.md +++ b/docs/bn/docs/python-types.md @@ -22,9 +22,8 @@ Python-এ ঐচ্ছিক "টাইপ হিন্ট" (যা "টাই চলুন একটি সাধারণ উদাহরণ দিয়ে শুরু করি: -```Python -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py *} + এই প্রোগ্রামটি কল করলে আউটপুট হয়: @@ -38,9 +37,8 @@ John Doe * প্রতিটির প্রথম অক্ষরকে `title()` ব্যবহার করে বড় হাতের অক্ষরে রূপান্তর করে। * তাদেরকে মাঝখানে একটি স্পেস দিয়ে concatenate করে। -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py hl[2] *} + ### এটি সম্পাদনা করুন @@ -82,9 +80,8 @@ John Doe এগুলিই "টাইপ হিন্ট": -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial002.py!} -``` +{* ../../docs_src/python_types/tutorial002.py hl[1] *} + এটি ডিফল্ট ভ্যালু ঘোষণা করার মত নয় যেমন: @@ -112,9 +109,8 @@ John Doe এই ফাংশনটি দেখুন, এটিতে ইতিমধ্যে টাইপ হিন্ট রয়েছে: -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial003.py!} -``` +{* ../../docs_src/python_types/tutorial003.py hl[1] *} + এডিটর ভেরিয়েবলগুলির টাইপ জানার কারণে, আপনি শুধুমাত্র অটোকমপ্লিশনই পান না, আপনি এরর চেকও পান: @@ -122,9 +118,8 @@ John Doe এখন আপনি জানেন যে আপনাকে এটি ঠিক করতে হবে, `age`-কে একটি স্ট্রিং হিসেবে রূপান্তর করতে `str(age)` ব্যবহার করতে হবে: -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial004.py!} -``` +{* ../../docs_src/python_types/tutorial004.py hl[2] *} + ## টাইপ ঘোষণা @@ -143,9 +138,8 @@ John Doe * `bool` * `bytes` -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial005.py!} -``` +{* ../../docs_src/python_types/tutorial005.py hl[1] *} + ### টাইপ প্যারামিটার সহ জেনেরিক টাইপ @@ -369,9 +363,8 @@ Python 3.6 এবং তার উপরের সংস্করণগুলি একটি উদাহরণ হিসেবে, এই ফাংশনটি নিন: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial009c.py!} -``` +{* ../../docs_src/python_types/tutorial009c.py hl[1,4] *} + `name` প্যারামিটারটি `Optional[str]` হিসেবে সংজ্ঞায়িত হয়েছে, কিন্তু এটি **অপশনাল নয়**, আপনি প্যারামিটার ছাড়া ফাংশনটি কল করতে পারবেন না: @@ -387,9 +380,8 @@ say_hi(name=None) # এটি কাজ করে, None বৈধ 🎉 সুখবর হল, একবার আপনি Python 3.10 ব্যবহার করা শুরু করলে, আপনাকে এগুলোর ব্যাপারে আর চিন্তা করতে হবে না, যেহুতু আপনি | ব্যবহার করেই ইউনিয়ন ঘোষণা করতে পারবেন: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial009c_py310.py!} -``` +{* ../../docs_src/python_types/tutorial009c_py310.py hl[1,4] *} + এবং তারপর আপনাকে নামগুলি যেমন `Optional` এবং `Union` নিয়ে আর চিন্তা করতে হবে না। 😎 @@ -451,15 +443,13 @@ Python 3.10-এ, `Union` এবং `Optional` জেনেরিকস ব্য ধরুন আপনার কাছে `Person` নামে একটি ক্লাস আছে, যার একটি নাম আছে: -```Python hl_lines="1-3" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[1:3] *} + তারপর আপনি একটি ভেরিয়েবলকে `Person` টাইপের হিসেবে ঘোষণা করতে পারেন: -```Python hl_lines="6" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[6] *} + এবং তারপর, আবার, আপনি এডিটর সাপোর্ট পেয়ে যাবেন: diff --git a/docs/de/docs/advanced/additional-responses.md b/docs/de/docs/advanced/additional-responses.md index a87c564910043..bf38d97952ecd 100644 --- a/docs/de/docs/advanced/additional-responses.md +++ b/docs/de/docs/advanced/additional-responses.md @@ -1,6 +1,6 @@ # Zusätzliche Responses in OpenAPI -/// warning | "Achtung" +/// warning | Achtung Dies ist ein eher fortgeschrittenes Thema. @@ -26,11 +26,9 @@ 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" +/// note | Hinweis Beachten Sie, dass Sie die `JSONResponse` direkt zurückgeben müssen. @@ -177,11 +175,9 @@ 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" +/// note | Hinweis Beachten Sie, dass Sie das Bild direkt mit einer `FileResponse` zurückgeben müssen. @@ -207,9 +203,7 @@ Sie können beispielsweise eine Response mit dem Statuscode `404` deklarieren, d Und eine Response mit dem Statuscode `200`, die Ihr `response_model` verwendet, aber ein benutzerdefiniertes Beispiel (`example`) enthält: -```Python hl_lines="20-31" -{!../../docs_src/additional_responses/tutorial003.py!} -``` +{* ../../docs_src/additional_responses/tutorial003.py hl[20:31] *} Es wird alles kombiniert und in Ihre OpenAPI eingebunden und in der API-Dokumentation angezeigt: @@ -243,9 +237,7 @@ Mit dieser Technik können Sie einige vordefinierte Responses in Ihren *Pfadoper Zum Beispiel: -```Python hl_lines="13-17 26" -{!../../docs_src/additional_responses/tutorial004.py!} -``` +{* ../../docs_src/additional_responses/tutorial004.py hl[13:17,26] *} ## Weitere Informationen zu OpenAPI-Responses diff --git a/docs/de/docs/advanced/additional-status-codes.md b/docs/de/docs/advanced/additional-status-codes.md index fc8d09e4cefb0..b07bb90ab0446 100644 --- a/docs/de/docs/advanced/additional-status-codes.md +++ b/docs/de/docs/advanced/additional-status-codes.md @@ -14,59 +14,9 @@ Sie möchten aber auch, dass sie neue Artikel akzeptiert. Und wenn die Elemente Um dies zu erreichen, importieren Sie `JSONResponse`, und geben Sie Ihren Inhalt direkt zurück, indem Sie den gewünschten `status_code` setzen: -//// tab | Python 3.10+ +{* ../../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!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="4 25" -{!> ../../docs_src/additional_status_codes/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4 26" -{!> ../../docs_src/additional_status_codes/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="2 23" -{!> ../../docs_src/additional_status_codes/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="4 25" -{!> ../../docs_src/additional_status_codes/tutorial001.py!} -``` - -//// - -/// warning | "Achtung" +/// warning | Achtung Wenn Sie eine `Response` direkt zurückgeben, wie im obigen Beispiel, wird sie direkt zurückgegeben. @@ -76,7 +26,7 @@ Stellen Sie sicher, dass sie die gewünschten Daten enthält und dass die Werte /// -/// note | "Technische Details" +/// note | Technische Details Sie können auch `from starlette.responses import JSONResponse` verwenden. diff --git a/docs/de/docs/advanced/advanced-dependencies.md b/docs/de/docs/advanced/advanced-dependencies.md index 54351714e396b..56eb7d4542bd9 100644 --- a/docs/de/docs/advanced/advanced-dependencies.md +++ b/docs/de/docs/advanced/advanced-dependencies.md @@ -18,35 +18,7 @@ Nicht die Klasse selbst (die bereits aufrufbar ist), sondern eine Instanz dieser Dazu deklarieren wir eine Methode `__call__`: -//// tab | Python 3.9+ - -```Python hl_lines="12" -{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/dependencies/tutorial011_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/dependencies/tutorial011.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[12] *} In diesem Fall ist dieses `__call__` das, was **FastAPI** verwendet, um nach zusätzlichen Parametern und Unterabhängigkeiten zu suchen, und das ist es auch, was später aufgerufen wird, um einen Wert an den Parameter in Ihrer *Pfadoperation-Funktion* zu übergeben. @@ -54,35 +26,7 @@ In diesem Fall ist dieses `__call__` das, was **FastAPI** verwendet, um nach zus Und jetzt können wir `__init__` verwenden, um die Parameter der Instanz zu deklarieren, die wir zum `Parametrisieren` der Abhängigkeit verwenden können: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/dependencies/tutorial011_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/dependencies/tutorial011.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[9] *} In diesem Fall wird **FastAPI** `__init__` nie berühren oder sich darum kümmern, wir werden es direkt in unserem Code verwenden. @@ -90,35 +34,7 @@ In diesem Fall wird **FastAPI** `__init__` nie berühren oder sich darum kümmer Wir könnten eine Instanz dieser Klasse erstellen mit: -//// tab | Python 3.9+ - -```Python hl_lines="18" -{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial011_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="16" -{!> ../../docs_src/dependencies/tutorial011.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[18] *} Und auf diese Weise können wir unsere Abhängigkeit „parametrisieren“, die jetzt `"bar"` enthält, als das Attribut `checker.fixed_content`. @@ -134,37 +50,9 @@ checker(q="somequery") ... und übergibt, was immer das als Wert dieser Abhängigkeit in unserer *Pfadoperation-Funktion* zurückgibt, als den Parameter `fixed_content_included`: -//// tab | Python 3.9+ - -```Python hl_lines="22" -{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="21" -{!> ../../docs_src/dependencies/tutorial011_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="20" -{!> ../../docs_src/dependencies/tutorial011.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[22] *} -/// tip | "Tipp" +/// tip | Tipp Das alles mag gekünstelt wirken. Und es ist möglicherweise noch nicht ganz klar, welchen Nutzen das hat. diff --git a/docs/de/docs/advanced/async-tests.md b/docs/de/docs/advanced/async-tests.md index 6c1981e255b2f..b82aadf000048 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 @@ -62,7 +58,7 @@ Der Marker `@pytest.mark.anyio` teilt pytest mit, dass diese Testfunktion asynch {* ../../docs_src/async_tests/test_main.py hl[7] *} -/// tip | "Tipp" +/// tip | Tipp Beachten Sie, dass die Testfunktion jetzt `async def` ist und nicht nur `def` wie zuvor, wenn Sie den `TestClient` verwenden. @@ -80,13 +76,13 @@ response = client.get('/') ... welches wir verwendet haben, um unsere Requests mit dem `TestClient` zu machen. -/// tip | "Tipp" +/// tip | Tipp Beachten Sie, dass wir async/await mit dem neuen `AsyncClient` verwenden – der Request ist asynchron. /// -/// warning | "Achtung" +/// warning | Achtung Falls Ihre Anwendung auf Lifespan-Events angewiesen ist, der `AsyncClient` löst diese Events nicht aus. Um sicherzustellen, dass sie ausgelöst werden, verwenden Sie `LifespanManager` von florimondmanca/asgi-lifespan. @@ -96,7 +92,7 @@ Falls Ihre Anwendung auf Lifespan-Events angewiesen ist, der `AsyncClient` löst Da die Testfunktion jetzt asynchron ist, können Sie in Ihren Tests neben dem Senden von Requests an Ihre FastAPI-Anwendung jetzt auch andere `async`hrone Funktionen aufrufen (und `await`en), genau so, wie Sie diese an anderer Stelle in Ihrem Code aufrufen würden. -/// tip | "Tipp" +/// tip | Tipp Wenn Sie einen `RuntimeError: Task attached to a different loop` erhalten, wenn Sie asynchrone Funktionsaufrufe in Ihre Tests integrieren (z. B. bei Verwendung von MongoDBs MotorClient), dann denken Sie daran, Objekte zu instanziieren, die einen Event Loop nur innerhalb asynchroner Funktionen benötigen, z. B. einen `@app.on_event("startup")`-Callback. diff --git a/docs/de/docs/advanced/behind-a-proxy.md b/docs/de/docs/advanced/behind-a-proxy.md index 74b25308a8b61..9e22822809122 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,7 +41,7 @@ browser --> proxy proxy --> server ``` -/// tip | "Tipp" +/// tip | Tipp Die IP `0.0.0.0` wird üblicherweise verwendet, um anzudeuten, dass das Programm alle auf diesem Computer/Server verfügbaren IPs abhört. @@ -84,7 +82,7 @@ $ uvicorn main:app --root-path /api/v1 Falls Sie Hypercorn verwenden, das hat auch die Option `--root-path`. -/// note | "Technische Details" +/// note | Technische Details Die ASGI-Spezifikation definiert einen `root_path` für diesen Anwendungsfall. @@ -98,9 +96,7 @@ Sie können den aktuellen `root_path` abrufen, der von Ihrer Anwendung für jede Hier fügen wir ihn, nur zu Demonstrationszwecken, in die Nachricht ein. -```Python hl_lines="8" -{!../../docs_src/behind_a_proxy/tutorial001.py!} -``` +{* ../../docs_src/behind_a_proxy/tutorial001.py hl[8] *} Wenn Sie Uvicorn dann starten mit: @@ -127,9 +123,7 @@ wäre die Response etwa: Falls Sie keine Möglichkeit haben, eine Kommandozeilenoption wie `--root-path` oder ähnlich zu übergeben, können Sie als Alternative beim Erstellen Ihrer FastAPI-Anwendung den Parameter `root_path` setzen: -```Python hl_lines="3" -{!../../docs_src/behind_a_proxy/tutorial002.py!} -``` +{* ../../docs_src/behind_a_proxy/tutorial002.py hl[3] *} Die Übergabe des `root_path` an `FastAPI` wäre das Äquivalent zur Übergabe der `--root-path`-Kommandozeilenoption an Uvicorn oder Hypercorn. @@ -178,7 +172,7 @@ Dann erstellen Sie eine Datei `traefik.toml` mit: Dadurch wird Traefik angewiesen, Port 9999 abzuhören und eine andere Datei `routes.toml` zu verwenden. -/// tip | "Tipp" +/// tip | Tipp Wir verwenden Port 9999 anstelle des Standard-HTTP-Ports 80, damit Sie ihn nicht mit Administratorrechten (`sudo`) ausführen müssen. @@ -248,7 +242,7 @@ Wenn Sie nun zur URL mit dem Port für Uvicorn gehen: -/// tip | "Tipp" +/// tip | Tipp Die Dokumentationsoberfläche interagiert mit dem von Ihnen ausgewählten Server. @@ -358,9 +350,7 @@ Die Dokumentationsoberfläche interagiert mit dem von Ihnen ausgewählten Server Wenn Sie nicht möchten, dass **FastAPI** einen automatischen Server inkludiert, welcher `root_path` verwendet, können Sie den Parameter `root_path_in_servers=False` verwenden: -```Python hl_lines="9" -{!../../docs_src/behind_a_proxy/tutorial004.py!} -``` +{* ../../docs_src/behind_a_proxy/tutorial004.py hl[9] *} Dann wird er nicht in das OpenAPI-Schema aufgenommen. diff --git a/docs/de/docs/advanced/custom-response.md b/docs/de/docs/advanced/custom-response.md index 357d2c5629ab9..43cb55e04a06f 100644 --- a/docs/de/docs/advanced/custom-response.md +++ b/docs/de/docs/advanced/custom-response.md @@ -12,7 +12,7 @@ Der Inhalt, den Sie von Ihrer *Pfadoperation-Funktion* zurückgeben, wird in die Und wenn diese `Response` einen JSON-Medientyp (`application/json`) hat, wie es bei `JSONResponse` und `UJSONResponse` der Fall ist, werden die von Ihnen zurückgegebenen Daten automatisch mit jedem Pydantic `response_model` konvertiert (und gefiltert), das Sie im *Pfadoperation-Dekorator* deklariert haben. -/// note | "Hinweis" +/// note | Hinweis Wenn Sie eine Response-Klasse ohne Medientyp verwenden, erwartet FastAPI, dass Ihre Response keinen Inhalt hat, und dokumentiert daher das Format der Response nicht in deren generierter OpenAPI-Dokumentation. @@ -30,9 +30,7 @@ Das liegt daran, dass FastAPI standardmäßig jedes enthaltene Element überprü Wenn Sie jedoch sicher sind, dass der von Ihnen zurückgegebene Inhalt **mit JSON serialisierbar** ist, können Sie ihn direkt an die Response-Klasse übergeben und die zusätzliche Arbeit vermeiden, die FastAPI hätte, indem es Ihren zurückgegebenen Inhalt durch den `jsonable_encoder` leitet, bevor es ihn an die Response-Klasse übergibt. -```Python hl_lines="2 7" -{!../../docs_src/custom_response/tutorial001b.py!} -``` +{* ../../docs_src/custom_response/tutorial001b.py hl[2,7] *} /// info @@ -44,7 +42,7 @@ Und er wird als solcher in OpenAPI dokumentiert. /// -/// tip | "Tipp" +/// tip | Tipp Die `ORJSONResponse` ist derzeit nur in FastAPI verfügbar, nicht in Starlette. @@ -57,9 +55,7 @@ Um eine Response mit HTML direkt von **FastAPI** zurückzugeben, verwenden Sie ` * Importieren Sie `HTMLResponse`. * Übergeben Sie `HTMLResponse` als den Parameter `response_class` Ihres *Pfadoperation-Dekorators*. -```Python hl_lines="2 7" -{!../../docs_src/custom_response/tutorial002.py!} -``` +{* ../../docs_src/custom_response/tutorial002.py hl[2,7] *} /// info @@ -77,11 +73,9 @@ Wie in [Eine Response direkt zurückgeben](response-directly.md){.internal-link Das gleiche Beispiel von oben, das eine `HTMLResponse` zurückgibt, könnte so aussehen: -```Python hl_lines="2 7 19" -{!../../docs_src/custom_response/tutorial003.py!} -``` +{* ../../docs_src/custom_response/tutorial003.py hl[2,7,19] *} -/// warning | "Achtung" +/// warning | Achtung Eine `Response`, die direkt von Ihrer *Pfadoperation-Funktion* zurückgegeben wird, wird in OpenAPI nicht dokumentiert (zum Beispiel wird der `Content-Type` nicht dokumentiert) und ist in der automatischen interaktiven Dokumentation nicht sichtbar. @@ -103,9 +97,7 @@ Die `response_class` wird dann nur zur Dokumentation der OpenAPI-Pfadoperation* Es könnte zum Beispiel so etwas sein: -```Python hl_lines="7 21 23" -{!../../docs_src/custom_response/tutorial004.py!} -``` +{* ../../docs_src/custom_response/tutorial004.py hl[7,21,23] *} In diesem Beispiel generiert die Funktion `generate_html_response()` bereits eine `Response` und gibt sie zurück, anstatt das HTML in einem `str` zurückzugeben. @@ -121,7 +113,7 @@ Hier sind einige der verfügbaren Responses. Bedenken Sie, dass Sie `Response` verwenden können, um alles andere zurückzugeben, oder sogar eine benutzerdefinierte Unterklasse zu erstellen. -/// note | "Technische Details" +/// note | Technische Details Sie können auch `from starlette.responses import HTMLResponse` verwenden. @@ -144,9 +136,7 @@ Sie akzeptiert die folgenden Parameter: FastAPI (eigentlich Starlette) fügt automatisch einen Content-Length-Header ein. Außerdem wird es einen Content-Type-Header einfügen, der auf dem media_type basiert, und für Texttypen einen Zeichensatz (charset) anfügen. -```Python hl_lines="1 18" -{!../../docs_src/response_directly/tutorial002.py!} -``` +{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *} ### `HTMLResponse` @@ -156,9 +146,7 @@ Nimmt Text oder Bytes entgegen und gibt eine HTML-Response zurück, wie Sie oben Nimmt Text oder Bytes entgegen und gibt eine Plain-Text-Response zurück. -```Python hl_lines="2 7 9" -{!../../docs_src/custom_response/tutorial005.py!} -``` +{* ../../docs_src/custom_response/tutorial005.py hl[2,7,9] *} ### `JSONResponse` @@ -174,17 +162,15 @@ Eine schnelle alternative JSON-Response mit `ujson`. -/// warning | "Achtung" +/// warning | Achtung `ujson` ist bei der Behandlung einiger Sonderfälle weniger sorgfältig als Pythons eingebaute Implementierung. /// -```Python hl_lines="2 7" -{!../../docs_src/custom_response/tutorial001.py!} -``` +{* ../../docs_src/custom_response/tutorial001.py hl[2,7] *} -/// tip | "Tipp" +/// tip | Tipp Möglicherweise ist `ORJSONResponse` eine schnellere Alternative. @@ -196,18 +182,14 @@ Gibt eine HTTP-Weiterleitung (HTTP-Redirect) zurück. Verwendet standardmäßig Sie können eine `RedirectResponse` direkt zurückgeben: -```Python hl_lines="2 9" -{!../../docs_src/custom_response/tutorial006.py!} -``` +{* ../../docs_src/custom_response/tutorial006.py hl[2,9] *} --- Oder Sie können sie im Parameter `response_class` verwenden: -```Python hl_lines="2 7 9" -{!../../docs_src/custom_response/tutorial006b.py!} -``` +{* ../../docs_src/custom_response/tutorial006b.py hl[2,7,9] *} Wenn Sie das tun, können Sie die URL direkt von Ihrer *Pfadoperation*-Funktion zurückgeben. @@ -217,17 +199,13 @@ In diesem Fall ist der verwendete `status_code` der Standardcode für die `Redir Sie können den Parameter `status_code` auch in Kombination mit dem Parameter `response_class` verwenden: -```Python hl_lines="2 7 9" -{!../../docs_src/custom_response/tutorial006c.py!} -``` +{* ../../docs_src/custom_response/tutorial006c.py hl[2,7,9] *} ### `StreamingResponse` Nimmt einen asynchronen Generator oder einen normalen Generator/Iterator und streamt den Responsebody. -```Python hl_lines="2 14" -{!../../docs_src/custom_response/tutorial007.py!} -``` +{* ../../docs_src/custom_response/tutorial007.py hl[2,14] *} #### Verwendung von `StreamingResponse` mit dateiähnlichen Objekten @@ -249,7 +227,7 @@ Das umfasst viele Bibliotheken zur Interaktion mit Cloud-Speicher, Videoverarbei Auf diese Weise können wir das Ganze in einen `with`-Block einfügen und so sicherstellen, dass das dateiartige Objekt nach Abschluss geschlossen wird. -/// tip | "Tipp" +/// tip | Tipp Beachten Sie, dass wir, da wir Standard-`open()` verwenden, welches `async` und `await` nicht unterstützt, hier die Pfadoperation mit normalen `def` deklarieren. @@ -268,15 +246,11 @@ Nimmt zur Instanziierung einen anderen Satz von Argumenten entgegen als die ande Datei-Responses enthalten die entsprechenden `Content-Length`-, `Last-Modified`- und `ETag`-Header. -```Python hl_lines="2 10" -{!../../docs_src/custom_response/tutorial009.py!} -``` +{* ../../docs_src/custom_response/tutorial009.py hl[2,10] *} Sie können auch den Parameter `response_class` verwenden: -```Python hl_lines="2 8 10" -{!../../docs_src/custom_response/tutorial009b.py!} -``` +{* ../../docs_src/custom_response/tutorial009b.py hl[2,8,10] *} In diesem Fall können Sie den Dateipfad direkt von Ihrer *Pfadoperation*-Funktion zurückgeben. @@ -290,9 +264,7 @@ Sie möchten etwa, dass Ihre Response eingerücktes und formatiertes JSON zurüc Sie könnten eine `CustomORJSONResponse` erstellen. Das Wichtigste, was Sie tun müssen, ist, eine `Response.render(content)`-Methode zu erstellen, die den Inhalt als `bytes` zurückgibt: -```Python hl_lines="9-14 17" -{!../../docs_src/custom_response/tutorial009c.py!} -``` +{* ../../docs_src/custom_response/tutorial009c.py hl[9:14,17] *} Statt: @@ -318,11 +290,9 @@ Der Parameter, der das definiert, ist `default_response_class`. Im folgenden Beispiel verwendet **FastAPI** standardmäßig `ORJSONResponse` in allen *Pfadoperationen*, anstelle von `JSONResponse`. -```Python hl_lines="2 4" -{!../../docs_src/custom_response/tutorial010.py!} -``` +{* ../../docs_src/custom_response/tutorial010.py hl[2,4] *} -/// tip | "Tipp" +/// tip | Tipp Sie können dennoch weiterhin `response_class` in *Pfadoperationen* überschreiben, wie bisher. diff --git a/docs/de/docs/advanced/dataclasses.md b/docs/de/docs/advanced/dataclasses.md index 573f500e8c0de..8e537c639400f 100644 --- a/docs/de/docs/advanced/dataclasses.md +++ b/docs/de/docs/advanced/dataclasses.md @@ -4,9 +4,7 @@ FastAPI basiert auf **Pydantic** und ich habe Ihnen gezeigt, wie Sie Pydantic-Mo Aber FastAPI unterstützt auf die gleiche Weise auch die Verwendung von `dataclasses`: -```Python hl_lines="1 7-12 19-20" -{!../../docs_src/dataclasses/tutorial001.py!} -``` +{* ../../docs_src/dataclasses/tutorial001.py hl[1,7:12,19:20] *} Das ist dank **Pydantic** ebenfalls möglich, da es `dataclasses` intern unterstützt. @@ -34,9 +32,7 @@ Wenn Sie jedoch eine Menge Datenklassen herumliegen haben, ist dies ein guter Tr Sie können `dataclasses` auch im Parameter `response_model` verwenden: -```Python hl_lines="1 7-13 19" -{!../../docs_src/dataclasses/tutorial002.py!} -``` +{* ../../docs_src/dataclasses/tutorial002.py hl[1,7:13,19] *} Die Datenklasse wird automatisch in eine Pydantic-Datenklasse konvertiert. @@ -52,9 +48,7 @@ In einigen Fällen müssen Sie möglicherweise immer noch Pydantics Version von In diesem Fall können Sie einfach die Standard-`dataclasses` durch `pydantic.dataclasses` ersetzen, was einen direkten Ersatz darstellt: -```{ .python .annotate hl_lines="1 5 8-11 14-17 23-25 28" } -{!../../docs_src/dataclasses/tutorial003.py!} -``` +{* ../../docs_src/dataclasses/tutorial003.py hl[1,5,8:11,14:17,23:25,28] *} 1. Wir importieren `field` weiterhin von Standard-`dataclasses`. diff --git a/docs/de/docs/advanced/events.md b/docs/de/docs/advanced/events.md index b0c4d3922c4e4..65fc9e484dfd5 100644 --- a/docs/de/docs/advanced/events.md +++ b/docs/de/docs/advanced/events.md @@ -30,15 +30,13 @@ Beginnen wir mit einem Beispiel und sehen es uns dann im Detail an. Wir erstellen eine asynchrone Funktion `lifespan()` mit `yield` wie folgt: -```Python hl_lines="16 19" -{!../../docs_src/events/tutorial003.py!} -``` +{* ../../docs_src/events/tutorial003.py hl[16,19] *} Hier simulieren wir das langsame *Hochfahren*, das Laden des Modells, indem wir die (Fake-)Modellfunktion vor dem `yield` in das Dictionary mit Modellen für maschinelles Lernen einfügen. Dieser Code wird ausgeführt, **bevor** die Anwendung **beginnt, Requests entgegenzunehmen**, während des *Hochfahrens*. Und dann, direkt nach dem `yield`, entladen wir das Modell. Dieser Code wird unmittelbar vor dem *Herunterfahren* ausgeführt, **nachdem** die Anwendung **die Bearbeitung von Requests abgeschlossen hat**. Dadurch könnten beispielsweise Ressourcen wie Arbeitsspeicher oder eine GPU freigegeben werden. -/// tip | "Tipp" +/// tip | Tipp Das *Herunterfahren* würde erfolgen, wenn Sie die Anwendung **stoppen**. @@ -50,9 +48,7 @@ Möglicherweise müssen Sie eine neue Version starten, oder Sie haben es einfach Das Erste, was auffällt, ist, dass wir eine asynchrone Funktion mit `yield` definieren. Das ist sehr ähnlich zu Abhängigkeiten mit `yield`. -```Python hl_lines="14-19" -{!../../docs_src/events/tutorial003.py!} -``` +{* ../../docs_src/events/tutorial003.py hl[14:19] *} Der erste Teil der Funktion, vor dem `yield`, wird ausgeführt **bevor** die Anwendung startet. @@ -64,9 +60,7 @@ Wie Sie sehen, ist die Funktion mit einem `@asynccontextmanager` versehen. Dadurch wird die Funktion in einen sogenannten „**asynchronen Kontextmanager**“ umgewandelt. -```Python hl_lines="1 13" -{!../../docs_src/events/tutorial003.py!} -``` +{* ../../docs_src/events/tutorial003.py hl[1,13] *} Ein **Kontextmanager** in Python ist etwas, das Sie in einer `with`-Anweisung verwenden können, zum Beispiel kann `open()` als Kontextmanager verwendet werden: @@ -88,13 +82,11 @@ In unserem obigen Codebeispiel verwenden wir ihn nicht direkt, sondern übergebe Der Parameter `lifespan` der `FastAPI`-App benötigt einen **asynchronen Kontextmanager**, wir können ihm also unseren neuen asynchronen Kontextmanager `lifespan` übergeben. -```Python hl_lines="22" -{!../../docs_src/events/tutorial003.py!} -``` +{* ../../docs_src/events/tutorial003.py hl[22] *} ## Alternative Events (deprecated) -/// warning | "Achtung" +/// warning | Achtung Der empfohlene Weg, das *Hochfahren* und *Herunterfahren* zu handhaben, ist die Verwendung des `lifespan`-Parameters der `FastAPI`-App, wie oben beschrieben. Wenn Sie einen `lifespan`-Parameter übergeben, werden die `startup`- und `shutdown`-Eventhandler nicht mehr aufgerufen. Es ist entweder alles `lifespan` oder alles Events, nicht beides. @@ -112,9 +104,7 @@ Diese Funktionen können mit `async def` oder normalem `def` deklariert werden. Um eine Funktion hinzuzufügen, die vor dem Start der Anwendung ausgeführt werden soll, deklarieren Sie diese mit dem Event `startup`: -```Python hl_lines="8" -{!../../docs_src/events/tutorial001.py!} -``` +{* ../../docs_src/events/tutorial001.py hl[8] *} In diesem Fall initialisiert die Eventhandler-Funktion `startup` die „Datenbank“ der Items (nur ein `dict`) mit einigen Werten. @@ -126,9 +116,7 @@ Und Ihre Anwendung empfängt erst dann Anfragen, wenn alle `startup`-Eventhandle Um eine Funktion hinzuzufügen, die beim Herunterfahren der Anwendung ausgeführt werden soll, deklarieren Sie sie mit dem Event `shutdown`: -```Python hl_lines="6" -{!../../docs_src/events/tutorial002.py!} -``` +{* ../../docs_src/events/tutorial002.py hl[6] *} Hier schreibt die `shutdown`-Eventhandler-Funktion eine Textzeile `"Application shutdown"` in eine Datei `log.txt`. @@ -138,7 +126,7 @@ In der Funktion `open()` bedeutet `mode="a"` „append“ („anhängen“), sod /// -/// tip | "Tipp" +/// tip | Tipp Beachten Sie, dass wir in diesem Fall eine Standard-Python-Funktion `open()` verwenden, die mit einer Datei interagiert. diff --git a/docs/de/docs/advanced/generate-clients.md b/docs/de/docs/advanced/generate-clients.md index 80c44b3f96563..38a69031c56b2 100644 --- a/docs/de/docs/advanced/generate-clients.md +++ b/docs/de/docs/advanced/generate-clients.md @@ -28,21 +28,7 @@ Es gibt auch mehrere andere Unternehmen, welche ähnliche Dienste anbieten und d Beginnen wir mit einer einfachen FastAPI-Anwendung: -//// tab | Python 3.9+ - -```Python hl_lines="7-9 12-13 16-17 21" -{!> ../../docs_src/generate_clients/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9-11 14-15 18 19 23" -{!> ../../docs_src/generate_clients/tutorial001.py!} -``` - -//// +{* ../../docs_src/generate_clients/tutorial001_py39.py hl[7:9,12:13,16:17,21] *} Beachten Sie, dass die *Pfadoperationen* die Modelle definieren, welche diese für die Request- und Response-Payload verwenden, indem sie die Modelle `Item` und `ResponseMessage` verwenden. @@ -127,7 +113,7 @@ Sie erhalten außerdem automatische Vervollständigung für die zu sendende Payl -/// tip | "Tipp" +/// tip | Tipp Beachten Sie die automatische Vervollständigung für `name` und `price`, welche in der FastAPI-Anwendung im `Item`-Modell definiert wurden. @@ -147,21 +133,7 @@ In vielen Fällen wird Ihre FastAPI-Anwendung größer sein und Sie werden wahrs Beispielsweise könnten Sie einen Abschnitt für **Items (Artikel)** und einen weiteren Abschnitt für **Users (Benutzer)** haben, und diese könnten durch Tags getrennt sein: -//// tab | Python 3.9+ - -```Python hl_lines="21 26 34" -{!> ../../docs_src/generate_clients/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="23 28 36" -{!> ../../docs_src/generate_clients/tutorial002.py!} -``` - -//// +{* ../../docs_src/generate_clients/tutorial002_py39.py hl[21,26,34] *} ### Einen TypeScript-Client mit Tags generieren @@ -208,21 +180,7 @@ Hier verwendet sie beispielsweise den ersten Tag (Sie werden wahrscheinlich nur Anschließend können Sie diese benutzerdefinierte Funktion als Parameter `generate_unique_id_function` an **FastAPI** übergeben: -//// tab | Python 3.9+ - -```Python hl_lines="6-7 10" -{!> ../../docs_src/generate_clients/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8-9 12" -{!> ../../docs_src/generate_clients/tutorial003.py!} -``` - -//// +{* ../../docs_src/generate_clients/tutorial003_py39.py hl[6:7,10] *} ### Einen TypeScript-Client mit benutzerdefinierten Operation-IDs generieren @@ -244,13 +202,7 @@ Aber für den generierten Client könnten wir die OpenAPI-Operation-IDs direkt v Wir könnten das OpenAPI-JSON in eine Datei `openapi.json` herunterladen und dann mit einem Skript wie dem folgenden **den vorangestellten Tag entfernen**: -//// tab | Python - -```Python -{!> ../../docs_src/generate_clients/tutorial004.py!} -``` - -//// +{* ../../docs_src/generate_clients/tutorial004.py *} //// tab | Node.js diff --git a/docs/de/docs/advanced/index.md b/docs/de/docs/advanced/index.md index 953ad317d6b3c..d93cd5fe82ded 100644 --- a/docs/de/docs/advanced/index.md +++ b/docs/de/docs/advanced/index.md @@ -6,7 +6,7 @@ Das Haupt-[Tutorial – Benutzerhandbuch](../tutorial/index.md){.internal-link t In den nächsten Abschnitten sehen Sie weitere Optionen, Konfigurationen und zusätzliche Funktionen. -/// tip | "Tipp" +/// tip | Tipp Die nächsten Abschnitte sind **nicht unbedingt „fortgeschritten“**. diff --git a/docs/de/docs/advanced/middleware.md b/docs/de/docs/advanced/middleware.md index b4001efda7a19..17b339788b007 100644 --- a/docs/de/docs/advanced/middleware.md +++ b/docs/de/docs/advanced/middleware.md @@ -43,7 +43,7 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") **FastAPI** enthält mehrere Middlewares für gängige Anwendungsfälle. Wir werden als Nächstes sehen, wie man sie verwendet. -/// note | "Technische Details" +/// note | Technische Details Für die nächsten Beispiele könnten Sie auch `from starlette.middleware.something import SomethingMiddleware` verwenden. @@ -57,17 +57,13 @@ Erzwingt, dass alle eingehenden Requests entweder `https` oder `wss` sein müsse Alle eingehenden Requests an `http` oder `ws` werden stattdessen an das sichere Schema umgeleitet. -```Python hl_lines="2 6" -{!../../docs_src/advanced_middleware/tutorial001.py!} -``` +{* ../../docs_src/advanced_middleware/tutorial001.py hl[2,6] *} ## `TrustedHostMiddleware` Erzwingt, dass alle eingehenden Requests einen korrekt gesetzten `Host`-Header haben, um sich vor HTTP-Host-Header-Angriffen zu schützen. -```Python hl_lines="2 6-8" -{!../../docs_src/advanced_middleware/tutorial002.py!} -``` +{* ../../docs_src/advanced_middleware/tutorial002.py hl[2,6:8] *} Die folgenden Argumente werden unterstützt: @@ -81,9 +77,7 @@ Verarbeitet GZip-Responses für alle Requests, die `"gzip"` im `Accept-Encoding` Diese Middleware verarbeitet sowohl Standard- als auch Streaming-Responses. -```Python hl_lines="2 6" -{!../../docs_src/advanced_middleware/tutorial003.py!} -``` +{* ../../docs_src/advanced_middleware/tutorial003.py hl[2,6] *} Die folgenden Argumente werden unterstützt: diff --git a/docs/de/docs/advanced/openapi-callbacks.md b/docs/de/docs/advanced/openapi-callbacks.md index f407d54507f97..53f06e24e77b4 100644 --- a/docs/de/docs/advanced/openapi-callbacks.md +++ b/docs/de/docs/advanced/openapi-callbacks.md @@ -31,11 +31,9 @@ Sie verfügt über eine *Pfadoperation*, die einen `Invoice`-Body empfängt, und Dieser Teil ist ziemlich normal, der größte Teil des Codes ist Ihnen wahrscheinlich bereits bekannt: -```Python hl_lines="9-13 36-53" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[9:13,36:53] *} -/// tip | "Tipp" +/// tip | Tipp Der Query-Parameter `callback_url` verwendet einen Pydantic-Url-Typ. @@ -64,7 +62,7 @@ Diese Dokumentation wird in der Swagger-Oberfläche unter `/docs` in Ihrer API a In diesem Beispiel wird nicht der Callback selbst implementiert (das könnte nur eine Codezeile sein), sondern nur der Dokumentationsteil. -/// tip | "Tipp" +/// tip | Tipp Der eigentliche Callback ist nur ein HTTP-Request. @@ -80,7 +78,7 @@ Sie wissen jedoch bereits, wie Sie mit **FastAPI** ganz einfach eine automatisch Daher werden wir dasselbe Wissen nutzen, um zu dokumentieren, wie die *externe API* aussehen sollte ... indem wir die *Pfadoperation(en)* erstellen, welche die externe API implementieren soll (die, welche Ihre API aufruft). -/// tip | "Tipp" +/// tip | Tipp Wenn Sie den Code zum Dokumentieren eines Callbacks schreiben, kann es hilfreich sein, sich vorzustellen, dass Sie dieser *externe Entwickler* sind. Und dass Sie derzeit die *externe API* implementieren, nicht *Ihre API*. @@ -92,9 +90,7 @@ Wenn Sie diese Sichtweise (des *externen Entwicklers*) vorübergehend übernehme Erstellen Sie zunächst einen neuen `APIRouter`, der einen oder mehrere Callbacks enthält. -```Python hl_lines="3 25" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[3,25] *} ### Die Callback-*Pfadoperation* erstellen @@ -105,9 +101,7 @@ Sie sollte wie eine normale FastAPI-*Pfadoperation* aussehen: * Sie sollte wahrscheinlich eine Deklaration des Bodys enthalten, die sie erhalten soll, z. B. `body: InvoiceEvent`. * Und sie könnte auch eine Deklaration der Response enthalten, die zurückgegeben werden soll, z. B. `response_model=InvoiceEventReceived`. -```Python hl_lines="16-18 21-22 28-32" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[16:18,21:22,28:32] *} Es gibt zwei Hauptunterschiede zu einer normalen *Pfadoperation*: @@ -163,7 +157,7 @@ und sie würde eine Response von dieser *externen API* mit einem JSON-Body wie d } ``` -/// tip | "Tipp" +/// tip | Tipp Beachten Sie, dass die verwendete Callback-URL die URL enthält, die als Query-Parameter in `callback_url` (`https://www.external.org/events`) empfangen wurde, und auch die Rechnungs-`id` aus dem JSON-Body (`2expen51ve`). @@ -175,11 +169,9 @@ An diesem Punkt haben Sie die benötigte(n) *Callback-Pfadoperation(en)* (diejen Verwenden Sie nun den Parameter `callbacks` im *Pfadoperation-Dekorator Ihrer API*, um das Attribut `.routes` (das ist eigentlich nur eine `list`e von Routen/*Pfadoperationen*) dieses Callback-Routers zu übergeben: -```Python hl_lines="35" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[35] *} -/// tip | "Tipp" +/// tip | Tipp Beachten Sie, dass Sie nicht den Router selbst (`invoices_callback_router`) an `callback=` übergeben, sondern das Attribut `.routes`, wie in `invoices_callback_router.routes`. diff --git a/docs/de/docs/advanced/openapi-webhooks.md b/docs/de/docs/advanced/openapi-webhooks.md index 9f1bb69598359..50b95eaf8b1c9 100644 --- a/docs/de/docs/advanced/openapi-webhooks.md +++ b/docs/de/docs/advanced/openapi-webhooks.md @@ -32,9 +32,7 @@ Webhooks sind in OpenAPI 3.1.0 und höher verfügbar und werden von FastAPI `0.9 Wenn Sie eine **FastAPI**-Anwendung erstellen, gibt es ein `webhooks`-Attribut, mit dem Sie *Webhooks* definieren können, genauso wie Sie *Pfadoperationen* definieren würden, zum Beispiel mit `@app.webhooks.post()`. -```Python hl_lines="9-13 36-53" -{!../../docs_src/openapi_webhooks/tutorial001.py!} -``` +{* ../../docs_src/openapi_webhooks/tutorial001.py hl[9:13,36:53] *} Die von Ihnen definierten Webhooks landen im **OpenAPI**-Schema und der automatischen **Dokumentations-Oberfläche**. diff --git a/docs/de/docs/advanced/path-operation-advanced-configuration.md b/docs/de/docs/advanced/path-operation-advanced-configuration.md index 2d8b88be585d1..b6e88d2c9a32d 100644 --- a/docs/de/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/de/docs/advanced/path-operation-advanced-configuration.md @@ -2,7 +2,7 @@ ## OpenAPI operationId -/// warning | "Achtung" +/// warning | Achtung Wenn Sie kein „Experte“ für OpenAPI sind, brauchen Sie dies wahrscheinlich nicht. @@ -12,9 +12,7 @@ Mit dem Parameter `operation_id` können Sie die OpenAPI `operationId` festlegen Sie müssten sicherstellen, dass sie für jede Operation eindeutig ist. -```Python hl_lines="6" -{!../../docs_src/path_operation_advanced_configuration/tutorial001.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial001.py hl[6] *} ### Verwendung des Namens der *Pfadoperation-Funktion* als operationId @@ -22,17 +20,15 @@ Wenn Sie die Funktionsnamen Ihrer API als `operationId`s verwenden möchten, kö Sie sollten dies tun, nachdem Sie alle Ihre *Pfadoperationen* hinzugefügt haben. -```Python hl_lines="2 12-21 24" -{!../../docs_src/path_operation_advanced_configuration/tutorial002.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial002.py hl[2,12:21,24] *} -/// tip | "Tipp" +/// tip | Tipp Wenn Sie `app.openapi()` manuell aufrufen, sollten Sie vorher die `operationId`s aktualisiert haben. /// -/// warning | "Achtung" +/// warning | Achtung Wenn Sie dies tun, müssen Sie sicherstellen, dass jede Ihrer *Pfadoperation-Funktionen* einen eindeutigen Namen hat. @@ -44,9 +40,7 @@ Auch wenn diese sich in unterschiedlichen Modulen (Python-Dateien) befinden. Um eine *Pfadoperation* aus dem generierten OpenAPI-Schema (und damit aus den automatischen Dokumentationssystemen) auszuschließen, verwenden Sie den Parameter `include_in_schema` und setzen Sie ihn auf `False`: -```Python hl_lines="6" -{!../../docs_src/path_operation_advanced_configuration/tutorial003.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial003.py hl[6] *} ## Fortgeschrittene Beschreibung mittels Docstring @@ -56,9 +50,7 @@ Das Hinzufügen eines `\f` (ein maskiertes „Form Feed“-Zeichen) führt dazu, Sie wird nicht in der Dokumentation angezeigt, aber andere Tools (z. B. Sphinx) können den Rest verwenden. -```Python hl_lines="19-29" -{!../../docs_src/path_operation_advanced_configuration/tutorial004.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial004.py hl[19:29] *} ## Zusätzliche Responses @@ -74,7 +66,7 @@ Es gibt hier in der Dokumentation ein ganzes Kapitel darüber, Sie können es un Wenn Sie in Ihrer Anwendung eine *Pfadoperation* deklarieren, generiert **FastAPI** automatisch die relevanten Metadaten dieser *Pfadoperation*, die in das OpenAPI-Schema aufgenommen werden sollen. -/// note | "Technische Details" +/// note | Technische Details In der OpenAPI-Spezifikation wird das Operationsobjekt genannt. @@ -86,7 +78,7 @@ Es enthält `tags`, `parameters`, `requestBody`, `responses`, usw. Dieses *Pfadoperation*-spezifische OpenAPI-Schema wird normalerweise automatisch von **FastAPI** generiert, Sie können es aber auch erweitern. -/// tip | "Tipp" +/// tip | Tipp Dies ist ein Low-Level Erweiterungspunkt. @@ -100,9 +92,7 @@ Sie können das OpenAPI-Schema für eine *Pfadoperation* erweitern, indem Sie de Dieses `openapi_extra` kann beispielsweise hilfreich sein, um OpenAPI-Erweiterungen zu deklarieren: -```Python hl_lines="6" -{!../../docs_src/path_operation_advanced_configuration/tutorial005.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial005.py hl[6] *} Wenn Sie die automatische API-Dokumentation öffnen, wird Ihre Erweiterung am Ende der spezifischen *Pfadoperation* angezeigt. @@ -149,9 +139,7 @@ Sie könnten sich beispielsweise dafür entscheiden, den Request mit Ihrem eigen Das könnte man mit `openapi_extra` machen: -```Python hl_lines="20-37 39-40" -{!../../docs_src/path_operation_advanced_configuration/tutorial006.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial006.py hl[20:37,39:40] *} In diesem Beispiel haben wir kein Pydantic-Modell deklariert. Tatsächlich wird der Requestbody nicht einmal als JSON geparst, sondern direkt als `bytes` gelesen und die Funktion `magic_data_reader ()` wäre dafür verantwortlich, ihn in irgendeiner Weise zu parsen. @@ -167,17 +155,13 @@ In der folgenden Anwendung verwenden wir beispielsweise weder die integrierte Fu //// tab | Pydantic v2 -```Python hl_lines="17-22 24" -{!> ../../docs_src/path_operation_advanced_configuration/tutorial007.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[17:22,24] *} //// //// tab | Pydantic v1 -```Python hl_lines="17-22 24" -{!> ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py hl[17:22,24] *} //// @@ -195,17 +179,13 @@ Und dann parsen wir in unserem Code diesen YAML-Inhalt direkt und verwenden dann //// tab | Pydantic v2 -```Python hl_lines="26-33" -{!> ../../docs_src/path_operation_advanced_configuration/tutorial007.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[26:33] *} //// //// tab | Pydantic v1 -```Python hl_lines="26-33" -{!> ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py hl[26:33] *} //// @@ -215,7 +195,7 @@ In Pydantic Version 1 war die Methode zum Parsen und Validieren eines Objekts `I /// -/// tip | "Tipp" +/// tip | Tipp Hier verwenden wir dasselbe Pydantic-Modell wieder. diff --git a/docs/de/docs/advanced/response-change-status-code.md b/docs/de/docs/advanced/response-change-status-code.md index 202df0d87f0ba..0aac32f4edb41 100644 --- a/docs/de/docs/advanced/response-change-status-code.md +++ b/docs/de/docs/advanced/response-change-status-code.md @@ -20,9 +20,7 @@ Sie können einen Parameter vom Typ `Response` in Ihrer *Pfadoperation-Funktion* Anschließend können Sie den `status_code` in diesem *vorübergehenden* Response-Objekt festlegen. -```Python hl_lines="1 9 12" -{!../../docs_src/response_change_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_change_status_code/tutorial001.py hl[1,9,12] *} Und dann können Sie wie gewohnt jedes benötigte Objekt zurückgeben (ein `dict`, ein Datenbankmodell usw.). diff --git a/docs/de/docs/advanced/response-cookies.md b/docs/de/docs/advanced/response-cookies.md index ba100870daf09..5fe2cf7e35439 100644 --- a/docs/de/docs/advanced/response-cookies.md +++ b/docs/de/docs/advanced/response-cookies.md @@ -6,9 +6,7 @@ Sie können einen Parameter vom Typ `Response` in Ihrer *Pfadoperation-Funktion* Und dann können Sie Cookies in diesem *vorübergehenden* Response-Objekt setzen. -```Python hl_lines="1 8-9" -{!../../docs_src/response_cookies/tutorial002.py!} -``` +{* ../../docs_src/response_cookies/tutorial002.py hl[1,8:9] *} Anschließend können Sie wie gewohnt jedes gewünschte Objekt zurückgeben (ein `dict`, ein Datenbankmodell, usw.). @@ -26,11 +24,9 @@ Dazu können Sie eine Response erstellen, wie unter [Eine Response direkt zurüc Setzen Sie dann Cookies darin und geben Sie sie dann zurück: -```Python hl_lines="10-12" -{!../../docs_src/response_cookies/tutorial001.py!} -``` +{* ../../docs_src/response_cookies/tutorial001.py hl[10:12] *} -/// tip | "Tipp" +/// tip | Tipp Beachten Sie, dass, wenn Sie eine Response direkt zurückgeben, anstatt den `Response`-Parameter zu verwenden, FastAPI diese direkt zurückgibt. @@ -42,7 +38,7 @@ Und auch, dass Sie keine Daten senden, die durch ein `response_model` hätten ge ### Mehr Informationen -/// note | "Technische Details" +/// note | Technische Details Sie können auch `from starlette.responses import Response` oder `from starlette.responses import JSONResponse` verwenden. diff --git a/docs/de/docs/advanced/response-directly.md b/docs/de/docs/advanced/response-directly.md index 70c045f57432b..b84aa8ab94a57 100644 --- a/docs/de/docs/advanced/response-directly.md +++ b/docs/de/docs/advanced/response-directly.md @@ -14,7 +14,7 @@ Das kann beispielsweise nützlich sein, um benutzerdefinierte Header oder Cookie Tatsächlich können Sie jede `Response` oder jede Unterklasse davon zurückgeben. -/// tip | "Tipp" +/// tip | Tipp `JSONResponse` selbst ist eine Unterklasse von `Response`. @@ -34,11 +34,9 @@ Sie können beispielsweise kein Pydantic-Modell in eine `JSONResponse` einfügen In diesen Fällen können Sie den `jsonable_encoder` verwenden, um Ihre Daten zu konvertieren, bevor Sie sie an eine Response übergeben: -```Python hl_lines="6-7 21-22" -{!../../docs_src/response_directly/tutorial001.py!} -``` +{* ../../docs_src/response_directly/tutorial001.py hl[6:7,21:22] *} -/// note | "Technische Details" +/// note | Technische Details Sie können auch `from starlette.responses import JSONResponse` verwenden. @@ -56,9 +54,7 @@ Nehmen wir an, Sie möchten eine ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="2 4 8 12 47 65 106 108-116 122-125 129-135 140 156" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="3 7 11 45 63 104 106-114 120-123 127-133 138 154" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[4,8,12,46,64,105,107:115,121:124,128:134,139,155] *} Sehen wir uns diese Änderungen nun Schritt für Schritt an. @@ -136,71 +72,7 @@ Die erste Änderung ist, dass wir jetzt das OAuth2-Sicherheitsschema mit zwei ve Der `scopes`-Parameter erhält ein `dict` mit jedem Scope als Schlüssel und dessen Beschreibung als Wert: -//// tab | Python 3.10+ - -```Python hl_lines="62-65" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="62-65" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="63-66" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="61-64" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="62-65" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="62-65" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[62:65] *} Da wir diese Scopes jetzt deklarieren, werden sie in der API-Dokumentation angezeigt, wenn Sie sich einloggen/autorisieren. @@ -218,7 +90,7 @@ Wir verwenden immer noch dasselbe `OAuth2PasswordRequestForm`. Es enthält eine Und wir geben die Scopes als Teil des JWT-Tokens zurück. -/// danger | "Gefahr" +/// danger | Gefahr Der Einfachheit halber fügen wir hier die empfangenen Scopes direkt zum Token hinzu. @@ -226,71 +98,7 @@ Aus Sicherheitsgründen sollten Sie jedoch sicherstellen, dass Sie in Ihrer Anwe /// -//// tab | Python 3.10+ - -```Python hl_lines="155" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="155" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="156" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="154" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="155" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="155" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[155] *} ## Scopes in *Pfadoperationen* und Abhängigkeiten deklarieren @@ -308,7 +116,7 @@ Und die Abhängigkeitsfunktion `get_current_active_user` kann auch Unterabhängi In diesem Fall erfordert sie den Scope `me` (sie könnte mehr als einen Scope erfordern). -/// note | "Hinweis" +/// note | Hinweis Sie müssen nicht unbedingt an verschiedenen Stellen verschiedene Scopes hinzufügen. @@ -316,73 +124,9 @@ Wir tun dies hier, um zu demonstrieren, wie **FastAPI** auf verschiedenen Ebenen /// -//// tab | Python 3.10+ - -```Python hl_lines="4 139 170" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="4 139 170" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4 140 171" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="3 138 167" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="4 139 168" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="4 139 168" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[4,139,170] *} -/// info | "Technische Details" +/// info | Technische Details `Security` ist tatsächlich eine Unterklasse von `Depends` und hat nur noch einen zusätzlichen Parameter, den wir später kennenlernen werden. @@ -406,71 +150,7 @@ Wir deklarieren auch einen speziellen Parameter vom Typ `SecurityScopes`, der au Diese `SecurityScopes`-Klasse ähnelt `Request` (`Request` wurde verwendet, um das Request-Objekt direkt zu erhalten). -//// tab | Python 3.10+ - -```Python hl_lines="8 105" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="8 105" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8 106" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="7 104" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="8 105" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="8 105" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[8,105] *} ## Die `scopes` verwenden @@ -484,71 +164,7 @@ Wir erstellen eine `HTTPException`, die wir später an mehreren Stellen wiederve In diese Exception fügen wir (falls vorhanden) die erforderlichen Scopes als durch Leerzeichen getrennten String ein (unter Verwendung von `scope_str`). Wir fügen diesen String mit den Scopes in den Header `WWW-Authenticate` ein (das ist Teil der Spezifikation). -//// tab | Python 3.10+ - -```Python hl_lines="105 107-115" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="105 107-115" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="106 108-116" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="104 106-114" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="105 107-115" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="105 107-115" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[105,107:115] *} ## Den `username` und das Format der Daten überprüfen @@ -564,71 +180,7 @@ Anstelle beispielsweise eines `dict`s oder etwas anderem, was später in der Anw Wir verifizieren auch, dass wir einen Benutzer mit diesem Benutzernamen haben, und wenn nicht, lösen wir dieselbe Exception aus, die wir zuvor erstellt haben. -//// tab | Python 3.10+ - -```Python hl_lines="46 116-127" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="46 116-127" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="47 117-128" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="45 115-126" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="46 116-127" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="46 116-127" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[46,116:127] *} ## Die `scopes` verifizieren @@ -636,71 +188,7 @@ Wir überprüfen nun, ob das empfangenen Token alle Scopes enthält, die von die Hierzu verwenden wir `security_scopes.scopes`, das eine `list`e mit allen diesen Scopes als `str` enthält. -//// tab | Python 3.10+ - -```Python hl_lines="128-134" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="128-134" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="129-135" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="127-133" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="128-134" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="128-134" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[128:134] *} ## Abhängigkeitsbaum und Scopes @@ -727,7 +215,7 @@ So sieht die Hierarchie der Abhängigkeiten und Scopes aus: * `security_scopes.scopes` enthält `["me"]` für die *Pfadoperation* `read_users_me`, da das in der Abhängigkeit `get_current_active_user` deklariert ist. * `security_scopes.scopes` wird `[]` (nichts) für die *Pfadoperation* `read_system_status` enthalten, da diese keine `Security` mit `scopes` deklariert hat, und deren Abhängigkeit `get_current_user` ebenfalls keinerlei `scopes` deklariert. -/// tip | "Tipp" +/// tip | Tipp Das Wichtige und „Magische“ hier ist, dass `get_current_user` für jede *Pfadoperation* eine andere Liste von `scopes` hat, die überprüft werden. @@ -771,7 +259,7 @@ Am häufigsten ist der „Implicit“-Flow. Am sichersten ist der „Code“-Flow, die Implementierung ist jedoch komplexer, da mehr Schritte erforderlich sind. Da er komplexer ist, schlagen viele Anbieter letztendlich den „Implicit“-Flow vor. -/// note | "Hinweis" +/// note | Hinweis Es ist üblich, dass jeder Authentifizierungsanbieter seine Flows anders benennt, um sie zu einem Teil seiner Marke zu machen. diff --git a/docs/de/docs/advanced/settings.md b/docs/de/docs/advanced/settings.md index 8b9ba2f488c8b..00cc2ac372e0e 100644 --- a/docs/de/docs/advanced/settings.md +++ b/docs/de/docs/advanced/settings.md @@ -8,7 +8,7 @@ Aus diesem Grund werden diese üblicherweise in Umgebungsvariablen bereitgestell ## Umgebungsvariablen -/// tip | "Tipp" +/// tip | Tipp Wenn Sie bereits wissen, was „Umgebungsvariablen“ sind und wie man sie verwendet, können Sie gerne mit dem nächsten Abschnitt weiter unten fortfahren. @@ -67,7 +67,7 @@ name = os.getenv("MY_NAME", "World") print(f"Hello {name} from Python") ``` -/// tip | "Tipp" +/// tip | Tipp Das zweite Argument für `os.getenv()` ist der zurückzugebende Defaultwert. @@ -124,7 +124,7 @@ Hello World from Python -/// tip | "Tipp" +/// tip | Tipp Weitere Informationen dazu finden Sie unter The Twelve-Factor App: Config. @@ -180,9 +180,7 @@ Sie können dieselben Validierungs-Funktionen und -Tools verwenden, die Sie für //// tab | Pydantic v2 -```Python hl_lines="2 5-8 11" -{!> ../../docs_src/settings/tutorial001.py!} -``` +{* ../../docs_src/settings/tutorial001.py hl[2,5:8,11] *} //// @@ -194,13 +192,11 @@ In Pydantic v1 würden Sie `BaseSettings` direkt von `pydantic` statt von `pydan /// -```Python hl_lines="2 5-8 11" -{!> ../../docs_src/settings/tutorial001_pv1.py!} -``` +{* ../../docs_src/settings/tutorial001_pv1.py hl[2,5:8,11] *} //// -/// tip | "Tipp" +/// tip | Tipp Für ein schnelles Copy-and-paste verwenden Sie nicht dieses Beispiel, sondern das letzte unten. @@ -214,9 +210,7 @@ Als Nächstes werden die Daten konvertiert und validiert. Wenn Sie also dieses ` Dann können Sie das neue `settings`-Objekt in Ihrer Anwendung verwenden: -```Python hl_lines="18-20" -{!../../docs_src/settings/tutorial001.py!} -``` +{* ../../docs_src/settings/tutorial001.py hl[18:20] *} ### Den Server ausführen @@ -232,7 +226,7 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uvicorn main:app -/// tip | "Tipp" +/// tip | Tipp Um mehrere Umgebungsvariablen für einen einzelnen Befehl festzulegen, trennen Sie diese einfach durch ein Leerzeichen und fügen Sie alle vor dem Befehl ein. @@ -250,17 +244,13 @@ Sie könnten diese Einstellungen in eine andere Moduldatei einfügen, wie Sie in Sie könnten beispielsweise eine Datei `config.py` haben mit: -```Python -{!../../docs_src/settings/app01/config.py!} -``` +{* ../../docs_src/settings/app01/config.py *} Und dann verwenden Sie diese in einer Datei `main.py`: -```Python hl_lines="3 11-13" -{!../../docs_src/settings/app01/main.py!} -``` +{* ../../docs_src/settings/app01/main.py hl[3,11:13] *} -/// tip | "Tipp" +/// tip | Tipp Sie benötigen außerdem eine Datei `__init__.py`, wie in [Größere Anwendungen – mehrere Dateien](../tutorial/bigger-applications.md){.internal-link target=_blank} gesehen. @@ -276,9 +266,7 @@ Dies könnte besonders beim Testen nützlich sein, da es sehr einfach ist, eine Ausgehend vom vorherigen Beispiel könnte Ihre Datei `config.py` so aussehen: -```Python hl_lines="10" -{!../../docs_src/settings/app02/config.py!} -``` +{* ../../docs_src/settings/app02/config.py hl[10] *} Beachten Sie, dass wir jetzt keine Standardinstanz `settings = Settings()` erstellen. @@ -286,37 +274,9 @@ Beachten Sie, dass wir jetzt keine Standardinstanz `settings = Settings()` erste Jetzt erstellen wir eine Abhängigkeit, die ein neues `config.Settings()` zurückgibt. -//// tab | Python 3.9+ - -```Python hl_lines="6 12-13" -{!> ../../docs_src/settings/app02_an_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="6 12-13" -{!> ../../docs_src/settings/app02_an/main.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="5 11-12" -{!> ../../docs_src/settings/app02/main.py!} -``` - -//// +{* ../../docs_src/settings/app02_an_py39/main.py hl[6,12:13] *} -/// tip | "Tipp" +/// tip | Tipp Wir werden das `@lru_cache` in Kürze besprechen. @@ -326,43 +286,13 @@ Im Moment nehmen Sie an, dass `get_settings()` eine normale Funktion ist. Und dann können wir das von der *Pfadoperation-Funktion* als Abhängigkeit einfordern und es überall dort verwenden, wo wir es brauchen. -//// tab | Python 3.9+ - -```Python hl_lines="17 19-21" -{!> ../../docs_src/settings/app02_an_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17 19-21" -{!> ../../docs_src/settings/app02_an/main.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="16 18-20" -{!> ../../docs_src/settings/app02/main.py!} -``` - -//// +{* ../../docs_src/settings/app02_an_py39/main.py hl[17,19:21] *} ### Einstellungen und Tests Dann wäre es sehr einfach, beim Testen ein anderes Einstellungsobjekt bereitzustellen, indem man eine Abhängigkeitsüberschreibung für `get_settings` erstellt: -```Python hl_lines="9-10 13 21" -{!../../docs_src/settings/app02/test_main.py!} -``` +{* ../../docs_src/settings/app02/test_main.py hl[9:10,13,21] *} Bei der Abhängigkeitsüberschreibung legen wir einen neuen Wert für `admin_email` fest, wenn wir das neue `Settings`-Objekt erstellen, und geben dann dieses neue Objekt zurück. @@ -374,7 +304,7 @@ Wenn Sie viele Einstellungen haben, die sich möglicherweise oft ändern, vielle Diese Praxis ist so weit verbreitet, dass sie einen Namen hat. Diese Umgebungsvariablen werden üblicherweise in einer Datei `.env` abgelegt und die Datei wird „dotenv“ genannt. -/// tip | "Tipp" +/// tip | Tipp Eine Datei, die mit einem Punkt (`.`) beginnt, ist eine versteckte Datei in Unix-ähnlichen Systemen wie Linux und macOS. @@ -384,7 +314,7 @@ Aber eine dotenv-Datei muss nicht unbedingt genau diesen Dateinamen haben. Pydantic unterstützt das Lesen dieser Dateitypen mithilfe einer externen Bibliothek. Weitere Informationen finden Sie unter Pydantic Settings: Dotenv (.env) support. -/// tip | "Tipp" +/// tip | Tipp Damit das funktioniert, müssen Sie `pip install python-dotenv` ausführen. @@ -405,11 +335,9 @@ Und dann aktualisieren Sie Ihre `config.py` mit: //// tab | Pydantic v2 -```Python hl_lines="9" -{!> ../../docs_src/settings/app03_an/config.py!} -``` +{* ../../docs_src/settings/app03_an/config.py hl[9] *} -/// tip | "Tipp" +/// tip | Tipp Das Attribut `model_config` wird nur für die Pydantic-Konfiguration verwendet. Weitere Informationen finden Sie unter Pydantic: Configuration. @@ -419,11 +347,9 @@ Das Attribut `model_config` wird nur für die Pydantic-Konfiguration verwendet. //// tab | Pydantic v1 -```Python hl_lines="9-10" -{!> ../../docs_src/settings/app03_an/config_pv1.py!} -``` +{* ../../docs_src/settings/app03_an/config_pv1.py hl[9:10] *} -/// tip | "Tipp" +/// tip | Tipp Die Klasse `Config` wird nur für die Pydantic-Konfiguration verwendet. Weitere Informationen finden Sie unter Pydantic Model Config. @@ -462,35 +388,7 @@ würden wir dieses Objekt für jeden Request erstellen und die `.env`-Datei für Da wir jedoch den `@lru_cache`-Dekorator oben verwenden, wird das `Settings`-Objekt nur einmal erstellt, nämlich beim ersten Aufruf. ✔️ -//// tab | Python 3.9+ - -```Python hl_lines="1 11" -{!> ../../docs_src/settings/app03_an_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 11" -{!> ../../docs_src/settings/app03_an/main.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="1 10" -{!> ../../docs_src/settings/app03/main.py!} -``` - -//// +{* ../../docs_src/settings/app03_an_py39/main.py hl[1,11] *} Dann wird bei allen nachfolgenden Aufrufen von `get_settings()`, in den Abhängigkeiten für darauffolgende Requests, dasselbe Objekt zurückgegeben, das beim ersten Aufruf zurückgegeben wurde, anstatt den Code von `get_settings()` erneut auszuführen und ein neues `Settings`-Objekt zu erstellen. diff --git a/docs/de/docs/advanced/sub-applications.md b/docs/de/docs/advanced/sub-applications.md index 172b8d3c1f7a7..f123147b3cf6e 100644 --- a/docs/de/docs/advanced/sub-applications.md +++ b/docs/de/docs/advanced/sub-applications.md @@ -10,9 +10,7 @@ Wenn Sie zwei unabhängige FastAPI-Anwendungen mit deren eigenen unabhängigen O Erstellen Sie zunächst die Hauptanwendung **FastAPI** und deren *Pfadoperationen*: -```Python hl_lines="3 6-8" -{!../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[3,6:8] *} ### Unteranwendung @@ -20,9 +18,7 @@ Erstellen Sie dann Ihre Unteranwendung und deren *Pfadoperationen*. Diese Unteranwendung ist nur eine weitere Standard-FastAPI-Anwendung, aber diese wird „gemountet“: -```Python hl_lines="11 14-16" -{!../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[11,14:16] *} ### Die Unteranwendung mounten @@ -30,9 +26,7 @@ Mounten Sie in Ihrer Top-Level-Anwendung `app` die Unteranwendung `subapi`. In diesem Fall wird sie im Pfad `/subapi` gemountet: -```Python hl_lines="11 19" -{!../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[11,19] *} ### Es in der automatischen API-Dokumentation betrachten diff --git a/docs/de/docs/advanced/templates.md b/docs/de/docs/advanced/templates.md index 6cb3fcf6c36aa..136ce60271f49 100644 --- a/docs/de/docs/advanced/templates.md +++ b/docs/de/docs/advanced/templates.md @@ -27,11 +27,9 @@ $ pip install jinja2 * Deklarieren Sie einen `Request`-Parameter in der *Pfadoperation*, welcher ein Template zurückgibt. * Verwenden Sie die von Ihnen erstellten `templates`, um eine `TemplateResponse` zu rendern und zurückzugeben, übergeben Sie den Namen des Templates, das Requestobjekt und ein „Kontext“-Dictionary mit Schlüssel-Wert-Paaren, die innerhalb des Jinja2-Templates verwendet werden sollen. -```Python hl_lines="4 11 15-18" -{!../../docs_src/templates/tutorial001.py!} -``` +{* ../../docs_src/templates/tutorial001.py hl[4,11,15:18] *} -/// note | "Hinweis" +/// note | Hinweis Vor FastAPI 0.108.0 und Starlette 0.29.0 war `name` der erste Parameter. @@ -39,13 +37,13 @@ Außerdem wurde in früheren Versionen das `request`-Objekt als Teil der Schlüs /// -/// tip | "Tipp" +/// tip | Tipp Durch die Deklaration von `response_class=HTMLResponse` kann die Dokumentationsoberfläche erkennen, dass die Response HTML sein wird. /// -/// note | "Technische Details" +/// note | Technische Details Sie können auch `from starlette.templating import Jinja2Templates` verwenden. diff --git a/docs/de/docs/advanced/testing-dependencies.md b/docs/de/docs/advanced/testing-dependencies.md index c565b30f2ff33..8299d6dd7ee79 100644 --- a/docs/de/docs/advanced/testing-dependencies.md +++ b/docs/de/docs/advanced/testing-dependencies.md @@ -28,59 +28,9 @@ Um eine Abhängigkeit für das Testen zu überschreiben, geben Sie als Schlüsse Und dann ruft **FastAPI** diese Überschreibung anstelle der ursprünglichen Abhängigkeit auf. -//// tab | Python 3.10+ +{* ../../docs_src/dependency_testing/tutorial001_an_py310.py hl[26:27,30] *} -```Python hl_lines="26-27 30" -{!> ../../docs_src/dependency_testing/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="28-29 32" -{!> ../../docs_src/dependency_testing/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="29-30 33" -{!> ../../docs_src/dependency_testing/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="24-25 28" -{!> ../../docs_src/dependency_testing/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="28-29 32" -{!> ../../docs_src/dependency_testing/tutorial001.py!} -``` - -//// - -/// tip | "Tipp" +/// tip | Tipp Sie können eine Überschreibung für eine Abhängigkeit festlegen, die an einer beliebigen Stelle in Ihrer **FastAPI**-Anwendung verwendet wird. @@ -96,7 +46,7 @@ Anschließend können Sie Ihre Überschreibungen zurücksetzen (entfernen), inde app.dependency_overrides = {} ``` -/// tip | "Tipp" +/// tip | Tipp Wenn Sie eine Abhängigkeit nur während einiger Tests überschreiben möchten, können Sie die Überschreibung zu Beginn des Tests (innerhalb der Testfunktion) festlegen und am Ende (am Ende der Testfunktion) zurücksetzen. diff --git a/docs/de/docs/advanced/testing-events.md b/docs/de/docs/advanced/testing-events.md index 3e63791c6b3fc..05d6bcb2b0a49 100644 --- a/docs/de/docs/advanced/testing-events.md +++ b/docs/de/docs/advanced/testing-events.md @@ -2,6 +2,4 @@ Wenn Sie in Ihren Tests Ihre Event-Handler (`startup` und `shutdown`) ausführen wollen, können Sie den `TestClient` mit einer `with`-Anweisung verwenden: -```Python hl_lines="9-12 20-24" -{!../../docs_src/app_testing/tutorial003.py!} -``` +{* ../../docs_src/app_testing/tutorial003.py hl[9:12,20:24] *} diff --git a/docs/de/docs/advanced/testing-websockets.md b/docs/de/docs/advanced/testing-websockets.md index 7ae7d92d6422c..5932e6d6a96ca 100644 --- a/docs/de/docs/advanced/testing-websockets.md +++ b/docs/de/docs/advanced/testing-websockets.md @@ -4,11 +4,9 @@ Sie können den schon bekannten `TestClient` zum Testen von WebSockets verwenden Dazu verwenden Sie den `TestClient` in einer `with`-Anweisung, eine Verbindung zum WebSocket herstellend: -```Python hl_lines="27-31" -{!../../docs_src/app_testing/tutorial002.py!} -``` +{* ../../docs_src/app_testing/tutorial002.py hl[27:31] *} -/// note | "Hinweis" +/// note | Hinweis Weitere Informationen finden Sie in der Starlette-Dokumentation zum Testen von WebSockets. diff --git a/docs/de/docs/advanced/using-request-directly.md b/docs/de/docs/advanced/using-request-directly.md index 6a0b96680e74e..a0a5ec1ab6ae8 100644 --- a/docs/de/docs/advanced/using-request-directly.md +++ b/docs/de/docs/advanced/using-request-directly.md @@ -29,13 +29,11 @@ Angenommen, Sie möchten auf die IP-Adresse/den Host des Clients in Ihrer *Pfado Dazu müssen Sie direkt auf den Request zugreifen. -```Python hl_lines="1 7-8" -{!../../docs_src/using_request_directly/tutorial001.py!} -``` +{* ../../docs_src/using_request_directly/tutorial001.py hl[1,7:8] *} Durch die Deklaration eines *Pfadoperation-Funktionsparameters*, dessen Typ der `Request` ist, weiß **FastAPI**, dass es den `Request` diesem Parameter übergeben soll. -/// tip | "Tipp" +/// tip | Tipp Beachten Sie, dass wir in diesem Fall einen Pfad-Parameter zusätzlich zum Request-Parameter deklarieren. @@ -49,7 +47,7 @@ Auf die gleiche Weise können Sie wie gewohnt jeden anderen Parameter deklariere Weitere Details zum `Request`-Objekt finden Sie in der offiziellen Starlette-Dokumentation. -/// note | "Technische Details" +/// note | Technische Details Sie können auch `from starlette.requests import Request` verwenden. diff --git a/docs/de/docs/advanced/websockets.md b/docs/de/docs/advanced/websockets.md index cf13fa23ce425..020c20bc01b5a 100644 --- a/docs/de/docs/advanced/websockets.md +++ b/docs/de/docs/advanced/websockets.md @@ -38,19 +38,15 @@ In der Produktion hätten Sie eine der oben genannten Optionen. Aber es ist die einfachste Möglichkeit, sich auf die Serverseite von WebSockets zu konzentrieren und ein funktionierendes Beispiel zu haben: -```Python hl_lines="2 6-38 41-43" -{!../../docs_src/websockets/tutorial001.py!} -``` +{* ../../docs_src/websockets/tutorial001.py hl[2,6:38,41:43] *} ## Einen `websocket` erstellen Erstellen Sie in Ihrer **FastAPI**-Anwendung einen `websocket`: -```Python hl_lines="1 46-47" -{!../../docs_src/websockets/tutorial001.py!} -``` +{* ../../docs_src/websockets/tutorial001.py hl[1,46:47] *} -/// note | "Technische Details" +/// note | Technische Details Sie können auch `from starlette.websockets import WebSocket` verwenden. @@ -62,9 +58,7 @@ Sie können auch `from starlette.websockets import WebSocket` verwenden. In Ihrer WebSocket-Route können Sie Nachrichten `await`en und Nachrichten senden. -```Python hl_lines="48-52" -{!../../docs_src/websockets/tutorial001.py!} -``` +{* ../../docs_src/websockets/tutorial001.py hl[48:52] *} Sie können Binär-, Text- und JSON-Daten empfangen und senden. @@ -115,57 +109,7 @@ In WebSocket-Endpunkten können Sie Folgendes aus `fastapi` importieren und verw Diese funktionieren auf die gleiche Weise wie für andere FastAPI-Endpunkte/*Pfadoperationen*: -//// tab | Python 3.10+ - -```Python hl_lines="68-69 82" -{!> ../../docs_src/websockets/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="68-69 82" -{!> ../../docs_src/websockets/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="69-70 83" -{!> ../../docs_src/websockets/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="66-67 79" -{!> ../../docs_src/websockets/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="68-69 81" -{!> ../../docs_src/websockets/tutorial002.py!} -``` - -//// +{* ../../docs_src/websockets/tutorial002_an_py310.py hl[68:69,82] *} /// info @@ -196,7 +140,7 @@ Dort können Sie einstellen: * Die „Item ID“, die im Pfad verwendet wird. * Das „Token“, das als Query-Parameter verwendet wird. -/// tip | "Tipp" +/// tip | Tipp Beachten Sie, dass der Query-„Token“ von einer Abhängigkeit verarbeitet wird. @@ -210,21 +154,7 @@ Damit können Sie den WebSocket verbinden und dann Nachrichten senden und empfan Wenn eine WebSocket-Verbindung geschlossen wird, löst `await websocket.receive_text()` eine `WebSocketDisconnect`-Exception aus, die Sie dann wie in folgendem Beispiel abfangen und behandeln können. -//// tab | Python 3.9+ - -```Python hl_lines="79-81" -{!> ../../docs_src/websockets/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="81-83" -{!> ../../docs_src/websockets/tutorial003.py!} -``` - -//// +{* ../../docs_src/websockets/tutorial003_py39.py hl[79:81] *} Zum Ausprobieren: @@ -238,7 +168,7 @@ Das wird die Ausnahme `WebSocketDisconnect` auslösen und alle anderen Clients e Client #1596980209979 left the chat ``` -/// tip | "Tipp" +/// tip | Tipp Die obige Anwendung ist ein minimales und einfaches Beispiel, das zeigt, wie Nachrichten verarbeitet und an mehrere WebSocket-Verbindungen gesendet werden. diff --git a/docs/de/docs/advanced/wsgi.md b/docs/de/docs/advanced/wsgi.md index 50abc84d1ee02..c0998a62110e2 100644 --- a/docs/de/docs/advanced/wsgi.md +++ b/docs/de/docs/advanced/wsgi.md @@ -12,9 +12,7 @@ Wrappen Sie dann die WSGI-Anwendung (z. B. Flask) mit der Middleware. Und dann mounten Sie das auf einem Pfad. -```Python hl_lines="2-3 23" -{!../../docs_src/wsgi/tutorial001.py!} -``` +{* ../../docs_src/wsgi/tutorial001.py hl[2:3,23] *} ## Es ansehen diff --git a/docs/de/docs/alternatives.md b/docs/de/docs/alternatives.md index 49e1cc6f092b2..611315501de20 100644 --- a/docs/de/docs/alternatives.md +++ b/docs/de/docs/alternatives.md @@ -30,13 +30,13 @@ Es wird von vielen Unternehmen verwendet, darunter Mozilla, Red Hat und Eventbri Es war eines der ersten Beispiele für **automatische API-Dokumentation**, und dies war insbesondere eine der ersten Ideen, welche „die Suche nach“ **FastAPI** inspirierten. -/// note | "Hinweis" +/// note | Hinweis Das Django REST Framework wurde von Tom Christie erstellt. Derselbe Schöpfer von Starlette und Uvicorn, auf denen **FastAPI** basiert. /// -/// check | "Inspirierte **FastAPI**" +/// check | Inspirierte **FastAPI** Eine automatische API-Dokumentationsoberfläche zu haben. @@ -56,7 +56,7 @@ Diese Entkopplung der Teile und die Tatsache, dass es sich um ein „Mikroframew Angesichts der Einfachheit von Flask schien es eine gute Ergänzung zum Erstellen von APIs zu sein. Als Nächstes musste ein „Django REST Framework“ für Flask gefunden werden. -/// check | "Inspirierte **FastAPI**" +/// check | Inspirierte **FastAPI** Ein Mikroframework zu sein. Es einfach zu machen, die benötigten Tools und Teile zu kombinieren. @@ -98,7 +98,7 @@ def read_url(): Sehen Sie sich die Ähnlichkeiten in `requests.get(...)` und `@app.get(...)` an. -/// check | "Inspirierte **FastAPI**" +/// check | Inspirierte **FastAPI** * Über eine einfache und intuitive API zu verfügen. * HTTP-Methodennamen (Operationen) direkt, auf einfache und intuitive Weise zu verwenden. @@ -118,7 +118,7 @@ Irgendwann wurde Swagger an die Linux Foundation übergeben und in OpenAPI umben Aus diesem Grund spricht man bei Version 2.0 häufig von „Swagger“ und ab Version 3 von „OpenAPI“. -/// check | "Inspirierte **FastAPI**" +/// check | Inspirierte **FastAPI** Einen offenen Standard für API-Spezifikationen zu übernehmen und zu verwenden, anstelle eines benutzerdefinierten Schemas. @@ -147,7 +147,7 @@ Für diese Funktionen wurde Marshmallow entwickelt. Es ist eine großartige Bibl Aber sie wurde erstellt, bevor Typhinweise in Python existierten. Um also ein Schema zu definieren, müssen Sie bestimmte Werkzeuge und Klassen verwenden, die von Marshmallow bereitgestellt werden. -/// check | "Inspirierte **FastAPI**" +/// check | Inspirierte **FastAPI** Code zu verwenden, um „Schemas“ zu definieren, welche Datentypen und Validierung automatisch bereitstellen. @@ -169,7 +169,7 @@ Webargs wurde von denselben Marshmallow-Entwicklern erstellt. /// -/// check | "Inspirierte **FastAPI**" +/// check | Inspirierte **FastAPI** Eingehende Requestdaten automatisch zu validieren. @@ -199,7 +199,7 @@ APISpec wurde von denselben Marshmallow-Entwicklern erstellt. /// -/// check | "Inspirierte **FastAPI**" +/// check | Inspirierte **FastAPI** Den offenen Standard für APIs, OpenAPI, zu unterstützen. @@ -231,7 +231,7 @@ Flask-apispec wurde von denselben Marshmallow-Entwicklern erstellt. /// -/// check | "Inspirierte **FastAPI**" +/// check | Inspirierte **FastAPI** Das OpenAPI-Schema automatisch zu generieren, aus demselben Code, welcher die Serialisierung und Validierung definiert. @@ -251,7 +251,7 @@ Da TypeScript-Daten jedoch nach der Kompilierung nach JavaScript nicht erhalten Es kann nicht sehr gut mit verschachtelten Modellen umgehen. Wenn es sich beim JSON-Body in der Anfrage also um ein JSON-Objekt mit inneren Feldern handelt, die wiederum verschachtelte JSON-Objekte sind, kann er nicht richtig dokumentiert und validiert werden. -/// check | "Inspirierte **FastAPI**" +/// check | Inspirierte **FastAPI** Python-Typen zu verwenden, um eine hervorragende Editorunterstützung zu erhalten. @@ -263,7 +263,7 @@ Python-Typen zu verwenden, um eine hervorragende Editorunterstützung zu erhalte Es war eines der ersten extrem schnellen Python-Frameworks, welches auf `asyncio` basierte. Es wurde so gestaltet, dass es Flask sehr ähnlich ist. -/// note | "Technische Details" +/// note | Technische Details Es verwendete `uvloop` anstelle der standardmäßigen Python-`asyncio`-Schleife. Das hat es so schnell gemacht. @@ -271,7 +271,7 @@ Hat eindeutig Uvicorn und Starlette inspiriert, welche derzeit in offenen Benchm /// -/// check | "Inspirierte **FastAPI**" +/// check | Inspirierte **FastAPI** Einen Weg zu finden, eine hervorragende Performanz zu haben. @@ -287,7 +287,7 @@ Es ist so konzipiert, dass es über Funktionen verfügt, welche zwei Parameter e Daher müssen Datenvalidierung, Serialisierung und Dokumentation im Code und nicht automatisch erfolgen. Oder sie müssen als Framework oberhalb von Falcon implementiert werden, so wie Hug. Dieselbe Unterscheidung findet auch in anderen Frameworks statt, die vom Design von Falcon inspiriert sind und ein Requestobjekt und ein Responseobjekt als Parameter haben. -/// check | "Inspirierte **FastAPI**" +/// check | Inspirierte **FastAPI** Wege zu finden, eine großartige Performanz zu erzielen. @@ -313,7 +313,7 @@ Das Dependency Injection System erfordert eine Vorab-Registrierung der Abhängig Routen werden an einer einzigen Stelle deklariert, indem Funktionen verwendet werden, die an anderen Stellen deklariert wurden (anstatt Dekoratoren zu verwenden, welche direkt über der Funktion platziert werden können, welche den Endpunkt verarbeitet). Dies ähnelt eher der Vorgehensweise von Django als der Vorgehensweise von Flask (und Starlette). Es trennt im Code Dinge, die relativ eng miteinander gekoppelt sind. -/// check | "Inspirierte **FastAPI**" +/// check | Inspirierte **FastAPI** Zusätzliche Validierungen für Datentypen zu definieren, mithilfe des „Default“-Werts von Modellattributen. Dies verbessert die Editorunterstützung und war zuvor in Pydantic nicht verfügbar. @@ -341,7 +341,7 @@ Hug wurde von Timothy Crosley erstellt, dem gleichen Schöpfer von fastapi Repository bereits geklont haben und tief in den Code eintauchen möchten, hier einen Leitfaden zum Einrichten Ihrer Umgebung. - -### Virtuelle Umgebung mit `venv` - -Sie können mit dem Python-Modul `venv` in einem Verzeichnis eine isolierte virtuelle lokale Umgebung erstellen. Machen wir das im geklonten Repository (da wo sich die `requirements.txt` befindet): - -
- -```console -$ python -m venv env -``` - -
- -Das erstellt ein Verzeichnis `./env/` mit den Python-Binärdateien und Sie können dann Packages in dieser lokalen Umgebung installieren. - -### Umgebung aktivieren - -Aktivieren Sie die neue Umgebung mit: - -//// tab | Linux, macOS - -
- -```console -$ source ./env/bin/activate -``` - -
- -//// - -//// tab | Windows PowerShell - -
- -```console -$ .\env\Scripts\Activate.ps1 -``` - -
- -//// - -//// tab | Windows Bash - -Oder, wenn Sie Bash für Windows verwenden (z. B. Git Bash): - -
- -```console -$ source ./env/Scripts/activate -``` - -
- -//// - -Um zu überprüfen, ob es funktioniert hat, geben Sie ein: - -//// tab | Linux, macOS, Windows Bash - -
- -```console -$ which pip - -some/directory/fastapi/env/bin/pip -``` - -
- -//// - -//// tab | Windows PowerShell - -
- -```console -$ Get-Command pip - -some/directory/fastapi/env/bin/pip -``` - -
- -//// - -Wenn die `pip` Binärdatei unter `env/bin/pip` angezeigt wird, hat es funktioniert. 🎉 - -Stellen Sie sicher, dass Sie über die neueste Version von pip in Ihrer lokalen Umgebung verfügen, um Fehler bei den nächsten Schritten zu vermeiden: - -
- -```console -$ python -m pip install --upgrade pip - ----> 100% -``` - -
- -/// tip | "Tipp" - -Aktivieren Sie jedes Mal, wenn Sie ein neues Package mit `pip` in dieser Umgebung installieren, die Umgebung erneut. - -Dadurch wird sichergestellt, dass Sie, wenn Sie ein von diesem Package installiertes Terminalprogramm verwenden, das Programm aus Ihrer lokalen Umgebung verwenden und kein anderes, das global installiert sein könnte. - -/// - -### Benötigtes mit pip installieren - -Nachdem Sie die Umgebung wie oben beschrieben aktiviert haben: - -
- -```console -$ pip install -r requirements.txt - ----> 100% -``` - -
- -Das installiert alle Abhängigkeiten und Ihr lokales FastAPI in Ihrer lokalen Umgebung. - -#### Das lokale FastAPI verwenden - -Wenn Sie eine Python-Datei erstellen, die FastAPI importiert und verwendet, und diese mit dem Python aus Ihrer lokalen Umgebung ausführen, wird Ihr geklonter lokaler FastAPI-Quellcode verwendet. - -Und wenn Sie diesen lokalen FastAPI-Quellcode aktualisieren und dann die Python-Datei erneut ausführen, wird die neue Version von FastAPI verwendet, die Sie gerade bearbeitet haben. - -Auf diese Weise müssen Sie Ihre lokale Version nicht „installieren“, um jede Änderung testen zu können. - -/// note | "Technische Details" - -Das geschieht nur, wenn Sie die Installation mit der enthaltenen `requirements.txt` durchführen, anstatt `pip install fastapi` direkt auszuführen. - -Das liegt daran, dass in der Datei `requirements.txt` die lokale Version von FastAPI mit der Option `-e` für die Installation im „editierbaren“ Modus markiert ist. - -/// - -### Den Code formatieren - -Es gibt ein Skript, das, wenn Sie es ausführen, Ihren gesamten Code formatiert und bereinigt: - -
- -```console -$ bash scripts/format.sh -``` - -
- -Es sortiert auch alle Ihre Importe automatisch. - -Damit es sie richtig sortiert, muss FastAPI lokal in Ihrer Umgebung installiert sein, mit dem Befehl vom obigen Abschnitt, welcher `-e` verwendet. - -## Dokumentation - -Stellen Sie zunächst sicher, dass Sie Ihre Umgebung wie oben beschrieben einrichten, was alles Benötigte installiert. - -### Dokumentation live - -Während der lokalen Entwicklung gibt es ein Skript, das die Site erstellt, auf Änderungen prüft und direkt neu lädt (Live Reload): - -
- -```console -$ python ./scripts/docs.py live - -[INFO] Serving on http://127.0.0.1:8008 -[INFO] Start watching changes -[INFO] Start detecting changes -``` - -
- -Das stellt die Dokumentation unter `http://127.0.0.1:8008` bereit. - -Auf diese Weise können Sie die Dokumentation/Quelldateien bearbeiten und die Änderungen live sehen. - -/// tip | "Tipp" - -Alternativ können Sie die Schritte des Skripts auch manuell ausführen. - -Gehen Sie in das Verzeichnis für die entsprechende Sprache. Das für die englischsprachige Hauptdokumentation befindet sich unter `docs/en/`: - -```console -$ cd docs/en/ -``` - -Führen Sie dann `mkdocs` in diesem Verzeichnis aus: - -```console -$ mkdocs serve --dev-addr 8008 -``` - -/// - -#### Typer-CLI (optional) - -Die Anleitung hier zeigt Ihnen, wie Sie das Skript unter `./scripts/docs.py` direkt mit dem `python` Programm verwenden. - -Sie können aber auch Typer CLI verwenden und erhalten dann Autovervollständigung für Kommandos in Ihrem Terminal, nach dem Sie dessen Vervollständigung installiert haben. - -Wenn Sie Typer CLI installieren, können Sie die Vervollständigung installieren mit: - -
- -```console -$ typer --install-completion - -zsh completion installed in /home/user/.bashrc. -Completion will take effect once you restart the terminal. -``` - -
- -### Dokumentationsstruktur - -Die Dokumentation verwendet MkDocs. - -Und es gibt zusätzliche Tools/Skripte für Übersetzungen, in `./scripts/docs.py`. - -/// tip | "Tipp" - -Sie müssen sich den Code in `./scripts/docs.py` nicht anschauen, verwenden Sie ihn einfach in der Kommandozeile. - -/// - -Die gesamte Dokumentation befindet sich im Markdown-Format im Verzeichnis `./docs/en/`. - -Viele der Tutorials enthalten Codeblöcke. - -In den meisten Fällen handelt es sich bei diesen Codeblöcken um vollständige Anwendungen, die unverändert ausgeführt werden können. - -Tatsächlich sind diese Codeblöcke nicht Teil des Markdowns, sondern Python-Dateien im Verzeichnis `./docs_src/`. - -Und diese Python-Dateien werden beim Generieren der Site in die Dokumentation eingefügt. - -### Dokumentation für Tests - -Tatsächlich arbeiten die meisten Tests mit den Beispielquelldateien in der Dokumentation. - -Dadurch wird sichergestellt, dass: - -* Die Dokumentation aktuell ist. -* Die Dokumentationsbeispiele ohne Änderung ausgeführt werden können. -* Die meisten Funktionalitäten durch die Dokumentation abgedeckt werden, sichergestellt durch die Testabdeckung. - -#### Gleichzeitig Apps und Dokumentation - -Wenn Sie die Beispiele ausführen, mit z. B.: - -
- -```console -$ uvicorn tutorial001:app --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -
- -wird das, da Uvicorn standardmäßig den Port `8000` verwendet, mit der Dokumentation auf dem Port `8008` nicht in Konflikt geraten. - -### Übersetzungen - -Hilfe bei Übersetzungen wird SEHR geschätzt! Und es kann nicht getan werden, ohne die Hilfe der Gemeinschaft. 🌎 🚀 - -Hier sind die Schritte, die Ihnen bei Übersetzungen helfen. - -#### Tipps und Richtlinien - -* Schauen Sie nach aktuellen Pull Requests für Ihre Sprache. Sie können die Pull Requests nach dem Label für Ihre Sprache filtern. Für Spanisch lautet das Label beispielsweise `lang-es`. - -* Sehen Sie diese Pull Requests durch (Review), schlagen Sie Änderungen vor, oder segnen Sie sie ab (Approval). Bei den Sprachen, die ich nicht spreche, warte ich, bis mehrere andere die Übersetzung durchgesehen haben, bevor ich den Pull Request merge. - -/// tip | "Tipp" - -Sie können Kommentare mit Änderungsvorschlägen zu vorhandenen Pull Requests hinzufügen. - -Schauen Sie sich die Dokumentation an, wie man ein Review zu einem Pull Request hinzufügt, welches den PR absegnet oder Änderungen vorschlägt. - -/// - -* Überprüfen Sie, ob es eine GitHub-Diskussion gibt, die Übersetzungen für Ihre Sprache koordiniert. Sie können sie abonnieren, und wenn ein neuer Pull Request zum Review vorliegt, wird der Diskussion automatisch ein Kommentar hinzugefügt. - -* Wenn Sie Seiten übersetzen, fügen Sie einen einzelnen Pull Request pro übersetzter Seite hinzu. Dadurch wird es für andere viel einfacher, ihn zu durchzusehen. - -* Um den Zwei-Buchstaben-Code für die Sprache zu finden, die Sie übersetzen möchten, schauen Sie sich die Tabelle List of ISO 639-1 codes an. - -#### Vorhandene Sprache - -Angenommen, Sie möchten eine Seite für eine Sprache übersetzen, die bereits Übersetzungen für einige Seiten hat, beispielsweise für Spanisch. - -Im Spanischen lautet der Zwei-Buchstaben-Code `es`. Das Verzeichnis für spanische Übersetzungen befindet sich also unter `docs/es/`. - -/// tip | "Tipp" - -Die Haupt („offizielle“) Sprache ist Englisch und befindet sich unter `docs/en/`. - -/// - -Führen Sie nun den Live-Server für die Dokumentation auf Spanisch aus: - -
- -```console -// Verwenden Sie das Kommando „live“ und fügen Sie den Sprach-Code als Argument hinten an -$ python ./scripts/docs.py live es - -[INFO] Serving on http://127.0.0.1:8008 -[INFO] Start watching changes -[INFO] Start detecting changes -``` - -
- -/// tip | "Tipp" - -Alternativ können Sie die Schritte des Skripts auch manuell ausführen. - -Gehen Sie in das Sprachverzeichnis, für die spanischen Übersetzungen ist das `docs/es/`: - -```console -$ cd docs/es/ -``` - -Dann führen Sie in dem Verzeichnis `mkdocs` aus: - -```console -$ mkdocs serve --dev-addr 8008 -``` - -/// - -Jetzt können Sie auf http://127.0.0.1:8008 gehen und Ihre Änderungen live sehen. - -Sie werden sehen, dass jede Sprache alle Seiten hat. Einige Seiten sind jedoch nicht übersetzt und haben oben eine Info-Box, dass die Übersetzung noch fehlt. - -Nehmen wir nun an, Sie möchten eine Übersetzung für den Abschnitt [Features](features.md){.internal-link target=_blank} hinzufügen. - -* Kopieren Sie die Datei: - -``` -docs/en/docs/features.md -``` - -* Fügen Sie sie an genau derselben Stelle ein, jedoch für die Sprache, die Sie übersetzen möchten, z. B.: - -``` -docs/es/docs/features.md -``` - -/// tip | "Tipp" - -Beachten Sie, dass die einzige Änderung in Pfad und Dateiname der Sprachcode ist, von `en` zu `es`. - -/// - -Wenn Sie in Ihrem Browser nachsehen, werden Sie feststellen, dass die Dokumentation jetzt Ihren neuen Abschnitt anzeigt (die Info-Box oben ist verschwunden). 🎉 - -Jetzt können Sie alles übersetzen und beim Speichern sehen, wie es aussieht. - -#### Neue Sprache - -Nehmen wir an, Sie möchten Übersetzungen für eine Sprache hinzufügen, die noch nicht übersetzt ist, nicht einmal einige Seiten. - -Angenommen, Sie möchten Übersetzungen für Kreolisch hinzufügen, diese sind jedoch noch nicht in den Dokumenten enthalten. - -Wenn Sie den Link von oben überprüfen, lautet der Sprachcode für Kreolisch `ht`. - -Der nächste Schritt besteht darin, das Skript auszuführen, um ein neues Übersetzungsverzeichnis zu erstellen: - -
- -```console -// Verwenden Sie das Kommando new-lang und fügen Sie den Sprach-Code als Argument hinten an -$ python ./scripts/docs.py new-lang ht - -Successfully initialized: docs/ht -``` - -
- -Jetzt können Sie in Ihrem Code-Editor das neu erstellte Verzeichnis `docs/ht/` sehen. - -Obiges Kommando hat eine Datei `docs/ht/mkdocs.yml` mit einer Minimal-Konfiguration erstellt, die alles von der `en`-Version erbt: - -```yaml -INHERIT: ../en/mkdocs.yml -``` - -/// tip | "Tipp" - -Sie können diese Datei mit diesem Inhalt auch einfach manuell erstellen. - -/// - -Das Kommando hat auch eine Dummy-Datei `docs/ht/index.md` für die Hauptseite erstellt. Sie können mit der Übersetzung dieser Datei beginnen. - -Sie können nun mit den obigen Instruktionen für eine „vorhandene Sprache“ fortfahren. - -Fügen Sie dem ersten Pull Request beide Dateien `docs/ht/mkdocs.yml` und `docs/ht/index.md` bei. 🎉 - -#### Vorschau des Ergebnisses - -Wie bereits oben erwähnt, können Sie `./scripts/docs.py` mit dem Befehl `live` verwenden, um eine Vorschau der Ergebnisse anzuzeigen (oder `mkdocs serve`). - -Sobald Sie fertig sind, können Sie auch alles so testen, wie es online aussehen würde, einschließlich aller anderen Sprachen. - -Bauen Sie dazu zunächst die gesamte Dokumentation: - -
- -```console -// Verwenden Sie das Kommando „build-all“, das wird ein wenig dauern -$ python ./scripts/docs.py build-all - -Building docs for: en -Building docs for: es -Successfully built docs for: es -``` - -
- -Dadurch werden alle diese unabhängigen MkDocs-Sites für jede Sprache erstellt, kombiniert und das endgültige Resultat unter `./site/` gespeichert. - -Dieses können Sie dann mit dem Befehl `serve` bereitstellen: - -
- -```console -// Verwenden Sie das Kommando „serve“ nachdem Sie „build-all“ ausgeführt haben. -$ python ./scripts/docs.py serve - -Warning: this is a very simple server. For development, use mkdocs serve instead. -This is here only to preview a site with translations already built. -Make sure you run the build-all command first. -Serving at: http://127.0.0.1:8008 -``` - -
- -#### Übersetzungsspezifische Tipps und Richtlinien - -* Übersetzen Sie nur die Markdown-Dokumente (`.md`). Übersetzen Sie nicht die Codebeispiele unter `./docs_src`. - -* In Codeblöcken innerhalb des Markdown-Dokuments, übersetzen Sie Kommentare (`# ein Kommentar`), aber lassen Sie den Rest unverändert. - -* Ändern Sie nichts, was in "``" (Inline-Code) eingeschlossen ist. - -* In Zeilen, die mit `===` oder `!!!` beginnen, übersetzen Sie nur den ` "... Text ..."`-Teil. Lassen Sie den Rest unverändert. - -* Sie können Info-Boxen wie `!!! warning` mit beispielsweise `!!! warning "Achtung"` übersetzen. Aber ändern Sie nicht das Wort direkt nach dem `!!!`, es bestimmt die Farbe der Info-Box. - -* Ändern Sie nicht die Pfade in Links zu Bildern, Codedateien, Markdown Dokumenten. - -* Wenn ein Markdown-Dokument übersetzt ist, ändern sich allerdings unter Umständen die `#hash-teile` in Links zu dessen Überschriften. Aktualisieren Sie diese Links, wenn möglich. - * Suchen Sie im übersetzten Dokument nach solchen Links mit dem Regex `#[^# ]`. - * Suchen Sie in allen bereits in ihre Sprache übersetzen Dokumenten nach `ihr-ubersetztes-dokument.md`. VS Code hat beispielsweise eine Option „Bearbeiten“ -> „In Dateien suchen“. - * Übersetzen Sie bei der Übersetzung eines Dokuments nicht „im Voraus“ `#hash-teile`, die zu Überschriften in noch nicht übersetzten Dokumenten verlinken. - -## Tests - -Es gibt ein Skript, das Sie lokal ausführen können, um den gesamten Code zu testen und Code Coverage Reporte in HTML zu generieren: - -
- -```console -$ bash scripts/test-cov-html.sh -``` - -
- -Dieses Kommando generiert ein Verzeichnis `./htmlcov/`. Wenn Sie die Datei `./htmlcov/index.html` in Ihrem Browser öffnen, können Sie interaktiv die Codebereiche erkunden, die von den Tests abgedeckt werden, und feststellen, ob Bereiche fehlen. diff --git a/docs/de/docs/deployment/concepts.md b/docs/de/docs/deployment/concepts.md index 3c1c0cfce7821..97ad854e2074e 100644 --- a/docs/de/docs/deployment/concepts.md +++ b/docs/de/docs/deployment/concepts.md @@ -151,7 +151,7 @@ Und dennoch möchten Sie wahrscheinlich nicht, dass die Anwendung tot bleibt, we Aber in den Fällen mit wirklich schwerwiegenden Fehlern, die den laufenden **Prozess** zum Absturz bringen, benötigen Sie eine externe Komponente, die den Prozess **neu startet**, zumindest ein paar Mal ... -/// tip | "Tipp" +/// tip | Tipp ... Obwohl es wahrscheinlich keinen Sinn macht, sie immer wieder neu zu starten, wenn die gesamte Anwendung einfach **sofort abstürzt**. Aber in diesen Fällen werden Sie es wahrscheinlich während der Entwicklung oder zumindest direkt nach dem Deployment bemerken. @@ -241,7 +241,7 @@ Hier sind einige mögliche Kombinationen und Strategien: * **Cloud-Dienste**, welche das für Sie erledigen * Der Cloud-Dienst wird wahrscheinlich **die Replikation für Sie übernehmen**. Er würde Sie möglicherweise **einen auszuführenden Prozess** oder ein **zu verwendendes Container-Image** definieren lassen, in jedem Fall wäre es höchstwahrscheinlich **ein einzelner Uvicorn-Prozess**, und der Cloud-Dienst wäre auch verantwortlich für die Replikation. -/// tip | "Tipp" +/// tip | Tipp Machen Sie sich keine Sorgen, wenn einige dieser Punkte zu **Containern**, Docker oder Kubernetes noch nicht viel Sinn ergeben. @@ -263,7 +263,7 @@ Und Sie müssen sicherstellen, dass es sich um einen einzelnen Prozess handelt, Natürlich gibt es Fälle, in denen es kein Problem darstellt, die Vorab-Schritte mehrmals auszuführen. In diesem Fall ist die Handhabung viel einfacher. -/// tip | "Tipp" +/// tip | Tipp Bedenken Sie außerdem, dass Sie, abhängig von Ihrer Einrichtung, in manchen Fällen **gar keine Vorab-Schritte** benötigen, bevor Sie die Anwendung starten. @@ -281,7 +281,7 @@ Hier sind einige mögliche Ideen: * Ein Bash-Skript, das die Vorab-Schritte ausführt und dann Ihre Anwendung startet * Sie benötigen immer noch eine Möglichkeit, *dieses* Bash-Skript zu starten/neu zu starten, Fehler zu erkennen, usw. -/// tip | "Tipp" +/// tip | Tipp Konkretere Beispiele hierfür mit Containern gebe ich Ihnen in einem späteren Kapitel: [FastAPI in Containern – Docker](docker.md){.internal-link target=_blank}. diff --git a/docs/de/docs/deployment/docker.md b/docs/de/docs/deployment/docker.md index c11dc41275f65..a2734e068356c 100644 --- a/docs/de/docs/deployment/docker.md +++ b/docs/de/docs/deployment/docker.md @@ -4,7 +4,7 @@ Beim Deployment von FastAPI-Anwendungen besteht ein gängiger Ansatz darin, ein Die Verwendung von Linux-Containern bietet mehrere Vorteile, darunter **Sicherheit**, **Replizierbarkeit**, **Einfachheit** und andere. -/// tip | "Tipp" +/// tip | Tipp Sie haben es eilig und kennen sich bereits aus? Springen Sie zum [`Dockerfile` unten 👇](#ein-docker-image-fur-fastapi-erstellen). @@ -231,7 +231,7 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] Da das Programm unter `/code` gestartet wird und sich darin das Verzeichnis `./app` mit Ihrem Code befindet, kann **Uvicorn** `app` sehen und aus `app.main` **importieren**. -/// tip | "Tipp" +/// tip | Tipp Lernen Sie, was jede Zeile bewirkt, indem Sie auf die Zahlenblasen im Code klicken. 👆 @@ -305,7 +305,7 @@ $ docker build -t myimage . -/// tip | "Tipp" +/// tip | Tipp Beachten Sie das `.` am Ende, es entspricht `./` und teilt Docker mit, welches Verzeichnis zum Erstellen des Containerimages verwendet werden soll. @@ -409,7 +409,7 @@ Wenn wir uns nur auf das **Containerimage** für eine FastAPI-Anwendung (und sp Es könnte sich um einen anderen Container handeln, zum Beispiel mit Traefik, welcher **HTTPS** und **automatischen** Erwerb von **Zertifikaten** handhabt. -/// tip | "Tipp" +/// tip | Tipp Traefik verfügt über Integrationen mit Docker, Kubernetes und anderen, sodass Sie damit ganz einfach HTTPS für Ihre Container einrichten und konfigurieren können. @@ -441,7 +441,7 @@ Bei der Verwendung von Containern ist normalerweise eine Komponente vorhanden, * Da diese Komponente die **Last** an Requests aufnehmen und diese (hoffentlich) **ausgewogen** auf die Worker verteilen würde, wird sie üblicherweise auch **Load Balancer** – Lastverteiler – genannt. -/// tip | "Tipp" +/// tip | Tipp Die gleiche **TLS-Terminierungsproxy**-Komponente, die für HTTPS verwendet wird, wäre wahrscheinlich auch ein **Load Balancer**. @@ -544,7 +544,7 @@ Dieses Image wäre vor allem in den oben beschriebenen Situationen nützlich: [C * tiangolo/uvicorn-gunicorn-fastapi. -/// warning | "Achtung" +/// warning | Achtung Es besteht eine hohe Wahrscheinlichkeit, dass Sie dieses oder ein ähnliches Basisimage **nicht** benötigen und es besser wäre, wenn Sie das Image von Grund auf neu erstellen würden, wie [oben beschrieben in: Ein Docker-Image für FastAPI erstellen](#ein-docker-image-fur-fastapi-erstellen). @@ -556,7 +556,7 @@ Es verfügt über **vernünftige Standardeinstellungen**, aber Sie können trotz Es unterstützt auch die Ausführung von **Vorab-Schritten vor dem Start** mit einem Skript. -/// tip | "Tipp" +/// tip | Tipp Um alle Konfigurationen und Optionen anzuzeigen, gehen Sie zur Docker-Image-Seite: tiangolo/uvicorn-gunicorn-fastapi. @@ -687,7 +687,7 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 11. Führe den Befehl `uvicorn` aus und weise ihn an, das aus `app.main` importierte `app`-Objekt zu verwenden. -/// tip | "Tipp" +/// tip | Tipp Klicken Sie auf die Zahlenblasen, um zu sehen, was jede Zeile bewirkt. diff --git a/docs/de/docs/deployment/https.md b/docs/de/docs/deployment/https.md index b1f0aca77e903..63058299505e3 100644 --- a/docs/de/docs/deployment/https.md +++ b/docs/de/docs/deployment/https.md @@ -4,7 +4,7 @@ Es ist leicht anzunehmen, dass HTTPS etwas ist, was einfach nur „aktiviert“ Aber es ist viel komplexer als das. -/// tip | "Tipp" +/// tip | Tipp Wenn Sie es eilig haben oder es Ihnen egal ist, fahren Sie mit den nächsten Abschnitten fort, um Schritt-für-Schritt-Anleitungen für die Einrichtung der verschiedenen Technologien zu erhalten. @@ -71,7 +71,7 @@ In dem oder den DNS-Server(n) würden Sie einen Eintrag (einen „`A record`“) Sie würden dies wahrscheinlich nur einmal tun, beim ersten Mal, wenn Sie alles einrichten. -/// tip | "Tipp" +/// tip | Tipp Dieser Domainnamen-Aspekt liegt weit vor HTTPS, aber da alles von der Domain und der IP-Adresse abhängt, lohnt es sich, das hier zu erwähnen. @@ -121,7 +121,7 @@ Danach verfügen der Client und der Server über eine **verschlüsselte TCP-Verb Und genau das ist **HTTPS**, es ist einfach **HTTP** innerhalb einer **sicheren TLS-Verbindung**, statt einer puren (unverschlüsselten) TCP-Verbindung. -/// tip | "Tipp" +/// tip | Tipp Beachten Sie, dass die Verschlüsselung der Kommunikation auf der **TCP-Ebene** und nicht auf der HTTP-Ebene erfolgt. diff --git a/docs/de/docs/deployment/manually.md b/docs/de/docs/deployment/manually.md index 2b4ed3fad9696..fdb33f7fea8de 100644 --- a/docs/de/docs/deployment/manually.md +++ b/docs/de/docs/deployment/manually.md @@ -36,7 +36,7 @@ $ pip install "uvicorn[standard]" -/// tip | "Tipp" +/// tip | Tipp Durch das Hinzufügen von `standard` installiert und verwendet Uvicorn einige empfohlene zusätzliche Abhängigkeiten. @@ -96,7 +96,7 @@ Running on 0.0.0.0:8080 over http (CTRL + C to quit) //// -/// warning | "Achtung" +/// warning | Achtung Denken Sie daran, die Option `--reload` zu entfernen, wenn Sie diese verwendet haben. diff --git a/docs/de/docs/deployment/versions.md b/docs/de/docs/deployment/versions.md index 2d10ac4b6441a..5b8c69754fff8 100644 --- a/docs/de/docs/deployment/versions.md +++ b/docs/de/docs/deployment/versions.md @@ -42,7 +42,7 @@ Gemäß den Konventionen zur semantischen Versionierung könnte jede Version unt FastAPI folgt auch der Konvention, dass jede „PATCH“-Versionsänderung für Bugfixes und abwärtskompatible Änderungen gedacht ist. -/// tip | "Tipp" +/// tip | Tipp Der „PATCH“ ist die letzte Zahl, zum Beispiel ist in `0.2.3` die PATCH-Version `3`. @@ -56,7 +56,7 @@ fastapi>=0.45.0,<0.46.0 Nicht abwärtskompatible Änderungen und neue Funktionen werden in „MINOR“-Versionen hinzugefügt. -/// tip | "Tipp" +/// tip | Tipp „MINOR“ ist die Zahl in der Mitte, zum Beispiel ist in `0.2.3` die MINOR-Version `2`. diff --git a/docs/de/docs/help-fastapi.md b/docs/de/docs/help-fastapi.md index 2c84a5e5b920b..0b9c5231632ed 100644 --- a/docs/de/docs/help-fastapi.md +++ b/docs/de/docs/help-fastapi.md @@ -228,7 +228,7 @@ Wenn Sie mir dabei helfen können, **helfen Sie mir, FastAPI am Laufen zu erhalt Treten Sie dem 👥 Discord-Chatserver 👥 bei und treffen Sie sich mit anderen Mitgliedern der FastAPI-Community. -/// tip | "Tipp" +/// tip | Tipp Wenn Sie Fragen haben, stellen Sie sie bei GitHub Diskussionen, es besteht eine viel bessere Chance, dass Sie hier Hilfe von den [FastAPI-Experten](fastapi-people.md#experten){.internal-link target=_blank} erhalten. diff --git a/docs/de/docs/how-to/conditional-openapi.md b/docs/de/docs/how-to/conditional-openapi.md index a0a4983bb4f11..50ae11f905eb1 100644 --- a/docs/de/docs/how-to/conditional-openapi.md +++ b/docs/de/docs/how-to/conditional-openapi.md @@ -29,9 +29,7 @@ Sie können problemlos dieselben Pydantic-Einstellungen verwenden, um Ihre gener Zum Beispiel: -```Python hl_lines="6 11" -{!../../docs_src/conditional_openapi/tutorial001.py!} -``` +{* ../../docs_src/conditional_openapi/tutorial001.py hl[6,11] *} Hier deklarieren wir die Einstellung `openapi_url` mit dem gleichen Defaultwert `"/openapi.json"`. diff --git a/docs/de/docs/how-to/configure-swagger-ui.md b/docs/de/docs/how-to/configure-swagger-ui.md index 31b9cd290758a..1ee72d20545bf 100644 --- a/docs/de/docs/how-to/configure-swagger-ui.md +++ b/docs/de/docs/how-to/configure-swagger-ui.md @@ -18,9 +18,7 @@ Ohne Änderung der Einstellungen ist die Syntaxhervorhebung standardmäßig akti Sie können sie jedoch deaktivieren, indem Sie `syntaxHighlight` auf `False` setzen: -```Python hl_lines="3" -{!../../docs_src/configure_swagger_ui/tutorial001.py!} -``` +{* ../../docs_src/configure_swagger_ui/tutorial001.py hl[3] *} ... und dann zeigt die Swagger-Oberfläche die Syntaxhervorhebung nicht mehr an: @@ -30,9 +28,7 @@ Sie können sie jedoch deaktivieren, indem Sie `syntaxHighlight` auf `False` set Auf die gleiche Weise könnten Sie das Theme der Syntaxhervorhebung mit dem Schlüssel `syntaxHighlight.theme` festlegen (beachten Sie, dass er einen Punkt in der Mitte hat): -```Python hl_lines="3" -{!../../docs_src/configure_swagger_ui/tutorial002.py!} -``` +{* ../../docs_src/configure_swagger_ui/tutorial002.py hl[3] *} Obige Konfiguration würde das Theme für die Farbe der Syntaxhervorhebung ändern: @@ -44,17 +40,13 @@ FastAPI enthält einige Defaultkonfigurationsparameter, die für die meisten Anw Es umfasst die folgenden Defaultkonfigurationen: -```Python -{!../../fastapi/openapi/docs.py[ln:7-23]!} -``` +{* ../../fastapi/openapi/docs.py ln[7:23] *} Sie können jede davon überschreiben, indem Sie im Argument `swagger_ui_parameters` einen anderen Wert festlegen. Um beispielsweise `deepLinking` zu deaktivieren, könnten Sie folgende Einstellungen an `swagger_ui_parameters` übergeben: -```Python hl_lines="3" -{!../../docs_src/configure_swagger_ui/tutorial003.py!} -``` +{* ../../docs_src/configure_swagger_ui/tutorial003.py hl[3] *} ## Andere Parameter der Swagger-Oberfläche diff --git a/docs/de/docs/how-to/custom-docs-ui-assets.md b/docs/de/docs/how-to/custom-docs-ui-assets.md index e5fd20a10f471..ab8cd9f6b8cde 100644 --- a/docs/de/docs/how-to/custom-docs-ui-assets.md +++ b/docs/de/docs/how-to/custom-docs-ui-assets.md @@ -18,9 +18,7 @@ Der erste Schritt besteht darin, die automatischen Dokumentationen zu deaktivier Um diese zu deaktivieren, setzen Sie deren URLs beim Erstellen Ihrer `FastAPI`-App auf `None`: -```Python hl_lines="8" -{!../../docs_src/custom_docs_ui/tutorial001.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial001.py hl[8] *} ### Die benutzerdefinierten Dokumentationen hinzufügen @@ -36,11 +34,9 @@ Sie können die internen Funktionen von FastAPI wiederverwenden, um die HTML-Sei Und genau so für ReDoc ... -```Python hl_lines="2-6 11-19 22-24 27-33" -{!../../docs_src/custom_docs_ui/tutorial001.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial001.py hl[2:6,11:19,22:24,27:33] *} -/// tip | "Tipp" +/// tip | Tipp Die *Pfadoperation* für `swagger_ui_redirect` ist ein Hilfsmittel bei der Verwendung von OAuth2. @@ -54,9 +50,7 @@ Swagger UI erledigt das hinter den Kulissen für Sie, benötigt aber diesen „U Um nun testen zu können, ob alles funktioniert, erstellen Sie eine *Pfadoperation*: -```Python hl_lines="36-38" -{!../../docs_src/custom_docs_ui/tutorial001.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial001.py hl[36:38] *} ### Es ausprobieren @@ -124,9 +118,7 @@ Danach könnte Ihre Dateistruktur wie folgt aussehen: * Importieren Sie `StaticFiles`. * „Mounten“ Sie eine `StaticFiles()`-Instanz in einem bestimmten Pfad. -```Python hl_lines="7 11" -{!../../docs_src/custom_docs_ui/tutorial002.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[7,11] *} ### Die statischen Dateien testen @@ -158,9 +150,7 @@ Wie bei der Verwendung eines benutzerdefinierten CDN besteht der erste Schritt d Um diese zu deaktivieren, setzen Sie deren URLs beim Erstellen Ihrer `FastAPI`-App auf `None`: -```Python hl_lines="9" -{!../../docs_src/custom_docs_ui/tutorial002.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[9] *} ### Die benutzerdefinierten Dokumentationen, mit statischen Dateien, hinzufügen @@ -176,11 +166,9 @@ Auch hier können Sie die internen Funktionen von FastAPI wiederverwenden, um di Und genau so für ReDoc ... -```Python hl_lines="2-6 14-22 25-27 30-36" -{!../../docs_src/custom_docs_ui/tutorial002.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[2:6,14:22,25:27,30:36] *} -/// tip | "Tipp" +/// tip | Tipp Die *Pfadoperation* für `swagger_ui_redirect` ist ein Hilfsmittel bei der Verwendung von OAuth2. @@ -194,9 +182,7 @@ Swagger UI erledigt das hinter den Kulissen für Sie, benötigt aber diesen „U Um nun testen zu können, ob alles funktioniert, erstellen Sie eine *Pfadoperation*: -```Python hl_lines="39-41" -{!../../docs_src/custom_docs_ui/tutorial002.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[39:41] *} ### Benutzeroberfläche, mit statischen Dateien, testen diff --git a/docs/de/docs/how-to/custom-request-and-route.md b/docs/de/docs/how-to/custom-request-and-route.md index f81fa1da3d5f7..3e6f709b6f63d 100644 --- a/docs/de/docs/how-to/custom-request-and-route.md +++ b/docs/de/docs/how-to/custom-request-and-route.md @@ -6,7 +6,7 @@ Das kann insbesondere eine gute Alternative zur Logik in einer Middleware sein. Wenn Sie beispielsweise den Requestbody lesen oder manipulieren möchten, bevor er von Ihrer Anwendung verarbeitet wird. -/// danger | "Gefahr" +/// danger | Gefahr Dies ist eine „fortgeschrittene“ Funktion. @@ -30,7 +30,7 @@ Und eine `APIRoute`-Unterklasse zur Verwendung dieser benutzerdefinierten Reques ### Eine benutzerdefinierte `GzipRequest`-Klasse erstellen -/// tip | "Tipp" +/// tip | Tipp Dies ist nur ein einfaches Beispiel, um zu demonstrieren, wie es funktioniert. Wenn Sie Gzip-Unterstützung benötigen, können Sie die bereitgestellte [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware){.internal-link target=_blank} verwenden. @@ -42,9 +42,7 @@ Wenn der Header kein `gzip` enthält, wird nicht versucht, den Body zu dekomprim Auf diese Weise kann dieselbe Routenklasse gzip-komprimierte oder unkomprimierte Requests verarbeiten. -```Python hl_lines="8-15" -{!../../docs_src/custom_request_and_route/tutorial001.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial001.py hl[8:15] *} ### Eine benutzerdefinierte `GzipRoute`-Klasse erstellen @@ -56,11 +54,9 @@ Diese Methode gibt eine Funktion zurück. Und diese Funktion empfängt einen Req Hier verwenden wir sie, um aus dem ursprünglichen Request einen `GzipRequest` zu erstellen. -```Python hl_lines="18-26" -{!../../docs_src/custom_request_and_route/tutorial001.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial001.py hl[18:26] *} -/// note | "Technische Details" +/// note | Technische Details Ein `Request` hat ein `request.scope`-Attribut, welches einfach ein Python-`dict` ist, welches die mit dem Request verbundenen Metadaten enthält. @@ -84,7 +80,7 @@ Aufgrund unserer Änderungen in `GzipRequest.body` wird der Requestbody jedoch b ## Zugriff auf den Requestbody in einem Exceptionhandler -/// tip | "Tipp" +/// tip | Tipp Um dasselbe Problem zu lösen, ist es wahrscheinlich viel einfacher, den `body` in einem benutzerdefinierten Handler für `RequestValidationError` zu verwenden ([Fehlerbehandlung](../tutorial/handling-errors.md#den-requestvalidationerror-body-verwenden){.internal-link target=_blank}). @@ -96,26 +92,18 @@ Wir können denselben Ansatz auch verwenden, um in einem Exceptionhandler auf de Alles, was wir tun müssen, ist, den Request innerhalb eines `try`/`except`-Blocks zu handhaben: -```Python hl_lines="13 15" -{!../../docs_src/custom_request_and_route/tutorial002.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial002.py hl[13,15] *} Wenn eine Exception auftritt, befindet sich die `Request`-Instanz weiterhin im Gültigkeitsbereich, sodass wir den Requestbody lesen und bei der Fehlerbehandlung verwenden können: -```Python hl_lines="16-18" -{!../../docs_src/custom_request_and_route/tutorial002.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial002.py hl[16:18] *} ## Benutzerdefinierte `APIRoute`-Klasse in einem Router Sie können auch den Parameter `route_class` eines `APIRouter` festlegen: -```Python hl_lines="26" -{!../../docs_src/custom_request_and_route/tutorial003.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial003.py hl[26] *} In diesem Beispiel verwenden die *Pfadoperationen* unter dem `router` die benutzerdefinierte `TimedRoute`-Klasse und haben in der Response einen zusätzlichen `X-Response-Time`-Header mit der Zeit, die zum Generieren der Response benötigt wurde: -```Python hl_lines="13-20" -{!../../docs_src/custom_request_and_route/tutorial003.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial003.py hl[13:20] *} diff --git a/docs/de/docs/how-to/extending-openapi.md b/docs/de/docs/how-to/extending-openapi.md index c895fb860d54b..3b14593641907 100644 --- a/docs/de/docs/how-to/extending-openapi.md +++ b/docs/de/docs/how-to/extending-openapi.md @@ -43,25 +43,19 @@ Fügen wir beispielsweise Strawberry-Dokumentation. @@ -49,7 +47,7 @@ Frühere Versionen von Starlette enthielten eine `GraphQLApp`-Klasse zur Integra Das wurde von Starlette deprecated, aber wenn Sie Code haben, der das verwendet, können Sie einfach zu starlette-graphene3 **migrieren**, welches denselben Anwendungsfall abdeckt und über eine **fast identische Schnittstelle** verfügt. -/// tip | "Tipp" +/// tip | Tipp Wenn Sie GraphQL benötigen, würde ich Ihnen trotzdem empfehlen, sich Strawberry anzuschauen, da es auf Typannotationen basiert, statt auf benutzerdefinierten Klassen und Typen. diff --git a/docs/de/docs/how-to/index.md b/docs/de/docs/how-to/index.md index 75779a01cef26..84a178fc8b438 100644 --- a/docs/de/docs/how-to/index.md +++ b/docs/de/docs/how-to/index.md @@ -6,7 +6,7 @@ Die meisten dieser Ideen sind mehr oder weniger **unabhängig**, und in den meis Wenn etwas für Ihr Projekt interessant und nützlich erscheint, lesen Sie es, andernfalls überspringen Sie es einfach. -/// tip | "Tipp" +/// tip | Tipp Wenn Sie strukturiert **FastAPI lernen** möchten (empfohlen), lesen Sie stattdessen Kapitel für Kapitel das [Tutorial – Benutzerhandbuch](../tutorial/index.md){.internal-link target=_blank}. diff --git a/docs/de/docs/how-to/separate-openapi-schemas.md b/docs/de/docs/how-to/separate-openapi-schemas.md index 974341dd2079b..4f6911e798104 100644 --- a/docs/de/docs/how-to/separate-openapi-schemas.md +++ b/docs/de/docs/how-to/separate-openapi-schemas.md @@ -10,123 +10,13 @@ Sehen wir uns an, wie das funktioniert und wie Sie es bei Bedarf ändern können Nehmen wir an, Sie haben ein Pydantic-Modell mit Defaultwerten wie dieses: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-7]!} - -# Code unterhalb weggelassen 👇 -``` - -
-👀 Vollständige Dateivorschau - -```Python -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} -``` - -
- -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-9]!} - -# Code unterhalb weggelassen 👇 -``` - -
-👀 Vollständige Dateivorschau - -```Python -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} -``` - -
- -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-9]!} - -# Code unterhalb weggelassen 👇 -``` - -
-👀 Vollständige Dateivorschau - -```Python -{!> ../../docs_src/separate_openapi_schemas/tutorial001.py!} -``` - -
- -//// +{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:7] hl[7] *} ### Modell für Eingabe Wenn Sie dieses Modell wie hier als Eingabe verwenden: -//// tab | Python 3.10+ - -```Python hl_lines="14" -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-15]!} - -# Code unterhalb weggelassen 👇 -``` - -
-👀 Vollständige Dateivorschau - -```Python -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} -``` - -
- -//// - -//// tab | Python 3.9+ - -```Python hl_lines="16" -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-17]!} - -# Code unterhalb weggelassen 👇 -``` - -
-👀 Vollständige Dateivorschau - -```Python -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} -``` - -
- -//// - -//// tab | Python 3.8+ - -```Python hl_lines="16" -{!> ../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-17]!} - -# Code unterhalb weggelassen 👇 -``` - -
-👀 Vollständige Dateivorschau - -```Python -{!> ../../docs_src/separate_openapi_schemas/tutorial001.py!} -``` - -
- -//// +{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:15] hl[14] *} ... dann ist das Feld `description` **nicht erforderlich**. Weil es den Defaultwert `None` hat. @@ -142,29 +32,7 @@ Sie können überprüfen, dass das Feld `description` in der Dokumentation kein Wenn Sie jedoch dasselbe Modell als Ausgabe verwenden, wie hier: -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="21" -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="21" -{!> ../../docs_src/separate_openapi_schemas/tutorial001.py!} -``` - -//// +{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py hl[19] *} ... dann, weil `description` einen Defaultwert hat, wird es, wenn Sie für dieses Feld **nichts zurückgeben**, immer noch diesen **Defaultwert** haben. @@ -223,29 +91,7 @@ Unterstützung für `separate_input_output_schemas` wurde in FastAPI `0.102.0` h /// -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/separate_openapi_schemas/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="12" -{!> ../../docs_src/separate_openapi_schemas/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="12" -{!> ../../docs_src/separate_openapi_schemas/tutorial002.py!} -``` - -//// +{* ../../docs_src/separate_openapi_schemas/tutorial002_py310.py hl[10] *} ### Gleiches Schema für Eingabe- und Ausgabemodelle in der Dokumentation diff --git a/docs/de/docs/python-types.md b/docs/de/docs/python-types.md index a43bf5ffe946b..81d43bc5bcc99 100644 --- a/docs/de/docs/python-types.md +++ b/docs/de/docs/python-types.md @@ -12,7 +12,7 @@ Dies ist lediglich eine **schnelle Anleitung / Auffrischung** über Pythons Typh Aber selbst wenn Sie **FastAPI** nie verwenden, wird es für Sie nützlich sein, ein wenig darüber zu lernen. -/// note | "Hinweis" +/// note | Hinweis Wenn Sie ein Python-Experte sind und bereits alles über Typhinweise wissen, überspringen Sie dieses Kapitel und fahren Sie mit dem nächsten fort. @@ -22,9 +22,7 @@ Wenn Sie ein Python-Experte sind und bereits alles über Typhinweise wissen, üb Fangen wir mit einem einfachen Beispiel an: -```Python -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py *} Dieses Programm gibt aus: @@ -38,9 +36,7 @@ Die Funktion macht Folgendes: * Schreibt den ersten Buchstaben eines jeden Wortes groß, mithilfe von `title()`. * Verkettet sie mit einem Leerzeichen in der Mitte. -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py hl[2] *} ### Bearbeiten Sie es @@ -82,9 +78,7 @@ Das war's. Das sind die „Typhinweise“: -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial002.py!} -``` +{* ../../docs_src/python_types/tutorial002.py hl[1] *} Das ist nicht das gleiche wie das Deklarieren von Defaultwerten, wie es hier der Fall ist: @@ -112,9 +106,7 @@ Hier können Sie durch die Optionen blättern, bis Sie diejenige finden, bei der Sehen Sie sich diese Funktion an, sie hat bereits Typhinweise: -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial003.py!} -``` +{* ../../docs_src/python_types/tutorial003.py hl[1] *} Da der Editor die Typen der Variablen kennt, erhalten Sie nicht nur Code-Vervollständigung, sondern auch eine Fehlerprüfung: @@ -122,9 +114,7 @@ Da der Editor die Typen der Variablen kennt, erhalten Sie nicht nur Code-Vervoll Jetzt, da Sie wissen, dass Sie das reparieren müssen, konvertieren Sie `age` mittels `str(age)` in einen String: -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial004.py!} -``` +{* ../../docs_src/python_types/tutorial004.py hl[2] *} ## Deklarieren von Typen @@ -143,9 +133,7 @@ Zum Beispiel diese: * `bool` * `bytes` -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial005.py!} -``` +{* ../../docs_src/python_types/tutorial005.py hl[1] *} ### Generische Typen mit Typ-Parametern @@ -207,7 +195,7 @@ Da die Liste ein Typ ist, welcher innere Typen enthält, werden diese von eckige //// -/// tip | "Tipp" +/// tip | Tipp Die inneren Typen in den eckigen Klammern werden als „Typ-Parameter“ bezeichnet. @@ -217,7 +205,7 @@ In diesem Fall ist `str` der Typ-Parameter, der an `List` übergeben wird (oder Das bedeutet: Die Variable `items` ist eine Liste – `list` – und jedes der Elemente in dieser Liste ist ein String – `str`. -/// tip | "Tipp" +/// tip | Tipp Wenn Sie Python 3.9 oder höher verwenden, müssen Sie `List` nicht von `typing` importieren, Sie können stattdessen den regulären `list`-Typ verwenden. @@ -320,9 +308,7 @@ Sie können deklarieren, dass ein Wert ein `str`, aber vielleicht auch `None` se In Python 3.6 und darüber (inklusive Python 3.10) können Sie das deklarieren, indem Sie `Optional` vom `typing` Modul importieren und verwenden. -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial009.py!} -``` +{* ../../docs_src/python_types/tutorial009.py hl[1,4] *} Wenn Sie `Optional[str]` anstelle von nur `str` verwenden, wird Ihr Editor Ihnen dabei helfen, Fehler zu erkennen, bei denen Sie annehmen könnten, dass ein Wert immer eine String (`str`) ist, obwohl er auch `None` sein könnte. @@ -369,9 +355,7 @@ Es geht nur um Wörter und Namen. Aber diese Worte können beeinflussen, wie Sie Nehmen wir zum Beispiel diese Funktion: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial009c.py!} -``` +{* ../../docs_src/python_types/tutorial009c.py hl[1,4] *} Der Parameter `name` ist definiert als `Optional[str]`, aber er ist **nicht optional**, Sie können die Funktion nicht ohne diesen Parameter aufrufen: @@ -387,9 +371,7 @@ say_hi(name=None) # Das funktioniert, None is gültig 🎉 Die gute Nachricht ist, dass Sie sich darüber keine Sorgen mehr machen müssen, wenn Sie Python 3.10 verwenden, da Sie einfach `|` verwenden können, um Vereinigungen von Typen zu definieren: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial009c_py310.py!} -``` +{* ../../docs_src/python_types/tutorial009c_py310.py hl[1,4] *} Und dann müssen Sie sich nicht mehr um Namen wie `Optional` und `Union` kümmern. 😎 @@ -451,15 +433,11 @@ Sie können auch eine Klasse als Typ einer Variablen deklarieren. Nehmen wir an, Sie haben eine Klasse `Person`, mit einem Namen: -```Python hl_lines="1-3" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[1:3] *} Dann können Sie eine Variable vom Typ `Person` deklarieren: -```Python hl_lines="6" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[6] *} Und wiederum bekommen Sie die volle Editor-Unterstützung: @@ -517,7 +495,7 @@ Um mehr über Required fields mehr erfahren. @@ -559,7 +537,7 @@ Im Moment müssen Sie nur wissen, dass `Annotated` existiert, und dass es Standa Später werden Sie sehen, wie **mächtig** es sein kann. -/// tip | "Tipp" +/// tip | Tipp Der Umstand, dass es **Standard-Python** ist, bedeutet, dass Sie immer noch die **bestmögliche Entwickler-Erfahrung** in ihrem Editor haben, sowie mit den Tools, die Sie nutzen, um ihren Code zu analysieren, zu refaktorisieren, usw. ✨ diff --git a/docs/de/docs/tutorial/background-tasks.md b/docs/de/docs/tutorial/background-tasks.md index cd857f5e7c41f..05779e12c475c 100644 --- a/docs/de/docs/tutorial/background-tasks.md +++ b/docs/de/docs/tutorial/background-tasks.md @@ -15,9 +15,7 @@ Hierzu zählen beispielsweise: Importieren Sie zunächst `BackgroundTasks` und definieren Sie einen Parameter in Ihrer *Pfadoperation-Funktion* mit der Typdeklaration `BackgroundTasks`: -```Python hl_lines="1 13" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *} **FastAPI** erstellt für Sie das Objekt vom Typ `BackgroundTasks` und übergibt es als diesen Parameter. @@ -33,17 +31,13 @@ In diesem Fall schreibt die Taskfunktion in eine Datei (den Versand einer E-Mail Und da der Schreibvorgang nicht `async` und `await` verwendet, definieren wir die Funktion mit normalem `def`: -```Python hl_lines="6-9" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *} ## Den Hintergrundtask hinzufügen Übergeben Sie innerhalb Ihrer *Pfadoperation-Funktion* Ihre Taskfunktion mit der Methode `.add_task()` an das *Hintergrundtasks*-Objekt: -```Python hl_lines="14" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[14] *} `.add_task()` erhält als Argumente: @@ -57,57 +51,7 @@ Die Verwendung von `BackgroundTasks` funktioniert auch mit dem ../../docs_src/background_tasks/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="13 15 22 25" -{!> ../../docs_src/background_tasks/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="14 16 23 26" -{!> ../../docs_src/background_tasks/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="11 13 20 23" -{!> ../../docs_src/background_tasks/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="13 15 22 25" -{!> ../../docs_src/background_tasks/tutorial002.py!} -``` - -//// +{* ../../docs_src/background_tasks/tutorial002_an_py310.py hl[13,15,22,25] *} In obigem Beispiel werden die Nachrichten, *nachdem* die Response gesendet wurde, in die Datei `log.txt` geschrieben. @@ -133,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 000fa1f437d97..59e91bdcce903 100644 --- a/docs/de/docs/tutorial/bigger-applications.md +++ b/docs/de/docs/tutorial/bigger-applications.md @@ -29,7 +29,7 @@ Nehmen wir an, Sie haben eine Dateistruktur wie diese: │   └── admin.py ``` -/// tip | "Tipp" +/// tip | Tipp Es gibt mehrere `__init__.py`-Dateien: eine in jedem Verzeichnis oder Unterverzeichnis. @@ -105,7 +105,7 @@ Alle die gleichen Optionen werden unterstützt. Alle die gleichen `parameters`, `responses`, `dependencies`, `tags`, usw. -/// tip | "Tipp" +/// tip | Tipp In diesem Beispiel heißt die Variable `router`, aber Sie können ihr einen beliebigen Namen geben. @@ -139,7 +139,7 @@ Wir werden nun eine einfache Abhängigkeit verwenden, um einen benutzerdefiniert //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -151,7 +151,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// -/// tip | "Tipp" +/// tip | Tipp Um dieses Beispiel zu vereinfachen, verwenden wir einen erfundenen Header. @@ -201,7 +201,7 @@ 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" +/// 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. @@ -222,7 +222,7 @@ 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" +/// 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. @@ -248,7 +248,7 @@ Daher verwenden wir einen relativen Import mit `..` für die Abhängigkeiten: #### Wie relative Importe funktionieren -/// tip | "Tipp" +/// tip | Tipp Wenn Sie genau wissen, wie Importe funktionieren, fahren Sie mit dem nächsten Abschnitt unten fort. @@ -319,7 +319,7 @@ Aber wir können immer noch _mehr_ `tags` hinzufügen, die auf eine bestimmte *P {!../../docs_src/bigger_applications/app/routers/items.py!} ``` -/// tip | "Tipp" +/// tip | Tipp Diese letzte Pfadoperation wird eine Kombination von Tags haben: `["items", "custom"]`. @@ -441,7 +441,7 @@ Mit `app.include_router()` können wir jeden `APIRouter` zur Hauptanwendung `Fas Es wird alle Routen von diesem Router als Teil von dieser inkludieren. -/// note | "Technische Details" +/// note | Technische Details Tatsächlich wird intern eine *Pfadoperation* für jede *Pfadoperation* erstellt, die im `APIRouter` deklariert wurde. @@ -504,7 +504,7 @@ Hier machen wir es ... nur um zu zeigen, dass wir es können 🤷: und es wird korrekt funktionieren, zusammen mit allen anderen *Pfadoperationen*, die mit `app.include_router()` hinzugefügt wurden. -/// info | "Sehr technische Details" +/// info | Sehr technische Details **Hinweis**: Dies ist ein sehr technisches Detail, das Sie wahrscheinlich **einfach überspringen** können. diff --git a/docs/de/docs/tutorial/body-fields.md b/docs/de/docs/tutorial/body-fields.md index d22524c678635..9fddfb1f042c6 100644 --- a/docs/de/docs/tutorial/body-fields.md +++ b/docs/de/docs/tutorial/body-fields.md @@ -6,59 +6,9 @@ So wie Sie zusätzliche Validation und Metadaten in Parametern der **Pfadoperati Importieren Sie es zuerst: -//// tab | Python 3.10+ +{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[4] *} -```Python hl_lines="4" -{!> ../../docs_src/body_fields/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="4" -{!> ../../docs_src/body_fields/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4" -{!> ../../docs_src/body_fields/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="2" -{!> ../../docs_src/body_fields/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="4" -{!> ../../docs_src/body_fields/tutorial001.py!} -``` - -//// - -/// warning | "Achtung" +/// warning | Achtung Beachten Sie, dass `Field` direkt von `pydantic` importiert wird, nicht von `fastapi`, wie die anderen (`Query`, `Path`, `Body`, usw.) @@ -68,61 +18,11 @@ Beachten Sie, dass `Field` direkt von `pydantic` importiert wird, nicht von `fas Dann können Sie `Field` mit Modellattributen deklarieren: -//// tab | Python 3.10+ - -```Python hl_lines="11-14" -{!> ../../docs_src/body_fields/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="11-14" -{!> ../../docs_src/body_fields/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="12-15" -{!> ../../docs_src/body_fields/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="9-12" -{!> ../../docs_src/body_fields/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="11-14" -{!> ../../docs_src/body_fields/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[11:14] *} `Field` funktioniert genauso wie `Query`, `Path` und `Body`, es hat die gleichen Parameter, usw. -/// note | "Technische Details" +/// 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. @@ -134,7 +34,7 @@ Denken Sie daran, dass `Query`, `Path` und andere von `fastapi` tatsächlich Fun /// -/// tip | "Tipp" +/// 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`. @@ -146,7 +46,7 @@ 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" +/// 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. diff --git a/docs/de/docs/tutorial/body-multiple-params.md b/docs/de/docs/tutorial/body-multiple-params.md index 26ae73ebcda8d..8a9978d34bd27 100644 --- a/docs/de/docs/tutorial/body-multiple-params.md +++ b/docs/de/docs/tutorial/body-multiple-params.md @@ -8,59 +8,9 @@ Zuerst einmal, Sie können `Path`-, `Query`- und Requestbody-Parameter-Deklarati Und Sie können auch Body-Parameter als optional kennzeichnen, indem Sie den Defaultwert auf `None` setzen: -//// tab | Python 3.10+ +{* ../../docs_src/body_multiple_params/tutorial001_an_py310.py hl[18:20] *} -```Python hl_lines="18-20" -{!> ../../docs_src/body_multiple_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="18-20" -{!> ../../docs_src/body_multiple_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="19-21" -{!> ../../docs_src/body_multiple_params/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="17-19" -{!> ../../docs_src/body_multiple_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="19-21" -{!> ../../docs_src/body_multiple_params/tutorial001.py!} -``` - -//// - -/// note | "Hinweis" +/// note | Hinweis Beachten Sie, dass in diesem Fall das `item`, welches vom Body genommen wird, optional ist. Da es `None` als Defaultwert hat. @@ -81,21 +31,7 @@ Im vorherigen Beispiel erwartete die *Pfadoperation* einen JSON-Body mit den Att Aber Sie können auch mehrere Body-Parameter deklarieren, z. B. `item` und `user`: -//// tab | Python 3.10+ - -```Python hl_lines="20" -{!> ../../docs_src/body_multiple_params/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="22" -{!> ../../docs_src/body_multiple_params/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial002_py310.py hl[20] *} In diesem Fall wird **FastAPI** bemerken, dass es mehr als einen Body-Parameter in der Funktion gibt (zwei Parameter, die Pydantic-Modelle sind). @@ -116,7 +52,7 @@ Es wird deshalb die Parameternamen als Schlüssel (Feldnamen) im Body verwenden, } ``` -/// note | "Hinweis" +/// note | Hinweis Beachten Sie, dass, obwohl `item` wie zuvor deklariert wurde, es nun unter einem Schlüssel `item` im Body erwartet wird. @@ -136,57 +72,7 @@ Wenn Sie diesen Parameter einfach so hinzufügen, wird **FastAPI** annehmen, das Aber Sie können **FastAPI** instruieren, ihn als weiteren Body-Schlüssel zu erkennen, indem Sie `Body` verwenden: -//// tab | Python 3.10+ - -```Python hl_lines="23" -{!> ../../docs_src/body_multiple_params/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="23" -{!> ../../docs_src/body_multiple_params/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24" -{!> ../../docs_src/body_multiple_params/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="20" -{!> ../../docs_src/body_multiple_params/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="22" -{!> ../../docs_src/body_multiple_params/tutorial003.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial003_an_py310.py hl[23] *} In diesem Fall erwartet **FastAPI** einen Body wie: @@ -226,57 +112,7 @@ q: str | None = None Zum Beispiel: -//// tab | Python 3.10+ - -```Python hl_lines="27" -{!> ../../docs_src/body_multiple_params/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="27" -{!> ../../docs_src/body_multiple_params/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="28" -{!> ../../docs_src/body_multiple_params/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="25" -{!> ../../docs_src/body_multiple_params/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="27" -{!> ../../docs_src/body_multiple_params/tutorial004.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[27] *} /// info @@ -298,57 +134,7 @@ item: Item = Body(embed=True) so wie in: -//// tab | Python 3.10+ - -```Python hl_lines="17" -{!> ../../docs_src/body_multiple_params/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="17" -{!> ../../docs_src/body_multiple_params/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18" -{!> ../../docs_src/body_multiple_params/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="15" -{!> ../../docs_src/body_multiple_params/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="17" -{!> ../../docs_src/body_multiple_params/tutorial005.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial005_an_py310.py hl[17] *} In diesem Fall erwartet **FastAPI** einen Body wie: diff --git a/docs/de/docs/tutorial/body-nested-models.md b/docs/de/docs/tutorial/body-nested-models.md index 13153aa68145f..6287490c6b09f 100644 --- a/docs/de/docs/tutorial/body-nested-models.md +++ b/docs/de/docs/tutorial/body-nested-models.md @@ -6,21 +6,7 @@ Mit **FastAPI** können Sie (dank Pydantic) beliebig tief verschachtelte Modelle Sie können ein Attribut als Kindtyp definieren, zum Beispiel eine Python-`list`e. -//// tab | Python 3.10+ - -```Python hl_lines="12" -{!> ../../docs_src/body_nested_models/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial001_py310.py hl[12] *} Das bewirkt, dass `tags` eine Liste ist, wenngleich es nichts über den Typ der Elemente der Liste aussagt. @@ -34,9 +20,7 @@ In Python 3.9 oder darüber können Sie einfach `list` verwenden, um diese Typan In Python-Versionen vor 3.9 (3.6 und darüber), müssen Sie zuerst `List` von Pythons Standardmodul `typing` importieren. -```Python hl_lines="1" -{!> ../../docs_src/body_nested_models/tutorial002.py!} -``` +{* ../../docs_src/body_nested_models/tutorial002.py hl[1] *} ### Eine `list`e mit einem Typ-Parameter deklarieren @@ -65,29 +49,7 @@ Verwenden Sie dieselbe Standardsyntax für Modellattribute mit inneren Typen. In unserem Beispiel können wir also bewirken, dass `tags` spezifisch eine „Liste von Strings“ ist: -//// tab | Python 3.10+ - -```Python hl_lines="12" -{!> ../../docs_src/body_nested_models/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial002_py310.py hl[12] *} ## Set-Typen @@ -97,29 +59,7 @@ Python hat einen Datentyp speziell für Mengen eindeutiger Dinge: das ../../docs_src/body_nested_models/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 14" -{!> ../../docs_src/body_nested_models/tutorial003.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial003_py310.py hl[12] *} Jetzt, selbst wenn Sie einen Request mit duplizierten Daten erhalten, werden diese zu einem Set eindeutiger Dinge konvertiert. @@ -141,57 +81,13 @@ Alles das beliebig tief verschachtelt. Wir können zum Beispiel ein `Image`-Modell definieren. -//// tab | Python 3.10+ - -```Python hl_lines="7-9" -{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9-11" -{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9-11" -{!> ../../docs_src/body_nested_models/tutorial004.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[7:9] *} ### Das Kindmodell als Typ verwenden Und dann können wir es als Typ eines Attributes verwenden. -//// tab | Python 3.10+ - -```Python hl_lines="18" -{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial004.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[18] *} Das würde bedeuten, dass **FastAPI** einen Body erwartet wie: @@ -224,29 +120,7 @@ Um alle Optionen kennenzulernen, die Sie haben, schauen Sie sich ../../docs_src/body_nested_models/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="4 10" -{!> ../../docs_src/body_nested_models/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4 10" -{!> ../../docs_src/body_nested_models/tutorial005.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial005_py310.py hl[2,8] *} Es wird getestet, ob der String eine gültige URL ist, und als solche wird er in JSON Schema / OpenAPI dokumentiert. @@ -254,29 +128,7 @@ Es wird getestet, ob der String eine gültige URL ist, und als solche wird er in Sie können Pydantic-Modelle auch als Typen innerhalb von `list`, `set`, usw. verwenden: -//// tab | Python 3.10+ - -```Python hl_lines="18" -{!> ../../docs_src/body_nested_models/tutorial006_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial006_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial006.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial006_py310.py hl[18] *} Das wird einen JSON-Body erwarten (konvertieren, validieren, dokumentieren), wie: @@ -314,29 +166,7 @@ Beachten Sie, dass der `images`-Schlüssel jetzt eine Liste von Bild-Objekten ha Sie können beliebig tief verschachtelte Modelle definieren: -//// tab | Python 3.10+ - -```Python hl_lines="7 12 18 21 25" -{!> ../../docs_src/body_nested_models/tutorial007_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9 14 20 23 27" -{!> ../../docs_src/body_nested_models/tutorial007_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 14 20 23 27" -{!> ../../docs_src/body_nested_models/tutorial007.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial007_py310.py hl[7,12,18,21,25] *} /// info @@ -360,21 +190,7 @@ images: list[Image] so wie in: -//// tab | Python 3.9+ - -```Python hl_lines="13" -{!> ../../docs_src/body_nested_models/tutorial008_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="15" -{!> ../../docs_src/body_nested_models/tutorial008.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial008_py39.py hl[13] *} ## Editor-Unterstützung überall @@ -404,23 +220,9 @@ Das schauen wir uns mal an. Im folgenden Beispiel akzeptieren Sie irgendein `dict`, solange es `int`-Schlüssel und `float`-Werte hat. -//// tab | Python 3.9+ - -```Python hl_lines="7" -{!> ../../docs_src/body_nested_models/tutorial009_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/body_nested_models/tutorial009.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial009_py39.py hl[7] *} -/// tip | "Tipp" +/// tip | Tipp Bedenken Sie, dass JSON nur `str` als Schlüssel unterstützt. diff --git a/docs/de/docs/tutorial/body-updates.md b/docs/de/docs/tutorial/body-updates.md index ed5c1890fe58e..574016c587f9c 100644 --- a/docs/de/docs/tutorial/body-updates.md +++ b/docs/de/docs/tutorial/body-updates.md @@ -6,29 +6,7 @@ Um einen Artikel zu aktualisieren, können Sie die ../../docs_src/body_updates/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="30-35" -{!> ../../docs_src/body_updates/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="30-35" -{!> ../../docs_src/body_updates/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial001_py310.py hl[28:33] *} `PUT` wird verwendet, um Daten zu empfangen, die die existierenden Daten ersetzen sollen. @@ -54,7 +32,7 @@ Sie können auch die ../../docs_src/body_updates/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="34" -{!> ../../docs_src/body_updates/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="34" -{!> ../../docs_src/body_updates/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial002_py310.py hl[32] *} ### Pydantics `update`-Parameter verwenden @@ -122,29 +78,7 @@ Die Beispiele hier verwenden `.copy()` für die Kompatibilität mit Pydantic v1, Wie in `stored_item_model.model_copy(update=update_data)`: -//// tab | Python 3.10+ - -```Python hl_lines="33" -{!> ../../docs_src/body_updates/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="35" -{!> ../../docs_src/body_updates/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="35" -{!> ../../docs_src/body_updates/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial002_py310.py hl[33] *} ### Rekapitulation zum teilweisen Ersetzen @@ -161,31 +95,9 @@ Zusammengefasst, um Teil-Ersetzungen vorzunehmen: * Speichern Sie die Daten in Ihrer Datenbank. * Geben Sie das aktualisierte Modell zurück. -//// tab | Python 3.10+ - -```Python hl_lines="28-35" -{!> ../../docs_src/body_updates/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="30-37" -{!> ../../docs_src/body_updates/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="30-37" -{!> ../../docs_src/body_updates/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial002_py310.py hl[28:35] *} -/// tip | "Tipp" +/// tip | Tipp Sie können tatsächlich die gleiche Technik mit einer HTTP `PUT` Operation verwenden. @@ -193,7 +105,7 @@ Aber dieses Beispiel verwendet `PATCH`, da dieses für solche Anwendungsfälle g /// -/// note | "Hinweis" +/// note | Hinweis Beachten Sie, dass das hereinkommende Modell immer noch validiert wird. diff --git a/docs/de/docs/tutorial/body.md b/docs/de/docs/tutorial/body.md index 3a64e747e31b7..e25323786dbbe 100644 --- a/docs/de/docs/tutorial/body.md +++ b/docs/de/docs/tutorial/body.md @@ -22,21 +22,7 @@ Da aber davon abgeraten wird, zeigt die interaktive Dokumentation mit Swagger-Be Zuerst müssen Sie `BaseModel` von `pydantic` importieren: -//// tab | Python 3.10+ - -```Python hl_lines="2" -{!> ../../docs_src/body/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4" -{!> ../../docs_src/body/tutorial001.py!} -``` - -//// +{* ../../docs_src/body/tutorial001_py310.py hl[2] *} ## Erstellen Sie Ihr Datenmodell @@ -44,21 +30,7 @@ Dann deklarieren Sie Ihr Datenmodell als eine Klasse, die von `BaseModel` erbt. Verwenden Sie Standard-Python-Typen für die Klassenattribute: -//// tab | Python 3.10+ - -```Python hl_lines="5-9" -{!> ../../docs_src/body/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="7-11" -{!> ../../docs_src/body/tutorial001.py!} -``` - -//// +{* ../../docs_src/body/tutorial001_py310.py hl[5:9] *} Wie auch bei Query-Parametern gilt, wenn ein Modellattribut einen Defaultwert hat, ist das Attribut nicht erforderlich. Ansonsten ist es erforderlich. Verwenden Sie `None`, um es als optional zu kennzeichnen. @@ -86,21 +58,7 @@ Da `description` und `tax` optional sind (mit `None` als Defaultwert), wäre fol Um es zu Ihrer *Pfadoperation* hinzuzufügen, deklarieren Sie es auf die gleiche Weise, wie Sie Pfad- und Query-Parameter deklariert haben: -//// tab | Python 3.10+ - -```Python hl_lines="16" -{!> ../../docs_src/body/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18" -{!> ../../docs_src/body/tutorial001.py!} -``` - -//// +{* ../../docs_src/body/tutorial001_py310.py hl[16] *} ... und deklarieren Sie seinen Typ als das Modell, welches Sie erstellt haben, `Item`. @@ -149,7 +107,7 @@ Aber Sie bekommen die gleiche Editor-Unterstützung in -/// tip | "Tipp" +/// tip | Tipp Wenn Sie PyCharm als Ihren Editor verwenden, probieren Sie das Pydantic PyCharm Plugin aus. @@ -167,21 +125,7 @@ Es verbessert die Editor-Unterstützung für Pydantic-Modelle, mit: Innerhalb der Funktion können Sie alle Attribute des Modells direkt verwenden: -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/body/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="21" -{!> ../../docs_src/body/tutorial002.py!} -``` - -//// +{* ../../docs_src/body/tutorial002_py310.py hl[19] *} ## Requestbody- + Pfad-Parameter @@ -189,21 +133,7 @@ Sie können Pfad- und Requestbody-Parameter gleichzeitig deklarieren. **FastAPI** erkennt, dass Funktionsparameter, die mit Pfad-Parametern übereinstimmen, **vom Pfad genommen** werden sollen, und dass Funktionsparameter, welche Pydantic-Modelle sind, **vom Requestbody genommen** werden sollen. -//// tab | Python 3.10+ - -```Python hl_lines="15-16" -{!> ../../docs_src/body/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17-18" -{!> ../../docs_src/body/tutorial003.py!} -``` - -//// +{* ../../docs_src/body/tutorial003_py310.py hl[15:16] *} ## Requestbody- + Pfad- + Query-Parameter @@ -211,21 +141,7 @@ Sie können auch zur gleichen Zeit **Body-**, **Pfad-** und **Query-Parameter** **FastAPI** wird jeden Parameter korrekt erkennen und die Daten vom richtigen Ort holen. -//// tab | Python 3.10+ - -```Python hl_lines="16" -{!> ../../docs_src/body/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18" -{!> ../../docs_src/body/tutorial004.py!} -``` - -//// +{* ../../docs_src/body/tutorial004_py310.py hl[16] *} Die Funktionsparameter werden wie folgt erkannt: @@ -233,7 +149,7 @@ Die Funktionsparameter werden wie folgt erkannt: * Wenn der Parameter ein **einfacher Typ** ist (wie `int`, `float`, `str`, `bool`, usw.), wird er als **Query**-Parameter interpretiert. * Wenn der Parameter vom Typ eines **Pydantic-Modells** ist, wird er als Request**body** interpretiert. -/// note | "Hinweis" +/// note | Hinweis FastAPI weiß, dass der Wert von `q` nicht erforderlich ist, wegen des definierten Defaultwertes `= None` diff --git a/docs/de/docs/tutorial/cookie-params.md b/docs/de/docs/tutorial/cookie-params.md index 4714a59aedc3a..711c8c8e9b89d 100644 --- a/docs/de/docs/tutorial/cookie-params.md +++ b/docs/de/docs/tutorial/cookie-params.md @@ -6,57 +6,7 @@ So wie `Query`- und `Path`-Parameter können Sie auch ../../docs_src/dependencies/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3" -{!> ../../docs_src/dependencies/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="3" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[3] *} ### Deklarieren der Abhängigkeit im „Dependant“ So wie auch `Body`, `Query`, usw., verwenden Sie `Depends` mit den Parametern Ihrer *Pfadoperation-Funktion*: -//// tab | Python 3.10+ - -```Python hl_lines="13 18" -{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="15 20" -{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="16 21" -{!> ../../docs_src/dependencies/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="11 16" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="15 20" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[13,18] *} Obwohl Sie `Depends` in den Parametern Ihrer Funktion genauso verwenden wie `Body`, `Query`, usw., funktioniert `Depends` etwas anders. @@ -230,7 +80,7 @@ Sie **rufen diese nicht direkt auf** (fügen Sie am Ende keine Klammern hinzu), Und diese Funktion akzeptiert Parameter auf die gleiche Weise wie *Pfadoperation-Funktionen*. -/// tip | "Tipp" +/// tip | Tipp Im nächsten Kapitel erfahren Sie, welche anderen „Dinge“, außer Funktionen, Sie als Abhängigkeiten verwenden können. @@ -275,31 +125,9 @@ commons: Annotated[dict, Depends(common_parameters)] Da wir jedoch `Annotated` verwenden, können wir diesen `Annotated`-Wert in einer Variablen speichern und an mehreren Stellen verwenden: -//// tab | Python 3.10+ - -```Python hl_lines="12 16 21" -{!> ../../docs_src/dependencies/tutorial001_02_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="14 18 23" -{!> ../../docs_src/dependencies/tutorial001_02_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="15 19 24" -{!> ../../docs_src/dependencies/tutorial001_02_an.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_02_an_py310.py hl[12,16,21] *} -/// tip | "Tipp" +/// tip | Tipp Das ist schlicht Standard-Python, es wird als „Typalias“ bezeichnet und ist eigentlich nicht **FastAPI**-spezifisch. @@ -321,7 +149,7 @@ Und Sie können Abhängigkeiten mit `async def` innerhalb normaler `def`-*Pfadop Es spielt keine Rolle. **FastAPI** weiß, was zu tun ist. -/// note | "Hinweis" +/// note | Hinweis Wenn Ihnen das nichts sagt, lesen Sie den [Async: *„In Eile?“*](../../async.md#in-eile){.internal-link target=_blank}-Abschnitt über `async` und `await` in der Dokumentation. diff --git a/docs/de/docs/tutorial/dependencies/sub-dependencies.md b/docs/de/docs/tutorial/dependencies/sub-dependencies.md index a20aed63b3b46..66bdc7043229c 100644 --- a/docs/de/docs/tutorial/dependencies/sub-dependencies.md +++ b/docs/de/docs/tutorial/dependencies/sub-dependencies.md @@ -10,57 +10,7 @@ Diese können so **tief** verschachtelt sein, wie nötig. Sie könnten eine erste Abhängigkeit („Dependable“) wie folgt erstellen: -//// tab | Python 3.10+ - -```Python hl_lines="8-9" -{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="8-9" -{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9-10" -{!> ../../docs_src/dependencies/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10 nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="6-7" -{!> ../../docs_src/dependencies/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.8 nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="8-9" -{!> ../../docs_src/dependencies/tutorial005.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[8:9] *} Diese deklariert einen optionalen Abfrageparameter `q` vom Typ `str` und gibt ihn dann einfach zurück. @@ -70,57 +20,7 @@ Das ist recht einfach (nicht sehr nützlich), hilft uns aber dabei, uns auf die Dann können Sie eine weitere Abhängigkeitsfunktion (ein „Dependable“) erstellen, die gleichzeitig eine eigene Abhängigkeit deklariert (also auch ein „Dependant“ ist): -//// tab | Python 3.10+ - -```Python hl_lines="13" -{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="13" -{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="14" -{!> ../../docs_src/dependencies/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10 nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="11" -{!> ../../docs_src/dependencies/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.8 nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="13" -{!> ../../docs_src/dependencies/tutorial005.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[13] *} Betrachten wir die deklarierten Parameter: @@ -133,57 +33,7 @@ Betrachten wir die deklarierten Parameter: Diese Abhängigkeit verwenden wir nun wie folgt: -//// tab | Python 3.10+ - -```Python hl_lines="23" -{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="23" -{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24" -{!> ../../docs_src/dependencies/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10 nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.8 nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="22" -{!> ../../docs_src/dependencies/tutorial005.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[23] *} /// info @@ -223,7 +73,7 @@ async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_ca //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -244,7 +94,7 @@ Einfach Funktionen, die genauso aussehen wie *Pfadoperation-Funktionen*. Dennoch ist es sehr mächtig und ermöglicht Ihnen die Deklaration beliebig tief verschachtelter Abhängigkeits-„Graphen“ (Bäume). -/// tip | "Tipp" +/// tip | Tipp All dies scheint angesichts dieser einfachen Beispiele möglicherweise nicht so nützlich zu sein. diff --git a/docs/de/docs/tutorial/encoder.md b/docs/de/docs/tutorial/encoder.md index 0ab72b8dd37fb..5678d7b8f1820 100644 --- a/docs/de/docs/tutorial/encoder.md +++ b/docs/de/docs/tutorial/encoder.md @@ -20,21 +20,7 @@ Sie können für diese Fälle `jsonable_encoder` verwenden. Es nimmt ein Objekt entgegen, wie etwa ein Pydantic-Modell, und gibt eine JSON-kompatible Version zurück: -//// tab | Python 3.10+ - -```Python hl_lines="4 21" -{!> ../../docs_src/encoder/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="5 22" -{!> ../../docs_src/encoder/tutorial001.py!} -``` - -//// +{* ../../docs_src/encoder/tutorial001_py310.py hl[4,21] *} In diesem Beispiel wird das Pydantic-Modell in ein `dict`, und das `datetime`-Objekt in ein `str` konvertiert. @@ -42,7 +28,7 @@ Das Resultat dieses Aufrufs ist etwas, das mit Pythons Standard- ../../docs_src/extra_data_types/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="1 3 12-16" -{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 3 13-17" -{!> ../../docs_src/extra_data_types/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="1 2 11-15" -{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="1 2 12-16" -{!> ../../docs_src/extra_data_types/tutorial001.py!} -``` - -//// +{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[1,3,12:16] *} Beachten Sie, dass die Parameter innerhalb der Funktion ihren natürlichen Datentyp haben und Sie beispielsweise normale Datumsmanipulationen durchführen können, wie zum Beispiel: -//// tab | Python 3.10+ - -```Python hl_lines="18-19" -{!> ../../docs_src/extra_data_types/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="18-19" -{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="19-20" -{!> ../../docs_src/extra_data_types/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="17-18" -{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="18-19" -{!> ../../docs_src/extra_data_types/tutorial001.py!} -``` - -//// +{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[18:19] *} diff --git a/docs/de/docs/tutorial/extra-models.md b/docs/de/docs/tutorial/extra-models.md index 14e8420654220..6aad1c0f42a3b 100644 --- a/docs/de/docs/tutorial/extra-models.md +++ b/docs/de/docs/tutorial/extra-models.md @@ -8,7 +8,7 @@ Insbesondere Benutzermodelle, denn: * Das **herausgehende Modell** sollte kein Passwort haben. * Das **Datenbankmodell** sollte wahrscheinlich ein gehashtes Passwort haben. -/// danger | "Gefahr" +/// danger | Gefahr Speichern Sie niemals das Klartext-Passwort eines Benutzers. Speichern Sie immer den „sicheren Hash“, den Sie verifizieren können. @@ -20,21 +20,7 @@ Falls Ihnen das nichts sagt, in den [Sicherheits-Kapiteln](security/simple-oauth Hier der generelle Weg, wie die Modelle mit ihren Passwort-Feldern aussehen könnten, und an welchen Orten sie verwendet werden würden. -//// tab | Python 3.10+ - -```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" -{!> ../../docs_src/extra_models/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" -{!> ../../docs_src/extra_models/tutorial001.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial001_py310.py hl[7,9,14,20,22,27:28,31:33,38:39] *} /// info @@ -154,7 +140,7 @@ UserInDB( ) ``` -/// warning | "Achtung" +/// warning | Achtung Die Hilfsfunktionen `fake_password_hasher` und `fake_save_user` demonstrieren nur den möglichen Fluss der Daten und bieten natürlich keine echte Sicherheit. @@ -176,21 +162,7 @@ Die ganze Datenkonvertierung, -validierung, -dokumentation, usw. wird immer noch Auf diese Weise beschreiben wir nur noch die Unterschiede zwischen den Modellen (mit Klartext-`password`, mit `hashed_password`, und ohne Passwort): -//// tab | Python 3.10+ - -```Python hl_lines="7 13-14 17-18 21-22" -{!> ../../docs_src/extra_models/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 15-16 19-20 23-24" -{!> ../../docs_src/extra_models/tutorial002.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial002_py310.py hl[7,13:14,17:18,21:22] *} ## `Union`, oder `anyOf` @@ -200,27 +172,13 @@ Das wird in OpenAPI mit `anyOf` angezeigt. Um das zu tun, verwenden Sie Pythons Standard-Typhinweis `typing.Union`: -/// note | "Hinweis" +/// note | Hinweis Listen Sie, wenn Sie eine `Union` definieren, denjenigen Typ zuerst, der am spezifischsten ist, gefolgt von den weniger spezifischen Typen. Im Beispiel oben, in `Union[PlaneItem, CarItem]` also den spezifischeren `PlaneItem` vor dem weniger spezifischen `CarItem`. /// -//// tab | Python 3.10+ - -```Python hl_lines="1 14-15 18-20 33" -{!> ../../docs_src/extra_models/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 14-15 18-20 33" -{!> ../../docs_src/extra_models/tutorial003.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial003_py310.py hl[1,14:15,18:20,33] *} ### `Union` in Python 3.10 @@ -242,21 +200,7 @@ Genauso können Sie eine Response deklarieren, die eine Liste von Objekten ist. Verwenden Sie dafür Pythons Standard `typing.List` (oder nur `list` in Python 3.9 und darüber): -//// tab | Python 3.9+ - -```Python hl_lines="18" -{!> ../../docs_src/extra_models/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 20" -{!> ../../docs_src/extra_models/tutorial004.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial004_py39.py hl[18] *} ## Response mit beliebigem `dict` @@ -266,21 +210,7 @@ Das ist nützlich, wenn Sie die gültigen Feld-/Attribut-Namen von vorneherein n In diesem Fall können Sie `typing.Dict` verwenden (oder nur `dict` in Python 3.9 und darüber): -//// tab | Python 3.9+ - -```Python hl_lines="6" -{!> ../../docs_src/extra_models/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 8" -{!> ../../docs_src/extra_models/tutorial005.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial005_py39.py hl[6] *} ## Zusammenfassung diff --git a/docs/de/docs/tutorial/first-steps.md b/docs/de/docs/tutorial/first-steps.md index fe3886b70c1b7..3104c8d61275d 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,7 +22,7 @@ $ uvicorn main:app --reload -/// note | "Hinweis" +/// note | Hinweis Der Befehl `uvicorn main:app` bezieht sich auf: @@ -133,13 +131,11 @@ 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" +/// note | Technische Details `FastAPI` ist eine Klasse, die direkt von `Starlette` erbt. @@ -149,9 +145,7 @@ Sie können alle get-Operation gehen -/// info | "`@decorator` Information" +/// info | `@decorator` Information Diese `@something`-Syntax wird in Python „Dekorator“ genannt. @@ -286,7 +276,7 @@ Oder die exotischeren: * `@app.patch()` * `@app.trace()` -/// tip | "Tipp" +/// tip | Tipp Es steht Ihnen frei, jede Operation (HTTP-Methode) so zu verwenden, wie Sie es möchten. @@ -306,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. @@ -320,11 +308,9 @@ 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}. @@ -332,9 +318,7 @@ Wenn Sie den Unterschied nicht kennen, lesen Sie [Async: *„In Eile?“*](../as ### 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 70dc0c523f614..31bc6d328a40a 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,7 +59,7 @@ Aber wenn der Client `http://example.com/items/bar` anfragt (ein nicht-existiere } ``` -/// tip | "Tipp" +/// tip | Tipp Wenn Sie eine `HTTPException` auslösen, können Sie dem Parameter `detail` jeden Wert übergeben, der nach JSON konvertiert werden kann, nicht nur `str`. @@ -81,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 @@ -95,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`. @@ -109,7 +101,7 @@ Sie erhalten also einen sauberen Error mit einem Statuscode `418` und dem JSON-I {"message": "Oops! yolo did something. There goes a rainbow..."} ``` -/// note | "Technische Details" +/// note | Technische Details Sie können auch `from starlette.requests import Request` und `from starlette.responses import JSONResponse` verwenden. @@ -135,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: @@ -166,7 +156,7 @@ path -> item_id #### `RequestValidationError` vs. `ValidationError` -/// warning | "Achtung" +/// warning | Achtung Das folgende sind technische Details, die Sie überspringen können, wenn sie für Sie nicht wichtig sind. @@ -188,11 +178,9 @@ 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" +/// note | Technische Details Sie können auch `from starlette.responses import PlainTextResponse` verwenden. @@ -206,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: @@ -264,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 c4901c2ee4bdc..8283cc9292776 100644 --- a/docs/de/docs/tutorial/header-params.md +++ b/docs/de/docs/tutorial/header-params.md @@ -6,57 +6,7 @@ So wie `Query`-, `Path`-, und `Cookie`-Parameter können Sie auch . @@ -43,7 +41,7 @@ Wenn Sie jedoch benutzerdefinierte Header haben, die ein Client in einem Browser /// -/// note | "Technische Details" +/// note | Technische Details Sie könnten auch `from starlette.requests import Request` verwenden. @@ -59,9 +57,7 @@ Und auch nachdem die `response` generiert wurde, bevor sie zurückgegeben wird. Sie könnten beispielsweise einen benutzerdefinierten Header `X-Process-Time` hinzufügen, der die Zeit in Sekunden enthält, die benötigt wurde, um den Request zu verarbeiten und eine Response zu generieren: -```Python hl_lines="10 12-13" -{!../../docs_src/middleware/tutorial001.py!} -``` +{* ../../docs_src/middleware/tutorial001.py hl[10,12:13] *} ## Andere Middlewares diff --git a/docs/de/docs/tutorial/path-operation-configuration.md b/docs/de/docs/tutorial/path-operation-configuration.md index 411916e9c5007..7473e515b3d2b 100644 --- a/docs/de/docs/tutorial/path-operation-configuration.md +++ b/docs/de/docs/tutorial/path-operation-configuration.md @@ -2,7 +2,7 @@ Es gibt mehrere Konfigurations-Parameter, die Sie Ihrem *Pfadoperation-Dekorator* übergeben können. -/// warning | "Achtung" +/// warning | Achtung Beachten Sie, dass diese Parameter direkt dem *Pfadoperation-Dekorator* übergeben werden, nicht der *Pfadoperation-Funktion*. @@ -16,33 +16,11 @@ Sie können direkt den `int`-Code übergeben, etwa `404`. Aber falls Sie sich nicht mehr erinnern, wofür jede Nummer steht, können Sie die Abkürzungs-Konstanten in `status` verwenden: -//// tab | Python 3.10+ - -```Python hl_lines="1 15" -{!> ../../docs_src/path_operation_configuration/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="3 17" -{!> ../../docs_src/path_operation_configuration/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3 17" -{!> ../../docs_src/path_operation_configuration/tutorial001.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial001_py310.py hl[1,15] *} Dieser Statuscode wird in der Response verwendet und zum OpenAPI-Schema hinzugefügt. -/// note | "Technische Details" +/// note | Technische Details Sie können auch `from starlette import status` verwenden. @@ -54,29 +32,7 @@ Sie können auch `from starlette import status` verwenden. Sie können Ihrer *Pfadoperation* Tags hinzufügen, mittels des Parameters `tags`, dem eine `list`e von `str`s übergeben wird (in der Regel nur ein `str`): -//// tab | Python 3.10+ - -```Python hl_lines="15 20 25" -{!> ../../docs_src/path_operation_configuration/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="17 22 27" -{!> ../../docs_src/path_operation_configuration/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17 22 27" -{!> ../../docs_src/path_operation_configuration/tutorial002.py!} -``` - -//// +{* ../../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: @@ -90,37 +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: -//// tab | Python 3.10+ - -```Python hl_lines="18-19" -{!> ../../docs_src/path_operation_configuration/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="20-21" -{!> ../../docs_src/path_operation_configuration/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20-21" -{!> ../../docs_src/path_operation_configuration/tutorial003.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial003_py310.py hl[18:19] *} ## Beschreibung mittels Docstring @@ -128,29 +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). -//// tab | Python 3.10+ - -```Python hl_lines="17-25" -{!> ../../docs_src/path_operation_configuration/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="19-27" -{!> ../../docs_src/path_operation_configuration/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="19-27" -{!> ../../docs_src/path_operation_configuration/tutorial004.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial004_py310.py hl[17:25] *} In der interaktiven Dokumentation sieht das dann so aus: @@ -160,29 +70,7 @@ In der interaktiven Dokumentation sieht das dann so aus: Die Response können Sie mit dem Parameter `response_description` beschreiben: -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/path_operation_configuration/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="21" -{!> ../../docs_src/path_operation_configuration/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="21" -{!> ../../docs_src/path_operation_configuration/tutorial005.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial005_py310.py hl[19] *} /// info @@ -204,9 +92,7 @@ Daher, wenn Sie keine vergeben, wird **FastAPI** automatisch eine für „Erfolg Wenn Sie eine *Pfadoperation* als deprecated kennzeichnen möchten, ohne sie zu entfernen, fügen Sie den Parameter `deprecated` hinzu: -```Python hl_lines="16" -{!../../docs_src/path_operation_configuration/tutorial006.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial006.py 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 fc2d5dff113c1..1acdd5b4e21fd 100644 --- a/docs/de/docs/tutorial/path-params-numeric-validations.md +++ b/docs/de/docs/tutorial/path-params-numeric-validations.md @@ -6,57 +6,7 @@ So wie Sie mit `Query` für Query-Parameter zusätzliche Validierungen und Metad Importieren Sie zuerst `Path` von `fastapi`, und importieren Sie `Annotated`. -//// tab | Python 3.10+ - -```Python hl_lines="1 3" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="1 3" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3-4" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="3" -{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[1,3] *} /// info @@ -74,59 +24,9 @@ Sie können die gleichen Parameter deklarieren wie für `Query`. Um zum Beispiel einen `title`-Metadaten-Wert für den Pfad-Parameter `item_id` zu deklarieren, schreiben Sie: -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[10] *} -//// - -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="8" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} -``` - -//// - -/// note | "Hinweis" +/// note | Hinweis Ein Pfad-Parameter ist immer erforderlich, weil er Teil des Pfads sein muss. @@ -138,7 +38,7 @@ Doch selbst wenn Sie ihn mit `None` deklarieren, oder einen Defaultwert setzen, ## Sortieren Sie die Parameter, wie Sie möchten -/// tip | "Tipp" +/// tip | Tipp Wenn Sie `Annotated` verwenden, ist das folgende nicht so wichtig / nicht notwendig. @@ -160,7 +60,7 @@ Sie können Ihre Funktion also so deklarieren: //// tab | Python 3.8 nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -174,25 +74,11 @@ 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. -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/path_params_numeric_validations/tutorial002_an.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py hl[10] *} ## Sortieren Sie die Parameter wie Sie möchten: Tricks -/// tip | "Tipp" +/// tip | Tipp Wenn Sie `Annotated` verwenden, ist das folgende nicht so wichtig / nicht notwendig. @@ -213,64 +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. -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/path_params_numeric_validations/tutorial003_an.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py hl[10] *} ## Validierung von Zahlen: Größer oder gleich Mit `Query` und `Path` (und anderen, die Sie später kennenlernen), können Sie Zahlenbeschränkungen deklarieren. Hier, mit `ge=1`, wird festgelegt, dass `item_id` eine Ganzzahl benötigt, die größer oder gleich `1` ist (`g`reater than or `e`qual). -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/path_params_numeric_validations/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="8" -{!> ../../docs_src/path_params_numeric_validations/tutorial004.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py hl[10] *} ## Validierung von Zahlen: Größer und kleiner oder gleich @@ -279,35 +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 -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/path_params_numeric_validations/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/path_params_numeric_validations/tutorial005.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py hl[10] *} ## Validierung von Zahlen: Floats, größer und kleiner @@ -319,35 +133,7 @@ Hier wird es wichtig, in der Lage zu sein, lt. -//// tab | Python 3.9+ - -```Python hl_lines="13" -{!> ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="12" -{!> ../../docs_src/path_params_numeric_validations/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="11" -{!> ../../docs_src/path_params_numeric_validations/tutorial006.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py hl[13] *} ## Zusammenfassung @@ -368,7 +154,7 @@ Sie alle teilen die gleichen Parameter für zusätzliche Validierung und Metadat /// -/// note | "Technische Details" +/// note | Technische Details `Query`, `Path` und andere, die Sie von `fastapi` importieren, sind tatsächlich Funktionen. diff --git a/docs/de/docs/tutorial/path-params.md b/docs/de/docs/tutorial/path-params.md index 9cb172c941d88..1239909402e11 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,9 +16,7 @@ Wenn Sie dieses Beispiel ausführen und auf Modellen für maschinelles Lernen. @@ -169,9 +159,7 @@ Falls Sie sich fragen, was „AlexNet“, „ResNet“ und „LeNet“ ist, das 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 @@ -187,19 +175,15 @@ Der *Pfad-Parameter* wird ein * ../../docs_src/query_params_str_validations/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial001.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial001_py310.py hl[7] *} Der Query-Parameter `q` hat den Typ `Union[str, None]` (oder `str | None` in Python 3.10), was bedeutet, er ist entweder ein `str` oder `None`. Der Defaultwert ist `None`, also weiß FastAPI, der Parameter ist nicht erforderlich. -/// note | "Hinweis" +/// note | Hinweis FastAPI weiß nur dank des definierten Defaultwertes `=None`, dass der Wert von `q` nicht erforderlich ist @@ -123,21 +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`: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial002_an.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial002_an_py310.py hl[9] *} Beachten Sie, dass der Defaultwert immer noch `None` ist, sodass der Parameter immer noch optional ist. @@ -153,7 +125,7 @@ FastAPI wird nun: Frühere Versionen von FastAPI (vor 0.95.0) benötigten `Query` als Defaultwert des Parameters, statt es innerhalb von `Annotated` unterzubringen. Die Chance ist groß, dass Sie Quellcode sehen, der das immer noch so macht, darum erkläre ich es Ihnen. -/// tip | "Tipp" +/// tip | Tipp Verwenden Sie für neuen Code, und wann immer möglich, `Annotated`, wie oben erklärt. Es gibt mehrere Vorteile (unten erläutert) und keine Nachteile. 🍰 @@ -161,21 +133,7 @@ Verwenden Sie für neuen Code, und wann immer möglich, `Annotated`, wie oben er So würden Sie `Query()` als Defaultwert Ihres Funktionsparameters verwenden, den Parameter `max_length` auf 50 gesetzt: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial002.py!} -``` - -//// +{* ../../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). @@ -275,113 +233,13 @@ Da `Annotated` mehrere Metadaten haben kann, können Sie dieselbe Funktion auch Sie können auch einen Parameter `min_length` hinzufügen: -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial003.py!} -``` - -//// +{* ../../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: -//// tab | Python 3.10+ - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="12" -{!> ../../docs_src/query_params_str_validations/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial004.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial004_an_py310.py hl[11] *} Dieses bestimmte reguläre Suchmuster prüft, ob der erhaltene Parameter-Wert: @@ -399,11 +257,9 @@ 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: -//// tab | Python 3.10+ Pydantic v1 +//// tab | Pydantic v1 -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial004_an_py310_regex.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial004_regex_an_py310.py hl[11] *} //// @@ -415,37 +271,9 @@ Sie können natürlich andere Defaultwerte als `None` verwenden. Beispielsweise könnten Sie den `q` Query-Parameter so deklarieren, dass er eine `min_length` von `3` hat, und den Defaultwert `"fixedquery"`: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert +{* ../../docs_src/query_params_str_validations/tutorial005_an_py39.py hl[9] *} -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial005.py!} -``` - -//// - -/// note | "Hinweis" +/// note | Hinweis Ein Parameter ist optional (nicht erforderlich), wenn er irgendeinen Defaultwert, auch `None`, hat. @@ -485,77 +313,13 @@ q: Union[str, None] = Query(default=None, min_length=3) Wenn Sie einen Parameter erforderlich machen wollen, während Sie `Query` verwenden, deklarieren Sie ebenfalls einfach keinen Defaultwert: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial006.py!} -``` - -/// tip | "Tipp" - -Beachten Sie, dass, obwohl in diesem Fall `Query()` der Funktionsparameter-Defaultwert ist, wir nicht `default=None` zu `Query()` hinzufügen. - -Verwenden Sie bitte trotzdem die `Annotated`-Version. 😉 - -/// - -//// +{* ../../docs_src/query_params_str_validations/tutorial006_an_py39.py hl[9] *} ### Erforderlich mit Ellipse (`...`) Es gibt eine Alternative, die explizit deklariert, dass ein Wert erforderlich ist. Sie können als Default das Literal `...` setzen: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial006b_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial006b.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial006b_an_py39.py hl[9] *} /// info @@ -573,65 +337,15 @@ Sie können deklarieren, dass ein Parameter `None` akzeptiert, aber dennoch erfo Um das zu machen, deklarieren Sie, dass `None` ein gültiger Typ ist, aber verwenden Sie dennoch `...` als Default: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial006c_an_py310.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial006c_an_py310.py hl[9] *} -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial006c_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial006c_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial006c.py!} -``` - -//// - -/// tip | "Tipp" +/// tip | Tipp Pydantic, welches die gesamte Datenvalidierung und Serialisierung in FastAPI antreibt, hat ein spezielles Verhalten, wenn Sie `Optional` oder `Union[Something, None]` ohne Defaultwert verwenden, Sie können mehr darüber in der Pydantic-Dokumentation unter Required fields erfahren. /// -/// tip | "Tipp" +/// tip | Tipp Denken Sie daran, dass Sie in den meisten Fällen, wenn etwas erforderlich ist, einfach den Defaultwert weglassen können. Sie müssen also normalerweise `...` nicht verwenden. @@ -643,71 +357,7 @@ Wenn Sie einen Query-Parameter explizit mit `Query` auszeichnen, können Sie ihn Um zum Beispiel einen Query-Parameter `q` zu deklarieren, der mehrere Male in der URL vorkommen kann, schreiben Sie: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial011_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial011_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial011_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial011_py310.py!} -``` - -//// - -//// tab | Python 3.9+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial011_py39.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial011.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial011_an_py310.py hl[9] *} Dann, mit einer URL wie: @@ -728,7 +378,7 @@ Die Response für diese URL wäre also: } ``` -/// tip | "Tipp" +/// tip | Tipp Um einen Query-Parameter vom Typ `list` zu deklarieren, wie im Beispiel oben, müssen Sie explizit `Query` verwenden, sonst würde der Parameter als Requestbody interpretiert werden. @@ -742,49 +392,7 @@ Die interaktive API-Dokumentation wird entsprechend aktualisiert und erlaubt jet Und Sie können auch eine Default-`list`e von Werten definieren, wenn keine übergeben werden: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial012_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial012_an.py!} -``` - -//// - -//// tab | Python 3.9+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial012_py39.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial012.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial012_an_py39.py hl[9] *} Wenn Sie auf: @@ -807,37 +415,9 @@ gehen, wird der Default für `q` verwendet: `["foo", "bar"]`, und als Response e Sie können auch `list` direkt verwenden, anstelle von `List[str]` (oder `list[str]` in Python 3.9+): -//// tab | Python 3.9+ +{* ../../docs_src/query_params_str_validations/tutorial013_an_py39.py hl[9] *} -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial013_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial013_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial013.py!} -``` - -//// - -/// note | "Hinweis" +/// note | Hinweis Beachten Sie, dass FastAPI in diesem Fall den Inhalt der Liste nicht überprüft. @@ -851,7 +431,7 @@ Sie können mehr Informationen zum Parameter hinzufügen. Diese Informationen werden zur generierten OpenAPI hinzugefügt, und von den Dokumentations-Oberflächen und von externen Tools verwendet. -/// note | "Hinweis" +/// note | Hinweis Beachten Sie, dass verschiedene Tools OpenAPI möglicherweise unterschiedlich gut unterstützen. @@ -861,111 +441,11 @@ Einige könnten noch nicht alle zusätzlichen Informationen anzeigen, die Sie de Sie können einen Titel hinzufügen – `title`: -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial007_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial007_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial007_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial007_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial007.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial007_an_py310.py hl[10] *} Und eine Beschreibung – `description`: -//// tab | Python 3.10+ - -```Python hl_lines="14" -{!> ../../docs_src/query_params_str_validations/tutorial008_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="14" -{!> ../../docs_src/query_params_str_validations/tutorial008_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="15" -{!> ../../docs_src/query_params_str_validations/tutorial008_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial008_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="13" -{!> ../../docs_src/query_params_str_validations/tutorial008.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial008_an_py310.py hl[14] *} ## Alias-Parameter @@ -985,57 +465,7 @@ Aber Sie möchten dennoch exakt `item-query` verwenden. Dann können Sie einen `alias` deklarieren, und dieser Alias wird verwendet, um den Parameter-Wert zu finden: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial009_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial009_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial009_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial009_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial009.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial009_an_py310.py hl[9] *} ## Parameter als deprecated ausweisen @@ -1045,57 +475,7 @@ Sie müssen ihn eine Weile dort belassen, weil Clients ihn benutzen, aber Sie m In diesem Fall fügen Sie den Parameter `deprecated=True` zu `Query` hinzu. -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/query_params_str_validations/tutorial010_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="19" -{!> ../../docs_src/query_params_str_validations/tutorial010_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20" -{!> ../../docs_src/query_params_str_validations/tutorial010_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="16" -{!> ../../docs_src/query_params_str_validations/tutorial010_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="18" -{!> ../../docs_src/query_params_str_validations/tutorial010.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial010_an_py310.py hl[19] *} Die Dokumentation wird das so anzeigen: @@ -1105,57 +485,7 @@ Die Dokumentation wird das so anzeigen: Um einen Query-Parameter vom generierten OpenAPI-Schema auszuschließen (und daher von automatischen Dokumentations-Systemen), setzen Sie den Parameter `include_in_schema` in `Query` auf `False`. -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial014_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial014_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial014_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial014_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial014.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial014_an_py310.py hl[10] *} ## Zusammenfassung diff --git a/docs/de/docs/tutorial/query-params.md b/docs/de/docs/tutorial/query-params.md index bb1dbdf9c3db0..0b0f473e2614c 100644 --- a/docs/de/docs/tutorial/query-params.md +++ b/docs/de/docs/tutorial/query-params.md @@ -2,9 +2,7 @@ Wenn Sie in ihrer Funktion Parameter deklarieren, die nicht Teil der Pfad-Parameter sind, dann werden diese automatisch als „Query“-Parameter interpretiert. -```Python hl_lines="9" -{!../../docs_src/query_params/tutorial001.py!} -``` +{* ../../docs_src/query_params/tutorial001.py hl[9] *} Query-Parameter (Deutsch: Abfrage-Parameter) sind die Schlüssel-Wert-Paare, die nach dem `?` in einer URL aufgelistet sind, getrennt durch `&`-Zeichen. @@ -63,21 +61,7 @@ gehen, werden die Parameter-Werte Ihrer Funktion sein: Auf die gleiche Weise können Sie optionale Query-Parameter deklarieren, indem Sie deren Defaultwert auf `None` setzen: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/query_params/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params/tutorial002.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial002_py310.py hl[7] *} In diesem Fall wird der Funktionsparameter `q` optional, und standardmäßig `None` sein. @@ -91,21 +75,7 @@ Beachten Sie auch, dass **FastAPI** intelligent genug ist, um zu erkennen, dass Sie können auch `bool`-Typen deklarieren und sie werden konvertiert: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/query_params/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params/tutorial003.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial003_py310.py hl[7] *} Wenn Sie nun zu: @@ -147,21 +117,7 @@ Und Sie müssen sie auch nicht in einer spezifischen Reihenfolge deklarieren. Parameter werden anhand ihres Namens erkannt: -//// tab | Python 3.10+ - -```Python hl_lines="6 8" -{!> ../../docs_src/query_params/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8 10" -{!> ../../docs_src/query_params/tutorial004.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial004_py310.py hl[6,8] *} ## Erforderliche Query-Parameter @@ -171,9 +127,7 @@ Wenn Sie keinen spezifischen Wert haben wollen, sondern der Parameter einfach op Aber wenn Sie wollen, dass ein Query-Parameter erforderlich ist, vergeben Sie einfach keinen Defaultwert: -```Python hl_lines="6-7" -{!../../docs_src/query_params/tutorial005.py!} -``` +{* ../../docs_src/query_params/tutorial005.py hl[6:7] *} Hier ist `needy` ein erforderlicher Query-Parameter vom Typ `str`. @@ -219,21 +173,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy Und natürlich können Sie einige Parameter als erforderlich, einige mit Defaultwert, und einige als vollständig optional definieren: -//// tab | Python 3.10+ - -```Python hl_lines="8" -{!> ../../docs_src/query_params/tutorial006_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params/tutorial006.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial006_py310.py hl[8] *} In diesem Fall gibt es drei Query-Parameter: @@ -241,7 +181,7 @@ In diesem Fall gibt es drei Query-Parameter: * `skip`, ein `int` mit einem Defaultwert `0`. * `limit`, ein optionales `int`. -/// tip | "Tipp" +/// tip | Tipp Sie können auch `Enum`s verwenden, auf die gleiche Weise wie mit [Pfad-Parametern](path-params.md#vordefinierte-parameterwerte){.internal-link target=_blank}. diff --git a/docs/de/docs/tutorial/request-files.md b/docs/de/docs/tutorial/request-files.md index c0d0ef3f2e7a8..1f01b0d1ed6ee 100644 --- a/docs/de/docs/tutorial/request-files.md +++ b/docs/de/docs/tutorial/request-files.md @@ -16,69 +16,13 @@ Das, weil hochgeladene Dateien als „Formulardaten“ gesendet werden. Importieren Sie `File` und `UploadFile` von `fastapi`: -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/request_files/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1" -{!> ../../docs_src/request_files/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/request_files/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[3] *} ## `File`-Parameter definieren Erstellen Sie Datei-Parameter, so wie Sie es auch mit `Body` und `Form` machen würden: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/request_files/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/request_files/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/request_files/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[9] *} /// info @@ -88,7 +32,7 @@ Aber erinnern Sie sich, dass, wenn Sie `Query`, `Path`, `File` und andere von ` /// -/// tip | "Tipp" +/// tip | Tipp Um Dateibodys zu deklarieren, müssen Sie `File` verwenden, da diese Parameter sonst als Query-Parameter oder Body(-JSON)-Parameter interpretiert werden würden. @@ -106,35 +50,7 @@ Aber es gibt viele Fälle, in denen Sie davon profitieren, `UploadFile` zu verwe Definieren Sie einen Datei-Parameter mit dem Typ `UploadFile`: -//// tab | Python 3.9+ - -```Python hl_lines="14" -{!> ../../docs_src/request_files/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="13" -{!> ../../docs_src/request_files/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="12" -{!> ../../docs_src/request_files/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[14] *} `UploadFile` zu verwenden, hat mehrere Vorzüge gegenüber `bytes`: @@ -177,13 +93,13 @@ Wenn Sie sich innerhalb einer normalen `def`-*Pfadoperation-Funktion* befinden, contents = myfile.file.read() ``` -/// note | "Technische Details zu `async`" +/// note | Technische Details zu `async` Wenn Sie die `async`-Methoden verwenden, führt **FastAPI** die Datei-Methoden in einem Threadpool aus und erwartet sie. /// -/// note | "Technische Details zu Starlette" +/// note | Technische Details zu Starlette **FastAPI**s `UploadFile` erbt direkt von **Starlette**s `UploadFile`, fügt aber ein paar notwendige Teile hinzu, um es kompatibel mit **Pydantic** und anderen Teilen von FastAPI zu machen. @@ -195,7 +111,7 @@ HTML-Formulare (`
`) senden die Daten in einer „speziellen“ Kodi **FastAPI** stellt sicher, dass diese Daten korrekt ausgelesen werden, statt JSON zu erwarten. -/// note | "Technische Details" +/// note | Technische Details Daten aus Formularen werden, wenn es keine Dateien sind, normalerweise mit dem „media type“ `application/x-www-form-urlencoded` kodiert. @@ -205,7 +121,7 @@ Wenn Sie mehr über Formularfelder und ihre Kodierungen lesen möchten, besuchen /// -/// warning | "Achtung" +/// warning | Achtung Sie können mehrere `File`- und `Form`-Parameter in einer *Pfadoperation* deklarieren, aber Sie können nicht gleichzeitig auch `Body`-Felder deklarieren, welche Sie als JSON erwarten, da der Request den Body mittels `multipart/form-data` statt `application/json` kodiert. @@ -217,91 +133,13 @@ Das ist keine Limitation von **FastAPI**, sondern Teil des HTTP-Protokolls. Sie können eine Datei optional machen, indem Sie Standard-Typannotationen verwenden und den Defaultwert auf `None` setzen: -//// tab | Python 3.10+ - -```Python hl_lines="9 17" -{!> ../../docs_src/request_files/tutorial001_02_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9 17" -{!> ../../docs_src/request_files/tutorial001_02_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10 18" -{!> ../../docs_src/request_files/tutorial001_02_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="7 15" -{!> ../../docs_src/request_files/tutorial001_02_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="9 17" -{!> ../../docs_src/request_files/tutorial001_02.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *} ## `UploadFile` mit zusätzlichen Metadaten Sie können auch `File()` zusammen mit `UploadFile` verwenden, um zum Beispiel zusätzliche Metadaten zu setzen: -//// tab | Python 3.9+ - -```Python hl_lines="9 15" -{!> ../../docs_src/request_files/tutorial001_03_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8 14" -{!> ../../docs_src/request_files/tutorial001_03_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="7 13" -{!> ../../docs_src/request_files/tutorial001_03.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_03_an_py39.py hl[9,15] *} ## Mehrere Datei-Uploads @@ -311,53 +149,11 @@ Diese werden demselben Formularfeld zugeordnet, welches mit den Formulardaten ge Um das zu machen, deklarieren Sie eine Liste von `bytes` oder `UploadFile`s: -//// tab | Python 3.9+ - -```Python hl_lines="10 15" -{!> ../../docs_src/request_files/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11 16" -{!> ../../docs_src/request_files/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.9+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="8 13" -{!> ../../docs_src/request_files/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="10 15" -{!> ../../docs_src/request_files/tutorial002.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial002_an_py39.py hl[10,15] *} Sie erhalten, wie deklariert, eine `list`e von `bytes` oder `UploadFile`s. -/// note | "Technische Details" +/// note | Technische Details Sie können auch `from starlette.responses import HTMLResponse` verwenden. @@ -369,49 +165,7 @@ Sie können auch `from starlette.responses import HTMLResponse` verwenden. Und so wie zuvor können Sie `File()` verwenden, um zusätzliche Parameter zu setzen, sogar für `UploadFile`: -//// tab | Python 3.9+ - -```Python hl_lines="11 18-20" -{!> ../../docs_src/request_files/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="12 19-21" -{!> ../../docs_src/request_files/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.9+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="9 16" -{!> ../../docs_src/request_files/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="11 18" -{!> ../../docs_src/request_files/tutorial003.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial003_an_py39.py hl[11,18:20] *} ## Zusammenfassung diff --git a/docs/de/docs/tutorial/request-forms-and-files.md b/docs/de/docs/tutorial/request-forms-and-files.md index 2b89edbb401e4..3c5e11adff9da 100644 --- a/docs/de/docs/tutorial/request-forms-and-files.md +++ b/docs/de/docs/tutorial/request-forms-and-files.md @@ -12,75 +12,19 @@ Z. B. `pip install python-multipart`. ## `File` und `Form` importieren -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1" -{!> ../../docs_src/request_forms_and_files/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/request_forms_and_files/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[3] *} ## `File` und `Form`-Parameter definieren Erstellen Sie Datei- und Formularparameter, so wie Sie es auch mit `Body` und `Query` machen würden: -//// tab | Python 3.9+ - -```Python hl_lines="10-12" -{!> ../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9-11" -{!> ../../docs_src/request_forms_and_files/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="8" -{!> ../../docs_src/request_forms_and_files/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[10:12] *} Die Datei- und Formularfelder werden als Formulardaten hochgeladen, und Sie erhalten diese Dateien und Formularfelder. Und Sie können einige der Dateien als `bytes` und einige als `UploadFile` deklarieren. -/// warning | "Achtung" +/// warning | Achtung Sie können mehrere `File`- und `Form`-Parameter in einer *Pfadoperation* deklarieren, aber Sie können nicht gleichzeitig auch `Body`-Felder deklarieren, welche Sie als JSON erwarten, da der Request den Body mittels `multipart/form-data` statt `application/json` kodiert. diff --git a/docs/de/docs/tutorial/request-forms.md b/docs/de/docs/tutorial/request-forms.md index 0784aa8c0437b..2f88caaba104a 100644 --- a/docs/de/docs/tutorial/request-forms.md +++ b/docs/de/docs/tutorial/request-forms.md @@ -14,69 +14,13 @@ Z. B. `pip install python-multipart`. Importieren Sie `Form` von `fastapi`: -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/request_forms/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1" -{!> ../../docs_src/request_forms/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/request_forms/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[3] *} ## `Form`-Parameter definieren Erstellen Sie Formular-Parameter, so wie Sie es auch mit `Body` und `Query` machen würden: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/request_forms/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/request_forms/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/request_forms/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[9] *} Zum Beispiel stellt eine der Möglichkeiten, die OAuth2 Spezifikation zu verwenden (genannt „password flow“), die Bedingung, einen `username` und ein `password` als Formularfelder zu senden. @@ -90,7 +34,7 @@ Mit `Form` haben Sie die gleichen Konfigurationsmöglichkeiten wie mit `Body` (u /// -/// tip | "Tipp" +/// tip | Tipp Um Formularbodys zu deklarieren, verwenden Sie explizit `Form`, da diese Parameter sonst als Query-Parameter oder Body(-JSON)-Parameter interpretiert werden würden. @@ -102,7 +46,7 @@ HTML-Formulare (`
`) senden die Daten in einer „speziellen“ Kodi **FastAPI** stellt sicher, dass diese Daten korrekt ausgelesen werden, statt JSON zu erwarten. -/// note | "Technische Details" +/// note | Technische Details Daten aus Formularen werden normalerweise mit dem „media type“ `application/x-www-form-urlencoded` kodiert. @@ -112,7 +56,7 @@ Wenn Sie mehr über Formularfelder und ihre Kodierungen lesen möchten, besuchen /// -/// warning | "Achtung" +/// warning | Achtung Sie können mehrere `Form`-Parameter in einer *Pfadoperation* deklarieren, aber Sie können nicht gleichzeitig auch `Body`-Felder deklarieren, welche Sie als JSON erwarten, da der Request den Body mittels `application/x-www-form-urlencoded` statt `application/json` kodiert. diff --git a/docs/de/docs/tutorial/response-model.md b/docs/de/docs/tutorial/response-model.md index 31ad73c77042c..faf9be516ece1 100644 --- a/docs/de/docs/tutorial/response-model.md +++ b/docs/de/docs/tutorial/response-model.md @@ -4,29 +4,7 @@ Sie können den Typ der ../../docs_src/response_model/tutorial001_01_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="18 23" -{!> ../../docs_src/response_model/tutorial001_01_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18 23" -{!> ../../docs_src/response_model/tutorial001_01.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial001_01_py310.py hl[16,21] *} FastAPI wird diesen Rückgabetyp verwenden, um: @@ -59,31 +37,9 @@ Sie können `response_model` in jeder möglichen *Pfadoperation* verwenden: * `@app.delete()` * usw. -//// tab | 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!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="17 22 24-27" -{!> ../../docs_src/response_model/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17 22 24-27" -{!> ../../docs_src/response_model/tutorial001.py!} -``` - -//// - -/// note | "Hinweis" +/// note | Hinweis Beachten Sie, dass `response_model` ein Parameter der „Dekorator“-Methode ist (`get`, `post`, usw.). Nicht der *Pfadoperation-Funktion*, so wie die anderen Parameter. @@ -93,7 +49,7 @@ Beachten Sie, dass `response_model` ein Parameter der „Dekorator“-Methode is FastAPI wird dieses `response_model` nehmen, um die Daten zu dokumentieren, validieren, usw. und auch, um **die Ausgabedaten** entsprechend der Typdeklaration **zu konvertieren und filtern**. -/// tip | "Tipp" +/// tip | Tipp Wenn Sie in Ihrem Editor strikte Typchecks haben, mypy, usw., können Sie den Funktions-Rückgabetyp als `Any` deklarieren. @@ -113,21 +69,7 @@ Sie können auch `response_model=None` verwenden, um das Erstellen eines Respons Im Folgenden deklarieren wir ein `UserIn`-Modell; es enthält ein Klartext-Passwort: -//// tab | Python 3.10+ - -```Python hl_lines="7 9" -{!> ../../docs_src/response_model/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 11" -{!> ../../docs_src/response_model/tutorial002.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial002_py310.py hl[7,9] *} /// info @@ -140,21 +82,7 @@ oder `pip install pydantic[email]`. Wir verwenden dieses Modell, um sowohl unsere Eingabe- als auch Ausgabedaten zu deklarieren: -//// tab | Python 3.10+ - -```Python hl_lines="16" -{!> ../../docs_src/response_model/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18" -{!> ../../docs_src/response_model/tutorial002.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial002_py310.py hl[16] *} Immer wenn jetzt ein Browser einen Benutzer mit Passwort erzeugt, gibt die API dasselbe Passwort in der Response zurück. @@ -162,7 +90,7 @@ Hier ist das möglicherweise kein Problem, da es derselbe Benutzer ist, der das Aber wenn wir dasselbe Modell für eine andere *Pfadoperation* verwenden, könnten wir das Passwort dieses Benutzers zu jedem Client schicken. -/// danger | "Gefahr" +/// danger | Gefahr Speichern Sie niemals das Klartext-Passwort eines Benutzers, oder versenden Sie es in einer Response wie dieser, wenn Sie sich nicht der resultierenden Gefahren bewusst sind und nicht wissen, was Sie tun. @@ -172,57 +100,15 @@ Speichern Sie niemals das Klartext-Passwort eines Benutzers, oder versenden Sie Wir können stattdessen ein Eingabemodell mit dem Klartext-Passwort, und ein Ausgabemodell ohne das Passwort erstellen: -//// tab | Python 3.10+ - -```Python hl_lines="9 11 16" -{!> ../../docs_src/response_model/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 11 16" -{!> ../../docs_src/response_model/tutorial003.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_py310.py hl[9,11,16] *} Obwohl unsere *Pfadoperation-Funktion* hier denselben `user` von der Eingabe zurückgibt, der das Passwort enthält: -//// tab | Python 3.10+ - -```Python hl_lines="24" -{!> ../../docs_src/response_model/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24" -{!> ../../docs_src/response_model/tutorial003.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_py310.py hl[24] *} ... haben wir deklariert, dass `response_model` das Modell `UserOut` ist, welches das Passwort nicht enthält: -//// tab | Python 3.10+ - -```Python hl_lines="22" -{!> ../../docs_src/response_model/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="22" -{!> ../../docs_src/response_model/tutorial003.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_py310.py hl[22] *} Darum wird **FastAPI** sich darum kümmern, dass alle Daten, die nicht im Ausgabemodell deklariert sind, herausgefiltert werden (mittels Pydantic). @@ -246,21 +132,7 @@ Aber in den meisten Fällen, wenn wir so etwas machen, wollen wir nur, dass das Und in solchen Fällen können wir Klassen und Vererbung verwenden, um Vorteil aus den Typannotationen in der Funktion zu ziehen, was vom Editor und von Tools besser unterstützt wird, während wir gleichzeitig FastAPIs **Datenfilterung** behalten. -//// tab | Python 3.10+ - -```Python hl_lines="7-10 13-14 18" -{!> ../../docs_src/response_model/tutorial003_01_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9-13 15-16 20" -{!> ../../docs_src/response_model/tutorial003_01.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_01_py310.py hl[7:10,13:14,18] *} Damit erhalten wir Tool-Unterstützung, vom Editor und mypy, da dieser Code hinsichtlich der Typen korrekt ist, aber wir erhalten auch die Datenfilterung von FastAPI. @@ -302,9 +174,7 @@ Es kann Fälle geben, bei denen Sie etwas zurückgeben, das kein gültiges Pydan Der häufigste Anwendungsfall ist, wenn Sie [eine Response direkt zurückgeben, wie es später im Handbuch für fortgeschrittene Benutzer erläutert wird](../advanced/response-directly.md){.internal-link target=_blank}. -```Python hl_lines="8 10-11" -{!> ../../docs_src/response_model/tutorial003_02.py!} -``` +{* ../../docs_src/response_model/tutorial003_02.py hl[8,10:11] *} Dieser einfache Anwendungsfall wird automatisch von FastAPI gehandhabt, weil die Annotation des Rückgabetyps die Klasse (oder eine Unterklasse von) `Response` ist. @@ -314,9 +184,7 @@ Und Tools werden auch glücklich sein, weil sowohl `RedirectResponse` als auch ` Sie können auch eine Unterklasse von `Response` in der Typannotation verwenden. -```Python hl_lines="8-9" -{!> ../../docs_src/response_model/tutorial003_03.py!} -``` +{* ../../docs_src/response_model/tutorial003_03.py hl[8:9] *} Das wird ebenfalls funktionieren, weil `RedirectResponse` eine Unterklasse von `Response` ist, und FastAPI sich um diesen einfachen Anwendungsfall automatisch kümmert. @@ -326,21 +194,7 @@ Aber wenn Sie ein beliebiges anderes Objekt zurückgeben, das kein gültiger Pyd Das gleiche wird passieren, wenn Sie eine Union mehrerer Typen haben, und einer oder mehrere sind nicht gültige Pydantic-Typen. Zum Beispiel funktioniert folgendes nicht 💥: -//// tab | Python 3.10+ - -```Python hl_lines="8" -{!> ../../docs_src/response_model/tutorial003_04_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/response_model/tutorial003_04.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_04_py310.py hl[8] *} ... das scheitert, da die Typannotation kein Pydantic-Typ ist, und auch keine einzelne `Response`-Klasse, oder -Unterklasse, es ist eine Union (eines von beiden) von `Response` und `dict`. @@ -352,21 +206,7 @@ Aber Sie möchten dennoch den Rückgabetyp in der Funktion annotieren, um Unters In diesem Fall können Sie die Generierung des Responsemodells abschalten, indem Sie `response_model=None` setzen: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/response_model/tutorial003_05_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/response_model/tutorial003_05.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_05_py310.py hl[7] *} Das bewirkt, dass FastAPI die Generierung des Responsemodells unterlässt, und damit können Sie jede gewünschte Rückgabetyp-Annotation haben, ohne dass es Ihre FastAPI-Anwendung beeinflusst. 🤓 @@ -374,29 +214,7 @@ Das bewirkt, dass FastAPI die Generierung des Responsemodells unterlässt, und d Ihr Responsemodell könnte Defaultwerte haben, wie: -//// tab | Python 3.10+ - -```Python hl_lines="9 11-12" -{!> ../../docs_src/response_model/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="11 13-14" -{!> ../../docs_src/response_model/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11 13-14" -{!> ../../docs_src/response_model/tutorial004.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial004_py310.py hl[9,11:12] *} * `description: Union[str, None] = None` (oder `str | None = None` in Python 3.10) hat einen Defaultwert `None`. * `tax: float = 10.5` hat einen Defaultwert `10.5`. @@ -410,29 +228,7 @@ Wenn Sie zum Beispiel Modelle mit vielen optionalen Attributen in einer NoSQL-Da Sie können den *Pfadoperation-Dekorator*-Parameter `response_model_exclude_unset=True` setzen: -//// tab | Python 3.10+ - -```Python hl_lines="22" -{!> ../../docs_src/response_model/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="24" -{!> ../../docs_src/response_model/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24" -{!> ../../docs_src/response_model/tutorial004.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial004_py310.py hl[22] *} Die Defaultwerte werden dann nicht in der Response enthalten sein, sondern nur die tatsächlich gesetzten Werte. @@ -503,7 +299,7 @@ dann ist FastAPI klug genug (tatsächlich ist Pydantic klug genug) zu erkennen, Diese Felder werden also in der JSON-Response enthalten sein. -/// tip | "Tipp" +/// tip | Tipp Beachten Sie, dass Defaultwerte alles Mögliche sein können, nicht nur `None`. @@ -519,7 +315,7 @@ Diese nehmen ein `set` von `str`s entgegen, welches Namen von Attributen sind, d Das kann als schnelle Abkürzung verwendet werden, wenn Sie nur ein Pydantic-Modell haben und ein paar Daten von der Ausgabe ausschließen wollen. -/// tip | "Tipp" +/// tip | Tipp Es wird dennoch empfohlen, dass Sie die Ideen von oben verwenden, also mehrere Klassen statt dieser Parameter. @@ -529,23 +325,9 @@ Das trifft auch auf `response_model_by_alias` zu, welches ähnlich funktioniert. /// -//// tab | Python 3.10+ +{* ../../docs_src/response_model/tutorial005_py310.py hl[29,35] *} -```Python hl_lines="29 35" -{!> ../../docs_src/response_model/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="31 37" -{!> ../../docs_src/response_model/tutorial005.py!} -``` - -//// - -/// tip | "Tipp" +/// tip | Tipp Die Syntax `{"name", "description"}` erzeugt ein `set` mit diesen zwei Werten. @@ -557,21 +339,7 @@ Die Syntax `{"name", "description"}` erzeugt ein `set` mit diesen zwei Werten. Wenn Sie vergessen, ein `set` zu verwenden, und stattdessen eine `list`e oder ein `tuple` übergeben, wird FastAPI die dennoch in ein `set` konvertieren, und es wird korrekt funktionieren: -//// tab | Python 3.10+ - -```Python hl_lines="29 35" -{!> ../../docs_src/response_model/tutorial006_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="31 37" -{!> ../../docs_src/response_model/tutorial006.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial006_py310.py hl[29,35] *} ## Zusammenfassung diff --git a/docs/de/docs/tutorial/response-status-code.md b/docs/de/docs/tutorial/response-status-code.md index 5f017355bc722..a1b388a0a3b6b 100644 --- a/docs/de/docs/tutorial/response-status-code.md +++ b/docs/de/docs/tutorial/response-status-code.md @@ -10,7 +10,7 @@ So wie ein Responsemodell, können Sie auch einen HTTP-Statuscode für die Respo {* ../../docs_src/response_status_code/tutorial001.py hl[6] *} -/// note | "Hinweis" +/// note | Hinweis Beachten Sie, dass `status_code` ein Parameter der „Dekorator“-Methode ist (`get`, `post`, usw.). Nicht der *Pfadoperation-Funktion*, so wie die anderen Parameter und der Body. @@ -31,7 +31,7 @@ Das wird: -/// note | "Hinweis" +/// note | Hinweis Einige Responsecodes (siehe nächster Abschnitt) kennzeichnen, dass die Response keinen Body hat. @@ -41,7 +41,7 @@ FastAPI versteht das und wird in der OpenAPI-Dokumentation anzeigen, dass es kei ## Über HTTP-Statuscodes -/// note | "Hinweis" +/// note | Hinweis Wenn Sie bereits wissen, was HTTP-Statuscodes sind, überspringen Sie dieses Kapitel und fahren Sie mit dem nächsten fort. @@ -64,7 +64,7 @@ Kurz: * Für allgemeine Fehler beim Client können Sie einfach `400` verwenden. * `500` und darüber stehen für Server-Fehler. Diese verwenden Sie fast nie direkt. Wenn etwas an irgendeiner Stelle in Ihrem Anwendungscode oder im Server schiefläuft, wird automatisch einer dieser Fehler-Statuscodes zurückgegeben. -/// tip | "Tipp" +/// tip | Tipp Um mehr über Statuscodes zu lernen, und welcher wofür verwendet wird, lesen Sie die MDN Dokumentation über HTTP-Statuscodes. @@ -88,7 +88,7 @@ Diese sind nur eine Annehmlichkeit und enthalten dieselbe Nummer, aber auf diese -/// note | "Technische Details" +/// note | Technische Details Sie können auch `from starlette import status` verwenden. diff --git a/docs/de/docs/tutorial/schema-extra-example.md b/docs/de/docs/tutorial/schema-extra-example.md index 0da1a4ea4ba20..f065ad4caaa51 100644 --- a/docs/de/docs/tutorial/schema-extra-example.md +++ b/docs/de/docs/tutorial/schema-extra-example.md @@ -8,35 +8,15 @@ Hier sind mehrere Möglichkeiten, das zu tun. Sie können `examples` („Beispiele“) für ein Pydantic-Modell deklarieren, welche dem generierten JSON-Schema hinzugefügt werden. -//// tab | Python 3.10+ Pydantic v2 - -```Python hl_lines="13-24" -{!> ../../docs_src/schema_extra_example/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.10+ Pydantic v1 - -```Python hl_lines="13-23" -{!> ../../docs_src/schema_extra_example/tutorial001_py310_pv1.py!} -``` - -//// - -//// tab | Python 3.8+ Pydantic v2 +//// tab | Pydantic v2 -```Python hl_lines="15-26" -{!> ../../docs_src/schema_extra_example/tutorial001.py!} -``` +{* ../../docs_src/schema_extra_example/tutorial001_py310.py hl[13:24] *} //// -//// tab | Python 3.8+ Pydantic v1 +//// tab | Pydantic v1 -```Python hl_lines="15-25" -{!> ../../docs_src/schema_extra_example/tutorial001_pv1.py!} -``` +{* ../../docs_src/schema_extra_example/tutorial001_pv1_py310.py hl[13:23] *} //// @@ -58,7 +38,7 @@ Sie können `schema_extra` setzen, mit einem `dict`, das alle zusätzlichen Date //// -/// tip | "Tipp" +/// tip | Tipp Mit derselben Technik können Sie das JSON-Schema erweitern und Ihre eigenen benutzerdefinierten Zusatzinformationen hinzufügen. @@ -80,21 +60,7 @@ Mehr erfahren Sie am Ende dieser Seite. Wenn Sie `Field()` mit Pydantic-Modellen verwenden, können Sie ebenfalls zusätzliche `examples` deklarieren: -//// tab | Python 3.10+ - -```Python hl_lines="2 8-11" -{!> ../../docs_src/schema_extra_example/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4 10-13" -{!> ../../docs_src/schema_extra_example/tutorial002.py!} -``` - -//// +{* ../../docs_src/schema_extra_example/tutorial002_py310.py hl[2,8:11] *} ## `examples` im JSON-Schema – OpenAPI @@ -114,57 +80,7 @@ können Sie auch eine Gruppe von `examples` mit zusätzlichen Informationen dekl Hier übergeben wir `examples`, welches ein einzelnes Beispiel für die in `Body()` erwarteten Daten enthält: -//// tab | Python 3.10+ - -```Python hl_lines="22-29" -{!> ../../docs_src/schema_extra_example/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="22-29" -{!> ../../docs_src/schema_extra_example/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="23-30" -{!> ../../docs_src/schema_extra_example/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="18-25" -{!> ../../docs_src/schema_extra_example/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="20-27" -{!> ../../docs_src/schema_extra_example/tutorial003.py!} -``` - -//// +{* ../../docs_src/schema_extra_example/tutorial003_an_py310.py hl[22:29] *} ### Beispiel in der Dokumentations-Benutzeroberfläche @@ -176,57 +92,7 @@ Mit jeder der oben genannten Methoden würde es in `/docs` so aussehen: Sie können natürlich auch mehrere `examples` übergeben: -//// tab | Python 3.10+ - -```Python hl_lines="23-38" -{!> ../../docs_src/schema_extra_example/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="23-38" -{!> ../../docs_src/schema_extra_example/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24-39" -{!> ../../docs_src/schema_extra_example/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="19-34" -{!> ../../docs_src/schema_extra_example/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="21-36" -{!> ../../docs_src/schema_extra_example/tutorial004.py!} -``` - -//// +{* ../../docs_src/schema_extra_example/tutorial004_an_py310.py hl[23:38] *} Wenn Sie das tun, werden die Beispiele Teil des internen **JSON-Schemas** für diese Body-Daten. @@ -267,57 +133,7 @@ Jedes spezifische Beispiel-`dict` in den `examples` kann Folgendes enthalten: Sie können es so verwenden: -//// tab | Python 3.10+ - -```Python hl_lines="23-49" -{!> ../../docs_src/schema_extra_example/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="23-49" -{!> ../../docs_src/schema_extra_example/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24-50" -{!> ../../docs_src/schema_extra_example/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="19-45" -{!> ../../docs_src/schema_extra_example/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="21-47" -{!> ../../docs_src/schema_extra_example/tutorial005.py!} -``` - -//// +{* ../../docs_src/schema_extra_example/tutorial005_an_py310.py hl[23:49] *} ### OpenAPI-Beispiele in der Dokumentations-Benutzeroberfläche @@ -327,7 +143,7 @@ Wenn `openapi_examples` zu `Body()` hinzugefügt wird, würde `/docs` so aussehe ## Technische Details -/// tip | "Tipp" +/// tip | Tipp Wenn Sie bereits **FastAPI** Version **0.99.0 oder höher** verwenden, können Sie diese Details wahrscheinlich **überspringen**. @@ -337,7 +153,7 @@ Sie können dies als eine kurze **Geschichtsstunde** zu OpenAPI und JSON Schema /// -/// warning | "Achtung" +/// warning | Achtung Dies sind sehr technische Details zu den Standards **JSON Schema** und **OpenAPI**. diff --git a/docs/de/docs/tutorial/security/first-steps.md b/docs/de/docs/tutorial/security/first-steps.md index c552a681bea43..8fa33db7ef23d 100644 --- a/docs/de/docs/tutorial/security/first-steps.md +++ b/docs/de/docs/tutorial/security/first-steps.md @@ -20,35 +20,7 @@ Lassen Sie uns zunächst einfach den Code verwenden und sehen, wie er funktionie Kopieren Sie das Beispiel in eine Datei `main.py`: -//// tab | Python 3.9+ - -```Python -{!> ../../docs_src/security/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python -{!> ../../docs_src/security/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python -{!> ../../docs_src/security/tutorial001.py!} -``` - -//// +{* ../../docs_src/security/tutorial001_an_py39.py *} ## Ausführen @@ -82,7 +54,7 @@ Sie werden etwa Folgendes sehen: -/// check | "Authorize-Button!" +/// check | Authorize-Button! Sie haben bereits einen glänzenden, neuen „Authorize“-Button. @@ -94,7 +66,7 @@ Und wenn Sie darauf klicken, erhalten Sie ein kleines Anmeldeformular zur Eingab -/// note | "Hinweis" +/// note | Hinweis Es spielt keine Rolle, was Sie in das Formular eingeben, es wird noch nicht funktionieren. Wir kommen dahin. @@ -154,37 +126,9 @@ In dem Fall gibt Ihnen **FastAPI** ebenfalls die Tools, die Sie zum Erstellen br Wenn wir eine Instanz der Klasse `OAuth2PasswordBearer` erstellen, übergeben wir den Parameter `tokenUrl`. Dieser Parameter enthält die URL, die der Client (das Frontend, das im Browser des Benutzers ausgeführt wird) verwendet, wenn er den `username` und das `password` sendet, um einen Token zu erhalten. -//// tab | Python 3.9+ - -```Python hl_lines="8" -{!> ../../docs_src/security/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="7" -{!> ../../docs_src/security/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="6" -{!> ../../docs_src/security/tutorial001.py!} -``` - -//// +{* ../../docs_src/security/tutorial001_an_py39.py hl[8] *} -/// tip | "Tipp" +/// 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`. @@ -220,41 +164,13 @@ Es kann also mit `Depends` verwendet werden. Jetzt können Sie dieses `oauth2_scheme` als Abhängigkeit `Depends` übergeben. -//// tab | Python 3.9+ - -```Python hl_lines="12" -{!> ../../docs_src/security/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/security/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/security/tutorial001.py!} -``` - -//// +{* ../../docs_src/security/tutorial001_an_py39.py hl[12] *} Diese Abhängigkeit stellt einen `str` bereit, der dem Parameter `token` der *Pfadoperation-Funktion* zugewiesen wird. **FastAPI** weiß, dass es diese Abhängigkeit verwenden kann, um ein „Sicherheitsschema“ im OpenAPI-Schema (und der automatischen API-Dokumentation) zu definieren. -/// info | "Technische Details" +/// info | Technische Details **FastAPI** weiß, dass es die Klasse `OAuth2PasswordBearer` (deklariert in einer Abhängigkeit) verwenden kann, um das Sicherheitsschema in OpenAPI zu definieren, da es von `fastapi.security.oauth2.OAuth2` erbt, das wiederum von `fastapi.security.base.SecurityBase` erbt. diff --git a/docs/de/docs/tutorial/security/get-current-user.md b/docs/de/docs/tutorial/security/get-current-user.md index a9478a36e95d8..38f7ffcbfc5e8 100644 --- a/docs/de/docs/tutorial/security/get-current-user.md +++ b/docs/de/docs/tutorial/security/get-current-user.md @@ -2,35 +2,7 @@ Im vorherigen Kapitel hat das Sicherheitssystem (das auf dem Dependency Injection System basiert) der *Pfadoperation-Funktion* einen `token` vom Typ `str` überreicht: -//// tab | Python 3.9+ - -```Python hl_lines="12" -{!> ../../docs_src/security/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/security/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/security/tutorial001.py!} -``` - -//// +{* ../../docs_src/security/tutorial001_an_py39.py hl[12] *} Aber das ist immer noch nicht so nützlich. @@ -42,57 +14,7 @@ Erstellen wir zunächst ein Pydantic-Benutzermodell. So wie wir Pydantic zum Deklarieren von Bodys verwenden, können wir es auch überall sonst verwenden: -//// tab | Python 3.10+ - -```Python hl_lines="5 12-16" -{!> ../../docs_src/security/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="5 12-16" -{!> ../../docs_src/security/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="5 13-17" -{!> ../../docs_src/security/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="3 10-14" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="5 12-16" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// +{* ../../docs_src/security/tutorial002_an_py310.py hl[5,12:16] *} ## Eine `get_current_user`-Abhängigkeit erstellen @@ -104,175 +26,25 @@ Erinnern Sie sich, dass Abhängigkeiten Unterabhängigkeiten haben können? So wie wir es zuvor in der *Pfadoperation* direkt gemacht haben, erhält unsere neue Abhängigkeit `get_current_user` von der Unterabhängigkeit `oauth2_scheme` einen `token` vom Typ `str`: -//// tab | Python 3.10+ - -```Python hl_lines="25" -{!> ../../docs_src/security/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="25" -{!> ../../docs_src/security/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="26" -{!> ../../docs_src/security/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="23" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="25" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// +{* ../../docs_src/security/tutorial002_an_py310.py hl[25] *} ## Den Benutzer holen `get_current_user` wird eine von uns erstellte (gefakte) Hilfsfunktion verwenden, welche einen Token vom Typ `str` entgegennimmt und unser Pydantic-`User`-Modell zurückgibt: -//// tab | Python 3.10+ - -```Python hl_lines="19-22 26-27" -{!> ../../docs_src/security/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="19-22 26-27" -{!> ../../docs_src/security/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20-23 27-28" -{!> ../../docs_src/security/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="17-20 24-25" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="19-22 26-27" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// +{* ../../docs_src/security/tutorial002_an_py310.py hl[19:22,26:27] *} ## Den aktuellen Benutzer einfügen Und jetzt können wir wiederum `Depends` mit unserem `get_current_user` in der *Pfadoperation* verwenden: -//// tab | Python 3.10+ - -```Python hl_lines="31" -{!> ../../docs_src/security/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="31" -{!> ../../docs_src/security/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="32" -{!> ../../docs_src/security/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="29" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="31" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// +{* ../../docs_src/security/tutorial002_an_py310.py hl[31] *} Beachten Sie, dass wir als Typ von `current_user` das Pydantic-Modell `User` deklarieren. Das wird uns innerhalb der Funktion bei Codevervollständigung und Typprüfungen helfen. -/// tip | "Tipp" +/// tip | Tipp Sie erinnern sich vielleicht, dass Requestbodys ebenfalls mit Pydantic-Modellen deklariert werden. @@ -320,57 +92,7 @@ Und alle (oder beliebige Teile davon) können Vorteil ziehen aus der Wiederverwe Und alle diese Tausenden von *Pfadoperationen* können nur drei Zeilen lang sein: -//// tab | Python 3.10+ - -```Python hl_lines="30-32" -{!> ../../docs_src/security/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="30-32" -{!> ../../docs_src/security/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="31-33" -{!> ../../docs_src/security/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="28-30" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="30-32" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// +{* ../../docs_src/security/tutorial002_an_py310.py hl[30:32] *} ## Zusammenfassung diff --git a/docs/de/docs/tutorial/security/index.md b/docs/de/docs/tutorial/security/index.md index ad09273610bf0..b0124390174da 100644 --- a/docs/de/docs/tutorial/security/index.md +++ b/docs/de/docs/tutorial/security/index.md @@ -32,7 +32,7 @@ Heutzutage ist es nicht sehr populär und wird kaum verwendet. OAuth2 spezifiziert nicht, wie die Kommunikation verschlüsselt werden soll, sondern erwartet, dass Ihre Anwendung mit HTTPS bereitgestellt wird. -/// tip | "Tipp" +/// tip | Tipp Im Abschnitt über **Deployment** erfahren Sie, wie Sie HTTPS mithilfe von Traefik und Let's Encrypt kostenlos einrichten. @@ -89,7 +89,7 @@ OpenAPI definiert die folgenden Sicherheitsschemas: * Diese automatische Erkennung ist es, die in der OpenID Connect Spezifikation definiert ist. -/// tip | "Tipp" +/// tip | Tipp Auch die Integration anderer Authentifizierungs-/Autorisierungsanbieter wie Google, Facebook, Twitter, GitHub, usw. ist möglich und relativ einfach. diff --git a/docs/de/docs/tutorial/security/oauth2-jwt.md b/docs/de/docs/tutorial/security/oauth2-jwt.md index 79e8178408bdd..178a95d81dea6 100644 --- a/docs/de/docs/tutorial/security/oauth2-jwt.md +++ b/docs/de/docs/tutorial/security/oauth2-jwt.md @@ -44,7 +44,7 @@ $ pip install "python-jose[cryptography]" Hier verwenden wir das empfohlene: pyca/cryptography. -/// tip | "Tipp" +/// tip | Tipp Dieses Tutorial verwendete zuvor PyJWT. @@ -86,7 +86,7 @@ $ pip install "passlib[bcrypt]" -/// tip | "Tipp" +/// tip | Tipp Mit `passlib` können Sie sogar konfigurieren, Passwörter zu lesen, die von **Django**, einem **Flask**-Sicherheit-Plugin, oder vielen anderen erstellt wurden. @@ -102,7 +102,7 @@ Importieren Sie die benötigten Tools aus `passlib`. Erstellen Sie einen PassLib-„Kontext“. Der wird für das Hashen und Verifizieren von Passwörtern verwendet. -/// tip | "Tipp" +/// tip | Tipp Der PassLib-Kontext kann auch andere Hashing-Algorithmen verwenden, einschließlich deprecateter Alter, um etwa nur eine Verifizierung usw. zu ermöglichen. @@ -118,59 +118,9 @@ Und eine weitere, um zu überprüfen, ob ein empfangenes Passwort mit dem gespei Und noch eine, um einen Benutzer zu authentifizieren und zurückzugeben. -//// tab | Python 3.10+ +{* ../../docs_src/security/tutorial004_an_py310.py hl[7,48,55:56,59:60,69:75] *} -```Python hl_lines="7 48 55-56 59-60 69-75" -{!> ../../docs_src/security/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="7 48 55-56 59-60 69-75" -{!> ../../docs_src/security/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="7 49 56-57 60-61 70-76" -{!> ../../docs_src/security/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="6 47 54-55 58-59 68-74" -{!> ../../docs_src/security/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="7 48 55-56 59-60 69-75" -{!> ../../docs_src/security/tutorial004.py!} -``` - -//// - -/// note | "Hinweis" +/// note | Hinweis Wenn Sie sich die neue (gefakte) Datenbank `fake_users_db` anschauen, sehen Sie, wie das gehashte Passwort jetzt aussieht: `"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`. @@ -204,57 +154,7 @@ Definieren Sie ein Pydantic-Modell, das im Token-Endpunkt für die Response verw Erstellen Sie eine Hilfsfunktion, um einen neuen Zugriffstoken zu generieren. -//// tab | Python 3.10+ - -```Python hl_lines="6 12-14 28-30 78-86" -{!> ../../docs_src/security/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="6 12-14 28-30 78-86" -{!> ../../docs_src/security/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="6 13-15 29-31 79-87" -{!> ../../docs_src/security/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="5 11-13 27-29 77-85" -{!> ../../docs_src/security/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="6 12-14 28-30 78-86" -{!> ../../docs_src/security/tutorial004.py!} -``` - -//// +{* ../../docs_src/security/tutorial004_an_py310.py hl[6,12:14,28:30,78:86] *} ## Die Abhängigkeiten aktualisieren @@ -264,57 +164,7 @@ Dekodieren Sie den empfangenen Token, validieren Sie ihn und geben Sie den aktue Wenn der Token ungültig ist, geben Sie sofort einen HTTP-Fehler zurück. -//// tab | Python 3.10+ - -```Python hl_lines="89-106" -{!> ../../docs_src/security/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="89-106" -{!> ../../docs_src/security/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="90-107" -{!> ../../docs_src/security/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="88-105" -{!> ../../docs_src/security/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="89-106" -{!> ../../docs_src/security/tutorial004.py!} -``` - -//// +{* ../../docs_src/security/tutorial004_an_py310.py hl[89:106] *} ## Die *Pfadoperation* `/token` aktualisieren @@ -322,57 +172,7 @@ Erstellen Sie ein `timedelta` mit der Ablaufz Erstellen Sie einen echten JWT-Zugriffstoken und geben Sie ihn zurück. -//// tab | Python 3.10+ - -```Python hl_lines="117-132" -{!> ../../docs_src/security/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="117-132" -{!> ../../docs_src/security/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="118-133" -{!> ../../docs_src/security/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="114-129" -{!> ../../docs_src/security/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="115-130" -{!> ../../docs_src/security/tutorial004.py!} -``` - -//// +{* ../../docs_src/security/tutorial004_an_py310.py hl[117:132] *} ### Technische Details zum JWT-„Subjekt“ `sub` @@ -436,7 +236,7 @@ Wenn Sie die Developer Tools öffnen, können Sie sehen, dass die gesendeten Dat -/// note | "Hinweis" +/// note | Hinweis Beachten Sie den Header `Authorization` mit einem Wert, der mit `Bearer` beginnt. diff --git a/docs/de/docs/tutorial/security/simple-oauth2.md b/docs/de/docs/tutorial/security/simple-oauth2.md index 4c20fae5570fb..c0c93cd26d677 100644 --- a/docs/de/docs/tutorial/security/simple-oauth2.md +++ b/docs/de/docs/tutorial/security/simple-oauth2.md @@ -52,57 +52,7 @@ Lassen Sie uns nun die von **FastAPI** bereitgestellten Werkzeuge verwenden, um Importieren Sie zunächst `OAuth2PasswordRequestForm` und verwenden Sie es als Abhängigkeit mit `Depends` in der *Pfadoperation* für `/token`: -//// tab | Python 3.10+ - -```Python hl_lines="4 78" -{!> ../../docs_src/security/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="4 78" -{!> ../../docs_src/security/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4 79" -{!> ../../docs_src/security/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="2 74" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="4 76" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// +{* ../../docs_src/security/tutorial003_an_py310.py hl[4,78] *} `OAuth2PasswordRequestForm` ist eine Klassenabhängigkeit, die einen Formularbody deklariert mit: @@ -111,7 +61,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. * Einem optionalen `scope`-Feld als langem String, bestehend aus durch Leerzeichen getrennten Strings. * Einem optionalen `grant_type` („Art der Anmeldung“). -/// tip | "Tipp" +/// tip | Tipp Die OAuth2-Spezifikation *erfordert* tatsächlich ein Feld `grant_type` mit dem festen Wert `password`, aber `OAuth2PasswordRequestForm` erzwingt dies nicht. @@ -136,7 +86,7 @@ Da es sich jedoch um einen häufigen Anwendungsfall handelt, wird er zur Vereinf ### Die Formulardaten verwenden -/// tip | "Tipp" +/// tip | Tipp Die Instanz der Klassenabhängigkeit `OAuth2PasswordRequestForm` verfügt, statt eines Attributs `scope` mit dem durch Leerzeichen getrennten langen String, über das Attribut `scopes` mit einer tatsächlichen Liste von Strings, einem für jeden gesendeten Scope. @@ -150,57 +100,7 @@ Wenn es keinen solchen Benutzer gibt, geben wir die Fehlermeldung „Incorrect u Für den Fehler verwenden wir die Exception `HTTPException`: -//// tab | Python 3.10+ - -```Python hl_lines="3 79-81" -{!> ../../docs_src/security/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="3 79-81" -{!> ../../docs_src/security/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3 80-82" -{!> ../../docs_src/security/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="1 75-77" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="3 77-79" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// +{* ../../docs_src/security/tutorial003_an_py310.py hl[3,79:81] *} ### Das Passwort überprüfen @@ -226,57 +126,7 @@ Wenn Ihre Datenbank gestohlen wird, hat der Dieb nicht die Klartext-Passwörter Der Dieb kann also nicht versuchen, die gleichen Passwörter in einem anderen System zu verwenden (da viele Benutzer überall das gleiche Passwort verwenden, wäre dies gefährlich). -//// tab | Python 3.10+ - -```Python hl_lines="82-85" -{!> ../../docs_src/security/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="82-85" -{!> ../../docs_src/security/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="83-86" -{!> ../../docs_src/security/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="78-81" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="80-83" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// +{* ../../docs_src/security/tutorial003_an_py310.py hl[82:85] *} #### Über `**user_dict` @@ -310,7 +160,7 @@ Und es sollte einen `access_token` haben, mit einem String, der unseren Zugriffs In diesem einfachen Beispiel gehen wir einfach völlig unsicher vor und geben denselben `username` wie der Token zurück. -/// tip | "Tipp" +/// tip | Tipp Im nächsten Kapitel sehen Sie eine wirklich sichere Implementierung mit Passwort-Hashing und JWT-Tokens. @@ -318,59 +168,9 @@ Aber konzentrieren wir uns zunächst auf die spezifischen Details, die wir benö /// -//// tab | Python 3.10+ - -```Python hl_lines="87" -{!> ../../docs_src/security/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="87" -{!> ../../docs_src/security/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="88" -{!> ../../docs_src/security/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="83" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" +{* ../../docs_src/security/tutorial003_an_py310.py hl[87] *} -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="85" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// - -/// tip | "Tipp" +/// tip | Tipp Gemäß der Spezifikation sollten Sie ein JSON mit einem `access_token` und einem `token_type` zurückgeben, genau wie in diesem Beispiel. @@ -394,57 +194,7 @@ Beide Abhängigkeiten geben nur dann einen HTTP-Error zurück, wenn der Benutzer In unserem Endpunkt erhalten wir also nur dann einen Benutzer, wenn der Benutzer existiert, korrekt authentifiziert wurde und aktiv ist: -//// tab | Python 3.10+ - -```Python hl_lines="58-66 69-74 94" -{!> ../../docs_src/security/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="58-66 69-74 94" -{!> ../../docs_src/security/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="59-67 70-75 95" -{!> ../../docs_src/security/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="56-64 67-70 88" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="58-66 69-72 90" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// +{* ../../docs_src/security/tutorial003_an_py310.py hl[58:66,69:74,94] *} /// info diff --git a/docs/de/docs/tutorial/static-files.md b/docs/de/docs/tutorial/static-files.md index 4afd251aa04e1..50e86d68ec336 100644 --- a/docs/de/docs/tutorial/static-files.md +++ b/docs/de/docs/tutorial/static-files.md @@ -7,11 +7,9 @@ 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" +/// note | Technische Details Sie könnten auch `from starlette.staticfiles import StaticFiles` verwenden. diff --git a/docs/de/docs/tutorial/testing.md b/docs/de/docs/tutorial/testing.md index bda6d7d60779f..e7c1dda951bcd 100644 --- a/docs/de/docs/tutorial/testing.md +++ b/docs/de/docs/tutorial/testing.md @@ -26,11 +26,9 @@ 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" +/// tip | Tipp Beachten Sie, dass die Testfunktionen normal `def` und nicht `async def` sind. @@ -40,7 +38,7 @@ Dadurch können Sie `pytest` ohne Komplikationen direkt nutzen. /// -/// note | "Technische Details" +/// note | Technische Details Sie könnten auch `from starlette.testclient import TestClient` verwenden. @@ -48,7 +46,7 @@ Sie könnten auch `from starlette.testclient import TestClient` verwenden. /// -/// tip | "Tipp" +/// tip | Tipp Wenn Sie in Ihren Tests neben dem Senden von Anfragen an Ihre FastAPI-Anwendung auch `async`-Funktionen aufrufen möchten (z. B. asynchrone Datenbankfunktionen), werfen Sie einen Blick auf die [Async-Tests](../advanced/async-tests.md){.internal-link target=_blank} im Handbuch für fortgeschrittene Benutzer. @@ -74,9 +72,8 @@ Nehmen wir an, Sie haben eine Dateistruktur wie in [Größere Anwendungen](bigge In der Datei `main.py` haben Sie Ihre **FastAPI**-Anwendung: -```Python -{!../../docs_src/app_testing/main.py!} -``` +{* ../../docs_src/app_testing/main.py *} + ### Testdatei @@ -92,9 +89,8 @@ Dann könnten Sie eine Datei `test_main.py` mit Ihren Tests haben. Sie könnte s Da sich diese Datei im selben Package befindet, können Sie relative Importe verwenden, um das Objekt `app` aus dem `main`-Modul (`main.py`) zu importieren: -```Python hl_lines="3" -{!../../docs_src/app_testing/test_main.py!} -``` +{* ../../docs_src/app_testing/test_main.py hl[3] *} + ... und haben den Code für die Tests wie zuvor. @@ -148,7 +144,7 @@ Beide *Pfadoperationen* erfordern einen `X-Token`-Header. //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -162,7 +158,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -178,9 +174,8 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. Anschließend könnten Sie `test_main.py` mit den erweiterten Tests aktualisieren: -```Python -{!> ../../docs_src/app_testing/app_b/test_main.py!} -``` +{* ../../docs_src/app_testing/app_b/test_main.py *} + Wenn Sie möchten, dass der Client Informationen im Request übergibt und Sie nicht wissen, wie das geht, können Sie suchen (googeln), wie es mit `httpx` gemacht wird, oder sogar, wie es mit `requests` gemacht wird, da das Design von HTTPX auf dem Design von Requests basiert. diff --git a/docs/em/docs/advanced/additional-responses.md b/docs/em/docs/advanced/additional-responses.md index e4442135e14c0..655fc7ab6f159 100644 --- a/docs/em/docs/advanced/additional-responses.md +++ b/docs/em/docs/advanced/additional-responses.md @@ -26,9 +26,7 @@ 🖼, 📣 ➕1️⃣ 📨 ⏮️ 👔 📟 `404` & Pydantic 🏷 `Message`, 👆 💪 ✍: -```Python hl_lines="18 22" -{!../../docs_src/additional_responses/tutorial001.py!} -``` +{* ../../docs_src/additional_responses/tutorial001.py hl[18,22] *} /// note @@ -177,9 +175,7 @@ 🖼, 👆 💪 🚮 🌖 📻 🆎 `image/png`, 📣 👈 👆 *➡ 🛠️* 💪 📨 🎻 🎚 (⏮️ 📻 🆎 `application/json`) ⚖️ 🇩🇴 🖼: -```Python hl_lines="19-24 28" -{!../../docs_src/additional_responses/tutorial002.py!} -``` +{* ../../docs_src/additional_responses/tutorial002.py hl[19:24,28] *} /// note @@ -207,9 +203,7 @@ & 📨 ⏮️ 👔 📟 `200` 👈 ⚙️ 👆 `response_model`, ✋️ 🔌 🛃 `example`: -```Python hl_lines="20-31" -{!../../docs_src/additional_responses/tutorial003.py!} -``` +{* ../../docs_src/additional_responses/tutorial003.py hl[20:31] *} ⚫️ 🔜 🌐 🌀 & 🔌 👆 🗄, & 🎦 🛠️ 🩺: @@ -243,9 +237,7 @@ new_dict = {**old_dict, "new key": "new value"} 🖼: -```Python hl_lines="13-17 26" -{!../../docs_src/additional_responses/tutorial004.py!} -``` +{* ../../docs_src/additional_responses/tutorial004.py hl[13:17,26] *} ## 🌖 ℹ 🔃 🗄 📨 diff --git a/docs/em/docs/advanced/additional-status-codes.md b/docs/em/docs/advanced/additional-status-codes.md index 7a50e1bcadbfd..907c7e68ee132 100644 --- a/docs/em/docs/advanced/additional-status-codes.md +++ b/docs/em/docs/advanced/additional-status-codes.md @@ -14,9 +14,7 @@ 🏆 👈, 🗄 `JSONResponse`, & 📨 👆 🎚 📤 🔗, ⚒ `status_code` 👈 👆 💚: -```Python hl_lines="4 25" -{!../../docs_src/additional_status_codes/tutorial001.py!} -``` +{* ../../docs_src/additional_status_codes/tutorial001.py hl[4,25] *} /// warning @@ -28,7 +26,7 @@ /// -/// note | "📡 ℹ" +/// note | 📡 ℹ 👆 💪 ⚙️ `from starlette.responses import JSONResponse`. diff --git a/docs/em/docs/advanced/advanced-dependencies.md b/docs/em/docs/advanced/advanced-dependencies.md index 721428ce4ddc4..3404c2687272b 100644 --- a/docs/em/docs/advanced/advanced-dependencies.md +++ b/docs/em/docs/advanced/advanced-dependencies.md @@ -18,9 +18,7 @@ 👈, 👥 📣 👩‍🔬 `__call__`: -```Python hl_lines="10" -{!../../docs_src/dependencies/tutorial011.py!} -``` +{* ../../docs_src/dependencies/tutorial011.py hl[10] *} 👉 💼, 👉 `__call__` ⚫️❔ **FastAPI** 🔜 ⚙️ ✅ 🌖 🔢 & 🎧-🔗, & 👉 ⚫️❔ 🔜 🤙 🚶‍♀️ 💲 🔢 👆 *➡ 🛠️ 🔢* ⏪. @@ -28,9 +26,7 @@ & 🔜, 👥 💪 ⚙️ `__init__` 📣 🔢 👐 👈 👥 💪 ⚙️ "🔗" 🔗: -```Python hl_lines="7" -{!../../docs_src/dependencies/tutorial011.py!} -``` +{* ../../docs_src/dependencies/tutorial011.py hl[7] *} 👉 💼, **FastAPI** 🏆 🚫 ⏱ 👆 ⚖️ 💅 🔃 `__init__`, 👥 🔜 ⚙️ ⚫️ 🔗 👆 📟. @@ -38,9 +34,7 @@ 👥 💪 ✍ 👐 👉 🎓 ⏮️: -```Python hl_lines="16" -{!../../docs_src/dependencies/tutorial011.py!} -``` +{* ../../docs_src/dependencies/tutorial011.py hl[16] *} & 👈 🌌 👥 💪 "🔗" 👆 🔗, 👈 🔜 ✔️ `"bar"` 🔘 ⚫️, 🔢 `checker.fixed_content`. @@ -56,9 +50,7 @@ checker(q="somequery") ...& 🚶‍♀️ ⚫️❔ 👈 📨 💲 🔗 👆 *➡ 🛠️ 🔢* 🔢 `fixed_content_included`: -```Python hl_lines="20" -{!../../docs_src/dependencies/tutorial011.py!} -``` +{* ../../docs_src/dependencies/tutorial011.py hl[20] *} /// tip diff --git a/docs/em/docs/advanced/async-tests.md b/docs/em/docs/advanced/async-tests.md index 4d468acd4a172..283d4aa097c9a 100644 --- a/docs/em/docs/advanced/async-tests.md +++ b/docs/em/docs/advanced/async-tests.md @@ -32,15 +32,11 @@ 📁 `main.py` 🔜 ✔️: -```Python -{!../../docs_src/async_tests/main.py!} -``` +{* ../../docs_src/async_tests/main.py *} 📁 `test_main.py` 🔜 ✔️ 💯 `main.py`, ⚫️ 💪 👀 💖 👉 🔜: -```Python -{!../../docs_src/async_tests/test_main.py!} -``` +{* ../../docs_src/async_tests/test_main.py *} ## 🏃 ⚫️ @@ -60,9 +56,7 @@ $ pytest 📑 `@pytest.mark.anyio` 💬 ✳ 👈 👉 💯 🔢 🔜 🤙 🔁: -```Python hl_lines="7" -{!../../docs_src/async_tests/test_main.py!} -``` +{* ../../docs_src/async_tests/test_main.py hl[7] *} /// tip @@ -72,9 +66,7 @@ $ pytest ⤴️ 👥 💪 ✍ `AsyncClient` ⏮️ 📱, & 📨 🔁 📨 ⚫️, ⚙️ `await`. -```Python hl_lines="9-12" -{!../../docs_src/async_tests/test_main.py!} -``` +{* ../../docs_src/async_tests/test_main.py hl[9:12] *} 👉 🌓: diff --git a/docs/em/docs/advanced/behind-a-proxy.md b/docs/em/docs/advanced/behind-a-proxy.md index e66ddccf75a3f..8b14152c9d238 100644 --- a/docs/em/docs/advanced/behind-a-proxy.md +++ b/docs/em/docs/advanced/behind-a-proxy.md @@ -80,7 +80,7 @@ $ uvicorn main:app --root-path /api/v1 🚥 👆 ⚙️ Hypercorn, ⚫️ ✔️ 🎛 `--root-path`. -/// note | "📡 ℹ" +/// note | 📡 ℹ 🔫 🔧 🔬 `root_path` 👉 ⚙️ 💼. @@ -94,9 +94,7 @@ $ uvicorn main:app --root-path /api/v1 📥 👥 ✅ ⚫️ 📧 🎦 🎯. -```Python hl_lines="8" -{!../../docs_src/behind_a_proxy/tutorial001.py!} -``` +{* ../../docs_src/behind_a_proxy/tutorial001.py hl[8] *} ⤴️, 🚥 👆 ▶️ Uvicorn ⏮️: @@ -123,9 +121,7 @@ $ uvicorn main:app --root-path /api/v1 👐, 🚥 👆 🚫 ✔️ 🌌 🚚 📋 ⏸ 🎛 💖 `--root-path` ⚖️ 🌓, 👆 💪 ⚒ `root_path` 🔢 🕐❔ 🏗 👆 FastAPI 📱: -```Python hl_lines="3" -{!../../docs_src/behind_a_proxy/tutorial002.py!} -``` +{* ../../docs_src/behind_a_proxy/tutorial002.py hl[3] *} 🚶‍♀️ `root_path` `FastAPI` 🔜 🌓 🚶‍♀️ `--root-path` 📋 ⏸ 🎛 Uvicorn ⚖️ Hypercorn. @@ -305,9 +301,7 @@ $ uvicorn main:app --root-path /api/v1 🖼: -```Python hl_lines="4-7" -{!../../docs_src/behind_a_proxy/tutorial003.py!} -``` +{* ../../docs_src/behind_a_proxy/tutorial003.py hl[4:7] *} 🔜 🏗 🗄 🔗 💖: @@ -354,9 +348,7 @@ $ uvicorn main:app --root-path /api/v1 🚥 👆 🚫 💚 **FastAPI** 🔌 🏧 💽 ⚙️ `root_path`, 👆 💪 ⚙️ 🔢 `root_path_in_servers=False`: -```Python hl_lines="9" -{!../../docs_src/behind_a_proxy/tutorial004.py!} -``` +{* ../../docs_src/behind_a_proxy/tutorial004.py hl[9] *} & ⤴️ ⚫️ 🏆 🚫 🔌 ⚫️ 🗄 🔗. diff --git a/docs/em/docs/advanced/custom-response.md b/docs/em/docs/advanced/custom-response.md index 7147a45360d00..ab95b3e7be9c3 100644 --- a/docs/em/docs/advanced/custom-response.md +++ b/docs/em/docs/advanced/custom-response.md @@ -30,9 +30,7 @@ ✋️ 🚥 👆 🎯 👈 🎚 👈 👆 🛬 **🎻 ⏮️ 🎻**, 👆 💪 🚶‍♀️ ⚫️ 🔗 📨 🎓 & ❎ ➕ 🌥 👈 FastAPI 🔜 ✔️ 🚶‍♀️ 👆 📨 🎚 🔘 `jsonable_encoder` ⏭ 🚶‍♀️ ⚫️ 📨 🎓. -```Python hl_lines="2 7" -{!../../docs_src/custom_response/tutorial001b.py!} -``` +{* ../../docs_src/custom_response/tutorial001b.py hl[2,7] *} /// info @@ -57,9 +55,7 @@ * 🗄 `HTMLResponse`. * 🚶‍♀️ `HTMLResponse` 🔢 `response_class` 👆 *➡ 🛠️ 👨‍🎨*. -```Python hl_lines="2 7" -{!../../docs_src/custom_response/tutorial002.py!} -``` +{* ../../docs_src/custom_response/tutorial002.py hl[2,7] *} /// info @@ -77,9 +73,7 @@ 🎏 🖼 ⚪️➡️ 🔛, 🛬 `HTMLResponse`, 💪 👀 💖: -```Python hl_lines="2 7 19" -{!../../docs_src/custom_response/tutorial003.py!} -``` +{* ../../docs_src/custom_response/tutorial003.py hl[2,7,19] *} /// warning @@ -103,9 +97,7 @@ 🖼, ⚫️ 💪 🕳 💖: -```Python hl_lines="7 21 23" -{!../../docs_src/custom_response/tutorial004.py!} -``` +{* ../../docs_src/custom_response/tutorial004.py hl[7,21,23] *} 👉 🖼, 🔢 `generate_html_response()` ⏪ 🏗 & 📨 `Response` ↩️ 🛬 🕸 `str`. @@ -121,7 +113,7 @@ ✔️ 🤯 👈 👆 💪 ⚙️ `Response` 📨 🕳 🙆, ⚖️ ✍ 🛃 🎧-🎓. -/// note | "📡 ℹ" +/// note | 📡 ℹ 👆 💪 ⚙️ `from starlette.responses import HTMLResponse`. @@ -144,9 +136,7 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 🎚, ⚓️ 🔛 = & 🔁 = ✍ 🆎. -```Python hl_lines="1 18" -{!../../docs_src/response_directly/tutorial002.py!} -``` +{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *} ### `HTMLResponse` @@ -156,9 +146,7 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 ✊ ✍ ⚖️ 🔢 & 📨 ✅ ✍ 📨. -```Python hl_lines="2 7 9" -{!../../docs_src/custom_response/tutorial005.py!} -``` +{* ../../docs_src/custom_response/tutorial005.py hl[2,7,9] *} ### `JSONResponse` @@ -180,9 +168,7 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 /// -```Python hl_lines="2 7" -{!../../docs_src/custom_response/tutorial001.py!} -``` +{* ../../docs_src/custom_response/tutorial001.py hl[2,7] *} /// tip @@ -196,18 +182,14 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 👆 💪 📨 `RedirectResponse` 🔗: -```Python hl_lines="2 9" -{!../../docs_src/custom_response/tutorial006.py!} -``` +{* ../../docs_src/custom_response/tutorial006.py hl[2,9] *} --- ⚖️ 👆 💪 ⚙️ ⚫️ `response_class` 🔢: -```Python hl_lines="2 7 9" -{!../../docs_src/custom_response/tutorial006b.py!} -``` +{* ../../docs_src/custom_response/tutorial006b.py hl[2,7,9] *} 🚥 👆 👈, ⤴️ 👆 💪 📨 📛 🔗 ⚪️➡️ 👆 *➡ 🛠️* 🔢. @@ -217,17 +199,13 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 👆 💪 ⚙️ `status_code` 🔢 🌀 ⏮️ `response_class` 🔢: -```Python hl_lines="2 7 9" -{!../../docs_src/custom_response/tutorial006c.py!} -``` +{* ../../docs_src/custom_response/tutorial006c.py hl[2,7,9] *} ### `StreamingResponse` ✊ 🔁 🚂 ⚖️ 😐 🚂/🎻 & 🎏 📨 💪. -```Python hl_lines="2 14" -{!../../docs_src/custom_response/tutorial007.py!} -``` +{* ../../docs_src/custom_response/tutorial007.py hl[2,14] *} #### ⚙️ `StreamingResponse` ⏮️ 📁-💖 🎚 @@ -268,15 +246,11 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 📁 📨 🔜 🔌 ☑ `Content-Length`, `Last-Modified` & `ETag` 🎚. -```Python hl_lines="2 10" -{!../../docs_src/custom_response/tutorial009.py!} -``` +{* ../../docs_src/custom_response/tutorial009.py hl[2,10] *} 👆 💪 ⚙️ `response_class` 🔢: -```Python hl_lines="2 8 10" -{!../../docs_src/custom_response/tutorial009b.py!} -``` +{* ../../docs_src/custom_response/tutorial009b.py hl[2,8,10] *} 👉 💼, 👆 💪 📨 📁 ➡ 🔗 ⚪️➡️ 👆 *➡ 🛠️* 🔢. @@ -290,9 +264,7 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 👆 💪 ✍ `CustomORJSONResponse`. 👑 👜 👆 ✔️ ✍ `Response.render(content)` 👩‍🔬 👈 📨 🎚 `bytes`: -```Python hl_lines="9-14 17" -{!../../docs_src/custom_response/tutorial009c.py!} -``` +{* ../../docs_src/custom_response/tutorial009c.py hl[9:14,17] *} 🔜 ↩️ 🛬: @@ -318,9 +290,7 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 🖼 🔛, **FastAPI** 🔜 ⚙️ `ORJSONResponse` 🔢, 🌐 *➡ 🛠️*, ↩️ `JSONResponse`. -```Python hl_lines="2 4" -{!../../docs_src/custom_response/tutorial010.py!} -``` +{* ../../docs_src/custom_response/tutorial010.py hl[2,4] *} /// tip diff --git a/docs/em/docs/advanced/dataclasses.md b/docs/em/docs/advanced/dataclasses.md index ab76e5083498d..4dd597262a483 100644 --- a/docs/em/docs/advanced/dataclasses.md +++ b/docs/em/docs/advanced/dataclasses.md @@ -4,9 +4,7 @@ FastAPI 🏗 🔛 🔝 **Pydantic**, & 👤 ✔️ 🌏 👆 ❔ ⚙️ Pyda ✋️ FastAPI 🐕‍🦺 ⚙️ `dataclasses` 🎏 🌌: -```Python hl_lines="1 7-12 19-20" -{!../../docs_src/dataclasses/tutorial001.py!} -``` +{* ../../docs_src/dataclasses/tutorial001.py hl[1,7:12,19:20] *} 👉 🐕‍🦺 👏 **Pydantic**, ⚫️ ✔️ 🔗 🐕‍🦺 `dataclasses`. @@ -34,9 +32,7 @@ FastAPI 🏗 🔛 🔝 **Pydantic**, & 👤 ✔️ 🌏 👆 ❔ ⚙️ Pyda 👆 💪 ⚙️ `dataclasses` `response_model` 🔢: -```Python hl_lines="1 7-13 19" -{!../../docs_src/dataclasses/tutorial002.py!} -``` +{* ../../docs_src/dataclasses/tutorial002.py hl[1,7:13,19] *} 🎻 🔜 🔁 🗜 Pydantic 🎻. diff --git a/docs/em/docs/advanced/events.md b/docs/em/docs/advanced/events.md index 2eae2b3660782..68adb6d65b4c4 100644 --- a/docs/em/docs/advanced/events.md +++ b/docs/em/docs/advanced/events.md @@ -30,9 +30,7 @@ 👥 ✍ 🔁 🔢 `lifespan()` ⏮️ `yield` 💖 👉: -```Python hl_lines="16 19" -{!../../docs_src/events/tutorial003.py!} -``` +{* ../../docs_src/events/tutorial003.py hl[16,19] *} 📥 👥 ⚖ 😥 *🕴* 🛠️ 🚚 🏷 🚮 (❌) 🏷 🔢 📖 ⏮️ 🎰 🏫 🏷 ⏭ `yield`. 👉 📟 🔜 🛠️ **⏭** 🈸 **▶️ ✊ 📨**, ⏮️ *🕴*. @@ -50,9 +48,7 @@ 🥇 👜 👀, 👈 👥 ⚖ 🔁 🔢 ⏮️ `yield`. 👉 📶 🎏 🔗 ⏮️ `yield`. -```Python hl_lines="14-19" -{!../../docs_src/events/tutorial003.py!} -``` +{* ../../docs_src/events/tutorial003.py hl[14:19] *} 🥇 🍕 🔢, ⏭ `yield`, 🔜 🛠️ **⏭** 🈸 ▶️. @@ -64,9 +60,7 @@ 👈 🗜 🔢 🔘 🕳 🤙 "**🔁 🔑 👨‍💼**". -```Python hl_lines="1 13" -{!../../docs_src/events/tutorial003.py!} -``` +{* ../../docs_src/events/tutorial003.py hl[1,13] *} **🔑 👨‍💼** 🐍 🕳 👈 👆 💪 ⚙️ `with` 📄, 🖼, `open()` 💪 ⚙️ 🔑 👨‍💼: @@ -88,9 +82,7 @@ async with lifespan(app): `lifespan` 🔢 `FastAPI` 📱 ✊ **🔁 🔑 👨‍💼**, 👥 💪 🚶‍♀️ 👆 🆕 `lifespan` 🔁 🔑 👨‍💼 ⚫️. -```Python hl_lines="22" -{!../../docs_src/events/tutorial003.py!} -``` +{* ../../docs_src/events/tutorial003.py hl[22] *} ## 🎛 🎉 (😢) @@ -112,9 +104,7 @@ async with lifespan(app): 🚮 🔢 👈 🔜 🏃 ⏭ 🈸 ▶️, 📣 ⚫️ ⏮️ 🎉 `"startup"`: -```Python hl_lines="8" -{!../../docs_src/events/tutorial001.py!} -``` +{* ../../docs_src/events/tutorial001.py hl[8] *} 👉 💼, `startup` 🎉 🐕‍🦺 🔢 🔜 🔢 🏬 "💽" ( `dict`) ⏮️ 💲. @@ -126,9 +116,7 @@ async with lifespan(app): 🚮 🔢 👈 🔜 🏃 🕐❔ 🈸 🤫 🔽, 📣 ⚫️ ⏮️ 🎉 `"shutdown"`: -```Python hl_lines="6" -{!../../docs_src/events/tutorial002.py!} -``` +{* ../../docs_src/events/tutorial002.py hl[6] *} 📥, `shutdown` 🎉 🐕‍🦺 🔢 🔜 ✍ ✍ ⏸ `"Application shutdown"` 📁 `log.txt`. diff --git a/docs/em/docs/advanced/generate-clients.md b/docs/em/docs/advanced/generate-clients.md index f09d75623c0c8..a680c9051ea89 100644 --- a/docs/em/docs/advanced/generate-clients.md +++ b/docs/em/docs/advanced/generate-clients.md @@ -16,21 +16,7 @@ ➡️ ▶️ ⏮️ 🙅 FastAPI 🈸: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9-11 14-15 18 19 23" -{!> ../../docs_src/generate_clients/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="7-9 12-13 16-17 21" -{!> ../../docs_src/generate_clients/tutorial001_py39.py!} -``` - -//// +{* ../../docs_src/generate_clients/tutorial001.py hl[9:11,14:15,18,19,23] *} 👀 👈 *➡ 🛠️* 🔬 🏷 👫 ⚙️ 📨 🚀 & 📨 🚀, ⚙️ 🏷 `Item` & `ResponseMessage`. @@ -136,21 +122,7 @@ frontend-app@1.0.0 generate-client /home/user/code/frontend-app 🖼, 👆 💪 ✔️ 📄 **🏬** & ➕1️⃣ 📄 **👩‍💻**, & 👫 💪 👽 🔖: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="23 28 36" -{!> ../../docs_src/generate_clients/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="21 26 34" -{!> ../../docs_src/generate_clients/tutorial002_py39.py!} -``` - -//// +{* ../../docs_src/generate_clients/tutorial002.py hl[23,28,36] *} ### 🏗 📕 👩‍💻 ⏮️ 🔖 @@ -197,21 +169,7 @@ FastAPI ⚙️ **😍 🆔** 🔠 *➡ 🛠️*, ⚫️ ⚙️ **🛠️ 🆔** 👆 💪 ⤴️ 🚶‍♀️ 👈 🛃 🔢 **FastAPI** `generate_unique_id_function` 🔢: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="8-9 12" -{!> ../../docs_src/generate_clients/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="6-7 10" -{!> ../../docs_src/generate_clients/tutorial003_py39.py!} -``` - -//// +{* ../../docs_src/generate_clients/tutorial003.py hl[8:9,12] *} ### 🏗 📕 👩‍💻 ⏮️ 🛃 🛠️ 🆔 @@ -233,9 +191,7 @@ FastAPI ⚙️ **😍 🆔** 🔠 *➡ 🛠️*, ⚫️ ⚙️ **🛠️ 🆔** 👥 💪 ⏬ 🗄 🎻 📁 `openapi.json` & ⤴️ 👥 💪 **❎ 👈 🔡 🔖** ⏮️ ✍ 💖 👉: -```Python -{!../../docs_src/generate_clients/tutorial004.py!} -``` +{* ../../docs_src/generate_clients/tutorial004.py *} ⏮️ 👈, 🛠️ 🆔 🔜 📁 ⚪️➡️ 👜 💖 `items-get_items` `get_items`, 👈 🌌 👩‍💻 🚂 💪 🏗 🙅 👩‍🔬 📛. diff --git a/docs/em/docs/advanced/middleware.md b/docs/em/docs/advanced/middleware.md index 23d2918d74f67..cb04fa3fbcddb 100644 --- a/docs/em/docs/advanced/middleware.md +++ b/docs/em/docs/advanced/middleware.md @@ -43,7 +43,7 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") **FastAPI** 🔌 📚 🛠️ ⚠ ⚙️ 💼, 👥 🔜 👀 ⏭ ❔ ⚙️ 👫. -/// note | "📡 ℹ" +/// note | 📡 ℹ ⏭ 🖼, 👆 💪 ⚙️ `from starlette.middleware.something import SomethingMiddleware`. @@ -57,17 +57,13 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") 🙆 📨 📨 `http` ⚖️ `ws` 🔜 ❎ 🔐 ⚖ ↩️. -```Python hl_lines="2 6" -{!../../docs_src/advanced_middleware/tutorial001.py!} -``` +{* ../../docs_src/advanced_middleware/tutorial001.py hl[2,6] *} ## `TrustedHostMiddleware` 🛠️ 👈 🌐 📨 📨 ✔️ ☑ ⚒ `Host` 🎚, ✔ 💂‍♂ 🛡 🇺🇸🔍 🦠 🎚 👊. -```Python hl_lines="2 6-8" -{!../../docs_src/advanced_middleware/tutorial002.py!} -``` +{* ../../docs_src/advanced_middleware/tutorial002.py hl[2,6:8] *} 📄 ❌ 🐕‍🦺: @@ -81,9 +77,7 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") 🛠️ 🔜 🍵 👯‍♂️ 🐩 & 🎥 📨. -```Python hl_lines="2 6" -{!../../docs_src/advanced_middleware/tutorial003.py!} -``` +{* ../../docs_src/advanced_middleware/tutorial003.py hl[2,6] *} 📄 ❌ 🐕‍🦺: diff --git a/docs/em/docs/advanced/openapi-callbacks.md b/docs/em/docs/advanced/openapi-callbacks.md index f7b5e7ed9dd94..b0a8216681559 100644 --- a/docs/em/docs/advanced/openapi-callbacks.md +++ b/docs/em/docs/advanced/openapi-callbacks.md @@ -31,9 +31,7 @@ 👉 🍕 📶 😐, 🌅 📟 🎲 ⏪ 😰 👆: -```Python hl_lines="9-13 36-53" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[9:13,36:53] *} /// tip @@ -92,9 +90,7 @@ httpx.post(callback_url, json={"description": "Invoice paid", "paid": True}) 🥇 ✍ 🆕 `APIRouter` 👈 🔜 🔌 1️⃣ ⚖️ 🌅 ⏲. -```Python hl_lines="3 25" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[3,25] *} ### ✍ ⏲ *➡ 🛠️* @@ -105,9 +101,7 @@ httpx.post(callback_url, json={"description": "Invoice paid", "paid": True}) * ⚫️ 🔜 🎲 ✔️ 📄 💪 ⚫️ 🔜 📨, ✅ `body: InvoiceEvent`. * & ⚫️ 💪 ✔️ 📄 📨 ⚫️ 🔜 📨, ✅ `response_model=InvoiceEventReceived`. -```Python hl_lines="16-18 21-22 28-32" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[16:18,21:22,28:32] *} 📤 2️⃣ 👑 🔺 ⚪️➡️ 😐 *➡ 🛠️*: @@ -175,9 +169,7 @@ https://www.external.org/events/invoices/2expen51ve 🔜 ⚙️ 🔢 `callbacks` *👆 🛠️ ➡ 🛠️ 👨‍🎨* 🚶‍♀️ 🔢 `.routes` (👈 🤙 `list` 🛣/*➡ 🛠️*) ⚪️➡️ 👈 ⏲ 📻: -```Python hl_lines="35" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[35] *} /// tip diff --git a/docs/em/docs/advanced/path-operation-advanced-configuration.md b/docs/em/docs/advanced/path-operation-advanced-configuration.md index 805bfdf30e8bb..9d9d5fa8da53d 100644 --- a/docs/em/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/em/docs/advanced/path-operation-advanced-configuration.md @@ -12,9 +12,7 @@ 👆 🔜 ✔️ ⚒ 💭 👈 ⚫️ 😍 🔠 🛠️. -```Python hl_lines="6" -{!../../docs_src/path_operation_advanced_configuration/tutorial001.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial001.py hl[6] *} ### ⚙️ *➡ 🛠️ 🔢* 📛 { @@ -22,9 +20,7 @@ 👆 🔜 ⚫️ ⏮️ ❎ 🌐 👆 *➡ 🛠️*. -```Python hl_lines="2 12-21 24" -{!../../docs_src/path_operation_advanced_configuration/tutorial002.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial002.py hl[2,12:21,24] *} /// tip @@ -44,9 +40,7 @@ 🚫 *➡ 🛠️* ⚪️➡️ 🏗 🗄 🔗 (& ➡️, ⚪️➡️ 🏧 🧾 ⚙️), ⚙️ 🔢 `include_in_schema` & ⚒ ⚫️ `False`: -```Python hl_lines="6" -{!../../docs_src/path_operation_advanced_configuration/tutorial003.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial003.py hl[6] *} ## 🏧 📛 ⚪️➡️ #️⃣ @@ -56,9 +50,7 @@ ⚫️ 🏆 🚫 🎦 🆙 🧾, ✋️ 🎏 🧰 (✅ 🐉) 🔜 💪 ⚙️ 🎂. -```Python hl_lines="19-29" -{!../../docs_src/path_operation_advanced_configuration/tutorial004.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial004.py hl[19:29] *} ## 🌖 📨 @@ -74,7 +66,7 @@ 🕐❔ 👆 📣 *➡ 🛠️* 👆 🈸, **FastAPI** 🔁 🏗 🔗 🗃 🔃 👈 *➡ 🛠️* 🔌 🗄 🔗. -/// note | "📡 ℹ" +/// note | 📡 ℹ 🗄 🔧 ⚫️ 🤙 🛠️ 🎚. @@ -100,9 +92,7 @@ 👉 `openapi_extra` 💪 👍, 🖼, 📣 [🗄 ↔](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions): -```Python hl_lines="6" -{!../../docs_src/path_operation_advanced_configuration/tutorial005.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial005.py hl[6] *} 🚥 👆 📂 🏧 🛠️ 🩺, 👆 ↔ 🔜 🎦 🆙 🔝 🎯 *➡ 🛠️*. @@ -149,9 +139,7 @@ 👆 💪 👈 ⏮️ `openapi_extra`: -```Python hl_lines="20-37 39-40" -{!../../docs_src/path_operation_advanced_configuration/tutorial006.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial006.py hl[20:37,39:40] *} 👉 🖼, 👥 🚫 📣 🙆 Pydantic 🏷. 👐, 📨 💪 🚫 🎻 🎻, ⚫️ ✍ 🔗 `bytes`, & 🔢 `magic_data_reader()` 🔜 🈚 🎻 ⚫️ 🌌. @@ -165,9 +153,7 @@ 🖼, 👉 🈸 👥 🚫 ⚙️ FastAPI 🛠️ 🛠️ ⚗ 🎻 🔗 ⚪️➡️ Pydantic 🏷 🚫 🏧 🔬 🎻. 👐, 👥 📣 📨 🎚 🆎 📁, 🚫 🎻: -```Python hl_lines="17-22 24" -{!../../docs_src/path_operation_advanced_configuration/tutorial007.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[17:22,24] *} 👐, 👐 👥 🚫 ⚙️ 🔢 🛠️ 🛠️, 👥 ⚙️ Pydantic 🏷 ❎ 🏗 🎻 🔗 💽 👈 👥 💚 📨 📁. @@ -175,9 +161,7 @@ & ⤴️ 👆 📟, 👥 🎻 👈 📁 🎚 🔗, & ⤴️ 👥 🔄 ⚙️ 🎏 Pydantic 🏷 ✔ 📁 🎚: -```Python hl_lines="26-33" -{!../../docs_src/path_operation_advanced_configuration/tutorial007.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[26:33] *} /// tip diff --git a/docs/em/docs/advanced/response-change-status-code.md b/docs/em/docs/advanced/response-change-status-code.md index 7f2e8c157294c..4933484dd32f5 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 6b9e9a4d98d33..d9fdbaa87276d 100644 --- a/docs/em/docs/advanced/response-cookies.md +++ b/docs/em/docs/advanced/response-cookies.md @@ -6,9 +6,7 @@ & ⤴️ 👆 💪 ⚒ 🍪 👈 *🔀* 📨 🎚. -```Python hl_lines="1 8-9" -{!../../docs_src/response_cookies/tutorial002.py!} -``` +{* ../../docs_src/response_cookies/tutorial002.py hl[1,8:9] *} & ⤴️ 👆 💪 📨 🙆 🎚 👆 💪, 👆 🛎 🔜 ( `dict`, 💽 🏷, ♒️). @@ -26,9 +24,7 @@ ⤴️ ⚒ 🍪 ⚫️, & ⤴️ 📨 ⚫️: -```Python hl_lines="10-12" -{!../../docs_src/response_cookies/tutorial001.py!} -``` +{* ../../docs_src/response_cookies/tutorial001.py hl[10:12] *} /// tip @@ -42,7 +38,7 @@ ### 🌅 ℹ -/// note | "📡 ℹ" +/// note | 📡 ℹ 👆 💪 ⚙️ `from starlette.responses import Response` ⚖️ `from starlette.responses import JSONResponse`. diff --git a/docs/em/docs/advanced/response-directly.md b/docs/em/docs/advanced/response-directly.md index dcffc56c61892..29819a205513d 100644 --- a/docs/em/docs/advanced/response-directly.md +++ b/docs/em/docs/advanced/response-directly.md @@ -34,11 +34,9 @@ 📚 💼, 👆 💪 ⚙️ `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 | "📡 ℹ" +/// note | 📡 ℹ 👆 💪 ⚙️ `from starlette.responses import JSONResponse`. @@ -56,9 +54,7 @@ 👆 💪 🚮 👆 📂 🎚 🎻, 🚮 ⚫️ `Response`, & 📨 ⚫️: -```Python hl_lines="1 18" -{!../../docs_src/response_directly/tutorial002.py!} -``` +{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *} ## 🗒 diff --git a/docs/em/docs/advanced/response-headers.md b/docs/em/docs/advanced/response-headers.md index cbbbae23788d9..e9e1b62d2ff34 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,11 +22,9 @@ ✍ 📨 🔬 [📨 📨 🔗](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 | "📡 ℹ" +/// note | 📡 ℹ 👆 💪 ⚙️ `from starlette.responses import Response` ⚖️ `from starlette.responses import JSONResponse`. diff --git a/docs/em/docs/advanced/security/http-basic-auth.md b/docs/em/docs/advanced/security/http-basic-auth.md index e6fe3e32c8bc5..73736f3b35eab 100644 --- a/docs/em/docs/advanced/security/http-basic-auth.md +++ b/docs/em/docs/advanced/security/http-basic-auth.md @@ -20,9 +20,7 @@ * ⚫️ 📨 🎚 🆎 `HTTPBasicCredentials`: * ⚫️ 🔌 `username` & `password` 📨. -```Python hl_lines="2 6 10" -{!../../docs_src/security/tutorial006.py!} -``` +{* ../../docs_src/security/tutorial006.py hl[2,6,10] *} 🕐❔ 👆 🔄 📂 📛 🥇 🕰 (⚖️ 🖊 "🛠️" 🔼 🩺) 🖥 🔜 💭 👆 👆 🆔 & 🔐: @@ -42,9 +40,7 @@ ⤴️ 👥 💪 ⚙️ `secrets.compare_digest()` 🚚 👈 `credentials.username` `"stanleyjobson"`, & 👈 `credentials.password` `"swordfish"`. -```Python hl_lines="1 11-21" -{!../../docs_src/security/tutorial007.py!} -``` +{* ../../docs_src/security/tutorial007.py hl[1,11:21] *} 👉 🔜 🎏: @@ -108,6 +104,4 @@ if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish": ⏮️ 🔍 👈 🎓 ❌, 📨 `HTTPException` ⏮️ 👔 📟 4️⃣0️⃣1️⃣ (🎏 📨 🕐❔ 🙅‍♂ 🎓 🚚) & 🚮 🎚 `WWW-Authenticate` ⚒ 🖥 🎦 💳 📋 🔄: -```Python hl_lines="23-27" -{!../../docs_src/security/tutorial007.py!} -``` +{* ../../docs_src/security/tutorial007.py hl[23:27] *} diff --git a/docs/em/docs/advanced/security/oauth2-scopes.md b/docs/em/docs/advanced/security/oauth2-scopes.md index 661be034e5f90..b8c49bd11267d 100644 --- a/docs/em/docs/advanced/security/oauth2-scopes.md +++ b/docs/em/docs/advanced/security/oauth2-scopes.md @@ -62,9 +62,7 @@ Oauth2️⃣ 👫 🎻. 🥇, ➡️ 🔜 👀 🍕 👈 🔀 ⚪️➡️ 🖼 👑 **🔰 - 👩‍💻 🦮** [Oauth2️⃣ ⏮️ 🔐 (& 🔁), 📨 ⏮️ 🥙 🤝](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. 🔜 ⚙️ Oauth2️⃣ ↔: -```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" -{!../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[2,4,8,12,46,64,105,107:115,121:124,128:134,139,155] *} 🔜 ➡️ 📄 👈 🔀 🔁 🔁. @@ -74,9 +72,7 @@ Oauth2️⃣ 👫 🎻. `scopes` 🔢 📨 `dict` ⏮️ 🔠 ↔ 🔑 & 📛 💲: -```Python hl_lines="62-65" -{!../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[62:65] *} ↩️ 👥 🔜 📣 📚 ↔, 👫 🔜 🎦 🆙 🛠️ 🩺 🕐❔ 👆 🕹-/✔. @@ -102,9 +98,7 @@ Oauth2️⃣ 👫 🎻. /// -```Python hl_lines="155" -{!../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[155] *} ## 📣 ↔ *➡ 🛠️* & 🔗 @@ -130,11 +124,9 @@ Oauth2️⃣ 👫 🎻. /// -```Python hl_lines="4 139 168" -{!../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[4,139,168] *} -/// info | "📡 ℹ" +/// info | 📡 ℹ `Security` 🤙 🏿 `Depends`, & ⚫️ ✔️ 1️⃣ ➕ 🔢 👈 👥 🔜 👀 ⏪. @@ -158,9 +150,7 @@ Oauth2️⃣ 👫 🎻. 👉 `SecurityScopes` 🎓 🎏 `Request` (`Request` ⚙️ 🤚 📨 🎚 🔗). -```Python hl_lines="8 105" -{!../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[8,105] *} ## ⚙️ `scopes` @@ -174,9 +164,7 @@ Oauth2️⃣ 👫 🎻. 👉 ⚠, 👥 🔌 ↔ 🚚 (🚥 🙆) 🎻 👽 🚀 (⚙️ `scope_str`). 👥 🚮 👈 🎻 ⚗ ↔ `WWW-Authenticate` 🎚 (👉 🍕 🔌). -```Python hl_lines="105 107-115" -{!../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[105,107:115] *} ## ✔ `username` & 💽 💠 @@ -192,9 +180,7 @@ Oauth2️⃣ 👫 🎻. 👥 ✔ 👈 👥 ✔️ 👩‍💻 ⏮️ 👈 🆔, & 🚥 🚫, 👥 🤚 👈 🎏 ⚠ 👥 ✍ ⏭. -```Python hl_lines="46 116-127" -{!../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[46,116:127] *} ## ✔ `scopes` @@ -202,9 +188,7 @@ Oauth2️⃣ 👫 🎻. 👉, 👥 ⚙️ `security_scopes.scopes`, 👈 🔌 `list` ⏮️ 🌐 👫 ↔ `str`. -```Python hl_lines="128-134" -{!../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[128:134] *} ## 🔗 🌲 & ↔ diff --git a/docs/em/docs/advanced/settings.md b/docs/em/docs/advanced/settings.md index 59fb71d73b03b..7fdd0d68a652a 100644 --- a/docs/em/docs/advanced/settings.md +++ b/docs/em/docs/advanced/settings.md @@ -148,9 +148,7 @@ Hello World from Python 👆 💪 ⚙️ 🌐 🎏 🔬 ⚒ & 🧰 👆 ⚙️ Pydantic 🏷, 💖 🎏 📊 🆎 & 🌖 🔬 ⏮️ `Field()`. -```Python hl_lines="2 5-8 11" -{!../../docs_src/settings/tutorial001.py!} -``` +{* ../../docs_src/settings/tutorial001.py hl[2,5:8,11] *} /// tip @@ -166,9 +164,7 @@ Hello World from Python ⤴️ 👆 💪 ⚙️ 🆕 `settings` 🎚 👆 🈸: -```Python hl_lines="18-20" -{!../../docs_src/settings/tutorial001.py!} -``` +{* ../../docs_src/settings/tutorial001.py hl[18:20] *} ### 🏃 💽 @@ -202,15 +198,11 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uvicorn main:app 🖼, 👆 💪 ✔️ 📁 `config.py` ⏮️: -```Python -{!../../docs_src/settings/app01/config.py!} -``` +{* ../../docs_src/settings/app01/config.py *} & ⤴️ ⚙️ ⚫️ 📁 `main.py`: -```Python hl_lines="3 11-13" -{!../../docs_src/settings/app01/main.py!} -``` +{* ../../docs_src/settings/app01/main.py hl[3,11:13] *} /// tip @@ -228,9 +220,7 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uvicorn main:app 👟 ⚪️➡️ ⏮️ 🖼, 👆 `config.py` 📁 💪 👀 💖: -```Python hl_lines="10" -{!../../docs_src/settings/app02/config.py!} -``` +{* ../../docs_src/settings/app02/config.py hl[10] *} 👀 👈 🔜 👥 🚫 ✍ 🔢 👐 `settings = Settings()`. @@ -238,9 +228,7 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uvicorn main:app 🔜 👥 ✍ 🔗 👈 📨 🆕 `config.Settings()`. -```Python hl_lines="5 11-12" -{!../../docs_src/settings/app02/main.py!} -``` +{* ../../docs_src/settings/app02/main.py hl[5,11:12] *} /// tip @@ -252,17 +240,13 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uvicorn main:app & ⤴️ 👥 💪 🚚 ⚫️ ⚪️➡️ *➡ 🛠️ 🔢* 🔗 & ⚙️ ⚫️ 🙆 👥 💪 ⚫️. -```Python hl_lines="16 18-20" -{!../../docs_src/settings/app02/main.py!} -``` +{* ../../docs_src/settings/app02/main.py hl[16,18:20] *} ### ⚒ & 🔬 ⤴️ ⚫️ 🔜 📶 ⏩ 🚚 🎏 ⚒ 🎚 ⏮️ 🔬 🏗 🔗 🔐 `get_settings`: -```Python hl_lines="9-10 13 21" -{!../../docs_src/settings/app02/test_main.py!} -``` +{* ../../docs_src/settings/app02/test_main.py hl[9:10,13,21] *} 🔗 🔐 👥 ⚒ 🆕 💲 `admin_email` 🕐❔ 🏗 🆕 `Settings` 🎚, & ⤴️ 👥 📨 👈 🆕 🎚. @@ -303,9 +287,7 @@ APP_NAME="ChimichangApp" & ⤴️ ℹ 👆 `config.py` ⏮️: -```Python hl_lines="9-10" -{!../../docs_src/settings/app03/config.py!} -``` +{* ../../docs_src/settings/app03/config.py hl[9:10] *} 📥 👥 ✍ 🎓 `Config` 🔘 👆 Pydantic `Settings` 🎓, & ⚒ `env_file` 📁 ⏮️ 🇨🇻 📁 👥 💚 ⚙️. @@ -338,9 +320,7 @@ def get_settings(): ✋️ 👥 ⚙️ `@lru_cache` 👨‍🎨 🔛 🔝, `Settings` 🎚 🔜 ✍ 🕴 🕐, 🥇 🕰 ⚫️ 🤙. 👶 👶 -```Python hl_lines="1 10" -{!../../docs_src/settings/app03/main.py!} -``` +{* ../../docs_src/settings/app03/main.py hl[1,10] *} ⤴️ 🙆 🏁 🤙 `get_settings()` 🔗 ⏭ 📨, ↩️ 🛠️ 🔗 📟 `get_settings()` & 🏗 🆕 `Settings` 🎚, ⚫️ 🔜 📨 🎏 🎚 👈 📨 🔛 🥇 🤙, 🔄 & 🔄. diff --git a/docs/em/docs/advanced/sub-applications.md b/docs/em/docs/advanced/sub-applications.md index e19f3f2340017..7a802cd77f87a 100644 --- a/docs/em/docs/advanced/sub-applications.md +++ b/docs/em/docs/advanced/sub-applications.md @@ -10,9 +10,7 @@ 🥇, ✍ 👑, 🔝-🎚, **FastAPI** 🈸, & 🚮 *➡ 🛠️*: -```Python hl_lines="3 6-8" -{!../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[3,6:8] *} ### 🎧-🈸 @@ -20,9 +18,7 @@ 👉 🎧-🈸 ➕1️⃣ 🐩 FastAPI 🈸, ✋️ 👉 1️⃣ 👈 🔜 "🗻": -```Python hl_lines="11 14-16" -{!../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[11,14:16] *} ### 🗻 🎧-🈸 @@ -30,9 +26,7 @@ 👉 💼, ⚫️ 🔜 📌 ➡ `/subapi`: -```Python hl_lines="11 19" -{!../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[11,19] *} ### ✅ 🏧 🛠️ 🩺 diff --git a/docs/em/docs/advanced/templates.md b/docs/em/docs/advanced/templates.md index 66c7484a6d65d..ad4d4fc714784 100644 --- a/docs/em/docs/advanced/templates.md +++ b/docs/em/docs/advanced/templates.md @@ -27,9 +27,7 @@ $ pip install jinja2 * 📣 `Request` 🔢 *➡ 🛠️* 👈 🔜 📨 📄. * ⚙️ `templates` 👆 ✍ ✍ & 📨 `TemplateResponse`, 🚶‍♀️ `request` 1️⃣ 🔑-💲 👫 Jinja2️⃣ "🔑". -```Python hl_lines="4 11 15-18" -{!../../docs_src/templates/tutorial001.py!} -``` +{* ../../docs_src/templates/tutorial001.py hl[4,11,15:18] *} /// note @@ -43,7 +41,7 @@ $ pip install jinja2 /// -/// note | "📡 ℹ" +/// note | 📡 ℹ 👆 💪 ⚙️ `from starlette.templating import Jinja2Templates`. diff --git a/docs/em/docs/advanced/testing-dependencies.md b/docs/em/docs/advanced/testing-dependencies.md index 027767df193cf..b2b4b480d088d 100644 --- a/docs/em/docs/advanced/testing-dependencies.md +++ b/docs/em/docs/advanced/testing-dependencies.md @@ -28,9 +28,7 @@ & ⤴️ **FastAPI** 🔜 🤙 👈 🔐 ↩️ ⏮️ 🔗. -```Python hl_lines="28-29 32" -{!../../docs_src/dependency_testing/tutorial001.py!} -``` +{* ../../docs_src/dependency_testing/tutorial001.py hl[28:29,32] *} /// tip diff --git a/docs/em/docs/advanced/testing-events.md b/docs/em/docs/advanced/testing-events.md index 071d49c212b2d..f62e9e0694ede 100644 --- a/docs/em/docs/advanced/testing-events.md +++ b/docs/em/docs/advanced/testing-events.md @@ -2,6 +2,4 @@ 🕐❔ 👆 💪 👆 🎉 🐕‍🦺 (`startup` & `shutdown`) 🏃 👆 💯, 👆 💪 ⚙️ `TestClient` ⏮️ `with` 📄: -```Python hl_lines="9-12 20-24" -{!../../docs_src/app_testing/tutorial003.py!} -``` +{* ../../docs_src/app_testing/tutorial003.py hl[9:12,20:24] *} diff --git a/docs/em/docs/advanced/testing-websockets.md b/docs/em/docs/advanced/testing-websockets.md index 62939c343866a..2a01de62903be 100644 --- a/docs/em/docs/advanced/testing-websockets.md +++ b/docs/em/docs/advanced/testing-websockets.md @@ -4,9 +4,7 @@ 👉, 👆 ⚙️ `TestClient` `with` 📄, 🔗*️⃣: -```Python hl_lines="27-31" -{!../../docs_src/app_testing/tutorial002.py!} -``` +{* ../../docs_src/app_testing/tutorial002.py hl[27:31] *} /// note diff --git a/docs/em/docs/advanced/using-request-directly.md b/docs/em/docs/advanced/using-request-directly.md index ae212364f259a..9530d49bc594f 100644 --- a/docs/em/docs/advanced/using-request-directly.md +++ b/docs/em/docs/advanced/using-request-directly.md @@ -29,9 +29,7 @@ 👈 👆 💪 🔐 📨 🔗. -```Python hl_lines="1 7-8" -{!../../docs_src/using_request_directly/tutorial001.py!} -``` +{* ../../docs_src/using_request_directly/tutorial001.py hl[1,7:8] *} 📣 *➡ 🛠️ 🔢* 🔢 ⏮️ 🆎 ➖ `Request` **FastAPI** 🔜 💭 🚶‍♀️ `Request` 👈 🔢. @@ -49,7 +47,7 @@ 👆 💪 ✍ 🌅 ℹ 🔃 `Request` 🎚 🛂 💃 🧾 🕸. -/// note | "📡 ℹ" +/// note | 📡 ℹ 👆 💪 ⚙️ `from starlette.requests import Request`. diff --git a/docs/em/docs/advanced/websockets.md b/docs/em/docs/advanced/websockets.md index 7957eba1ff721..cc6e5c5f029e4 100644 --- a/docs/em/docs/advanced/websockets.md +++ b/docs/em/docs/advanced/websockets.md @@ -38,19 +38,15 @@ $ pip install websockets ✋️ ⚫️ 🙅 🌌 🎯 🔛 💽-🚄 *️⃣ & ✔️ 👷 🖼: -```Python hl_lines="2 6-38 41-43" -{!../../docs_src/websockets/tutorial001.py!} -``` +{* ../../docs_src/websockets/tutorial001.py hl[2,6:38,41:43] *} ## ✍ `websocket` 👆 **FastAPI** 🈸, ✍ `websocket`: -```Python hl_lines="1 46-47" -{!../../docs_src/websockets/tutorial001.py!} -``` +{* ../../docs_src/websockets/tutorial001.py hl[1,46:47] *} -/// note | "📡 ℹ" +/// note | 📡 ℹ 👆 💪 ⚙️ `from starlette.websockets import WebSocket`. @@ -62,9 +58,7 @@ $ pip install websockets 👆 *️⃣ 🛣 👆 💪 `await` 📧 & 📨 📧. -```Python hl_lines="48-52" -{!../../docs_src/websockets/tutorial001.py!} -``` +{* ../../docs_src/websockets/tutorial001.py hl[48:52] *} 👆 💪 📨 & 📨 💱, ✍, & 🎻 💽. @@ -115,9 +109,7 @@ $ uvicorn main:app --reload 👫 👷 🎏 🌌 🎏 FastAPI 🔗/*➡ 🛠️*: -```Python hl_lines="66-77 76-91" -{!../../docs_src/websockets/tutorial002.py!} -``` +{* ../../docs_src/websockets/tutorial002.py hl[66:77,76:91] *} /// info @@ -162,9 +154,7 @@ $ uvicorn main:app --reload 🕐❔ *️⃣ 🔗 📪, `await websocket.receive_text()` 🔜 🤚 `WebSocketDisconnect` ⚠, ❔ 👆 💪 ⤴️ ✊ & 🍵 💖 👉 🖼. -```Python hl_lines="81-83" -{!../../docs_src/websockets/tutorial003.py!} -``` +{* ../../docs_src/websockets/tutorial003.py hl[81:83] *} 🔄 ⚫️ 👅: diff --git a/docs/em/docs/advanced/wsgi.md b/docs/em/docs/advanced/wsgi.md index 8c0008c74fdd9..d923347d5a4cc 100644 --- a/docs/em/docs/advanced/wsgi.md +++ b/docs/em/docs/advanced/wsgi.md @@ -12,9 +12,7 @@ & ⤴️ 🗻 👈 🔽 ➡. -```Python hl_lines="2-3 22" -{!../../docs_src/wsgi/tutorial001.py!} -``` +{* ../../docs_src/wsgi/tutorial001.py hl[2:3,22] *} ## ✅ ⚫️ diff --git a/docs/em/docs/alternatives.md b/docs/em/docs/alternatives.md index 5309de51f6956..59b58728520a9 100644 --- a/docs/em/docs/alternatives.md +++ b/docs/em/docs/alternatives.md @@ -36,7 +36,7 @@ /// -/// check | "😮 **FastAPI** " +/// check | 😮 **FastAPI** ✔️ 🏧 🛠️ 🧾 🕸 👩‍💻 🔢. @@ -56,7 +56,7 @@ 👐 🦁 🏺, ⚫️ 😑 💖 👍 🏏 🏗 🔗. ⏭ 👜 🔎 "✳ 🎂 🛠️" 🏺. -/// check | "😮 **FastAPI** " +/// check | 😮 **FastAPI** ◾-🛠️. ⚒ ⚫️ ⏩ 🌀 & 🏏 🧰 & 🍕 💪. @@ -98,7 +98,7 @@ def read_url(): 👀 🔀 `requests.get(...)` & `@app.get(...)`. -/// check | "😮 **FastAPI** " +/// check | 😮 **FastAPI** * ✔️ 🙅 & 🏋️ 🛠️. * ⚙️ 🇺🇸🔍 👩‍🔬 📛 (🛠️) 🔗, 🎯 & 🏋️ 🌌. @@ -118,7 +118,7 @@ def read_url(): 👈 ⚫️❔ 🕐❔ 💬 🔃 ⏬ 2️⃣.0️⃣ ⚫️ ⚠ 💬 "🦁", & ⏬ 3️⃣ ➕ "🗄". -/// check | "😮 **FastAPI** " +/// check | 😮 **FastAPI** 🛠️ & ⚙️ 📂 🐩 🛠️ 🔧, ↩️ 🛃 🔗. @@ -147,7 +147,7 @@ def read_url(): ✋️ ⚫️ ✍ ⏭ 📤 🔀 🐍 🆎 🔑. , 🔬 🔠 🔗 👆 💪 ⚙️ 🎯 🇨🇻 & 🎓 🚚 🍭. -/// check | "😮 **FastAPI** " +/// check | 😮 **FastAPI** ⚙️ 📟 🔬 "🔗" 👈 🚚 💽 🆎 & 🔬, 🔁. @@ -169,7 +169,7 @@ Webarg ✍ 🎏 🍭 👩‍💻. /// -/// check | "😮 **FastAPI** " +/// check | 😮 **FastAPI** ✔️ 🏧 🔬 📨 📨 💽. @@ -199,7 +199,7 @@ APISpec ✍ 🎏 🍭 👩‍💻. /// -/// check | "😮 **FastAPI** " +/// check | 😮 **FastAPI** 🐕‍🦺 📂 🐩 🛠️, 🗄. @@ -231,7 +231,7 @@ APISpec ✍ 🎏 🍭 👩‍💻. /// -/// check | "😮 **FastAPI** " +/// check | 😮 **FastAPI** 🏗 🗄 🔗 🔁, ⚪️➡️ 🎏 📟 👈 🔬 🛠️ & 🔬. @@ -251,7 +251,7 @@ APISpec ✍ 🎏 🍭 👩‍💻. ⚫️ 💪 🚫 🍵 🔁 🏷 📶 👍. , 🚥 🎻 💪 📨 🎻 🎚 👈 ✔️ 🔘 🏑 👈 🔄 🐦 🎻 🎚, ⚫️ 🚫🔜 ☑ 📄 & ✔. -/// check | "😮 **FastAPI** " +/// check | 😮 **FastAPI** ⚙️ 🐍 🆎 ✔️ 👑 👨‍🎨 🐕‍🦺. @@ -263,7 +263,7 @@ APISpec ✍ 🎏 🍭 👩‍💻. ⚫️ 🕐 🥇 📶 ⏩ 🐍 🛠️ ⚓️ 🔛 `asyncio`. ⚫️ ⚒ 📶 🎏 🏺. -/// note | "📡 ℹ" +/// note | 📡 ℹ ⚫️ ⚙️ `uvloop` ↩️ 🔢 🐍 `asyncio` ➰. 👈 ⚫️❔ ⚒ ⚫️ ⏩. @@ -271,7 +271,7 @@ APISpec ✍ 🎏 🍭 👩‍💻. /// -/// check | "😮 **FastAPI** " +/// check | 😮 **FastAPI** 🔎 🌌 ✔️ 😜 🎭. @@ -287,7 +287,7 @@ APISpec ✍ 🎏 🍭 👩‍💻. , 💽 🔬, 🛠️, & 🧾, ✔️ ⌛ 📟, 🚫 🔁. ⚖️ 👫 ✔️ 🛠️ 🛠️ 🔛 🔝 🦅, 💖 🤗. 👉 🎏 🔺 🔨 🎏 🛠️ 👈 😮 🦅 🔧, ✔️ 1️⃣ 📨 🎚 & 1️⃣ 📨 🎚 🔢. -/// check | "😮 **FastAPI** " +/// check | 😮 **FastAPI** 🔎 🌌 🤚 👑 🎭. @@ -313,7 +313,7 @@ APISpec ✍ 🎏 🍭 👩‍💻. 🛣 📣 👁 🥉, ⚙️ 🔢 📣 🎏 🥉 (↩️ ⚙️ 👨‍🎨 👈 💪 🥉 ▶️️ 🔛 🔝 🔢 👈 🍵 🔗). 👉 🔐 ❔ ✳ 🔨 ⚫️ 🌘 ❔ 🏺 (& 💃) 🔨 ⚫️. ⚫️ 🎏 📟 👜 👈 📶 😆 🔗. -/// check | "😮 **FastAPI** " +/// check | 😮 **FastAPI** 🔬 ➕ 🔬 💽 🆎 ⚙️ "🔢" 💲 🏷 🔢. 👉 📉 👨‍🎨 🐕‍🦺, & ⚫️ 🚫 💪 Pydantic ⏭. @@ -341,7 +341,7 @@ APISpec ✍ 🎏 🍭 👩‍💻. /// -/// check | "💭 😮 **FastAPI**" +/// check | 💭 😮 **FastAPI** 🤗 😮 🍕 APIStar, & 1️⃣ 🧰 👤 🔎 🏆 👍, 🌟 APIStar. @@ -385,7 +385,7 @@ APIStar ✍ ✡ 🇺🇸🏛. 🎏 👨 👈 ✍: /// -/// check | "😮 **FastAPI** " +/// check | 😮 **FastAPI** 🔀. @@ -409,7 +409,7 @@ Pydantic 🗃 🔬 💽 🔬, 🛠️ & 🧾 (⚙️ 🎻 🔗) ⚓️ 🔛 ⚫️ ⭐ 🍭. 👐 ⚫️ ⏩ 🌘 🍭 📇. & ⚫️ ⚓️ 🔛 🎏 🐍 🆎 🔑, 👨‍🎨 🐕‍🦺 👑. -/// check | "**FastAPI** ⚙️ ⚫️" +/// check | **FastAPI** ⚙️ ⚫️ 🍵 🌐 💽 🔬, 💽 🛠️ & 🏧 🏷 🧾 (⚓️ 🔛 🎻 🔗). @@ -444,7 +444,7 @@ Pydantic 🗃 🔬 💽 🔬, 🛠️ & 🧾 (⚙️ 🎻 🔗) ⚓️ 🔛 👈 1️⃣ 👑 👜 👈 **FastAPI** 🚮 🔛 🔝, 🌐 ⚓️ 🔛 🐍 🆎 🔑 (⚙️ Pydantic). 👈, ➕ 🔗 💉 ⚙️, 💂‍♂ 🚙, 🗄 🔗 ⚡, ♒️. -/// note | "📡 ℹ" +/// note | 📡 ℹ 🔫 🆕 "🐩" ➖ 🛠️ ✳ 🐚 🏉 👨‍🎓. ⚫️ 🚫 "🐍 🐩" (🇩🇬), 👐 👫 🛠️ 🔨 👈. @@ -452,7 +452,7 @@ Pydantic 🗃 🔬 💽 🔬, 🛠️ & 🧾 (⚙️ 🎻 🔗) ⚓️ 🔛 /// -/// check | "**FastAPI** ⚙️ ⚫️" +/// check | **FastAPI** ⚙️ ⚫️ 🍵 🌐 🐚 🕸 🍕. ❎ ⚒ 🔛 🔝. @@ -470,7 +470,7 @@ Uvicorn 🌩-⏩ 🔫 💽, 🏗 🔛 uvloop & httptool. ⚫️ 👍 💽 💃 & **FastAPI**. -/// check | "**FastAPI** 👍 ⚫️" +/// check | **FastAPI** 👍 ⚫️ 👑 🕸 💽 🏃 **FastAPI** 🈸. diff --git a/docs/em/docs/contributing.md b/docs/em/docs/contributing.md deleted file mode 100644 index 3ac1afda4d068..0000000000000 --- a/docs/em/docs/contributing.md +++ /dev/null @@ -1,493 +0,0 @@ -# 🛠️ - 📉 - -🥇, 👆 💪 💚 👀 🔰 🌌 [ℹ FastAPI & 🤚 ℹ](help-fastapi.md){.internal-link target=_blank}. - -## 🛠️ - -🚥 👆 ⏪ 🖖 🗃 & 👆 💭 👈 👆 💪 ⏬ 🤿 📟, 📥 📄 ⚒ 🆙 👆 🌐. - -### 🕹 🌐 ⏮️ `venv` - -👆 💪 ✍ 🕹 🌐 📁 ⚙️ 🐍 `venv` 🕹: - -
- -```console -$ python -m venv env -``` - -
- -👈 🔜 ✍ 📁 `./env/` ⏮️ 🐍 💱 & ⤴️ 👆 🔜 💪 ❎ 📦 👈 ❎ 🌐. - -### 🔓 🌐 - -🔓 🆕 🌐 ⏮️: - -//// tab | 💾, 🇸🇻 - -
- -```console -$ source ./env/bin/activate -``` - -
- -//// - -//// tab | 🚪 📋 - -
- -```console -$ .\env\Scripts\Activate.ps1 -``` - -
- -//// - -//// tab | 🚪 🎉 - -⚖️ 🚥 👆 ⚙️ 🎉 🖥 (✅ 🐛 🎉): - -
- -```console -$ source ./env/Scripts/activate -``` - -
- -//// - -✅ ⚫️ 👷, ⚙️: - -//// tab | 💾, 🇸🇻, 🚪 🎉 - -
- -```console -$ which pip - -some/directory/fastapi/env/bin/pip -``` - -
- -//// - -//// tab | 🚪 📋 - -
- -```console -$ Get-Command pip - -some/directory/fastapi/env/bin/pip -``` - -
- -//// - -🚥 ⚫️ 🎦 `pip` 💱 `env/bin/pip` ⤴️ ⚫️ 👷. 👶 - -⚒ 💭 👆 ✔️ 📰 🐖 ⏬ 🔛 👆 🕹 🌐 ❎ ❌ 🔛 ⏭ 📶: - -
- -```console -$ python -m pip install --upgrade pip - ----> 100% -``` - -
- -/// tip - -🔠 🕰 👆 ❎ 🆕 📦 ⏮️ `pip` 🔽 👈 🌐, 🔓 🌐 🔄. - -👉 ⚒ 💭 👈 🚥 👆 ⚙️ 📶 📋 ❎ 👈 📦, 👆 ⚙️ 1️⃣ ⚪️➡️ 👆 🇧🇿 🌐 & 🚫 🙆 🎏 👈 💪 ❎ 🌐. - -/// - -### 🐖 - -⏮️ 🔓 🌐 🔬 🔛: - -
- -```console -$ pip install -r requirements.txt - ----> 100% -``` - -
- -⚫️ 🔜 ❎ 🌐 🔗 & 👆 🇧🇿 FastAPI 👆 🇧🇿 🌐. - -#### ⚙️ 👆 🇧🇿 FastAPI - -🚥 👆 ✍ 🐍 📁 👈 🗄 & ⚙️ FastAPI, & 🏃 ⚫️ ⏮️ 🐍 ⚪️➡️ 👆 🇧🇿 🌐, ⚫️ 🔜 ⚙️ 👆 🇧🇿 FastAPI ℹ 📟. - -& 🚥 👆 ℹ 👈 🇧🇿 FastAPI ℹ 📟, ⚫️ ❎ ⏮️ `-e`, 🕐❔ 👆 🏃 👈 🐍 📁 🔄, ⚫️ 🔜 ⚙️ 🍋 ⏬ FastAPI 👆 ✍. - -👈 🌌, 👆 🚫 ✔️ "❎" 👆 🇧🇿 ⏬ 💪 💯 🔠 🔀. - -### 📁 - -📤 ✍ 👈 👆 💪 🏃 👈 🔜 📁 & 🧹 🌐 👆 📟: - -
- -```console -$ bash scripts/format.sh -``` - -
- -⚫️ 🔜 🚘-😇 🌐 👆 🗄. - -⚫️ 😇 👫 ☑, 👆 💪 ✔️ FastAPI ❎ 🌐 👆 🌐, ⏮️ 📋 📄 🔛 ⚙️ `-e`. - -## 🩺 - -🥇, ⚒ 💭 👆 ⚒ 🆙 👆 🌐 🔬 🔛, 👈 🔜 ❎ 🌐 📄. - -🧾 ⚙️ . - -& 📤 ➕ 🧰/✍ 🥉 🍵 ✍ `./scripts/docs.py`. - -/// tip - -👆 🚫 💪 👀 📟 `./scripts/docs.py`, 👆 ⚙️ ⚫️ 📋 ⏸. - -/// - -🌐 🧾 ✍ 📁 📁 `./docs/en/`. - -📚 🔰 ✔️ 🍫 📟. - -🌅 💼, 👫 🍫 📟 ☑ 🏁 🈸 👈 💪 🏃. - -👐, 👈 🍫 📟 🚫 ✍ 🔘 ✍, 👫 🐍 📁 `./docs_src/` 📁. - -& 👈 🐍 📁 🔌/💉 🧾 🕐❔ 🏭 🕸. - -### 🩺 💯 - -🏆 💯 🤙 🏃 🛡 🖼 ℹ 📁 🧾. - -👉 ℹ ⚒ 💭 👈: - -* 🧾 🆙 📅. -* 🧾 🖼 💪 🏃. -* 🌅 ⚒ 📔 🧾, 🚚 💯 💰. - -⏮️ 🇧🇿 🛠️, 📤 ✍ 👈 🏗 🕸 & ✅ 🙆 🔀, 🖖-🔫: - -
- -```console -$ python ./scripts/docs.py live - -[INFO] Serving on http://127.0.0.1:8008 -[INFO] Start watching changes -[INFO] Start detecting changes -``` - -
- -⚫️ 🔜 🍦 🧾 🔛 `http://127.0.0.1:8008`. - -👈 🌌, 👆 💪 ✍ 🧾/ℹ 📁 & 👀 🔀 🖖. - -#### 🏎 ✳ (📦) - -👩‍🌾 📥 🎦 👆 ❔ ⚙️ ✍ `./scripts/docs.py` ⏮️ `python` 📋 🔗. - -✋️ 👆 💪 ⚙️ 🏎 ✳, & 👆 🔜 🤚 ✍ 👆 📶 📋 ⏮️ ❎ 🛠️. - -🚥 👆 ❎ 🏎 ✳, 👆 💪 ❎ 🛠️ ⏮️: - -
- -```console -$ typer --install-completion - -zsh completion installed in /home/user/.bashrc. -Completion will take effect once you restart the terminal. -``` - -
- -### 📱 & 🩺 🎏 🕰 - -🚥 👆 🏃 🖼 ⏮️, ✅: - -
- -```console -$ uvicorn tutorial001:app --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -
- -Uvicorn 🔢 🔜 ⚙️ ⛴ `8000`, 🧾 🔛 ⛴ `8008` 🏆 🚫 ⚔. - -### ✍ - -ℹ ⏮️ ✍ 📶 🌅 👍 ❗ & ⚫️ 💪 🚫 🔨 🍵 ℹ ⚪️➡️ 👪. 👶 👶 - -📥 📶 ℹ ⏮️ ✍. - -#### 💁‍♂ & 📄 - -* ✅ ⏳ ♻ 🚲 📨 👆 🇪🇸 & 🚮 📄 ✔ 🔀 ⚖️ ✔ 👫. - -/// tip - -👆 💪 🚮 🏤 ⏮️ 🔀 🔑 ♻ 🚲 📨. - -✅ 🩺 🔃 ❎ 🚲 📨 📄 ✔ ⚫️ ⚖️ 📨 🔀. - -/// - -* ✅ 👀 🚥 📤 1️⃣ 🛠️ ✍ 👆 🇪🇸. - -* 🚮 👁 🚲 📨 📍 📃 💬. 👈 🔜 ⚒ ⚫️ 🌅 ⏩ 🎏 📄 ⚫️. - -🇪🇸 👤 🚫 💬, 👤 🔜 ⌛ 📚 🎏 📄 ✍ ⏭ 🔗. - -* 👆 💪 ✅ 🚥 📤 ✍ 👆 🇪🇸 & 🚮 📄 👫, 👈 🔜 ℹ 👤 💭 👈 ✍ ☑ & 👤 💪 🔗 ⚫️. - -* ⚙️ 🎏 🐍 🖼 & 🕴 💬 ✍ 🩺. 👆 🚫 ✔️ 🔀 🕳 👉 👷. - -* ⚙️ 🎏 🖼, 📁 📛, & 🔗. 👆 🚫 ✔️ 🔀 🕳 ⚫️ 👷. - -* ✅ 2️⃣-🔤 📟 🇪🇸 👆 💚 💬 👆 💪 ⚙️ 🏓 📇 💾 6️⃣3️⃣9️⃣-1️⃣ 📟. - -#### ♻ 🇪🇸 - -➡️ 💬 👆 💚 💬 📃 🇪🇸 👈 ⏪ ✔️ ✍ 📃, 💖 🇪🇸. - -💼 🇪🇸, 2️⃣-🔤 📟 `es`. , 📁 🇪🇸 ✍ 🔎 `docs/es/`. - -/// tip - -👑 ("🛂") 🇪🇸 🇪🇸, 🔎 `docs/en/`. - -/// - -🔜 🏃 🖖 💽 🩺 🇪🇸: - -
- -```console -// Use the command "live" and pass the language code as a CLI argument -$ python ./scripts/docs.py live es - -[INFO] Serving on http://127.0.0.1:8008 -[INFO] Start watching changes -[INFO] Start detecting changes -``` - -
- -🔜 👆 💪 🚶 http://127.0.0.1:8008 & 👀 👆 🔀 🖖. - -🚥 👆 👀 FastAPI 🩺 🕸, 👆 🔜 👀 👈 🔠 🇪🇸 ✔️ 🌐 📃. ✋️ 📃 🚫 💬 & ✔️ 📨 🔃 ❌ ✍. - -✋️ 🕐❔ 👆 🏃 ⚫️ 🌐 💖 👉, 👆 🔜 🕴 👀 📃 👈 ⏪ 💬. - -🔜 ➡️ 💬 👈 👆 💚 🚮 ✍ 📄 [⚒](features.md){.internal-link target=_blank}. - -* 📁 📁: - -``` -docs/en/docs/features.md -``` - -* 📋 ⚫️ ⚫️❔ 🎏 🗺 ✋️ 🇪🇸 👆 💚 💬, ✅: - -``` -docs/es/docs/features.md -``` - -/// tip - -👀 👈 🕴 🔀 ➡ & 📁 📛 🇪🇸 📟, ⚪️➡️ `en` `es`. - -/// - -* 🔜 📂 ⬜ 📁 📁 🇪🇸: - -``` -docs/en/mkdocs.yml -``` - -* 🔎 🥉 🌐❔ 👈 `docs/features.md` 🔎 📁 📁. 👱 💖: - -```YAML hl_lines="8" -site_name: FastAPI -# More stuff -nav: -- FastAPI: index.md -- Languages: - - en: / - - es: /es/ -- features.md -``` - -* 📂 ⬜ 📁 📁 🇪🇸 👆 ✍, ✅: - -``` -docs/es/mkdocs.yml -``` - -* 🚮 ⚫️ 📤 ☑ 🎏 🗺 ⚫️ 🇪🇸, ✅: - -```YAML hl_lines="8" -site_name: FastAPI -# More stuff -nav: -- FastAPI: index.md -- Languages: - - en: / - - es: /es/ -- features.md -``` - -⚒ 💭 👈 🚥 📤 🎏 ⛔, 🆕 ⛔ ⏮️ 👆 ✍ ⚫️❔ 🎏 ✔ 🇪🇸 ⏬. - -🚥 👆 🚶 👆 🖥 👆 🔜 👀 👈 🔜 🩺 🎦 👆 🆕 📄. 👶 - -🔜 👆 💪 💬 ⚫️ 🌐 & 👀 ❔ ⚫️ 👀 👆 🖊 📁. - -#### 🆕 🇪🇸 - -➡️ 💬 👈 👆 💚 🚮 ✍ 🇪🇸 👈 🚫 💬, 🚫 📃. - -➡️ 💬 👆 💚 🚮 ✍ 🇭🇹, & ⚫️ 🚫 📤 🩺. - -✅ 🔗 ⚪️➡️ 🔛, 📟 "🇭🇹" `ht`. - -⏭ 🔁 🏃 ✍ 🏗 🆕 ✍ 📁: - -
- -```console -// Use the command new-lang, pass the language code as a CLI argument -$ python ./scripts/docs.py new-lang ht - -Successfully initialized: docs/ht -Updating ht -Updating en -``` - -
- -🔜 👆 💪 ✅ 👆 📟 👨‍🎨 ⏳ ✍ 📁 `docs/ht/`. - -/// tip - -✍ 🥇 🚲 📨 ⏮️ 👉, ⚒ 🆙 📳 🆕 🇪🇸, ⏭ ❎ ✍. - -👈 🌌 🎏 💪 ℹ ⏮️ 🎏 📃 ⏪ 👆 👷 🔛 🥇 🕐. 👶 - -/// - -▶️ ✍ 👑 📃, `docs/ht/index.md`. - -⤴️ 👆 💪 😣 ⏮️ ⏮️ 👩‍🌾, "♻ 🇪🇸". - -##### 🆕 🇪🇸 🚫 🐕‍🦺 - -🚥 🕐❔ 🏃‍♂ 🖖 💽 ✍ 👆 🤚 ❌ 🔃 🇪🇸 🚫 ➖ 🐕‍🦺, 🕳 💖: - -``` - raise TemplateNotFound(template) -jinja2.exceptions.TemplateNotFound: partials/language/xx.html -``` - -👈 ⛓ 👈 🎢 🚫 🐕‍🦺 👈 🇪🇸 (👉 💼, ⏮️ ❌ 2️⃣-🔤 📟 `xx`). - -✋️ 🚫 😟, 👆 💪 ⚒ 🎢 🇪🇸 🇪🇸 & ⤴️ 💬 🎚 🩺. - -🚥 👆 💪 👈, ✍ `mkdocs.yml` 👆 🆕 🇪🇸, ⚫️ 🔜 ✔️ 🕳 💖: - -```YAML hl_lines="5" -site_name: FastAPI -# More stuff -theme: - # More stuff - language: xx -``` - -🔀 👈 🇪🇸 ⚪️➡️ `xx` (⚪️➡️ 👆 🇪🇸 📟) `en`. - -⤴️ 👆 💪 ▶️ 🖖 💽 🔄. - -#### 🎮 🏁 - -🕐❔ 👆 ⚙️ ✍ `./scripts/docs.py` ⏮️ `live` 📋 ⚫️ 🕴 🎦 📁 & ✍ 💪 ⏮️ 🇪🇸. - -✋️ 🕐 👆 🔨, 👆 💪 💯 ⚫️ 🌐 ⚫️ 🔜 👀 💳. - -👈, 🥇 🏗 🌐 🩺: - -
- -```console -// Use the command "build-all", this will take a bit -$ python ./scripts/docs.py build-all - -Updating es -Updating en -Building docs for: en -Building docs for: es -Successfully built docs for: es -Copying en index.md to README.md -``` - -
- -👈 🏗 🌐 🩺 `./docs_build/` 🔠 🇪🇸. 👉 🔌 ❎ 🙆 📁 ⏮️ ❌ ✍, ⏮️ 🗒 💬 👈 "👉 📁 🚫 ✔️ ✍". ✋️ 👆 🚫 ✔️ 🕳 ⏮️ 👈 📁. - -⤴️ ⚫️ 🏗 🌐 👈 🔬 ⬜ 🕸 🔠 🇪🇸, 🌀 👫, & 🏗 🏁 🔢 `./site/`. - -⤴️ 👆 💪 🍦 👈 ⏮️ 📋 `serve`: - -
- -```console -// Use the command "serve" after running "build-all" -$ python ./scripts/docs.py serve - -Warning: this is a very simple server. For development, use mkdocs serve instead. -This is here only to preview a site with translations already built. -Make sure you run the build-all command first. -Serving at: http://127.0.0.1:8008 -``` - -
- -## 💯 - -📤 ✍ 👈 👆 💪 🏃 🌐 💯 🌐 📟 & 🏗 💰 📄 🕸: - -
- -```console -$ bash scripts/test-cov-html.sh -``` - -
- -👉 📋 🏗 📁 `./htmlcov/`, 🚥 👆 📂 📁 `./htmlcov/index.html` 👆 🖥, 👆 💪 🔬 🖥 🇹🇼 📟 👈 📔 💯, & 👀 🚥 📤 🙆 🇹🇼 ❌. diff --git a/docs/em/docs/how-to/conditional-openapi.md b/docs/em/docs/how-to/conditional-openapi.md index a5932933a6d4e..e47ea0c35c387 100644 --- a/docs/em/docs/how-to/conditional-openapi.md +++ b/docs/em/docs/how-to/conditional-openapi.md @@ -29,9 +29,7 @@ 🖼: -```Python hl_lines="6 11" -{!../../docs_src/conditional_openapi/tutorial001.py!} -``` +{* ../../docs_src/conditional_openapi/tutorial001.py hl[6,11] *} 📥 👥 📣 ⚒ `openapi_url` ⏮️ 🎏 🔢 `"/openapi.json"`. diff --git a/docs/em/docs/how-to/custom-request-and-route.md b/docs/em/docs/how-to/custom-request-and-route.md index 0425e6267c494..8974e7d95a5fd 100644 --- a/docs/em/docs/how-to/custom-request-and-route.md +++ b/docs/em/docs/how-to/custom-request-and-route.md @@ -42,9 +42,7 @@ 👈 🌌, 🎏 🛣 🎓 💪 🍵 🗜 🗜 ⚖️ 🗜 📨. -```Python hl_lines="8-15" -{!../../docs_src/custom_request_and_route/tutorial001.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial001.py hl[8:15] *} ### ✍ 🛃 `GzipRoute` 🎓 @@ -56,11 +54,9 @@ 📥 👥 ⚙️ ⚫️ ✍ `GzipRequest` ⚪️➡️ ⏮️ 📨. -```Python hl_lines="18-26" -{!../../docs_src/custom_request_and_route/tutorial001.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial001.py hl[18:26] *} -/// note | "📡 ℹ" +/// note | 📡 ℹ `Request` ✔️ `request.scope` 🔢, 👈 🐍 `dict` ⚗ 🗃 🔗 📨. @@ -96,26 +92,18 @@ 🌐 👥 💪 🍵 📨 🔘 `try`/`except` 🍫: -```Python hl_lines="13 15" -{!../../docs_src/custom_request_and_route/tutorial002.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial002.py hl[13,15] *} 🚥 ⚠ 📉, `Request` 👐 🔜 ↔, 👥 💪 ✍ & ⚒ ⚙️ 📨 💪 🕐❔ 🚚 ❌: -```Python hl_lines="16-18" -{!../../docs_src/custom_request_and_route/tutorial002.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial002.py hl[16:18] *} ## 🛃 `APIRoute` 🎓 📻 👆 💪 ⚒ `route_class` 🔢 `APIRouter`: -```Python hl_lines="26" -{!../../docs_src/custom_request_and_route/tutorial003.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial003.py hl[26] *} 👉 🖼, *➡ 🛠️* 🔽 `router` 🔜 ⚙️ 🛃 `TimedRoute` 🎓, & 🔜 ✔️ ➕ `X-Response-Time` 🎚 📨 ⏮️ 🕰 ⚫️ ✊ 🏗 📨: -```Python hl_lines="13-20" -{!../../docs_src/custom_request_and_route/tutorial003.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial003.py hl[13:20] *} diff --git a/docs/em/docs/how-to/extending-openapi.md b/docs/em/docs/how-to/extending-openapi.md index 698c78ec14a51..c3e6c7f66705f 100644 --- a/docs/em/docs/how-to/extending-openapi.md +++ b/docs/em/docs/how-to/extending-openapi.md @@ -46,25 +46,19 @@ 🥇, ✍ 🌐 👆 **FastAPI** 🈸 🛎: -```Python hl_lines="1 4 7-9" -{!../../docs_src/extending_openapi/tutorial001.py!} -``` +{* ../../docs_src/extending_openapi/tutorial001.py hl[1,4,7:9] *} ### 🏗 🗄 🔗 ⤴️, ⚙️ 🎏 🚙 🔢 🏗 🗄 🔗, 🔘 `custom_openapi()` 🔢: -```Python hl_lines="2 15-20" -{!../../docs_src/extending_openapi/tutorial001.py!} -``` +{* ../../docs_src/extending_openapi/tutorial001.py hl[2,15:20] *} ### 🔀 🗄 🔗 🔜 👆 💪 🚮 📄 ↔, ❎ 🛃 `x-logo` `info` "🎚" 🗄 🔗: -```Python hl_lines="21-23" -{!../../docs_src/extending_openapi/tutorial001.py!} -``` +{* ../../docs_src/extending_openapi/tutorial001.py hl[21:23] *} ### 💾 🗄 🔗 @@ -74,17 +68,13 @@ ⚫️ 🔜 🏗 🕴 🕐, & ⤴️ 🎏 💾 🔗 🔜 ⚙️ ⏭ 📨. -```Python hl_lines="13-14 24-25" -{!../../docs_src/extending_openapi/tutorial001.py!} -``` +{* ../../docs_src/extending_openapi/tutorial001.py hl[13:14,24:25] *} ### 🔐 👩‍🔬 🔜 👆 💪 ❎ `.openapi()` 👩‍🔬 ⏮️ 👆 🆕 🔢. -```Python hl_lines="28" -{!../../docs_src/extending_openapi/tutorial001.py!} -``` +{* ../../docs_src/extending_openapi/tutorial001.py hl[28] *} ### ✅ ⚫️ diff --git a/docs/em/docs/how-to/graphql.md b/docs/em/docs/how-to/graphql.md index 5d0d95567253e..083e9ebd2876f 100644 --- a/docs/em/docs/how-to/graphql.md +++ b/docs/em/docs/how-to/graphql.md @@ -35,9 +35,7 @@ 📥 🤪 🎮 ❔ 👆 💪 🛠️ 🍓 ⏮️ FastAPI: -```Python hl_lines="3 22 25-26" -{!../../docs_src/graphql/tutorial001.py!} -``` +{* ../../docs_src/graphql/tutorial001.py hl[3,22,25:26] *} 👆 💪 💡 🌅 🔃 🍓 🍓 🧾. diff --git a/docs/em/docs/tutorial/background-tasks.md b/docs/em/docs/tutorial/background-tasks.md index 0f4585ebe1a8b..aed60c754a7f6 100644 --- a/docs/em/docs/tutorial/background-tasks.md +++ b/docs/em/docs/tutorial/background-tasks.md @@ -15,9 +15,7 @@ 🥇, 🗄 `BackgroundTasks` & 🔬 🔢 👆 *➡ 🛠️ 🔢* ⏮️ 🆎 📄 `BackgroundTasks`: -```Python hl_lines="1 13" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *} **FastAPI** 🔜 ✍ 🎚 🆎 `BackgroundTasks` 👆 & 🚶‍♀️ ⚫️ 👈 🔢. @@ -33,17 +31,13 @@ & ✍ 🛠️ 🚫 ⚙️ `async` & `await`, 👥 🔬 🔢 ⏮️ 😐 `def`: -```Python hl_lines="6-9" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *} ## 🚮 🖥 📋 🔘 👆 *➡ 🛠️ 🔢*, 🚶‍♀️ 👆 📋 🔢 *🖥 📋* 🎚 ⏮️ 👩‍🔬 `.add_task()`: -```Python hl_lines="14" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[14] *} `.add_task()` 📨 ❌: @@ -57,21 +51,7 @@ **FastAPI** 💭 ⚫️❔ 🔠 💼 & ❔ 🏤-⚙️ 🎏 🎚, 👈 🌐 🖥 📋 🔗 👯‍♂️ & 🏃 🖥 ⏮️: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="13 15 22 25" -{!> ../../docs_src/background_tasks/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="11 13 20 23" -{!> ../../docs_src/background_tasks/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/background_tasks/tutorial002.py hl[13,15,22,25] *} 👉 🖼, 📧 🔜 ✍ `log.txt` 📁 *⏮️* 📨 📨. @@ -97,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 074ab302c8336..68f506f27ecd7 100644 --- a/docs/em/docs/tutorial/bigger-applications.md +++ b/docs/em/docs/tutorial/bigger-applications.md @@ -414,7 +414,7 @@ from .routers.users import router ⚫️ 🔜 🔌 🌐 🛣 ⚪️➡️ 👈 📻 🍕 ⚫️. -/// note | "📡 ℹ" +/// note | 📡 ℹ ⚫️ 🔜 🤙 🔘 ✍ *➡ 🛠️* 🔠 *➡ 🛠️* 👈 📣 `APIRouter`. @@ -477,7 +477,7 @@ from .routers.users import router & ⚫️ 🔜 👷 ☑, 👯‍♂️ ⏮️ 🌐 🎏 *➡ 🛠️* 🚮 ⏮️ `app.include_router()`. -/// info | "📶 📡 ℹ" +/// info | 📶 📡 ℹ **🗒**: 👉 📶 📡 ℹ 👈 👆 🎲 💪 **🚶**. diff --git a/docs/em/docs/tutorial/body-fields.md b/docs/em/docs/tutorial/body-fields.md index eb3093de2725a..f202284b5bc64 100644 --- a/docs/em/docs/tutorial/body-fields.md +++ b/docs/em/docs/tutorial/body-fields.md @@ -6,21 +6,7 @@ 🥇, 👆 ✔️ 🗄 ⚫️: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="4" -{!> ../../docs_src/body_fields/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="2" -{!> ../../docs_src/body_fields/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/body_fields/tutorial001.py hl[4] *} /// warning @@ -32,25 +18,11 @@ 👆 💪 ⤴️ ⚙️ `Field` ⏮️ 🏷 🔢: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="11-14" -{!> ../../docs_src/body_fields/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="9-12" -{!> ../../docs_src/body_fields/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/body_fields/tutorial001.py hl[11:14] *} `Field` 👷 🎏 🌌 `Query`, `Path` & `Body`, ⚫️ ✔️ 🌐 🎏 🔢, ♒️. -/// note | "📡 ℹ" +/// note | 📡 ℹ 🤙, `Query`, `Path` & 🎏 👆 🔜 👀 ⏭ ✍ 🎚 🏿 ⚠ `Param` 🎓, ❔ ⚫️ 🏿 Pydantic `FieldInfo` 🎓. diff --git a/docs/em/docs/tutorial/body-multiple-params.md b/docs/em/docs/tutorial/body-multiple-params.md index 2e20c83f951fc..3a2f2bd547675 100644 --- a/docs/em/docs/tutorial/body-multiple-params.md +++ b/docs/em/docs/tutorial/body-multiple-params.md @@ -8,21 +8,7 @@ & 👆 💪 📣 💪 🔢 📦, ⚒ 🔢 `None`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="19-21" -{!> ../../docs_src/body_multiple_params/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="17-19" -{!> ../../docs_src/body_multiple_params/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial001.py hl[19:21] *} /// note @@ -45,21 +31,7 @@ ✋️ 👆 💪 📣 💗 💪 🔢, ✅ `item` & `user`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="22" -{!> ../../docs_src/body_multiple_params/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="20" -{!> ../../docs_src/body_multiple_params/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial002.py hl[22] *} 👉 💼, **FastAPI** 🔜 👀 👈 📤 🌅 🌘 1️⃣ 💪 🔢 🔢 (2️⃣ 🔢 👈 Pydantic 🏷). @@ -100,21 +72,7 @@ ✋️ 👆 💪 💡 **FastAPI** 😥 ⚫️ ➕1️⃣ 💪 🔑 ⚙️ `Body`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="22" -{!> ../../docs_src/body_multiple_params/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="20" -{!> ../../docs_src/body_multiple_params/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial003.py hl[22] *} 👉 💼, **FastAPI** 🔜 ⌛ 💪 💖: @@ -154,21 +112,7 @@ q: str | None = None 🖼: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="27" -{!> ../../docs_src/body_multiple_params/tutorial004.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="26" -{!> ../../docs_src/body_multiple_params/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial004.py hl[27] *} /// info @@ -190,21 +134,7 @@ item: Item = Body(embed=True) : -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="17" -{!> ../../docs_src/body_multiple_params/tutorial005.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="15" -{!> ../../docs_src/body_multiple_params/tutorial005_py310.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial005.py hl[17] *} 👉 💼 **FastAPI** 🔜 ⌛ 💪 💖: diff --git a/docs/em/docs/tutorial/body-nested-models.md b/docs/em/docs/tutorial/body-nested-models.md index 3b56b7a07cdfa..6c8d5a61008c8 100644 --- a/docs/em/docs/tutorial/body-nested-models.md +++ b/docs/em/docs/tutorial/body-nested-models.md @@ -6,21 +6,7 @@ 👆 💪 🔬 🔢 🏾. 🖼, 🐍 `list`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="12" -{!> ../../docs_src/body_nested_models/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial001.py hl[14] *} 👉 🔜 ⚒ `tags` 📇, 👐 ⚫️ 🚫 📣 🆎 🔣 📇. @@ -34,9 +20,7 @@ ✋️ 🐍 ⏬ ⏭ 3️⃣.9️⃣ (3️⃣.6️⃣ & 🔛), 👆 🥇 💪 🗄 `List` ⚪️➡️ 🐩 🐍 `typing` 🕹: -```Python hl_lines="1" -{!> ../../docs_src/body_nested_models/tutorial002.py!} -``` +{* ../../docs_src/body_nested_models/tutorial002.py hl[1] *} ### 📣 `list` ⏮️ 🆎 🔢 @@ -65,29 +49,7 @@ my_list: List[str] , 👆 🖼, 👥 💪 ⚒ `tags` 🎯 "📇 🎻": -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial002_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="12" -{!> ../../docs_src/body_nested_models/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial002.py hl[14] *} ## ⚒ 🆎 @@ -97,29 +59,7 @@ my_list: List[str] ⤴️ 👥 💪 📣 `tags` ⚒ 🎻: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="1 14" -{!> ../../docs_src/body_nested_models/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial003_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="12" -{!> ../../docs_src/body_nested_models/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial003.py hl[1,14] *} ⏮️ 👉, 🚥 👆 📨 📨 ⏮️ ❎ 📊, ⚫️ 🔜 🗜 ⚒ 😍 🏬. @@ -141,57 +81,13 @@ my_list: List[str] 🖼, 👥 💪 🔬 `Image` 🏷: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9-11" -{!> ../../docs_src/body_nested_models/tutorial004.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="9-11" -{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7-9" -{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial004.py hl[9:11] *} ### ⚙️ 📊 🆎 & ⤴️ 👥 💪 ⚙️ ⚫️ 🆎 🔢: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial004.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="18" -{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial004.py hl[20] *} 👉 🔜 ⛓ 👈 **FastAPI** 🔜 ⌛ 💪 🎏: @@ -224,29 +120,7 @@ my_list: List[str] 🖼, `Image` 🏷 👥 ✔️ `url` 🏑, 👥 💪 📣 ⚫️ ↩️ `str`, Pydantic `HttpUrl`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="4 10" -{!> ../../docs_src/body_nested_models/tutorial005.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="4 10" -{!> ../../docs_src/body_nested_models/tutorial005_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="2 8" -{!> ../../docs_src/body_nested_models/tutorial005_py310.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial005.py hl[4,10] *} 🎻 🔜 ✅ ☑ 📛, & 📄 🎻 🔗 / 🗄 ✅. @@ -254,29 +128,7 @@ my_list: List[str] 👆 💪 ⚙️ Pydantic 🏷 🏾 `list`, `set`, ♒️: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial006.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial006_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="18" -{!> ../../docs_src/body_nested_models/tutorial006_py310.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial006.py hl[20] *} 👉 🔜 ⌛ (🗜, ✔, 📄, ♒️) 🎻 💪 💖: @@ -314,29 +166,7 @@ my_list: List[str] 👆 💪 🔬 🎲 🙇 🐦 🏷: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9 14 20 23 27" -{!> ../../docs_src/body_nested_models/tutorial007.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="9 14 20 23 27" -{!> ../../docs_src/body_nested_models/tutorial007_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7 12 18 21 25" -{!> ../../docs_src/body_nested_models/tutorial007_py310.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial007.py hl[9,14,20,23,27] *} /// info @@ -360,21 +190,7 @@ images: list[Image] : -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="15" -{!> ../../docs_src/body_nested_models/tutorial008.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="13" -{!> ../../docs_src/body_nested_models/tutorial008_py39.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial008.py hl[15] *} ## 👨‍🎨 🐕‍🦺 🌐 @@ -404,21 +220,7 @@ images: list[Image] 👉 💼, 👆 🔜 🚫 🙆 `dict` 📏 ⚫️ ✔️ `int` 🔑 ⏮️ `float` 💲: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/body_nested_models/tutorial009.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="7" -{!> ../../docs_src/body_nested_models/tutorial009_py39.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial009.py hl[9] *} /// tip diff --git a/docs/em/docs/tutorial/body-updates.md b/docs/em/docs/tutorial/body-updates.md index 4a4b3b6b876f2..7e2fbfaf79e18 100644 --- a/docs/em/docs/tutorial/body-updates.md +++ b/docs/em/docs/tutorial/body-updates.md @@ -6,29 +6,7 @@ 👆 💪 ⚙️ `jsonable_encoder` 🗜 🔢 💽 📊 👈 💪 🏪 🎻 (✅ ⏮️ ☁ 💽). 🖼, 🏭 `datetime` `str`. -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="30-35" -{!> ../../docs_src/body_updates/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="30-35" -{!> ../../docs_src/body_updates/tutorial001_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="28-33" -{!> ../../docs_src/body_updates/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial001.py hl[30:35] *} `PUT` ⚙️ 📨 💽 👈 🔜 ❎ ♻ 💽. @@ -76,29 +54,7 @@ ⤴️ 👆 💪 ⚙️ 👉 🏗 `dict` ⏮️ 🕴 💽 👈 ⚒ (📨 📨), 🚫 🔢 💲: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="34" -{!> ../../docs_src/body_updates/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="34" -{!> ../../docs_src/body_updates/tutorial002_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="32" -{!> ../../docs_src/body_updates/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial002.py hl[34] *} ### ⚙️ Pydantic `update` 🔢 @@ -106,29 +62,7 @@ 💖 `stored_item_model.copy(update=update_data)`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="35" -{!> ../../docs_src/body_updates/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="35" -{!> ../../docs_src/body_updates/tutorial002_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="33" -{!> ../../docs_src/body_updates/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial002.py hl[35] *} ### 🍕 ℹ 🌃 @@ -145,29 +79,7 @@ * 🖊 💽 👆 💽. * 📨 ℹ 🏷. -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="30-37" -{!> ../../docs_src/body_updates/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="30-37" -{!> ../../docs_src/body_updates/tutorial002_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="28-35" -{!> ../../docs_src/body_updates/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial002.py hl[30:37] *} /// tip diff --git a/docs/em/docs/tutorial/body.md b/docs/em/docs/tutorial/body.md index 3468fc5122bcb..09e1d7ccaa345 100644 --- a/docs/em/docs/tutorial/body.md +++ b/docs/em/docs/tutorial/body.md @@ -22,21 +22,7 @@ 🥇, 👆 💪 🗄 `BaseModel` ⚪️➡️ `pydantic`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="4" -{!> ../../docs_src/body/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="2" -{!> ../../docs_src/body/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/body/tutorial001.py hl[4] *} ## ✍ 👆 💽 🏷 @@ -44,21 +30,7 @@ ⚙️ 🐩 🐍 🆎 🌐 🔢: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="7-11" -{!> ../../docs_src/body/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="5-9" -{!> ../../docs_src/body/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/body/tutorial001.py hl[7:11] *} 🎏 🕐❔ 📣 🔢 🔢, 🕐❔ 🏷 🔢 ✔️ 🔢 💲, ⚫️ 🚫 ✔. ⏪, ⚫️ ✔. ⚙️ `None` ⚒ ⚫️ 📦. @@ -86,21 +58,7 @@ 🚮 ⚫️ 👆 *➡ 🛠️*, 📣 ⚫️ 🎏 🌌 👆 📣 ➡ & 🔢 🔢: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="18" -{!> ../../docs_src/body/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="16" -{!> ../../docs_src/body/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/body/tutorial001.py hl[18] *} ...& 📣 🚮 🆎 🏷 👆 ✍, `Item`. @@ -167,21 +125,7 @@ 🔘 🔢, 👆 💪 🔐 🌐 🔢 🏷 🎚 🔗: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="21" -{!> ../../docs_src/body/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="19" -{!> ../../docs_src/body/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/body/tutorial002.py hl[21] *} ## 📨 💪 ➕ ➡ 🔢 @@ -189,21 +133,7 @@ **FastAPI** 🔜 🤔 👈 🔢 🔢 👈 🏏 ➡ 🔢 🔜 **✊ ⚪️➡️ ➡**, & 👈 🔢 🔢 👈 📣 Pydantic 🏷 🔜 **✊ ⚪️➡️ 📨 💪**. -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="17-18" -{!> ../../docs_src/body/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="15-16" -{!> ../../docs_src/body/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/body/tutorial003.py hl[17:18] *} ## 📨 💪 ➕ ➡ ➕ 🔢 🔢 @@ -211,21 +141,7 @@ **FastAPI** 🔜 🤔 🔠 👫 & ✊ 📊 ⚪️➡️ ☑ 🥉. -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="18" -{!> ../../docs_src/body/tutorial004.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="16" -{!> ../../docs_src/body/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/body/tutorial004.py hl[18] *} 🔢 🔢 🔜 🤔 ⏩: diff --git a/docs/em/docs/tutorial/cookie-params.md b/docs/em/docs/tutorial/cookie-params.md index f4956e76f3e12..4699fe2a545dc 100644 --- a/docs/em/docs/tutorial/cookie-params.md +++ b/docs/em/docs/tutorial/cookie-params.md @@ -6,21 +6,7 @@ 🥇 🗄 `Cookie`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="1" -{!> ../../docs_src/cookie_params/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/cookie_params/tutorial001.py hl[3] *} ## 📣 `Cookie` 🔢 @@ -28,23 +14,9 @@ 🥇 💲 🔢 💲, 👆 💪 🚶‍♀️ 🌐 ➕ 🔬 ⚖️ ✍ 🔢: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7" -{!> ../../docs_src/cookie_params/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/cookie_params/tutorial001.py hl[9] *} -/// note | "📡 ℹ" +/// note | 📡 ℹ `Cookie` "👭" 🎓 `Path` & `Query`. ⚫️ 😖 ⚪️➡️ 🎏 ⚠ `Param` 🎓. diff --git a/docs/em/docs/tutorial/cors.md b/docs/em/docs/tutorial/cors.md index 5829319cb2a15..44ab4adc59120 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,7 @@ 🌖 ℹ 🔃 , ✅ 🦎 ⚜ 🧾. -/// note | "📡 ℹ" +/// note | 📡 ℹ 👆 💪 ⚙️ `from starlette.middleware.cors import CORSMiddleware`. diff --git a/docs/em/docs/tutorial/debugging.md b/docs/em/docs/tutorial/debugging.md index 9320370d66f10..97e61a763f7bd 100644 --- a/docs/em/docs/tutorial/debugging.md +++ b/docs/em/docs/tutorial/debugging.md @@ -6,9 +6,7 @@ 👆 FastAPI 🈸, 🗄 & 🏃 `uvicorn` 🔗: -```Python hl_lines="1 15" -{!../../docs_src/debugging/tutorial001.py!} -``` +{* ../../docs_src/debugging/tutorial001.py hl[1,15] *} ### 🔃 `__name__ == "__main__"` diff --git a/docs/em/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/em/docs/tutorial/dependencies/classes-as-dependencies.md index 3e58d506ceccb..41938bc7b89ee 100644 --- a/docs/em/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/em/docs/tutorial/dependencies/classes-as-dependencies.md @@ -6,21 +6,7 @@ ⏮️ 🖼, 👥 🛬 `dict` ⚪️➡️ 👆 🔗 ("☑"): -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001.py hl[9] *} ✋️ ⤴️ 👥 🤚 `dict` 🔢 `commons` *➡ 🛠️ 🔢*. @@ -83,57 +69,15 @@ fluffy = Cat(name="Mr Fluffy") ⤴️, 👥 💪 🔀 🔗 "☑" `common_parameters` ⚪️➡️ 🔛 🎓 `CommonQueryParams`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="11-15" -{!> ../../docs_src/dependencies/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="9-13" -{!> ../../docs_src/dependencies/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial002.py hl[11:15] *} 💸 🙋 `__init__` 👩‍🔬 ⚙️ ✍ 👐 🎓: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="12" -{!> ../../docs_src/dependencies/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="10" -{!> ../../docs_src/dependencies/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial002.py hl[12] *} ...⚫️ ✔️ 🎏 🔢 👆 ⏮️ `common_parameters`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="6" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001.py hl[9] *} 📚 🔢 ⚫️❔ **FastAPI** 🔜 ⚙️ "❎" 🔗. @@ -149,21 +93,7 @@ fluffy = Cat(name="Mr Fluffy") 🔜 👆 💪 📣 👆 🔗 ⚙️ 👉 🎓. -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial002.py hl[19] *} **FastAPI** 🤙 `CommonQueryParams` 🎓. 👉 ✍ "👐" 👈 🎓 & 👐 🔜 🚶‍♀️ 🔢 `commons` 👆 🔢. @@ -203,21 +133,7 @@ commons = Depends(CommonQueryParams) ...: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial003.py hl[19] *} ✋️ 📣 🆎 💡 👈 🌌 👆 👨‍🎨 🔜 💭 ⚫️❔ 🔜 🚶‍♀️ 🔢 `commons`, & ⤴️ ⚫️ 💪 ℹ 👆 ⏮️ 📟 🛠️, 🆎 ✅, ♒️: @@ -251,21 +167,7 @@ commons: CommonQueryParams = Depends() 🎏 🖼 🔜 ⤴️ 👀 💖: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial004.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial004.py hl[19] *} ...& **FastAPI** 🔜 💭 ⚫️❔. diff --git a/docs/em/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/em/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index cd36ad1004d7a..ab144a497b543 100644 --- a/docs/em/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/em/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -14,9 +14,7 @@ ⚫️ 🔜 `list` `Depends()`: -```Python hl_lines="17" -{!../../docs_src/dependencies/tutorial006.py!} -``` +{* ../../docs_src/dependencies/tutorial006.py hl[17] *} 👉 🔗 🔜 🛠️/❎ 🎏 🌌 😐 🔗. ✋️ 👫 💲 (🚥 👫 📨 🙆) 🏆 🚫 🚶‍♀️ 👆 *➡ 🛠️ 🔢*. @@ -46,17 +44,13 @@ 👫 💪 📣 📨 📄 (💖 🎚) ⚖️ 🎏 🎧-🔗: -```Python hl_lines="6 11" -{!../../docs_src/dependencies/tutorial006.py!} -``` +{* ../../docs_src/dependencies/tutorial006.py hl[6,11] *} ### 🤚 ⚠ 👫 🔗 💪 `raise` ⚠, 🎏 😐 🔗: -```Python hl_lines="8 13" -{!../../docs_src/dependencies/tutorial006.py!} -``` +{* ../../docs_src/dependencies/tutorial006.py hl[8,13] *} ### 📨 💲 @@ -64,9 +58,7 @@ , 👆 💪 🏤-⚙️ 😐 🔗 (👈 📨 💲) 👆 ⏪ ⚙️ 👱 🙆, & ✋️ 💲 🏆 🚫 ⚙️, 🔗 🔜 🛠️: -```Python hl_lines="9 14" -{!../../docs_src/dependencies/tutorial006.py!} -``` +{* ../../docs_src/dependencies/tutorial006.py hl[9,14] *} ## 🔗 👪 *➡ 🛠️* diff --git a/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md index e0d6dba24ebba..1b37b1cf29599 100644 --- a/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md @@ -10,7 +10,7 @@ FastAPI 🐕‍🦺 🔗 👈 🔑 👨‍💼. @@ -224,9 +212,7 @@ with open("./somefile.txt") as f: 👆 💪 ⚙️ 👫 🔘 **FastAPI** 🔗 ⏮️ `yield` ⚙️ `with` ⚖️ `async with` 📄 🔘 🔗 🔢: -```Python hl_lines="1-9 13" -{!../../docs_src/dependencies/tutorial010.py!} -``` +{* ../../docs_src/dependencies/tutorial010.py hl[1:9,13] *} /// tip diff --git a/docs/em/docs/tutorial/dependencies/global-dependencies.md b/docs/em/docs/tutorial/dependencies/global-dependencies.md index bb69e78a828a2..5a22e5f1c8ad6 100644 --- a/docs/em/docs/tutorial/dependencies/global-dependencies.md +++ b/docs/em/docs/tutorial/dependencies/global-dependencies.md @@ -6,9 +6,7 @@ 👈 💼, 👫 🔜 ✔ 🌐 *➡ 🛠️* 🈸: -```Python hl_lines="15" -{!../../docs_src/dependencies/tutorial012.py!} -``` +{* ../../docs_src/dependencies/tutorial012.py hl[15] *} & 🌐 💭 📄 🔃 [❎ `dependencies` *➡ 🛠️ 👨‍🎨*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} ✔, ✋️ 👉 💼, 🌐 *➡ 🛠️* 📱. diff --git a/docs/em/docs/tutorial/dependencies/index.md b/docs/em/docs/tutorial/dependencies/index.md index b029b85b72869..ce87d9ee484ee 100644 --- a/docs/em/docs/tutorial/dependencies/index.md +++ b/docs/em/docs/tutorial/dependencies/index.md @@ -31,21 +31,7 @@ ⚫️ 🔢 👈 💪 ✊ 🌐 🎏 🔢 👈 *➡ 🛠️ 🔢* 💪 ✊: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="8-11" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="6-7" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001.py hl[8:11] *} 👈 ⚫️. @@ -67,41 +53,13 @@ ### 🗄 `Depends` -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="3" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="1" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001.py hl[3] *} ### 📣 🔗, "⚓️" 🎏 🌌 👆 ⚙️ `Body`, `Query`, ♒️. ⏮️ 👆 *➡ 🛠️ 🔢* 🔢, ⚙️ `Depends` ⏮️ 🆕 🔢: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="15 20" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="11 16" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001.py hl[15,20] *} 👐 👆 ⚙️ `Depends` 🔢 👆 🔢 🎏 🌌 👆 ⚙️ `Body`, `Query`, ♒️, `Depends` 👷 👄 🎏. diff --git a/docs/em/docs/tutorial/dependencies/sub-dependencies.md b/docs/em/docs/tutorial/dependencies/sub-dependencies.md index a1e7be1340321..6d622e952fa3b 100644 --- a/docs/em/docs/tutorial/dependencies/sub-dependencies.md +++ b/docs/em/docs/tutorial/dependencies/sub-dependencies.md @@ -10,21 +10,7 @@ 👆 💪 ✍ 🥇 🔗 ("☑") 💖: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="8-9" -{!> ../../docs_src/dependencies/tutorial005.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="6-7" -{!> ../../docs_src/dependencies/tutorial005_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial005.py hl[8:9] *} ⚫️ 📣 📦 🔢 🔢 `q` `str`, & ⤴️ ⚫️ 📨 ⚫️. @@ -34,21 +20,7 @@ ⤴️ 👆 💪 ✍ ➕1️⃣ 🔗 🔢 ("☑") 👈 🎏 🕰 📣 🔗 🚮 👍 (⚫️ "⚓️" 💁‍♂️): -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="13" -{!> ../../docs_src/dependencies/tutorial005.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="11" -{!> ../../docs_src/dependencies/tutorial005_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial005.py hl[13] *} ➡️ 🎯 🔛 🔢 📣: @@ -61,21 +33,7 @@ ⤴️ 👥 💪 ⚙️ 🔗 ⏮️: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="22" -{!> ../../docs_src/dependencies/tutorial005.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial005_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial005.py hl[22] *} /// info diff --git a/docs/em/docs/tutorial/encoder.md b/docs/em/docs/tutorial/encoder.md index 21419ef21f6ad..ad05f701e2e9e 100644 --- a/docs/em/docs/tutorial/encoder.md +++ b/docs/em/docs/tutorial/encoder.md @@ -20,21 +20,7 @@ ⚫️ 📨 🎚, 💖 Pydantic 🏷, & 📨 🎻 🔗 ⏬: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="5 22" -{!> ../../docs_src/encoder/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="4 21" -{!> ../../docs_src/encoder/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/encoder/tutorial001.py hl[5,22] *} 👉 🖼, ⚫️ 🔜 🗜 Pydantic 🏷 `dict`, & `datetime` `str`. diff --git a/docs/em/docs/tutorial/extra-data-types.md b/docs/em/docs/tutorial/extra-data-types.md index 1d473bd9364d1..f15a74b4a3a96 100644 --- a/docs/em/docs/tutorial/extra-data-types.md +++ b/docs/em/docs/tutorial/extra-data-types.md @@ -55,36 +55,8 @@ 📥 🖼 *➡ 🛠️* ⏮️ 🔢 ⚙️ 🔛 🆎. -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="1 3 12-16" -{!> ../../docs_src/extra_data_types/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="1 2 11-15" -{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/extra_data_types/tutorial001.py hl[1,3,12:16] *} 🗒 👈 🔢 🔘 🔢 ✔️ 👫 🐠 💽 🆎, & 👆 💪, 🖼, 🎭 😐 📅 🎭, 💖: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="18-19" -{!> ../../docs_src/extra_data_types/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="17-18" -{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/extra_data_types/tutorial001.py hl[18:19] *} diff --git a/docs/em/docs/tutorial/extra-models.md b/docs/em/docs/tutorial/extra-models.md index 4fdf196e8e750..19ab5b7986957 100644 --- a/docs/em/docs/tutorial/extra-models.md +++ b/docs/em/docs/tutorial/extra-models.md @@ -20,21 +20,7 @@ 📥 🏢 💭 ❔ 🏷 💪 👀 💖 ⏮️ 👫 🔐 🏑 & 🥉 🌐❔ 👫 ⚙️: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" -{!> ../../docs_src/extra_models/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" -{!> ../../docs_src/extra_models/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial001.py hl[9,11,16,22,24,29:30,33:35,40:41] *} ### 🔃 `**user_in.dict()` @@ -168,21 +154,7 @@ UserInDB( 👈 🌌, 👥 💪 📣 🔺 🖖 🏷 (⏮️ 🔢 `password`, ⏮️ `hashed_password` & 🍵 🔐): -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9 15-16 19-20 23-24" -{!> ../../docs_src/extra_models/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7 13-14 17-18 21-22" -{!> ../../docs_src/extra_models/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial002.py hl[9,15:16,19:20,23:24] *} ## `Union` ⚖️ `anyOf` @@ -198,21 +170,7 @@ UserInDB( /// -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="1 14-15 18-20 33" -{!> ../../docs_src/extra_models/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="1 14-15 18-20 33" -{!> ../../docs_src/extra_models/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial003.py hl[1,14:15,18:20,33] *} ### `Union` 🐍 3️⃣.1️⃣0️⃣ @@ -234,21 +192,7 @@ some_variable: PlaneItem | CarItem 👈, ⚙️ 🐩 🐍 `typing.List` (⚖️ `list` 🐍 3️⃣.9️⃣ & 🔛): -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="1 20" -{!> ../../docs_src/extra_models/tutorial004.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="18" -{!> ../../docs_src/extra_models/tutorial004_py39.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial004.py hl[1,20] *} ## 📨 ⏮️ ❌ `dict` @@ -258,21 +202,7 @@ some_variable: PlaneItem | CarItem 👉 💼, 👆 💪 ⚙️ `typing.Dict` (⚖️ `dict` 🐍 3️⃣.9️⃣ & 🔛): -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="1 8" -{!> ../../docs_src/extra_models/tutorial005.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="6" -{!> ../../docs_src/extra_models/tutorial005_py39.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial005.py hl[1,8] *} ## 🌃 diff --git a/docs/em/docs/tutorial/first-steps.md b/docs/em/docs/tutorial/first-steps.md index d8cc05c40593c..a8f936b01df4a 100644 --- a/docs/em/docs/tutorial/first-steps.md +++ b/docs/em/docs/tutorial/first-steps.md @@ -2,9 +2,7 @@ 🙅 FastAPI 📁 💪 👀 💖 👉: -```Python -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py *} 📁 👈 📁 `main.py`. @@ -133,13 +131,11 @@ INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ### 🔁 1️⃣: 🗄 `FastAPI` -```Python hl_lines="1" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[1] *} `FastAPI` 🐍 🎓 👈 🚚 🌐 🛠️ 👆 🛠️. -/// note | "📡 ℹ" +/// note | 📡 ℹ `FastAPI` 🎓 👈 😖 🔗 ⚪️➡️ `Starlette`. @@ -149,9 +145,7 @@ INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ### 🔁 2️⃣: ✍ `FastAPI` "👐" -```Python hl_lines="3" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[3] *} 📥 `app` 🔢 🔜 "👐" 🎓 `FastAPI`. @@ -171,9 +165,7 @@ $ uvicorn main:app --reload 🚥 👆 ✍ 👆 📱 💖: -```Python hl_lines="3" -{!../../docs_src/first_steps/tutorial002.py!} -``` +{* ../../docs_src/first_steps/tutorial002.py hl[3] *} & 🚮 ⚫️ 📁 `main.py`, ⤴️ 👆 🔜 🤙 `uvicorn` 💖: @@ -250,16 +242,14 @@ https://example.com/items/foo #### 🔬 *➡ 🛠️ 👨‍🎨* -```Python hl_lines="6" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[6] *} `@app.get("/")` 💬 **FastAPI** 👈 🔢 ▶️️ 🔛 🈚 🚚 📨 👈 🚶: * ➡ `/` * ⚙️ get 🛠️ -/// info | "`@decorator` ℹ" +/// info | `@decorator` ℹ 👈 `@something` ❕ 🐍 🤙 "👨‍🎨". @@ -306,9 +296,7 @@ https://example.com/items/foo * **🛠️**: `get`. * **🔢**: 🔢 🔛 "👨‍🎨" (🔛 `@app.get("/")`). -```Python hl_lines="7" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[7] *} 👉 🐍 🔢. @@ -320,9 +308,7 @@ https://example.com/items/foo 👆 💪 🔬 ⚫️ 😐 🔢 ↩️ `async def`: -```Python hl_lines="7" -{!../../docs_src/first_steps/tutorial003.py!} -``` +{* ../../docs_src/first_steps/tutorial003.py hl[7] *} /// note @@ -332,9 +318,7 @@ https://example.com/items/foo ### 🔁 5️⃣: 📨 🎚 -```Python hl_lines="8" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[8] *} 👆 💪 📨 `dict`, `list`, ⭐ 💲 `str`, `int`, ♒️. diff --git a/docs/em/docs/tutorial/handling-errors.md b/docs/em/docs/tutorial/handling-errors.md index 7f6a704eb0856..d73b730e120d3 100644 --- a/docs/em/docs/tutorial/handling-errors.md +++ b/docs/em/docs/tutorial/handling-errors.md @@ -25,9 +25,7 @@ ### 🗄 `HTTPException` -```Python hl_lines="1" -{!../../docs_src/handling_errors/tutorial001.py!} -``` +{* ../../docs_src/handling_errors/tutorial001.py hl[1] *} ### 🤚 `HTTPException` 👆 📟 @@ -41,9 +39,7 @@ 👉 🖼, 🕐❔ 👩‍💻 📨 🏬 🆔 👈 🚫 🔀, 🤚 ⚠ ⏮️ 👔 📟 `404`: -```Python hl_lines="11" -{!../../docs_src/handling_errors/tutorial001.py!} -``` +{* ../../docs_src/handling_errors/tutorial001.py hl[11] *} ### 📉 📨 @@ -81,9 +77,7 @@ ✋️ 💼 👆 💪 ⚫️ 🏧 😐, 👆 💪 🚮 🛃 🎚: -```Python hl_lines="14" -{!../../docs_src/handling_errors/tutorial002.py!} -``` +{* ../../docs_src/handling_errors/tutorial002.py hl[14] *} ## ❎ 🛃 ⚠ 🐕‍🦺 @@ -95,9 +89,7 @@ 👆 💪 🚮 🛃 ⚠ 🐕‍🦺 ⏮️ `@app.exception_handler()`: -```Python hl_lines="5-7 13-18 24" -{!../../docs_src/handling_errors/tutorial003.py!} -``` +{* ../../docs_src/handling_errors/tutorial003.py hl[5:7,13:18,24] *} 📥, 🚥 👆 📨 `/unicorns/yolo`, *➡ 🛠️* 🔜 `raise` `UnicornException`. @@ -109,7 +101,7 @@ {"message": "Oops! yolo did something. There goes a rainbow..."} ``` -/// note | "📡 ℹ" +/// note | 📡 ℹ 👆 💪 ⚙️ `from starlette.requests import Request` & `from starlette.responses import JSONResponse`. @@ -135,9 +127,7 @@ ⚠ 🐕‍🦺 🔜 📨 `Request` & ⚠. -```Python hl_lines="2 14-16" -{!../../docs_src/handling_errors/tutorial004.py!} -``` +{* ../../docs_src/handling_errors/tutorial004.py hl[2,14:16] *} 🔜, 🚥 👆 🚶 `/items/foo`, ↩️ 💆‍♂ 🔢 🎻 ❌ ⏮️: @@ -188,11 +178,9 @@ path -> item_id 🖼, 👆 💪 💚 📨 ✅ ✍ 📨 ↩️ 🎻 👫 ❌: -```Python hl_lines="3-4 9-11 22" -{!../../docs_src/handling_errors/tutorial004.py!} -``` +{* ../../docs_src/handling_errors/tutorial004.py hl[3:4,9:11,22] *} -/// note | "📡 ℹ" +/// note | 📡 ℹ 👆 💪 ⚙️ `from starlette.responses import PlainTextResponse`. @@ -206,9 +194,7 @@ path -> item_id 👆 💪 ⚙️ ⚫️ ⏪ 🛠️ 👆 📱 🕹 💪 & ℹ ⚫️, 📨 ⚫️ 👩‍💻, ♒️. -```Python hl_lines="14" -{!../../docs_src/handling_errors/tutorial005.py!} -``` +{* ../../docs_src/handling_errors/tutorial005.py hl[14] *} 🔜 🔄 📨 ❌ 🏬 💖: @@ -266,8 +252,6 @@ from starlette.exceptions import HTTPException as StarletteHTTPException 🚥 👆 💚 ⚙️ ⚠ ⤴️ ⏮️ 🎏 🔢 ⚠ 🐕‍🦺 ⚪️➡️ **FastAPI**, 👆 💪 🗄 & 🏤-⚙️ 🔢 ⚠ 🐕‍🦺 ⚪️➡️ `fastapi.exception_handlers`: -```Python hl_lines="2-5 15 21" -{!../../docs_src/handling_errors/tutorial006.py!} -``` +{* ../../docs_src/handling_errors/tutorial006.py hl[2:5,15,21] *} 👉 🖼 👆 `print`😅 ❌ ⏮️ 📶 🎨 📧, ✋️ 👆 🤚 💭. 👆 💪 ⚙️ ⚠ & ⤴️ 🏤-⚙️ 🔢 ⚠ 🐕‍🦺. diff --git a/docs/em/docs/tutorial/header-params.md b/docs/em/docs/tutorial/header-params.md index 34abd3a4c0f1a..fa5e3a22b4ef6 100644 --- a/docs/em/docs/tutorial/header-params.md +++ b/docs/em/docs/tutorial/header-params.md @@ -6,21 +6,7 @@ 🥇 🗄 `Header`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="3" -{!> ../../docs_src/header_params/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="1" -{!> ../../docs_src/header_params/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/header_params/tutorial001.py hl[3] *} ## 📣 `Header` 🔢 @@ -28,23 +14,9 @@ 🥇 💲 🔢 💲, 👆 💪 🚶‍♀️ 🌐 ➕ 🔬 ⚖️ ✍ 🔢: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/header_params/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7" -{!> ../../docs_src/header_params/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/header_params/tutorial001.py hl[9] *} -/// note | "📡 ℹ" +/// note | 📡 ℹ `Header` "👭" 🎓 `Path`, `Query` & `Cookie`. ⚫️ 😖 ⚪️➡️ 🎏 ⚠ `Param` 🎓. @@ -74,21 +46,7 @@ 🚥 🤔 👆 💪 ❎ 🏧 🛠️ 🎦 🔠, ⚒ 🔢 `convert_underscores` `Header` `False`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="10" -{!> ../../docs_src/header_params/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="8" -{!> ../../docs_src/header_params/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/header_params/tutorial002.py hl[10] *} /// warning @@ -106,29 +64,7 @@ 🖼, 📣 🎚 `X-Token` 👈 💪 😑 🌅 🌘 🕐, 👆 💪 ✍: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/header_params/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/header_params/tutorial003_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7" -{!> ../../docs_src/header_params/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/header_params/tutorial003.py hl[9] *} 🚥 👆 🔗 ⏮️ 👈 *➡ 🛠️* 📨 2️⃣ 🇺🇸🔍 🎚 💖: diff --git a/docs/em/docs/tutorial/metadata.md b/docs/em/docs/tutorial/metadata.md index a30db113db153..eaf605de1e9e4 100644 --- a/docs/em/docs/tutorial/metadata.md +++ b/docs/em/docs/tutorial/metadata.md @@ -17,9 +17,7 @@ 👆 💪 ⚒ 👫 ⏩: -```Python hl_lines="3-16 19-31" -{!../../docs_src/metadata/tutorial001.py!} -``` +{* ../../docs_src/metadata/tutorial001.py hl[3:16,19:31] *} /// tip @@ -51,9 +49,7 @@ ✍ 🗃 👆 🔖 & 🚶‍♀️ ⚫️ `openapi_tags` 🔢: -```Python hl_lines="3-16 18" -{!../../docs_src/metadata/tutorial004.py!} -``` +{* ../../docs_src/metadata/tutorial004.py hl[3:16,18] *} 👀 👈 👆 💪 ⚙️ ✍ 🔘 📛, 🖼 "💳" 🔜 🎦 🦁 (**💳**) & "🎀" 🔜 🎦 ❕ (_🎀_). @@ -67,9 +63,7 @@ ⚙️ `tags` 🔢 ⏮️ 👆 *➡ 🛠️* (& `APIRouter`Ⓜ) 🛠️ 👫 🎏 🔖: -```Python hl_lines="21 26" -{!../../docs_src/metadata/tutorial004.py!} -``` +{* ../../docs_src/metadata/tutorial004.py hl[21,26] *} /// info @@ -97,9 +91,7 @@ 🖼, ⚒ ⚫️ 🍦 `/api/v1/openapi.json`: -```Python hl_lines="3" -{!../../docs_src/metadata/tutorial002.py!} -``` +{* ../../docs_src/metadata/tutorial002.py hl[3] *} 🚥 👆 💚 ❎ 🗄 🔗 🍕 👆 💪 ⚒ `openapi_url=None`, 👈 🔜 ❎ 🧾 👩‍💻 🔢 👈 ⚙️ ⚫️. @@ -116,6 +108,4 @@ 🖼, ⚒ 🦁 🎚 🍦 `/documentation` & ❎ 📄: -```Python hl_lines="3" -{!../../docs_src/metadata/tutorial003.py!} -``` +{* ../../docs_src/metadata/tutorial003.py hl[3] *} diff --git a/docs/em/docs/tutorial/middleware.md b/docs/em/docs/tutorial/middleware.md index cd0777ebbb09d..d203471e88e00 100644 --- a/docs/em/docs/tutorial/middleware.md +++ b/docs/em/docs/tutorial/middleware.md @@ -11,7 +11,7 @@ * ⚫️ 💪 🕳 👈 **📨** ⚖️ 🏃 🙆 💪 📟. * ⤴️ ⚫️ 📨 **📨**. -/// note | "📡 ℹ" +/// note | 📡 ℹ 🚥 👆 ✔️ 🔗 ⏮️ `yield`, 🚪 📟 🔜 🏃 *⏮️* 🛠️. @@ -31,9 +31,7 @@ * ⤴️ ⚫️ 📨 `response` 🏗 🔗 *➡ 🛠️*. * 👆 💪 ⤴️ 🔀 🌅 `response` ⏭ 🛬 ⚫️. -```Python hl_lines="8-9 11 14" -{!../../docs_src/middleware/tutorial001.py!} -``` +{* ../../docs_src/middleware/tutorial001.py hl[8:9,11,14] *} /// tip @@ -43,7 +41,7 @@ /// -/// note | "📡 ℹ" +/// note | 📡 ℹ 👆 💪 ⚙️ `from starlette.requests import Request`. @@ -59,9 +57,7 @@ 🖼, 👆 💪 🚮 🛃 🎚 `X-Process-Time` ⚗ 🕰 🥈 👈 ⚫️ ✊ 🛠️ 📨 & 🏗 📨: -```Python hl_lines="10 12-13" -{!../../docs_src/middleware/tutorial001.py!} -``` +{* ../../docs_src/middleware/tutorial001.py hl[10,12:13] *} ## 🎏 🛠️ diff --git a/docs/em/docs/tutorial/path-operation-configuration.md b/docs/em/docs/tutorial/path-operation-configuration.md index 9529928fbf12d..c6030c0890037 100644 --- a/docs/em/docs/tutorial/path-operation-configuration.md +++ b/docs/em/docs/tutorial/path-operation-configuration.md @@ -16,33 +16,11 @@ ✋️ 🚥 👆 🚫 💭 ⚫️❔ 🔠 🔢 📟, 👆 💪 ⚙️ ⌨ 📉 `status`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="3 17" -{!> ../../docs_src/path_operation_configuration/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="3 17" -{!> ../../docs_src/path_operation_configuration/tutorial001_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="1 15" -{!> ../../docs_src/path_operation_configuration/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial001.py hl[3,17] *} 👈 👔 📟 🔜 ⚙️ 📨 & 🔜 🚮 🗄 🔗. -/// note | "📡 ℹ" +/// note | 📡 ℹ 👆 💪 ⚙️ `from starlette import status`. @@ -54,29 +32,7 @@ 👆 💪 🚮 🔖 👆 *➡ 🛠️*, 🚶‍♀️ 🔢 `tags` ⏮️ `list` `str` (🛎 1️⃣ `str`): -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="17 22 27" -{!> ../../docs_src/path_operation_configuration/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="17 22 27" -{!> ../../docs_src/path_operation_configuration/tutorial002_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="15 20 25" -{!> ../../docs_src/path_operation_configuration/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial002.py hl[17,22,27] *} 👫 🔜 🚮 🗄 🔗 & ⚙️ 🏧 🧾 🔢: @@ -90,37 +46,13 @@ **FastAPI** 🐕‍🦺 👈 🎏 🌌 ⏮️ ✅ 🎻: -```Python hl_lines="1 8-10 13 18" -{!../../docs_src/path_operation_configuration/tutorial002b.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial002b.py hl[1,8:10,13,18] *} ## 📄 & 📛 👆 💪 🚮 `summary` & `description`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="20-21" -{!> ../../docs_src/path_operation_configuration/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="20-21" -{!> ../../docs_src/path_operation_configuration/tutorial003_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="18-19" -{!> ../../docs_src/path_operation_configuration/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial003.py hl[20:21] *} ## 📛 ⚪️➡️ #️⃣ @@ -128,29 +60,7 @@ 👆 💪 ✍ #️⃣ , ⚫️ 🔜 🔬 & 🖥 ☑ (✊ 🔘 🏧 #️⃣ 📐). -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="19-27" -{!> ../../docs_src/path_operation_configuration/tutorial004.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="19-27" -{!> ../../docs_src/path_operation_configuration/tutorial004_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="17-25" -{!> ../../docs_src/path_operation_configuration/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial004.py hl[19:27] *} ⚫️ 🔜 ⚙️ 🎓 🩺: @@ -160,29 +70,7 @@ 👆 💪 ✔ 📨 📛 ⏮️ 🔢 `response_description`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="21" -{!> ../../docs_src/path_operation_configuration/tutorial005.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="21" -{!> ../../docs_src/path_operation_configuration/tutorial005_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="19" -{!> ../../docs_src/path_operation_configuration/tutorial005_py310.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial005.py hl[21] *} /// info @@ -204,9 +92,7 @@ 🚥 👆 💪 ™ *➡ 🛠️* 😢, ✋️ 🍵 ❎ ⚫️, 🚶‍♀️ 🔢 `deprecated`: -```Python hl_lines="16" -{!../../docs_src/path_operation_configuration/tutorial006.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial006.py hl[16] *} ⚫️ 🔜 🎯 ™ 😢 🎓 🩺: diff --git a/docs/em/docs/tutorial/path-params-numeric-validations.md b/docs/em/docs/tutorial/path-params-numeric-validations.md index c25f0323e96c9..b45e0557b6e19 100644 --- a/docs/em/docs/tutorial/path-params-numeric-validations.md +++ b/docs/em/docs/tutorial/path-params-numeric-validations.md @@ -6,21 +6,7 @@ 🥇, 🗄 `Path` ⚪️➡️ `fastapi`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="3" -{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="1" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial001.py hl[3] *} ## 📣 🗃 @@ -28,21 +14,7 @@ 🖼, 📣 `title` 🗃 💲 ➡ 🔢 `item_id` 👆 💪 🆎: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="10" -{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="8" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial001.py hl[10] *} /// note @@ -70,9 +42,7 @@ , 👆 💪 📣 👆 🔢: -```Python hl_lines="7" -{!../../docs_src/path_params_numeric_validations/tutorial002.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial002.py hl[7] *} ## ✔ 🔢 👆 💪, 🎱 @@ -82,9 +52,7 @@ 🐍 🏆 🚫 🕳 ⏮️ 👈 `*`, ✋️ ⚫️ 🔜 💭 👈 🌐 📄 🔢 🔜 🤙 🇨🇻 ❌ (🔑-💲 👫), 💭 kwargs. 🚥 👫 🚫 ✔️ 🔢 💲. -```Python hl_lines="7" -{!../../docs_src/path_params_numeric_validations/tutorial003.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *} ## 🔢 🔬: 👑 🌘 ⚖️ 🌓 @@ -92,9 +60,7 @@ 📥, ⏮️ `ge=1`, `item_id` 🔜 💪 🔢 🔢 "`g`🅾 🌘 ⚖️ `e`🅾" `1`. -```Python hl_lines="8" -{!../../docs_src/path_params_numeric_validations/tutorial004.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial004.py hl[8] *} ## 🔢 🔬: 🌘 🌘 & 🌘 🌘 ⚖️ 🌓 @@ -103,9 +69,7 @@ * `gt`: `g`🅾 `t`👲 * `le`: `l`👭 🌘 ⚖️ `e`🅾 -```Python hl_lines="9" -{!../../docs_src/path_params_numeric_validations/tutorial005.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial005.py hl[9] *} ## 🔢 🔬: 🎈, 🌘 🌘 & 🌘 🌘 @@ -117,9 +81,7 @@ & 🎏 lt. -```Python hl_lines="11" -{!../../docs_src/path_params_numeric_validations/tutorial006.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial006.py hl[11] *} ## 🌃 @@ -140,7 +102,7 @@ /// -/// note | "📡 ℹ" +/// note | 📡 ℹ 🕐❔ 👆 🗄 `Query`, `Path` & 🎏 ⚪️➡️ `fastapi`, 👫 🤙 🔢. diff --git a/docs/em/docs/tutorial/path-params.md b/docs/em/docs/tutorial/path-params.md index daf5417ebd8d6..a914dc9050a69 100644 --- a/docs/em/docs/tutorial/path-params.md +++ b/docs/em/docs/tutorial/path-params.md @@ -2,9 +2,7 @@ 👆 💪 📣 ➡ "🔢" ⚖️ "🔢" ⏮️ 🎏 ❕ ⚙️ 🐍 📁 🎻: -```Python hl_lines="6-7" -{!../../docs_src/path_params/tutorial001.py!} -``` +{* ../../docs_src/path_params/tutorial001.py hl[6:7] *} 💲 ➡ 🔢 `item_id` 🔜 🚶‍♀️ 👆 🔢 ❌ `item_id`. @@ -18,9 +16,7 @@ 👆 💪 📣 🆎 ➡ 🔢 🔢, ⚙️ 🐩 🐍 🆎 ✍: -```Python hl_lines="7" -{!../../docs_src/path_params/tutorial002.py!} -``` +{* ../../docs_src/path_params/tutorial002.py hl[7] *} 👉 💼, `item_id` 📣 `int`. @@ -121,17 +117,13 @@ ↩️ *➡ 🛠️* 🔬 ✔, 👆 💪 ⚒ 💭 👈 ➡ `/users/me` 📣 ⏭ 1️⃣ `/users/{user_id}`: -```Python hl_lines="6 11" -{!../../docs_src/path_params/tutorial003.py!} -``` +{* ../../docs_src/path_params/tutorial003.py hl[6,11] *} ⏪, ➡ `/users/{user_id}` 🔜 🏏 `/users/me`, "💭" 👈 ⚫️ 📨 🔢 `user_id` ⏮️ 💲 `"me"`. ➡, 👆 🚫🔜 ↔ ➡ 🛠️: -```Python hl_lines="6 11" -{!../../docs_src/path_params/tutorial003b.py!} -``` +{* ../../docs_src/path_params/tutorial003b.py hl[6,11] *} 🥇 🕐 🔜 🕧 ⚙️ ↩️ ➡ 🏏 🥇. @@ -147,9 +139,7 @@ ⤴️ ✍ 🎓 🔢 ⏮️ 🔧 💲, ❔ 🔜 💪 ☑ 💲: -```Python hl_lines="1 6-9" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[1,6:9] *} /// info @@ -167,9 +157,7 @@ ⤴️ ✍ *➡ 🔢* ⏮️ 🆎 ✍ ⚙️ 🔢 🎓 👆 ✍ (`ModelName`): -```Python hl_lines="16" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[16] *} ### ✅ 🩺 @@ -185,17 +173,13 @@ 👆 💪 🔬 ⚫️ ⏮️ *🔢 👨‍🎓* 👆 ✍ 🔢 `ModelName`: -```Python hl_lines="17" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[17] *} #### 🤚 *🔢 💲* 👆 💪 🤚 ☑ 💲 ( `str` 👉 💼) ⚙️ `model_name.value`, ⚖️ 🏢, `your_enum_member.value`: -```Python hl_lines="20" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[20] *} /// tip @@ -209,9 +193,7 @@ 👫 🔜 🗜 👫 🔗 💲 (🎻 👉 💼) ⏭ 🛬 👫 👩‍💻: -```Python hl_lines="18 21 23" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[18,21,23] *} 👆 👩‍💻 👆 🔜 🤚 🎻 📨 💖: @@ -250,9 +232,7 @@ , 👆 💪 ⚙️ ⚫️ ⏮️: -```Python hl_lines="6" -{!../../docs_src/path_params/tutorial004.py!} -``` +{* ../../docs_src/path_params/tutorial004.py hl[6] *} /// tip diff --git a/docs/em/docs/tutorial/query-params-str-validations.md b/docs/em/docs/tutorial/query-params-str-validations.md index f75c0a26fa65b..dbaab5735dcad 100644 --- a/docs/em/docs/tutorial/query-params-str-validations.md +++ b/docs/em/docs/tutorial/query-params-str-validations.md @@ -4,21 +4,7 @@ ➡️ ✊ 👉 🈸 🖼: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial001.py hl[9] *} 🔢 🔢 `q` 🆎 `Union[str, None]` (⚖️ `str | None` 🐍 3️⃣.1️⃣0️⃣), 👈 ⛓ 👈 ⚫️ 🆎 `str` ✋️ 💪 `None`, & 👐, 🔢 💲 `None`, FastAPI 🔜 💭 ⚫️ 🚫 ✔. @@ -38,41 +24,13 @@ FastAPI 🔜 💭 👈 💲 `q` 🚫 ✔ ↩️ 🔢 💲 `= None`. 🏆 👈, 🥇 🗄 `Query` ⚪️➡️ `fastapi`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="3" -{!> ../../docs_src/query_params_str_validations/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="1" -{!> ../../docs_src/query_params_str_validations/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial002.py hl[3] *} ## ⚙️ `Query` 🔢 💲 & 🔜 ⚙️ ⚫️ 🔢 💲 👆 🔢, ⚒ 🔢 `max_length` 5️⃣0️⃣: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial002.py hl[9] *} 👥 ✔️ ❎ 🔢 💲 `None` 🔢 ⏮️ `Query()`, 👥 💪 🔜 ⚒ 🔢 💲 ⏮️ 🔢 `Query(default=None)`, ⚫️ 🍦 🎏 🎯 ⚖ 👈 🔢 💲. @@ -134,41 +92,13 @@ q: Union[str, None] = Query(default=None, max_length=50) 👆 💪 🚮 🔢 `min_length`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial003.py hl[10] *} ## 🚮 🥔 🧬 👆 💪 🔬 🥔 🧬 👈 🔢 🔜 🏏: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial004.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial004.py hl[11] *} 👉 🎯 🥔 🧬 ✅ 👈 📨 🔢 💲: @@ -186,9 +116,7 @@ q: Union[str, None] = Query(default=None, max_length=50) ➡️ 💬 👈 👆 💚 📣 `q` 🔢 🔢 ✔️ `min_length` `3`, & ✔️ 🔢 💲 `"fixedquery"`: -```Python hl_lines="7" -{!../../docs_src/query_params_str_validations/tutorial005.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial005.py hl[7] *} /// note @@ -218,17 +146,13 @@ q: Union[str, None] = Query(default=None, min_length=3) , 🕐❔ 👆 💪 📣 💲 ✔ ⏪ ⚙️ `Query`, 👆 💪 🎯 🚫 📣 🔢 💲: -```Python hl_lines="7" -{!../../docs_src/query_params_str_validations/tutorial006.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial006.py hl[7] *} ### ✔ ⏮️ ❕ (`...`) 📤 🎛 🌌 🎯 📣 👈 💲 ✔. 👆 💪 ⚒ `default` 🔢 🔑 💲 `...`: -```Python hl_lines="7" -{!../../docs_src/query_params_str_validations/tutorial006b.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial006b.py hl[7] *} /// info @@ -246,21 +170,7 @@ q: Union[str, None] = Query(default=None, min_length=3) 👈, 👆 💪 📣 👈 `None` ☑ 🆎 ✋️ ⚙️ `default=...`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial006c.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial006c_py310.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial006c.py hl[9] *} /// tip @@ -272,9 +182,7 @@ Pydantic, ❔ ⚫️❔ 🏋️ 🌐 💽 🔬 & 🛠️ FastAPI, ✔️ 🚥 👆 💭 😬 ⚙️ `...`, 👆 💪 🗄 & ⚙️ `Required` ⚪️➡️ Pydantic: -```Python hl_lines="2 8" -{!../../docs_src/query_params_str_validations/tutorial006d.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial006d.py hl[2,8] *} /// tip @@ -288,29 +196,7 @@ Pydantic, ❔ ⚫️❔ 🏋️ 🌐 💽 🔬 & 🛠️ FastAPI, ✔️ 🖼, 📣 🔢 🔢 `q` 👈 💪 😑 💗 🕰 📛, 👆 💪 ✍: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial011.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial011_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial011_py310.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial011.py hl[9] *} ⤴️, ⏮️ 📛 💖: @@ -345,21 +231,7 @@ http://localhost:8000/items/?q=foo&q=bar & 👆 💪 🔬 🔢 `list` 💲 🚥 👌 🚚: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial012.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial012_py39.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial012.py hl[9] *} 🚥 👆 🚶: @@ -382,9 +254,7 @@ http://localhost:8000/items/ 👆 💪 ⚙️ `list` 🔗 ↩️ `List[str]` (⚖️ `list[str]` 🐍 3️⃣.9️⃣ ➕): -```Python hl_lines="7" -{!../../docs_src/query_params_str_validations/tutorial013.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial013.py hl[7] *} /// note @@ -410,39 +280,11 @@ http://localhost:8000/items/ 👆 💪 🚮 `title`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial007.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial007_py310.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial007.py hl[10] *} & `description`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="13" -{!> ../../docs_src/query_params_str_validations/tutorial008.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial008_py310.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial008.py hl[13] *} ## 📛 🔢 @@ -462,21 +304,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems ⤴️ 👆 💪 📣 `alias`, & 👈 📛 ⚫️❔ 🔜 ⚙️ 🔎 🔢 💲: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial009.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial009_py310.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial009.py hl[9] *} ## 😛 🔢 @@ -486,21 +314,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems ⤴️ 🚶‍♀️ 🔢 `deprecated=True` `Query`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="18" -{!> ../../docs_src/query_params_str_validations/tutorial010.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="16" -{!> ../../docs_src/query_params_str_validations/tutorial010_py310.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial010.py hl[18] *} 🩺 🔜 🎦 ⚫️ 💖 👉: @@ -510,21 +324,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems 🚫 🔢 🔢 ⚪️➡️ 🏗 🗄 🔗 (& ➡️, ⚪️➡️ 🏧 🧾 ⚙️), ⚒ 🔢 `include_in_schema` `Query` `False`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial014.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial014_py310.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial014.py hl[10] *} ## 🌃 diff --git a/docs/em/docs/tutorial/query-params.md b/docs/em/docs/tutorial/query-params.md index c8432f182fac2..5c8d868a9a65d 100644 --- a/docs/em/docs/tutorial/query-params.md +++ b/docs/em/docs/tutorial/query-params.md @@ -2,9 +2,7 @@ 🕐❔ 👆 📣 🎏 🔢 🔢 👈 🚫 🍕 ➡ 🔢, 👫 🔁 🔬 "🔢" 🔢. -```Python hl_lines="9" -{!../../docs_src/query_params/tutorial001.py!} -``` +{* ../../docs_src/query_params/tutorial001.py hl[9] *} 🔢 ⚒ 🔑-💲 👫 👈 🚶 ⏮️ `?` 📛, 🎏 `&` 🦹. @@ -63,21 +61,7 @@ http://127.0.0.1:8000/items/?skip=20 🎏 🌌, 👆 💪 📣 📦 🔢 🔢, ⚒ 👫 🔢 `None`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/query_params/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7" -{!> ../../docs_src/query_params/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial002.py hl[9] *} 👉 💼, 🔢 🔢 `q` 🔜 📦, & 🔜 `None` 🔢. @@ -91,21 +75,7 @@ http://127.0.0.1:8000/items/?skip=20 👆 💪 📣 `bool` 🆎, & 👫 🔜 🗜: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/query_params/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7" -{!> ../../docs_src/query_params/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial003.py hl[9] *} 👉 💼, 🚥 👆 🚶: @@ -148,21 +118,7 @@ http://127.0.0.1:8000/items/foo?short=yes 👫 🔜 🔬 📛: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="8 10" -{!> ../../docs_src/query_params/tutorial004.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="6 8" -{!> ../../docs_src/query_params/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial004.py hl[8,10] *} ## ✔ 🔢 🔢 @@ -172,9 +128,7 @@ http://127.0.0.1:8000/items/foo?short=yes ✋️ 🕐❔ 👆 💚 ⚒ 🔢 🔢 ✔, 👆 💪 🚫 📣 🙆 🔢 💲: -```Python hl_lines="6-7" -{!../../docs_src/query_params/tutorial005.py!} -``` +{* ../../docs_src/query_params/tutorial005.py hl[6:7] *} 📥 🔢 🔢 `needy` ✔ 🔢 🔢 🆎 `str`. @@ -218,21 +172,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy & ↗️, 👆 💪 🔬 🔢 ✔, ✔️ 🔢 💲, & 🍕 📦: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="10" -{!> ../../docs_src/query_params/tutorial006.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="8" -{!> ../../docs_src/query_params/tutorial006_py310.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial006.py hl[10] *} 👉 💼, 📤 3️⃣ 🔢 🔢: diff --git a/docs/em/docs/tutorial/request-files.md b/docs/em/docs/tutorial/request-files.md index 102690f4bd46e..c3bdeafd48fd9 100644 --- a/docs/em/docs/tutorial/request-files.md +++ b/docs/em/docs/tutorial/request-files.md @@ -16,17 +16,13 @@ 🗄 `File` & `UploadFile` ⚪️➡️ `fastapi`: -```Python hl_lines="1" -{!../../docs_src/request_files/tutorial001.py!} -``` +{* ../../docs_src/request_files/tutorial001.py hl[1] *} ## 🔬 `File` 🔢 ✍ 📁 🔢 🎏 🌌 👆 🔜 `Body` ⚖️ `Form`: -```Python hl_lines="7" -{!../../docs_src/request_files/tutorial001.py!} -``` +{* ../../docs_src/request_files/tutorial001.py hl[7] *} /// info @@ -54,9 +50,7 @@ 🔬 📁 🔢 ⏮️ 🆎 `UploadFile`: -```Python hl_lines="12" -{!../../docs_src/request_files/tutorial001.py!} -``` +{* ../../docs_src/request_files/tutorial001.py hl[12] *} ⚙️ `UploadFile` ✔️ 📚 📈 🤭 `bytes`: @@ -99,13 +93,13 @@ contents = await myfile.read() contents = myfile.file.read() ``` -/// note | "`async` 📡 ℹ" +/// note | `async` 📡 ℹ 🕐❔ 👆 ⚙️ `async` 👩‍🔬, **FastAPI** 🏃 📁 👩‍🔬 🧵 & ⌛ 👫. /// -/// note | "💃 📡 ℹ" +/// note | 💃 📡 ℹ **FastAPI**'Ⓜ `UploadFile` 😖 🔗 ⚪️➡️ **💃**'Ⓜ `UploadFile`, ✋️ 🚮 💪 🍕 ⚒ ⚫️ 🔗 ⏮️ **Pydantic** & 🎏 🍕 FastAPI. @@ -117,7 +111,7 @@ contents = myfile.file.read() **FastAPI** 🔜 ⚒ 💭 ✍ 👈 📊 ⚪️➡️ ▶️️ 🥉 ↩️ 🎻. -/// note | "📡 ℹ" +/// note | 📡 ℹ 📊 ⚪️➡️ 📨 🛎 🗜 ⚙️ "📻 🆎" `application/x-www-form-urlencoded` 🕐❔ ⚫️ 🚫 🔌 📁. @@ -139,29 +133,13 @@ contents = myfile.file.read() 👆 💪 ⚒ 📁 📦 ⚙️ 🐩 🆎 ✍ & ⚒ 🔢 💲 `None`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9 17" -{!> ../../docs_src/request_files/tutorial001_02.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7 14" -{!> ../../docs_src/request_files/tutorial001_02_py310.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_02.py hl[9,17] *} ## `UploadFile` ⏮️ 🌖 🗃 👆 💪 ⚙️ `File()` ⏮️ `UploadFile`, 🖼, ⚒ 🌖 🗃: -```Python hl_lines="13" -{!../../docs_src/request_files/tutorial001_03.py!} -``` +{* ../../docs_src/request_files/tutorial001_03.py hl[13] *} ## 💗 📁 📂 @@ -171,25 +149,11 @@ contents = myfile.file.read() ⚙️ 👈, 📣 📇 `bytes` ⚖️ `UploadFile`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="10 15" -{!> ../../docs_src/request_files/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="8 13" -{!> ../../docs_src/request_files/tutorial002_py39.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial002.py hl[10,15] *} 👆 🔜 📨, 📣, `list` `bytes` ⚖️ `UploadFile`Ⓜ. -/// note | "📡 ℹ" +/// note | 📡 ℹ 👆 💪 ⚙️ `from starlette.responses import HTMLResponse`. @@ -201,21 +165,7 @@ contents = myfile.file.read() & 🎏 🌌 ⏭, 👆 💪 ⚙️ `File()` ⚒ 🌖 🔢, `UploadFile`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="18" -{!> ../../docs_src/request_files/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="16" -{!> ../../docs_src/request_files/tutorial003_py39.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial003.py hl[18] *} ## 🌃 diff --git a/docs/em/docs/tutorial/request-forms-and-files.md b/docs/em/docs/tutorial/request-forms-and-files.md index 80793dae408be..680b1a96a50c8 100644 --- a/docs/em/docs/tutorial/request-forms-and-files.md +++ b/docs/em/docs/tutorial/request-forms-and-files.md @@ -12,17 +12,13 @@ ## 🗄 `File` & `Form` -```Python hl_lines="1" -{!../../docs_src/request_forms_and_files/tutorial001.py!} -``` +{* ../../docs_src/request_forms_and_files/tutorial001.py hl[1] *} ## 🔬 `File` & `Form` 🔢 ✍ 📁 & 📨 🔢 🎏 🌌 👆 🔜 `Body` ⚖️ `Query`: -```Python hl_lines="8" -{!../../docs_src/request_forms_and_files/tutorial001.py!} -``` +{* ../../docs_src/request_forms_and_files/tutorial001.py hl[8] *} 📁 & 📨 🏑 🔜 📂 📨 📊 & 👆 🔜 📨 📁 & 📨 🏑. diff --git a/docs/em/docs/tutorial/request-forms.md b/docs/em/docs/tutorial/request-forms.md index cbe4e2862dad9..1cc1ea5dcb5f8 100644 --- a/docs/em/docs/tutorial/request-forms.md +++ b/docs/em/docs/tutorial/request-forms.md @@ -14,17 +14,13 @@ 🗄 `Form` ⚪️➡️ `fastapi`: -```Python hl_lines="1" -{!../../docs_src/request_forms/tutorial001.py!} -``` +{* ../../docs_src/request_forms/tutorial001.py hl[1] *} ## 🔬 `Form` 🔢 ✍ 📨 🔢 🎏 🌌 👆 🔜 `Body` ⚖️ `Query`: -```Python hl_lines="7" -{!../../docs_src/request_forms/tutorial001.py!} -``` +{* ../../docs_src/request_forms/tutorial001.py hl[7] *} 🖼, 1️⃣ 🌌 Oauth2️⃣ 🔧 💪 ⚙️ (🤙 "🔐 💧") ⚫️ ✔ 📨 `username` & `password` 📨 🏑. @@ -50,7 +46,7 @@ **FastAPI** 🔜 ⚒ 💭 ✍ 👈 📊 ⚪️➡️ ▶️️ 🥉 ↩️ 🎻. -/// note | "📡 ℹ" +/// note | 📡 ℹ 📊 ⚪️➡️ 📨 🛎 🗜 ⚙️ "📻 🆎" `application/x-www-form-urlencoded`. diff --git a/docs/em/docs/tutorial/response-model.md b/docs/em/docs/tutorial/response-model.md index fb5c17dd65684..477376458d2d6 100644 --- a/docs/em/docs/tutorial/response-model.md +++ b/docs/em/docs/tutorial/response-model.md @@ -4,29 +4,7 @@ 👆 💪 ⚙️ **🆎 ✍** 🎏 🌌 👆 🔜 🔢 💽 🔢 **🔢**, 👆 💪 ⚙️ Pydantic 🏷, 📇, 📖, 📊 💲 💖 🔢, 🎻, ♒️. -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="18 23" -{!> ../../docs_src/response_model/tutorial001_01.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="18 23" -{!> ../../docs_src/response_model/tutorial001_01_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="16 21" -{!> ../../docs_src/response_model/tutorial001_01_py310.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial001_01.py hl[18,23] *} FastAPI 🔜 ⚙️ 👉 📨 🆎: @@ -59,29 +37,7 @@ FastAPI 🔜 ⚙️ 👉 📨 🆎: * `@app.delete()` * ♒️. -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="17 22 24-27" -{!> ../../docs_src/response_model/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="17 22 24-27" -{!> ../../docs_src/response_model/tutorial001_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="17 22 24-27" -{!> ../../docs_src/response_model/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial001.py hl[17,22,24:27] *} /// note @@ -113,21 +69,7 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & ** 📥 👥 📣 `UserIn` 🏷, ⚫️ 🔜 🔌 🔢 🔐: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9 11" -{!> ../../docs_src/response_model/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7 9" -{!> ../../docs_src/response_model/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial002.py hl[9,11] *} /// info @@ -140,21 +82,7 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & ** & 👥 ⚙️ 👉 🏷 📣 👆 🔢 & 🎏 🏷 📣 👆 🔢: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="18" -{!> ../../docs_src/response_model/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="16" -{!> ../../docs_src/response_model/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial002.py hl[18] *} 🔜, 🕐❔ 🖥 🏗 👩‍💻 ⏮️ 🔐, 🛠️ 🔜 📨 🎏 🔐 📨. @@ -172,57 +100,15 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & ** 👥 💪 ↩️ ✍ 🔢 🏷 ⏮️ 🔢 🔐 & 🔢 🏷 🍵 ⚫️: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9 11 16" -{!> ../../docs_src/response_model/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="9 11 16" -{!> ../../docs_src/response_model/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003.py hl[9,11,16] *} 📥, ✋️ 👆 *➡ 🛠️ 🔢* 🛬 🎏 🔢 👩‍💻 👈 🔌 🔐: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="24" -{!> ../../docs_src/response_model/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="24" -{!> ../../docs_src/response_model/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003.py hl[24] *} ...👥 📣 `response_model` 👆 🏷 `UserOut`, 👈 🚫 🔌 🔐: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="22" -{!> ../../docs_src/response_model/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="22" -{!> ../../docs_src/response_model/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003.py hl[22] *} , **FastAPI** 🔜 ✊ 💅 🖥 👅 🌐 💽 👈 🚫 📣 🔢 🏷 (⚙️ Pydantic). @@ -246,21 +132,7 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & ** & 👈 💼, 👥 💪 ⚙️ 🎓 & 🧬 ✊ 📈 🔢 **🆎 ✍** 🤚 👍 🐕‍🦺 👨‍🎨 & 🧰, & 🤚 FastAPI **💽 🖥**. -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9-13 15-16 20" -{!> ../../docs_src/response_model/tutorial003_01.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7-10 13-14 18" -{!> ../../docs_src/response_model/tutorial003_01_py310.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_01.py hl[9:13,15:16,20] *} ⏮️ 👉, 👥 🤚 🏭 🐕‍🦺, ⚪️➡️ 👨‍🎨 & ✍ 👉 📟 ☑ ⚖ 🆎, ✋️ 👥 🤚 💽 🖥 ⚪️➡️ FastAPI. @@ -302,9 +174,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 🏆 ⚠ 💼 🔜 [🛬 📨 🔗 🔬 ⏪ 🏧 🩺](../advanced/response-directly.md){.internal-link target=_blank}. -```Python hl_lines="8 10-11" -{!> ../../docs_src/response_model/tutorial003_02.py!} -``` +{* ../../docs_src/response_model/tutorial003_02.py hl[8,10:11] *} 👉 🙅 💼 🍵 🔁 FastAPI ↩️ 📨 🆎 ✍ 🎓 (⚖️ 🏿) `Response`. @@ -314,9 +184,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 👆 💪 ⚙️ 🏿 `Response` 🆎 ✍: -```Python hl_lines="8-9" -{!> ../../docs_src/response_model/tutorial003_03.py!} -``` +{* ../../docs_src/response_model/tutorial003_03.py hl[8:9] *} 👉 🔜 👷 ↩️ `RedirectResponse` 🏿 `Response`, & FastAPI 🔜 🔁 🍵 👉 🙅 💼. @@ -326,21 +194,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 🎏 🔜 🔨 🚥 👆 ✔️ 🕳 💖 🇪🇺 🖖 🎏 🆎 🌐❔ 1️⃣ ⚖️ 🌅 👫 🚫 ☑ Pydantic 🆎, 🖼 👉 🔜 ❌ 👶: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="10" -{!> ../../docs_src/response_model/tutorial003_04.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="8" -{!> ../../docs_src/response_model/tutorial003_04_py310.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_04.py hl[10] *} ...👉 ❌ ↩️ 🆎 ✍ 🚫 Pydantic 🆎 & 🚫 👁 `Response` 🎓 ⚖️ 🏿, ⚫️ 🇪🇺 (🙆 2️⃣) 🖖 `Response` & `dict`. @@ -352,21 +206,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 👉 💼, 👆 💪 ❎ 📨 🏷 ⚡ ⚒ `response_model=None`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/response_model/tutorial003_05.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7" -{!> ../../docs_src/response_model/tutorial003_05_py310.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_05.py hl[9] *} 👉 🔜 ⚒ FastAPI 🚶 📨 🏷 ⚡ & 👈 🌌 👆 💪 ✔️ 🙆 📨 🆎 ✍ 👆 💪 🍵 ⚫️ 🤕 👆 FastAPI 🈸. 👶 @@ -374,29 +214,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 👆 📨 🏷 💪 ✔️ 🔢 💲, 💖: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="11 13-14" -{!> ../../docs_src/response_model/tutorial004.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="11 13-14" -{!> ../../docs_src/response_model/tutorial004_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="9 11-12" -{!> ../../docs_src/response_model/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial004.py hl[11,13:14] *} * `description: Union[str, None] = None` (⚖️ `str | None = None` 🐍 3️⃣.1️⃣0️⃣) ✔️ 🔢 `None`. * `tax: float = 10.5` ✔️ 🔢 `10.5`. @@ -410,29 +228,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 👆 💪 ⚒ *➡ 🛠️ 👨‍🎨* 🔢 `response_model_exclude_unset=True`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="24" -{!> ../../docs_src/response_model/tutorial004.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="24" -{!> ../../docs_src/response_model/tutorial004_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="22" -{!> ../../docs_src/response_model/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial004.py hl[24] *} & 👈 🔢 💲 🏆 🚫 🔌 📨, 🕴 💲 🤙 ⚒. @@ -521,21 +317,7 @@ FastAPI 🙃 🥃 (🤙, Pydantic 🙃 🥃) 🤔 👈, ✋️ `description`, `t /// -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="31 37" -{!> ../../docs_src/response_model/tutorial005.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="29 35" -{!> ../../docs_src/response_model/tutorial005_py310.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial005.py hl[31,37] *} /// tip @@ -549,21 +331,7 @@ FastAPI 🙃 🥃 (🤙, Pydantic 🙃 🥃) 🤔 👈, ✋️ `description`, `t 🚥 👆 💭 ⚙️ `set` & ⚙️ `list` ⚖️ `tuple` ↩️, FastAPI 🔜 🗜 ⚫️ `set` & ⚫️ 🔜 👷 ☑: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="31 37" -{!> ../../docs_src/response_model/tutorial006.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="29 35" -{!> ../../docs_src/response_model/tutorial006_py310.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial006.py hl[31,37] *} ## 🌃 diff --git a/docs/em/docs/tutorial/response-status-code.md b/docs/em/docs/tutorial/response-status-code.md index cefff708f331e..413ceb9169740 100644 --- a/docs/em/docs/tutorial/response-status-code.md +++ b/docs/em/docs/tutorial/response-status-code.md @@ -8,9 +8,7 @@ * `@app.delete()` * ♒️. -```Python hl_lines="6" -{!../../docs_src/response_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_status_code/tutorial001.py hl[6] *} /// note @@ -76,9 +74,7 @@ FastAPI 💭 👉, & 🔜 🏭 🗄 🩺 👈 🇵🇸 📤 🙅‍♂ 📨 ➡️ 👀 ⏮️ 🖼 🔄: -```Python hl_lines="6" -{!../../docs_src/response_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_status_code/tutorial001.py hl[6] *} `201` 👔 📟 "✍". @@ -86,15 +82,13 @@ FastAPI 💭 👉, & 🔜 🏭 🗄 🩺 👈 🇵🇸 📤 🙅‍♂ 📨 👆 💪 ⚙️ 🏪 🔢 ⚪️➡️ `fastapi.status`. -```Python hl_lines="1 6" -{!../../docs_src/response_status_code/tutorial002.py!} -``` +{* ../../docs_src/response_status_code/tutorial002.py hl[1,6] *} 👫 🏪, 👫 🧑‍🤝‍🧑 🎏 🔢, ✋️ 👈 🌌 👆 💪 ⚙️ 👨‍🎨 📋 🔎 👫: -/// note | "📡 ℹ" +/// note | 📡 ℹ 👆 💪 ⚙️ `from starlette import status`. diff --git a/docs/em/docs/tutorial/schema-extra-example.md b/docs/em/docs/tutorial/schema-extra-example.md index e4f877a8e65f5..1bd314c513db9 100644 --- a/docs/em/docs/tutorial/schema-extra-example.md +++ b/docs/em/docs/tutorial/schema-extra-example.md @@ -8,21 +8,7 @@ 👆 💪 📣 `example` Pydantic 🏷 ⚙️ `Config` & `schema_extra`, 🔬 Pydantic 🩺: 🔗 🛃: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="15-23" -{!> ../../docs_src/schema_extra_example/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="13-21" -{!> ../../docs_src/schema_extra_example/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/schema_extra_example/tutorial001.py hl[15:23] *} 👈 ➕ ℹ 🔜 🚮-🔢 **🎻 🔗** 👈 🏷, & ⚫️ 🔜 ⚙️ 🛠️ 🩺. @@ -40,21 +26,7 @@ 👆 💪 ⚙️ 👉 🚮 `example` 🔠 🏑: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="4 10-13" -{!> ../../docs_src/schema_extra_example/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="2 8-11" -{!> ../../docs_src/schema_extra_example/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/schema_extra_example/tutorial002.py hl[4,10:13] *} /// warning @@ -80,21 +52,7 @@ 📥 👥 🚶‍♀️ `example` 📊 ⌛ `Body()`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="20-25" -{!> ../../docs_src/schema_extra_example/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="18-23" -{!> ../../docs_src/schema_extra_example/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/schema_extra_example/tutorial003.py hl[20:25] *} ### 🖼 🩺 🎚 @@ -115,21 +73,7 @@ * `value`: 👉 ☑ 🖼 🎦, ✅ `dict`. * `externalValue`: 🎛 `value`, 📛 ☝ 🖼. 👐 👉 5️⃣📆 🚫 🐕‍🦺 📚 🧰 `value`. -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="21-47" -{!> ../../docs_src/schema_extra_example/tutorial004.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="19-45" -{!> ../../docs_src/schema_extra_example/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/schema_extra_example/tutorial004.py hl[21:47] *} ### 🖼 🩺 🎚 diff --git a/docs/em/docs/tutorial/security/first-steps.md b/docs/em/docs/tutorial/security/first-steps.md index 6245f52ab66fd..8fb459a651e79 100644 --- a/docs/em/docs/tutorial/security/first-steps.md +++ b/docs/em/docs/tutorial/security/first-steps.md @@ -20,9 +20,7 @@ 📁 🖼 📁 `main.py`: -```Python -{!../../docs_src/security/tutorial001.py!} -``` +{* ../../docs_src/security/tutorial001.py *} ## 🏃 ⚫️ @@ -56,7 +54,7 @@ $ uvicorn main:app --reload -/// check | "✔ 🔼 ❗" +/// check | ✔ 🔼 ❗ 👆 ⏪ ✔️ ✨ 🆕 "✔" 🔼. @@ -128,9 +126,7 @@ Oauth2️⃣ 🔧 👈 👩‍💻 ⚖️ 🛠️ 💪 🔬 💽 👈 🔓 👩 🕐❔ 👥 ✍ 👐 `OAuth2PasswordBearer` 🎓 👥 🚶‍♀️ `tokenUrl` 🔢. 👉 🔢 🔌 📛 👈 👩‍💻 (🕸 🏃 👩‍💻 🖥) 🔜 ⚙️ 📨 `username` & `password` ✔ 🤚 🤝. -```Python hl_lines="6" -{!../../docs_src/security/tutorial001.py!} -``` +{* ../../docs_src/security/tutorial001.py hl[6] *} /// tip @@ -168,15 +164,13 @@ 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 | "📡 ℹ" +/// info | 📡 ℹ **FastAPI** 🔜 💭 👈 ⚫️ 💪 ⚙️ 🎓 `OAuth2PasswordBearer` (📣 🔗) 🔬 💂‍♂ ⚖ 🗄 ↩️ ⚫️ 😖 ⚪️➡️ `fastapi.security.oauth2.OAuth2`, ❔ 🔄 😖 ⚪️➡️ `fastapi.security.base.SecurityBase`. diff --git a/docs/em/docs/tutorial/security/get-current-user.md b/docs/em/docs/tutorial/security/get-current-user.md index 4e5b4ebfc708a..2f4a26f3525ab 100644 --- a/docs/em/docs/tutorial/security/get-current-user.md +++ b/docs/em/docs/tutorial/security/get-current-user.md @@ -2,9 +2,7 @@ ⏮️ 📃 💂‍♂ ⚙️ (❔ 🧢 🔛 🔗 💉 ⚙️) 🤝 *➡ 🛠️ 🔢* `token` `str`: -```Python hl_lines="10" -{!../../docs_src/security/tutorial001.py!} -``` +{* ../../docs_src/security/tutorial001.py hl[10] *} ✋️ 👈 🚫 👈 ⚠. @@ -16,21 +14,7 @@ 🎏 🌌 👥 ⚙️ Pydantic 📣 💪, 👥 💪 ⚙️ ⚫️ 🙆 🙆: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="5 12-16" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="3 10-14" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial002.py hl[5,12:16] *} ## ✍ `get_current_user` 🔗 @@ -42,61 +26,19 @@ 🎏 👥 🔨 ⏭ *➡ 🛠️* 🔗, 👆 🆕 🔗 `get_current_user` 🔜 📨 `token` `str` ⚪️➡️ 🎧-🔗 `oauth2_scheme`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="25" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="23" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial002.py hl[25] *} ## 🤚 👩‍💻 `get_current_user` 🔜 ⚙️ (❌) 🚙 🔢 👥 ✍, 👈 ✊ 🤝 `str` & 📨 👆 Pydantic `User` 🏷: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="19-22 26-27" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="17-20 24-25" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial002.py hl[19:22,26:27] *} ## 💉 ⏮️ 👩‍💻 🔜 👥 💪 ⚙️ 🎏 `Depends` ⏮️ 👆 `get_current_user` *➡ 🛠️*: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="31" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="29" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial002.py hl[31] *} 👀 👈 👥 📣 🆎 `current_user` Pydantic 🏷 `User`. @@ -150,21 +92,7 @@ & 🌐 👉 💯 *➡ 🛠️* 💪 🤪 3️⃣ ⏸: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="30-32" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="28-30" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial002.py hl[30:32] *} ## 🌃 diff --git a/docs/em/docs/tutorial/security/oauth2-jwt.md b/docs/em/docs/tutorial/security/oauth2-jwt.md index 95fa58f718358..ee7bc2d28af98 100644 --- a/docs/em/docs/tutorial/security/oauth2-jwt.md +++ b/docs/em/docs/tutorial/security/oauth2-jwt.md @@ -118,21 +118,7 @@ $ pip install "passlib[bcrypt]" & ➕1️⃣ 1️⃣ 🔓 & 📨 👩‍💻. -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="7 48 55-56 59-60 69-75" -{!> ../../docs_src/security/tutorial004.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="6 47 54-55 58-59 68-74" -{!> ../../docs_src/security/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial004.py hl[7,48,55:56,59:60,69:75] *} /// note @@ -168,21 +154,7 @@ $ openssl rand -hex 32 ✍ 🚙 🔢 🏗 🆕 🔐 🤝. -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="6 12-14 28-30 78-86" -{!> ../../docs_src/security/tutorial004.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="5 11-13 27-29 77-85" -{!> ../../docs_src/security/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial004.py hl[6,12:14,28:30,78:86] *} ## ℹ 🔗 @@ -192,21 +164,7 @@ $ openssl rand -hex 32 🚥 🤝 ❌, 📨 🇺🇸🔍 ❌ ▶️️ ↖️. -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="89-106" -{!> ../../docs_src/security/tutorial004.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="88-105" -{!> ../../docs_src/security/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial004.py hl[89:106] *} ## ℹ `/token` *➡ 🛠️* @@ -214,21 +172,7 @@ $ openssl rand -hex 32 ✍ 🎰 🥙 🔐 🤝 & 📨 ⚫️. -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="115-130" -{!> ../../docs_src/security/tutorial004.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="114-129" -{!> ../../docs_src/security/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial004.py hl[115:130] *} ### 📡 ℹ 🔃 🥙 "📄" `sub` diff --git a/docs/em/docs/tutorial/security/simple-oauth2.md b/docs/em/docs/tutorial/security/simple-oauth2.md index 43d928ce79c39..1fd513d48d28c 100644 --- a/docs/em/docs/tutorial/security/simple-oauth2.md +++ b/docs/em/docs/tutorial/security/simple-oauth2.md @@ -52,21 +52,7 @@ Oauth2️⃣ 👫 🎻. 🥇, 🗄 `OAuth2PasswordRequestForm`, & ⚙️ ⚫️ 🔗 ⏮️ `Depends` *➡ 🛠️* `/token`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="4 76" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="2 74" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial003.py hl[4,76] *} `OAuth2PasswordRequestForm` 🎓 🔗 👈 📣 📨 💪 ⏮️: @@ -114,21 +100,7 @@ Oauth2️⃣ 🔌 🤙 *🚚* 🏑 `grant_type` ⏮️ 🔧 💲 `password`, ✋ ❌, 👥 ⚙️ ⚠ `HTTPException`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="3 77-79" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="1 75-77" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial003.py hl[3,77:79] *} ### ✅ 🔐 @@ -154,21 +126,7 @@ Oauth2️⃣ 🔌 🤙 *🚚* 🏑 `grant_type` ⏮️ 🔧 💲 `password`, ✋ , 🧙‍♀ 🏆 🚫 💪 🔄 ⚙️ 👈 🎏 🔐 ➕1️⃣ ⚙️ (📚 👩‍💻 ⚙️ 🎏 🔐 🌐, 👉 🔜 ⚠). -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="80-83" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="78-81" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial003.py hl[80:83] *} #### 🔃 `**user_dict` @@ -210,21 +168,7 @@ UserInDB( /// -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="85" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="83" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial003.py hl[85] *} /// tip @@ -250,21 +194,7 @@ UserInDB( , 👆 🔗, 👥 🔜 🕴 🤚 👩‍💻 🚥 👩‍💻 🔀, ☑ 🔓, & 🦁: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="58-66 69-72 90" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="55-64 67-70 88" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial003.py hl[58:66,69:72,90] *} /// info diff --git a/docs/em/docs/tutorial/sql-databases.md b/docs/em/docs/tutorial/sql-databases.md deleted file mode 100644 index c59d8c13145fb..0000000000000 --- a/docs/em/docs/tutorial/sql-databases.md +++ /dev/null @@ -1,900 +0,0 @@ -# 🗄 (🔗) 💽 - -**FastAPI** 🚫 🚚 👆 ⚙️ 🗄 (🔗) 💽. - -✋️ 👆 💪 ⚙️ 🙆 🔗 💽 👈 👆 💚. - -📥 👥 🔜 👀 🖼 ⚙️ 🇸🇲. - -👆 💪 💪 🛠️ ⚫️ 🙆 💽 🐕‍🦺 🇸🇲, 💖: - -* ✳ -* ✳ -* 🗄 -* 🐸 -* 🤸‍♂ 🗄 💽, ♒️. - -👉 🖼, 👥 🔜 ⚙️ **🗄**, ↩️ ⚫️ ⚙️ 👁 📁 & 🐍 ✔️ 🛠️ 🐕‍🦺. , 👆 💪 📁 👉 🖼 & 🏃 ⚫️. - -⏪, 👆 🏭 🈸, 👆 💪 💚 ⚙️ 💽 💽 💖 **✳**. - -/// tip - -📤 🛂 🏗 🚂 ⏮️ **FastAPI** & **✳**, 🌐 ⚓️ 🔛 **☁**, 🔌 🕸 & 🌖 🧰: https://github.com/tiangolo/full-stack-fastapi-postgresql - -/// - -/// note - -👀 👈 📚 📟 🐩 `SQLAlchemy` 📟 👆 🔜 ⚙️ ⏮️ 🙆 🛠️. - - **FastAPI** 🎯 📟 🤪 🕧. - -/// - -## 🐜 - -**FastAPI** 👷 ⏮️ 🙆 💽 & 🙆 👗 🗃 💬 💽. - -⚠ ⚓ ⚙️ "🐜": "🎚-🔗 🗺" 🗃. - -🐜 ✔️ 🧰 🗜 ("*🗺*") 🖖 *🎚* 📟 & 💽 🏓 ("*🔗*"). - -⏮️ 🐜, 👆 🛎 ✍ 🎓 👈 🎨 🏓 🗄 💽, 🔠 🔢 🎓 🎨 🏓, ⏮️ 📛 & 🆎. - -🖼 🎓 `Pet` 💪 🎨 🗄 🏓 `pets`. - -& 🔠 *👐* 🎚 👈 🎓 🎨 ⏭ 💽. - -🖼 🎚 `orion_cat` (👐 `Pet`) 💪 ✔️ 🔢 `orion_cat.type`, 🏓 `type`. & 💲 👈 🔢 💪, ✅ `"cat"`. - -👫 🐜 ✔️ 🧰 ⚒ 🔗 ⚖️ 🔗 🖖 🏓 ⚖️ 👨‍💼. - -👉 🌌, 👆 💪 ✔️ 🔢 `orion_cat.owner` & 👨‍💼 🔜 🔌 💽 👉 🐶 👨‍💼, ✊ ⚪️➡️ 🏓 *👨‍💼*. - -, `orion_cat.owner.name` 💪 📛 (⚪️➡️ `name` 🏓 `owners` 🏓) 👉 🐶 👨‍💼. - -⚫️ 💪 ✔️ 💲 💖 `"Arquilian"`. - -& 🐜 🔜 🌐 👷 🤚 ℹ ⚪️➡️ 🔗 🏓 *👨‍💼* 🕐❔ 👆 🔄 🔐 ⚫️ ⚪️➡️ 👆 🐶 🎚. - -⚠ 🐜 🖼: ✳-🐜 (🍕 ✳ 🛠️), 🇸🇲 🐜 (🍕 🇸🇲, 🔬 🛠️) & 🏒 (🔬 🛠️), 👪 🎏. - -📥 👥 🔜 👀 ❔ 👷 ⏮️ **🇸🇲 🐜**. - -🎏 🌌 👆 💪 ⚙️ 🙆 🎏 🐜. - -/// tip - -📤 🌓 📄 ⚙️ 🏒 📥 🩺. - -/// - -## 📁 📊 - -👫 🖼, ➡️ 💬 👆 ✔️ 📁 📛 `my_super_project` 👈 🔌 🎧-📁 🤙 `sql_app` ⏮️ 📊 💖 👉: - -``` -. -└── sql_app - ├── __init__.py - ├── crud.py - ├── database.py - ├── main.py - ├── models.py - └── schemas.py -``` - -📁 `__init__.py` 🛁 📁, ✋️ ⚫️ 💬 🐍 👈 `sql_app` ⏮️ 🌐 🚮 🕹 (🐍 📁) 📦. - -🔜 ➡️ 👀 ⚫️❔ 🔠 📁/🕹 🔨. - -## ❎ `SQLAlchemy` - -🥇 👆 💪 ❎ `SQLAlchemy`: - -
- -```console -$ pip install sqlalchemy - ----> 100% -``` - -
- -## ✍ 🇸🇲 🍕 - -➡️ 🔗 📁 `sql_app/database.py`. - -### 🗄 🇸🇲 🍕 - -```Python hl_lines="1-3" -{!../../docs_src/sql_databases/sql_app/database.py!} -``` - -### ✍ 💽 📛 🇸🇲 - -```Python hl_lines="5-6" -{!../../docs_src/sql_databases/sql_app/database.py!} -``` - -👉 🖼, 👥 "🔗" 🗄 💽 (📂 📁 ⏮️ 🗄 💽). - -📁 🔜 🔎 🎏 📁 📁 `sql_app.db`. - -👈 ⚫️❔ 🏁 🍕 `./sql_app.db`. - -🚥 👆 ⚙️ **✳** 💽 ↩️, 👆 🔜 ✔️ ✍ ⏸: - -```Python -SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db" -``` - -...& 🛠️ ⚫️ ⏮️ 👆 💽 📊 & 🎓 (📊 ✳, ✳ ⚖️ 🙆 🎏). - -/// tip - -👉 👑 ⏸ 👈 👆 🔜 ✔️ 🔀 🚥 👆 💚 ⚙️ 🎏 💽. - -/// - -### ✍ 🇸🇲 `engine` - -🥇 🔁 ✍ 🇸🇲 "🚒". - -👥 🔜 ⏪ ⚙️ 👉 `engine` 🎏 🥉. - -```Python hl_lines="8-10" -{!../../docs_src/sql_databases/sql_app/database.py!} -``` - -#### 🗒 - -❌: - -```Python -connect_args={"check_same_thread": False} -``` - -...💪 🕴 `SQLite`. ⚫️ 🚫 💪 🎏 💽. - -/// info | "📡 ℹ" - -🔢 🗄 🔜 🕴 ✔ 1️⃣ 🧵 🔗 ⏮️ ⚫️, 🤔 👈 🔠 🧵 🔜 🍵 🔬 📨. - -👉 ❎ 😫 🤝 🎏 🔗 🎏 👜 (🎏 📨). - -✋️ FastAPI, ⚙️ 😐 🔢 (`def`) 🌅 🌘 1️⃣ 🧵 💪 🔗 ⏮️ 💽 🎏 📨, 👥 💪 ⚒ 🗄 💭 👈 ⚫️ 🔜 ✔ 👈 ⏮️ `connect_args={"check_same_thread": False}`. - -, 👥 🔜 ⚒ 💭 🔠 📨 🤚 🚮 👍 💽 🔗 🎉 🔗, 📤 🙅‍♂ 💪 👈 🔢 🛠️. - -/// - -### ✍ `SessionLocal` 🎓 - -🔠 👐 `SessionLocal` 🎓 🔜 💽 🎉. 🎓 ⚫️ 🚫 💽 🎉. - -✋️ 🕐 👥 ✍ 👐 `SessionLocal` 🎓, 👉 👐 🔜 ☑ 💽 🎉. - -👥 📛 ⚫️ `SessionLocal` 🔬 ⚫️ ⚪️➡️ `Session` 👥 🏭 ⚪️➡️ 🇸🇲. - -👥 🔜 ⚙️ `Session` (1️⃣ 🗄 ⚪️➡️ 🇸🇲) ⏪. - -✍ `SessionLocal` 🎓, ⚙️ 🔢 `sessionmaker`: - -```Python hl_lines="11" -{!../../docs_src/sql_databases/sql_app/database.py!} -``` - -### ✍ `Base` 🎓 - -🔜 👥 🔜 ⚙️ 🔢 `declarative_base()` 👈 📨 🎓. - -⏪ 👥 🔜 😖 ⚪️➡️ 👉 🎓 ✍ 🔠 💽 🏷 ⚖️ 🎓 (🐜 🏷): - -```Python hl_lines="13" -{!../../docs_src/sql_databases/sql_app/database.py!} -``` - -## ✍ 💽 🏷 - -➡️ 🔜 👀 📁 `sql_app/models.py`. - -### ✍ 🇸🇲 🏷 ⚪️➡️ `Base` 🎓 - -👥 🔜 ⚙️ 👉 `Base` 🎓 👥 ✍ ⏭ ✍ 🇸🇲 🏷. - -/// tip - -🇸🇲 ⚙️ ⚖ "**🏷**" 🔗 👉 🎓 & 👐 👈 🔗 ⏮️ 💽. - -✋️ Pydantic ⚙️ ⚖ "**🏷**" 🔗 🕳 🎏, 💽 🔬, 🛠️, & 🧾 🎓 & 👐. - -/// - -🗄 `Base` ⚪️➡️ `database` (📁 `database.py` ⚪️➡️ 🔛). - -✍ 🎓 👈 😖 ⚪️➡️ ⚫️. - -👫 🎓 🇸🇲 🏷. - -```Python hl_lines="4 7-8 18-19" -{!../../docs_src/sql_databases/sql_app/models.py!} -``` - -`__tablename__` 🔢 💬 🇸🇲 📛 🏓 ⚙️ 💽 🔠 👫 🏷. - -### ✍ 🏷 🔢/🏓 - -🔜 ✍ 🌐 🏷 (🎓) 🔢. - -🔠 👫 🔢 🎨 🏓 🚮 🔗 💽 🏓. - -👥 ⚙️ `Column` ⚪️➡️ 🇸🇲 🔢 💲. - -& 👥 🚶‍♀️ 🇸🇲 🎓 "🆎", `Integer`, `String`, & `Boolean`, 👈 🔬 🆎 💽, ❌. - -```Python hl_lines="1 10-13 21-24" -{!../../docs_src/sql_databases/sql_app/models.py!} -``` - -### ✍ 💛 - -🔜 ✍ 💛. - -👉, 👥 ⚙️ `relationship` 🚚 🇸🇲 🐜. - -👉 🔜 ▶️️, 🌅 ⚖️ 🌘, "🎱" 🔢 👈 🔜 🔌 💲 ⚪️➡️ 🎏 🏓 🔗 👉 1️⃣. - -```Python hl_lines="2 15 26" -{!../../docs_src/sql_databases/sql_app/models.py!} -``` - -🕐❔ 🔐 🔢 `items` `User`, `my_user.items`, ⚫️ 🔜 ✔️ 📇 `Item` 🇸🇲 🏷 (⚪️➡️ `items` 🏓) 👈 ✔️ 💱 🔑 ☝ 👉 ⏺ `users` 🏓. - -🕐❔ 👆 🔐 `my_user.items`, 🇸🇲 🔜 🤙 🚶 & ☕ 🏬 ⚪️➡️ 💽 `items` 🏓 & 🔗 👫 📥. - -& 🕐❔ 🔐 🔢 `owner` `Item`, ⚫️ 🔜 🔌 `User` 🇸🇲 🏷 ⚪️➡️ `users` 🏓. ⚫️ 🔜 ⚙️ `owner_id` 🔢/🏓 ⏮️ 🚮 💱 🔑 💭 ❔ ⏺ 🤚 ⚪️➡️ `users` 🏓. - -## ✍ Pydantic 🏷 - -🔜 ➡️ ✅ 📁 `sql_app/schemas.py`. - -/// tip - -❎ 😨 🖖 🇸🇲 *🏷* & Pydantic *🏷*, 👥 🔜 ✔️ 📁 `models.py` ⏮️ 🇸🇲 🏷, & 📁 `schemas.py` ⏮️ Pydantic 🏷. - -👫 Pydantic 🏷 🔬 🌅 ⚖️ 🌘 "🔗" (☑ 📊 💠). - -👉 🔜 ℹ 👥 ❎ 😨 ⏪ ⚙️ 👯‍♂️. - -/// - -### ✍ ▶️ Pydantic *🏷* / 🔗 - -✍ `ItemBase` & `UserBase` Pydantic *🏷* (⚖️ ➡️ 💬 "🔗") ✔️ ⚠ 🔢 ⏪ 🏗 ⚖️ 👂 📊. - -& ✍ `ItemCreate` & `UserCreate` 👈 😖 ⚪️➡️ 👫 (👫 🔜 ✔️ 🎏 🔢), ➕ 🙆 🌖 📊 (🔢) 💪 🏗. - -, 👩‍💻 🔜 ✔️ `password` 🕐❔ 🏗 ⚫️. - -✋️ 💂‍♂, `password` 🏆 🚫 🎏 Pydantic *🏷*, 🖼, ⚫️ 🏆 🚫 📨 ⚪️➡️ 🛠️ 🕐❔ 👂 👩‍💻. - -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="3 6-8 11-12 23-24 27-28" -{!> ../../docs_src/sql_databases/sql_app/schemas.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="3 6-8 11-12 23-24 27-28" -{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="1 4-6 9-10 21-22 25-26" -{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} -``` - -//// - -#### 🇸🇲 👗 & Pydantic 👗 - -👀 👈 🇸🇲 *🏷* 🔬 🔢 ⚙️ `=`, & 🚶‍♀️ 🆎 🔢 `Column`, 💖: - -```Python -name = Column(String) -``` - -⏪ Pydantic *🏷* 📣 🆎 ⚙️ `:`, 🆕 🆎 ✍ ❕/🆎 🔑: - -```Python -name: str -``` - -✔️ ⚫️ 🤯, 👆 🚫 🤚 😕 🕐❔ ⚙️ `=` & `:` ⏮️ 👫. - -### ✍ Pydantic *🏷* / 🔗 👂 / 📨 - -🔜 ✍ Pydantic *🏷* (🔗) 👈 🔜 ⚙️ 🕐❔ 👂 💽, 🕐❔ 🛬 ⚫️ ⚪️➡️ 🛠️. - -🖼, ⏭ 🏗 🏬, 👥 🚫 💭 ⚫️❔ 🔜 🆔 🛠️ ⚫️, ✋️ 🕐❔ 👂 ⚫️ (🕐❔ 🛬 ⚫️ ⚪️➡️ 🛠️) 👥 🔜 ⏪ 💭 🚮 🆔. - -🎏 🌌, 🕐❔ 👂 👩‍💻, 👥 💪 🔜 📣 👈 `items` 🔜 🔌 🏬 👈 💭 👉 👩‍💻. - -🚫 🕴 🆔 📚 🏬, ✋️ 🌐 💽 👈 👥 🔬 Pydantic *🏷* 👂 🏬: `Item`. - -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="15-17 31-34" -{!> ../../docs_src/sql_databases/sql_app/schemas.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="15-17 31-34" -{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="13-15 29-32" -{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} -``` - -//// - -/// tip - -👀 👈 `User`, Pydantic *🏷* 👈 🔜 ⚙️ 🕐❔ 👂 👩‍💻 (🛬 ⚫️ ⚪️➡️ 🛠️) 🚫 🔌 `password`. - -/// - -### ⚙️ Pydantic `orm_mode` - -🔜, Pydantic *🏷* 👂, `Item` & `User`, 🚮 🔗 `Config` 🎓. - -👉 `Config` 🎓 ⚙️ 🚚 📳 Pydantic. - -`Config` 🎓, ⚒ 🔢 `orm_mode = True`. - -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="15 19-20 31 36-37" -{!> ../../docs_src/sql_databases/sql_app/schemas.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="15 19-20 31 36-37" -{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="13 17-18 29 34-35" -{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} -``` - -//// - -/// tip - -👀 ⚫️ ⚖ 💲 ⏮️ `=`, 💖: - -`orm_mode = True` - -⚫️ 🚫 ⚙️ `:` 🆎 📄 ⏭. - -👉 ⚒ 📁 💲, 🚫 📣 🆎. - -/// - -Pydantic `orm_mode` 🔜 💬 Pydantic *🏷* ✍ 💽 🚥 ⚫️ 🚫 `dict`, ✋️ 🐜 🏷 (⚖️ 🙆 🎏 ❌ 🎚 ⏮️ 🔢). - -👉 🌌, ↩️ 🕴 🔄 🤚 `id` 💲 ⚪️➡️ `dict`,: - -```Python -id = data["id"] -``` - -⚫️ 🔜 🔄 🤚 ⚫️ ⚪️➡️ 🔢,: - -```Python -id = data.id -``` - -& ⏮️ 👉, Pydantic *🏷* 🔗 ⏮️ 🐜, & 👆 💪 📣 ⚫️ `response_model` ❌ 👆 *➡ 🛠️*. - -👆 🔜 💪 📨 💽 🏷 & ⚫️ 🔜 ✍ 💽 ⚪️➡️ ⚫️. - -#### 📡 ℹ 🔃 🐜 📳 - -🇸🇲 & 📚 🎏 🔢 "🙃 🚚". - -👈 ⛓, 🖼, 👈 👫 🚫 ☕ 💽 💛 ⚪️➡️ 💽 🚥 👆 🔄 🔐 🔢 👈 🔜 🔌 👈 💽. - -🖼, 🔐 🔢 `items`: - -```Python -current_user.items -``` - -🔜 ⚒ 🇸🇲 🚶 `items` 🏓 & 🤚 🏬 👉 👩‍💻, ✋️ 🚫 ⏭. - -🍵 `orm_mode`, 🚥 👆 📨 🇸🇲 🏷 ⚪️➡️ 👆 *➡ 🛠️*, ⚫️ 🚫🔜 🔌 💛 💽. - -🚥 👆 📣 📚 💛 👆 Pydantic 🏷. - -✋️ ⏮️ 🐜 📳, Pydantic ⚫️ 🔜 🔄 🔐 💽 ⚫️ 💪 ⚪️➡️ 🔢 (↩️ 🤔 `dict`), 👆 💪 📣 🎯 💽 👆 💚 📨 & ⚫️ 🔜 💪 🚶 & 🤚 ⚫️, ⚪️➡️ 🐜. - -## 💩 🇨🇻 - -🔜 ➡️ 👀 📁 `sql_app/crud.py`. - -👉 📁 👥 🔜 ✔️ ♻ 🔢 🔗 ⏮️ 💽 💽. - -**💩** 👟 ⚪️➡️: **🅱**📧, **Ⓜ**💳, **👤** = , & **🇨🇮**📧. - -...👐 👉 🖼 👥 🕴 🏗 & 👂. - -### ✍ 💽 - -🗄 `Session` ⚪️➡️ `sqlalchemy.orm`, 👉 🔜 ✔ 👆 📣 🆎 `db` 🔢 & ✔️ 👻 🆎 ✅ & 🛠️ 👆 🔢. - -🗄 `models` (🇸🇲 🏷) & `schemas` (Pydantic *🏷* / 🔗). - -✍ 🚙 🔢: - -* ✍ 👁 👩‍💻 🆔 & 📧. -* ✍ 💗 👩‍💻. -* ✍ 💗 🏬. - -```Python hl_lines="1 3 6-7 10-11 14-15 27-28" -{!../../docs_src/sql_databases/sql_app/crud.py!} -``` - -/// tip - -🏗 🔢 👈 🕴 💡 🔗 ⏮️ 💽 (🤚 👩‍💻 ⚖️ 🏬) 🔬 👆 *➡ 🛠️ 🔢*, 👆 💪 🌖 💪 ♻ 👫 💗 🍕 & 🚮 ⚒ 💯 👫. - -/// - -### ✍ 💽 - -🔜 ✍ 🚙 🔢 ✍ 💽. - -🔁: - -* ✍ 🇸🇲 🏷 *👐* ⏮️ 👆 📊. -* `add` 👈 👐 🎚 👆 💽 🎉. -* `commit` 🔀 💽 (👈 👫 🖊). -* `refresh` 👆 👐 (👈 ⚫️ 🔌 🙆 🆕 📊 ⚪️➡️ 💽, 💖 🏗 🆔). - -```Python hl_lines="18-24 31-36" -{!../../docs_src/sql_databases/sql_app/crud.py!} -``` - -/// tip - -🇸🇲 🏷 `User` 🔌 `hashed_password` 👈 🔜 🔌 🔐 #️⃣ ⏬ 🔐. - -✋️ ⚫️❔ 🛠️ 👩‍💻 🚚 ⏮️ 🔐, 👆 💪 ⚗ ⚫️ & 🏗 #️⃣ 🔐 👆 🈸. - - & ⤴️ 🚶‍♀️ `hashed_password` ❌ ⏮️ 💲 🖊. - -/// - -/// warning - -👉 🖼 🚫 🔐, 🔐 🚫#️⃣. - -🎰 👨‍❤‍👨 🈸 👆 🔜 💪 #️⃣ 🔐 & 🙅 🖊 👫 🔢. - -🌅 ℹ, 🚶 🔙 💂‍♂ 📄 🔰. - -📥 👥 🎯 🕴 🔛 🧰 & 👨‍🔧 💽. - -/// - -/// tip - -↩️ 🚶‍♀️ 🔠 🇨🇻 ❌ `Item` & 👂 🔠 1️⃣ 👫 ⚪️➡️ Pydantic *🏷*, 👥 🏭 `dict` ⏮️ Pydantic *🏷*'Ⓜ 📊 ⏮️: - -`item.dict()` - - & ⤴️ 👥 🚶‍♀️ `dict`'Ⓜ 🔑-💲 👫 🇨🇻 ❌ 🇸🇲 `Item`, ⏮️: - -`Item(**item.dict())` - - & ⤴️ 👥 🚶‍♀️ ➕ 🇨🇻 ❌ `owner_id` 👈 🚫 🚚 Pydantic *🏷*, ⏮️: - -`Item(**item.dict(), owner_id=user_id)` - -/// - -## 👑 **FastAPI** 📱 - -& 🔜 📁 `sql_app/main.py` ➡️ 🛠️ & ⚙️ 🌐 🎏 🍕 👥 ✍ ⏭. - -### ✍ 💽 🏓 - -📶 🙃 🌌 ✍ 💽 🏓: - -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/sql_databases/sql_app/main.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="7" -{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} -``` - -//// - -#### ⚗ 🗒 - -🛎 👆 🔜 🎲 🔢 👆 💽 (✍ 🏓, ♒️) ⏮️ . - -& 👆 🔜 ⚙️ ⚗ "🛠️" (👈 🚮 👑 👨‍🏭). - -"🛠️" ⚒ 🔁 💪 🕐❔ 👆 🔀 📊 👆 🇸🇲 🏷, 🚮 🆕 🔢, ♒️. 🔁 👈 🔀 💽, 🚮 🆕 🏓, 🆕 🏓, ♒️. - -👆 💪 🔎 🖼 ⚗ FastAPI 🏗 📄 ⚪️➡️ [🏗 ⚡ - 📄](../project-generation.md){.internal-link target=_blank}. 🎯 `alembic` 📁 ℹ 📟. - -### ✍ 🔗 - -🔜 ⚙️ `SessionLocal` 🎓 👥 ✍ `sql_app/database.py` 📁 ✍ 🔗. - -👥 💪 ✔️ 🔬 💽 🎉/🔗 (`SessionLocal`) 📍 📨, ⚙️ 🎏 🎉 🔘 🌐 📨 & ⤴️ 🔐 ⚫️ ⏮️ 📨 🏁. - -& ⤴️ 🆕 🎉 🔜 ✍ ⏭ 📨. - -👈, 👥 🔜 ✍ 🆕 🔗 ⏮️ `yield`, 🔬 ⏭ 📄 🔃 [🔗 ⏮️ `yield`](dependencies/dependencies-with-yield.md){.internal-link target=_blank}. - -👆 🔗 🔜 ✍ 🆕 🇸🇲 `SessionLocal` 👈 🔜 ⚙️ 👁 📨, & ⤴️ 🔐 ⚫️ 🕐 📨 🏁. - -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="15-20" -{!> ../../docs_src/sql_databases/sql_app/main.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="13-18" -{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} -``` - -//// - -/// info - -👥 🚮 🏗 `SessionLocal()` & 🚚 📨 `try` 🍫. - - & ⤴️ 👥 🔐 ⚫️ `finally` 🍫. - -👉 🌌 👥 ⚒ 💭 💽 🎉 🕧 📪 ⏮️ 📨. 🚥 📤 ⚠ ⏪ 🏭 📨. - -✋️ 👆 💪 🚫 🤚 ➕1️⃣ ⚠ ⚪️➡️ 🚪 📟 (⏮️ `yield`). 👀 🌖 [🔗 ⏮️ `yield` & `HTTPException`](dependencies/dependencies-with-yield.md#yield-httpexception){.internal-link target=_blank} - -/// - -& ⤴️, 🕐❔ ⚙️ 🔗 *➡ 🛠️ 🔢*, 👥 📣 ⚫️ ⏮️ 🆎 `Session` 👥 🗄 🔗 ⚪️➡️ 🇸🇲. - -👉 🔜 ⤴️ 🤝 👥 👍 👨‍🎨 🐕‍🦺 🔘 *➡ 🛠️ 🔢*, ↩️ 👨‍🎨 🔜 💭 👈 `db` 🔢 🆎 `Session`: - -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="24 32 38 47 53" -{!> ../../docs_src/sql_databases/sql_app/main.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="22 30 36 45 51" -{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} -``` - -//// - -/// info | "📡 ℹ" - -🔢 `db` 🤙 🆎 `SessionLocal`, ✋️ 👉 🎓 (✍ ⏮️ `sessionmaker()`) "🗳" 🇸🇲 `Session`,, 👨‍🎨 🚫 🤙 💭 ⚫️❔ 👩‍🔬 🚚. - -✋️ 📣 🆎 `Session`, 👨‍🎨 🔜 💪 💭 💪 👩‍🔬 (`.add()`, `.query()`, `.commit()`, ♒️) & 💪 🚚 👍 🐕‍🦺 (💖 🛠️). 🆎 📄 🚫 📉 ☑ 🎚. - -/// - -### ✍ 👆 **FastAPI** *➡ 🛠️* - -🔜, 😒, 📥 🐩 **FastAPI** *➡ 🛠️* 📟. - -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="23-28 31-34 37-42 45-49 52-55" -{!> ../../docs_src/sql_databases/sql_app/main.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="21-26 29-32 35-40 43-47 50-53" -{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} -``` - -//// - -👥 🏗 💽 🎉 ⏭ 🔠 📨 🔗 ⏮️ `yield`, & ⤴️ 📪 ⚫️ ⏮️. - -& ⤴️ 👥 💪 ✍ 🚚 🔗 *➡ 🛠️ 🔢*, 🤚 👈 🎉 🔗. - -⏮️ 👈, 👥 💪 🤙 `crud.get_user` 🔗 ⚪️➡️ 🔘 *➡ 🛠️ 🔢* & ⚙️ 👈 🎉. - -/// tip - -👀 👈 💲 👆 📨 🇸🇲 🏷, ⚖️ 📇 🇸🇲 🏷. - -✋️ 🌐 *➡ 🛠️* ✔️ `response_model` ⏮️ Pydantic *🏷* / 🔗 ⚙️ `orm_mode`, 💽 📣 👆 Pydantic 🏷 🔜 ⚗ ⚪️➡️ 👫 & 📨 👩‍💻, ⏮️ 🌐 😐 ⛽ & 🔬. - -/// - -/// tip - -👀 👈 📤 `response_models` 👈 ✔️ 🐩 🐍 🆎 💖 `List[schemas.Item]`. - -✋️ 🎚/🔢 👈 `List` Pydantic *🏷* ⏮️ `orm_mode`, 💽 🔜 🗃 & 📨 👩‍💻 🛎, 🍵 ⚠. - -/// - -### 🔃 `def` 🆚 `async def` - -📥 👥 ⚙️ 🇸🇲 📟 🔘 *➡ 🛠️ 🔢* & 🔗, &, 🔄, ⚫️ 🔜 🚶 & 🔗 ⏮️ 🔢 💽. - -👈 💪 ⚠ 🚚 "⌛". - -✋️ 🇸🇲 🚫 ✔️ 🔗 ⚙️ `await` 🔗, 🔜 ⏮️ 🕳 💖: - -```Python -user = await db.query(User).first() -``` - -...& ↩️ 👥 ⚙️: - -```Python -user = db.query(User).first() -``` - -⤴️ 👥 🔜 📣 *➡ 🛠️ 🔢* & 🔗 🍵 `async def`, ⏮️ 😐 `def`,: - -```Python hl_lines="2" -@app.get("/users/{user_id}", response_model=schemas.User) -def read_user(user_id: int, db: Session = Depends(get_db)): - db_user = crud.get_user(db, user_id=user_id) - ... -``` - -/// info - -🚥 👆 💪 🔗 👆 🔗 💽 🔁, 👀 [🔁 🗄 (🔗) 💽](../advanced/async-sql-databases.md){.internal-link target=_blank}. - -/// - -/// note | "📶 📡 ℹ" - -🚥 👆 😟 & ✔️ ⏬ 📡 💡, 👆 💪 ✅ 📶 📡 ℹ ❔ 👉 `async def` 🆚 `def` 🍵 [🔁](../async.md#i_2){.internal-link target=_blank} 🩺. - -/// - -## 🛠️ - -↩️ 👥 ⚙️ 🇸🇲 🔗 & 👥 🚫 🚚 🙆 😇 🔌-⚫️ 👷 ⏮️ **FastAPI**, 👥 💪 🛠️ 💽 🛠️ ⏮️ 🔗. - -& 📟 🔗 🇸🇲 & 🇸🇲 🏷 🖖 🎏 🔬 📁, 👆 🔜 💪 🎭 🛠️ ⏮️ ⚗ 🍵 ✔️ ❎ FastAPI, Pydantic, ⚖️ 🕳 🙆. - -🎏 🌌, 👆 🔜 💪 ⚙️ 🎏 🇸🇲 🏷 & 🚙 🎏 🍕 👆 📟 👈 🚫 🔗 **FastAPI**. - -🖼, 🖥 📋 👨‍🏭 ⏮️ 🥒, 🅿, ⚖️ 📶. - -## 📄 🌐 📁 - - 💭 👆 🔜 ✔️ 📁 📛 `my_super_project` 👈 🔌 🎧-📁 🤙 `sql_app`. - -`sql_app` 🔜 ✔️ 📄 📁: - -* `sql_app/__init__.py`: 🛁 📁. - -* `sql_app/database.py`: - -```Python -{!../../docs_src/sql_databases/sql_app/database.py!} -``` - -* `sql_app/models.py`: - -```Python -{!../../docs_src/sql_databases/sql_app/models.py!} -``` - -* `sql_app/schemas.py`: - -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python -{!> ../../docs_src/sql_databases/sql_app/schemas.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python -{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python -{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} -``` - -//// - -* `sql_app/crud.py`: - -```Python -{!../../docs_src/sql_databases/sql_app/crud.py!} -``` - -* `sql_app/main.py`: - -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python -{!> ../../docs_src/sql_databases/sql_app/main.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python -{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} -``` - -//// - -## ✅ ⚫️ - -👆 💪 📁 👉 📟 & ⚙️ ⚫️. - -/// info - -👐, 📟 🎦 📥 🍕 💯. 🌅 📟 👉 🩺. - -/// - -⤴️ 👆 💪 🏃 ⚫️ ⏮️ Uvicorn: - - -
- -```console -$ uvicorn sql_app.main:app --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -
- -& ⤴️, 👆 💪 📂 👆 🖥 http://127.0.0.1:8000/docs. - -& 👆 🔜 💪 🔗 ⏮️ 👆 **FastAPI** 🈸, 👂 📊 ⚪️➡️ 🎰 💽: - - - -## 🔗 ⏮️ 💽 🔗 - -🚥 👆 💚 🔬 🗄 💽 (📁) 🔗, ➡ FastAPI, ℹ 🚮 🎚, 🚮 🏓, 🏓, ⏺, 🔀 📊, ♒️. 👆 💪 ⚙️ 💽 🖥 🗄. - -⚫️ 🔜 👀 💖 👉: - - - -👆 💪 ⚙️ 💳 🗄 🖥 💖 🗄 📋 ⚖️ ExtendsClass. - -## 🎛 💽 🎉 ⏮️ 🛠️ - -🚥 👆 💪 🚫 ⚙️ 🔗 ⏮️ `yield` - 🖼, 🚥 👆 🚫 ⚙️ **🐍 3️⃣.7️⃣** & 💪 🚫 ❎ "🐛" 🤔 🔛 **🐍 3️⃣.6️⃣** - 👆 💪 ⚒ 🆙 🎉 "🛠️" 🎏 🌌. - -"🛠️" 🌖 🔢 👈 🕧 🛠️ 🔠 📨, ⏮️ 📟 🛠️ ⏭, & 📟 🛠️ ⏮️ 🔗 🔢. - -### ✍ 🛠️ - -🛠️ 👥 🔜 🚮 (🔢) 🔜 ✍ 🆕 🇸🇲 `SessionLocal` 🔠 📨, 🚮 ⚫️ 📨 & ⤴️ 🔐 ⚫️ 🕐 📨 🏁. - -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="14-22" -{!> ../../docs_src/sql_databases/sql_app/alt_main.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="12-20" -{!> ../../docs_src/sql_databases/sql_app_py39/alt_main.py!} -``` - -//// - -/// info - -👥 🚮 🏗 `SessionLocal()` & 🚚 📨 `try` 🍫. - - & ⤴️ 👥 🔐 ⚫️ `finally` 🍫. - -👉 🌌 👥 ⚒ 💭 💽 🎉 🕧 📪 ⏮️ 📨. 🚥 📤 ⚠ ⏪ 🏭 📨. - -/// - -### 🔃 `request.state` - -`request.state` 🏠 🔠 `Request` 🎚. ⚫️ 📤 🏪 ❌ 🎚 📎 📨 ⚫️, 💖 💽 🎉 👉 💼. 👆 💪 ✍ 🌅 🔃 ⚫️ 💃 🩺 🔃 `Request` 🇵🇸. - -👥 👉 💼, ⚫️ ℹ 👥 🚚 👁 💽 🎉 ⚙️ 🔘 🌐 📨, & ⤴️ 🔐 ⏮️ (🛠️). - -### 🔗 ⏮️ `yield` ⚖️ 🛠️ - -❎ **🛠️** 📥 🎏 ⚫️❔ 🔗 ⏮️ `yield` 🔨, ⏮️ 🔺: - -* ⚫️ 🚚 🌖 📟 & 👄 🌅 🏗. -* 🛠️ ✔️ `async` 🔢. - * 🚥 📤 📟 ⚫️ 👈 ✔️ "⌛" 🕸, ⚫️ 💪 "🍫" 👆 🈸 📤 & 📉 🎭 🍖. - * 👐 ⚫️ 🎲 🚫 📶 ⚠ 📥 ⏮️ 🌌 `SQLAlchemy` 👷. - * ✋️ 🚥 👆 🚮 🌖 📟 🛠️ 👈 ✔️ 📚 👤/🅾 ⌛, ⚫️ 💪 ⤴️ ⚠. -* 🛠️ 🏃 *🔠* 📨. - * , 🔗 🔜 ✍ 🔠 📨. - * 🕐❔ *➡ 🛠️* 👈 🍵 👈 📨 🚫 💪 💽. - -/// tip - -⚫️ 🎲 👍 ⚙️ 🔗 ⏮️ `yield` 🕐❔ 👫 🥃 ⚙️ 💼. - -/// - -/// info - -🔗 ⏮️ `yield` 🚮 ⏳ **FastAPI**. - -⏮️ ⏬ 👉 🔰 🕴 ✔️ 🖼 ⏮️ 🛠️ & 📤 🎲 📚 🈸 ⚙️ 🛠️ 💽 🎉 🧾. - -/// diff --git a/docs/em/docs/tutorial/static-files.md b/docs/em/docs/tutorial/static-files.md index 0627031b3b8ef..6ff6e37a9e4c8 100644 --- a/docs/em/docs/tutorial/static-files.md +++ b/docs/em/docs/tutorial/static-files.md @@ -7,11 +7,9 @@ * 🗄 `StaticFiles`. * "🗻" `StaticFiles()` 👐 🎯 ➡. -```Python hl_lines="2 6" -{!../../docs_src/static_files/tutorial001.py!} -``` +{* ../../docs_src/static_files/tutorial001.py hl[2,6] *} -/// note | "📡 ℹ" +/// note | 📡 ℹ 👆 💪 ⚙️ `from starlette.staticfiles import StaticFiles`. diff --git a/docs/em/docs/tutorial/testing.md b/docs/em/docs/tutorial/testing.md index 5f3d5e7363479..cb4a1ca217f1b 100644 --- a/docs/em/docs/tutorial/testing.md +++ b/docs/em/docs/tutorial/testing.md @@ -26,9 +26,7 @@ ✍ 🙅 `assert` 📄 ⏮️ 🐩 🐍 🧬 👈 👆 💪 ✅ (🔄, 🐩 `pytest`). -```Python hl_lines="2 12 15-18" -{!../../docs_src/app_testing/tutorial001.py!} -``` +{* ../../docs_src/app_testing/tutorial001.py hl[2,12,15:18] *} /// tip @@ -40,7 +38,7 @@ /// -/// note | "📡 ℹ" +/// note | 📡 ℹ 👆 💪 ⚙️ `from starlette.testclient import TestClient`. @@ -74,9 +72,7 @@ 📁 `main.py` 👆 ✔️ 👆 **FastAPI** 📱: -```Python -{!../../docs_src/app_testing/main.py!} -``` +{* ../../docs_src/app_testing/main.py *} ### 🔬 📁 @@ -92,9 +88,7 @@ ↩️ 👉 📁 🎏 📦, 👆 💪 ⚙️ ⚖ 🗄 🗄 🎚 `app` ⚪️➡️ `main` 🕹 (`main.py`): -```Python hl_lines="3" -{!../../docs_src/app_testing/test_main.py!} -``` +{* ../../docs_src/app_testing/test_main.py hl[3] *} ...& ✔️ 📟 💯 💖 ⏭. @@ -122,29 +116,13 @@ 👯‍♂️ *➡ 🛠️* 🚚 `X-Token` 🎚. -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python -{!> ../../docs_src/app_testing/app_b/main.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python -{!> ../../docs_src/app_testing/app_b_py310/main.py!} -``` - -//// +{* ../../docs_src/app_testing/app_b/main.py *} ### ↔ 🔬 📁 👆 💪 ⤴️ ℹ `test_main.py` ⏮️ ↔ 💯: -```Python -{!> ../../docs_src/app_testing/app_b/test_main.py!} -``` +{* ../../docs_src/app_testing/app_b/test_main.py *} 🕐❔ 👆 💪 👩‍💻 🚶‍♀️ ℹ 📨 & 👆 🚫 💭 ❔, 👆 💪 🔎 (🇺🇸🔍) ❔ ⚫️ `httpx`, ⚖️ ❔ ⚫️ ⏮️ `requests`, 🇸🇲 🔧 ⚓️ 🔛 📨' 🔧. diff --git a/docs/en/data/sponsors.yml b/docs/en/data/sponsors.yml index 6db9c509a64c0..1c83579e220fc 100644 --- a/docs/en/data/sponsors.yml +++ b/docs/en/data/sponsors.yml @@ -29,6 +29,9 @@ gold: - url: https://liblab.com?utm_source=fastapi title: liblab - Generate SDKs from FastAPI img: https://fastapi.tiangolo.com/img/sponsors/liblab.png + - url: https://docs.render.com/deploy-fastapi?utm_source=deploydoc&utm_medium=referral&utm_campaign=fastapi + title: Deploy & scale any full-stack web app on Render. Focus on building apps, not infra. + img: https://fastapi.tiangolo.com/img/sponsors/render.svg silver: - url: https://github.com/deepset-ai/haystack/ title: Build powerful search from composable, open source building blocks diff --git a/docs/en/data/sponsors_badge.yml b/docs/en/data/sponsors_badge.yml index d45028aaae8ef..7470b02385a26 100644 --- a/docs/en/data/sponsors_badge.yml +++ b/docs/en/data/sponsors_badge.yml @@ -31,3 +31,4 @@ logins: - zuplo-oss - Kong - speakeasy-api + - jess-render diff --git a/docs/en/docs/advanced/additional-status-codes.md b/docs/en/docs/advanced/additional-status-codes.md index e392494679d01..077a00488a096 100644 --- a/docs/en/docs/advanced/additional-status-codes.md +++ b/docs/en/docs/advanced/additional-status-codes.md @@ -26,7 +26,7 @@ Make sure it has the data you want it to have, and that the values are valid JSO /// -/// note | "Technical Details" +/// note | Technical Details You could also use `from starlette.responses import JSONResponse`. diff --git a/docs/en/docs/advanced/behind-a-proxy.md b/docs/en/docs/advanced/behind-a-proxy.md index 87a62e88b7f5d..1f0d0fd9f9757 100644 --- a/docs/en/docs/advanced/behind-a-proxy.md +++ b/docs/en/docs/advanced/behind-a-proxy.md @@ -82,7 +82,7 @@ $ fastapi run main.py --root-path /api/v1 If you use Hypercorn, it also has the option `--root-path`. -/// note | "Technical Details" +/// note | Technical Details The ASGI specification defines a `root_path` for this use case. diff --git a/docs/en/docs/advanced/custom-response.md b/docs/en/docs/advanced/custom-response.md index 1d6dc3f6d0ad0..8268dd81a9a48 100644 --- a/docs/en/docs/advanced/custom-response.md +++ b/docs/en/docs/advanced/custom-response.md @@ -30,9 +30,7 @@ This is because by default, FastAPI will inspect every item inside and make sure But if you are certain that the content that you are returning is **serializable with JSON**, you can pass it directly to the response class and avoid the extra overhead that FastAPI would have by passing your return content through the `jsonable_encoder` before passing it to the response class. -```Python hl_lines="2 7" -{!../../docs_src/custom_response/tutorial001b.py!} -``` +{* ../../docs_src/custom_response/tutorial001b.py hl[2,7] *} /// info @@ -57,9 +55,7 @@ To return a response with HTML directly from **FastAPI**, use `HTMLResponse`. * Import `HTMLResponse`. * Pass `HTMLResponse` as the parameter `response_class` of your *path operation decorator*. -```Python hl_lines="2 7" -{!../../docs_src/custom_response/tutorial002.py!} -``` +{* ../../docs_src/custom_response/tutorial002.py hl[2,7] *} /// info @@ -77,9 +73,7 @@ As seen in [Return a Response directly](response-directly.md){.internal-link tar The same example from above, returning an `HTMLResponse`, could look like: -```Python hl_lines="2 7 19" -{!../../docs_src/custom_response/tutorial003.py!} -``` +{* ../../docs_src/custom_response/tutorial003.py hl[2,7,19] *} /// warning @@ -103,9 +97,7 @@ The `response_class` will then be used only to document the OpenAPI *path operat For example, it could be something like: -```Python hl_lines="7 21 23" -{!../../docs_src/custom_response/tutorial004.py!} -``` +{* ../../docs_src/custom_response/tutorial004.py hl[7,21,23] *} In this example, the function `generate_html_response()` already generates and returns a `Response` instead of returning the HTML in a `str`. @@ -121,7 +113,7 @@ Here are some of the available responses. Keep in mind that you can use `Response` to return anything else, or even create a custom sub-class. -/// note | "Technical Details" +/// note | Technical Details You could also use `from starlette.responses import HTMLResponse`. @@ -144,9 +136,7 @@ It accepts the following parameters: FastAPI (actually Starlette) will automatically include a Content-Length header. It will also include a Content-Type header, based on the `media_type` and appending a charset for text types. -```Python hl_lines="1 18" -{!../../docs_src/response_directly/tutorial002.py!} -``` +{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *} ### `HTMLResponse` @@ -156,9 +146,7 @@ Takes some text or bytes and returns an HTML response, as you read above. Takes some text or bytes and returns a plain text response. -```Python hl_lines="2 7 9" -{!../../docs_src/custom_response/tutorial005.py!} -``` +{* ../../docs_src/custom_response/tutorial005.py hl[2,7,9] *} ### `JSONResponse` @@ -192,9 +180,7 @@ This requires installing `ujson` for example with `pip install ujson`. /// -```Python hl_lines="2 7" -{!../../docs_src/custom_response/tutorial001.py!} -``` +{* ../../docs_src/custom_response/tutorial001.py hl[2,7] *} /// tip @@ -208,18 +194,14 @@ Returns an HTTP redirect. Uses a 307 status code (Temporary Redirect) by default You can return a `RedirectResponse` directly: -```Python hl_lines="2 9" -{!../../docs_src/custom_response/tutorial006.py!} -``` +{* ../../docs_src/custom_response/tutorial006.py hl[2,9] *} --- Or you can use it in the `response_class` parameter: -```Python hl_lines="2 7 9" -{!../../docs_src/custom_response/tutorial006b.py!} -``` +{* ../../docs_src/custom_response/tutorial006b.py hl[2,7,9] *} If you do that, then you can return the URL directly from your *path operation* function. @@ -229,17 +211,13 @@ In this case, the `status_code` used will be the default one for the `RedirectRe You can also use the `status_code` parameter combined with the `response_class` parameter: -```Python hl_lines="2 7 9" -{!../../docs_src/custom_response/tutorial006c.py!} -``` +{* ../../docs_src/custom_response/tutorial006c.py hl[2,7,9] *} ### `StreamingResponse` Takes an async generator or a normal generator/iterator and streams the response body. -```Python hl_lines="2 14" -{!../../docs_src/custom_response/tutorial007.py!} -``` +{* ../../docs_src/custom_response/tutorial007.py hl[2,14] *} #### Using `StreamingResponse` with file-like objects @@ -249,9 +227,7 @@ That way, you don't have to read it all first in memory, and you can pass that g This includes many libraries to interact with cloud storage, video processing, and others. -```{ .python .annotate hl_lines="2 10-12 14" } -{!../../docs_src/custom_response/tutorial008.py!} -``` +{* ../../docs_src/custom_response/tutorial008.py hl[2,10:12,14] *} 1. This is the generator function. It's a "generator function" because it contains `yield` statements inside. 2. By using a `with` block, we make sure that the file-like object is closed after the generator function is done. So, after it finishes sending the response. @@ -280,15 +256,11 @@ Takes a different set of arguments to instantiate than the other response types: File responses will include appropriate `Content-Length`, `Last-Modified` and `ETag` headers. -```Python hl_lines="2 10" -{!../../docs_src/custom_response/tutorial009.py!} -``` +{* ../../docs_src/custom_response/tutorial009.py hl[2,10] *} You can also use the `response_class` parameter: -```Python hl_lines="2 8 10" -{!../../docs_src/custom_response/tutorial009b.py!} -``` +{* ../../docs_src/custom_response/tutorial009b.py hl[2,8,10] *} In this case, you can return the file path directly from your *path operation* function. @@ -302,9 +274,7 @@ Let's say you want it to return indented and formatted JSON, so you want to use You could create a `CustomORJSONResponse`. The main thing you have to do is create a `Response.render(content)` method that returns the content as `bytes`: -```Python hl_lines="9-14 17" -{!../../docs_src/custom_response/tutorial009c.py!} -``` +{* ../../docs_src/custom_response/tutorial009c.py hl[9:14,17] *} Now instead of returning: @@ -330,9 +300,7 @@ The parameter that defines this is `default_response_class`. In the example below, **FastAPI** will use `ORJSONResponse` by default, in all *path operations*, instead of `JSONResponse`. -```Python hl_lines="2 4" -{!../../docs_src/custom_response/tutorial010.py!} -``` +{* ../../docs_src/custom_response/tutorial010.py hl[2,4] *} /// tip diff --git a/docs/en/docs/advanced/dataclasses.md b/docs/en/docs/advanced/dataclasses.md index efc07eab2829c..2936c6d5dc34c 100644 --- a/docs/en/docs/advanced/dataclasses.md +++ b/docs/en/docs/advanced/dataclasses.md @@ -4,9 +4,7 @@ FastAPI is built on top of **Pydantic**, and I have been showing you how to use But FastAPI also supports using `dataclasses` the same way: -```Python hl_lines="1 7-12 19-20" -{!../../docs_src/dataclasses/tutorial001.py!} -``` +{* ../../docs_src/dataclasses/tutorial001.py hl[1,7:12,19:20] *} This is still supported thanks to **Pydantic**, as it has internal support for `dataclasses`. @@ -34,9 +32,7 @@ But if you have a bunch of dataclasses laying around, this is a nice trick to us You can also use `dataclasses` in the `response_model` parameter: -```Python hl_lines="1 7-13 19" -{!../../docs_src/dataclasses/tutorial002.py!} -``` +{* ../../docs_src/dataclasses/tutorial002.py hl[1,7:13,19] *} The dataclass will be automatically converted to a Pydantic dataclass. @@ -52,9 +48,7 @@ In some cases, you might still have to use Pydantic's version of `dataclasses`. In that case, you can simply swap the standard `dataclasses` with `pydantic.dataclasses`, which is a drop-in replacement: -```{ .python .annotate hl_lines="1 5 8-11 14-17 23-25 28" } -{!../../docs_src/dataclasses/tutorial003.py!} -``` +{* ../../docs_src/dataclasses/tutorial003.py hl[1,5,8:11,14:17,23:25,28] *} 1. We still import `field` from standard `dataclasses`. diff --git a/docs/en/docs/advanced/events.md b/docs/en/docs/advanced/events.md index efce492f41a99..19465d891cadc 100644 --- a/docs/en/docs/advanced/events.md +++ b/docs/en/docs/advanced/events.md @@ -30,9 +30,7 @@ Let's start with an example and then see it in detail. We create an async function `lifespan()` with `yield` like this: -```Python hl_lines="16 19" -{!../../docs_src/events/tutorial003.py!} -``` +{* ../../docs_src/events/tutorial003.py hl[16,19] *} Here we are simulating the expensive *startup* operation of loading the model by putting the (fake) model function in the dictionary with machine learning models before the `yield`. This code will be executed **before** the application **starts taking requests**, during the *startup*. @@ -50,9 +48,7 @@ Maybe you need to start a new version, or you just got tired of running it. 🤷 The first thing to notice, is that we are defining an async function with `yield`. This is very similar to Dependencies with `yield`. -```Python hl_lines="14-19" -{!../../docs_src/events/tutorial003.py!} -``` +{* ../../docs_src/events/tutorial003.py hl[14:19] *} The first part of the function, before the `yield`, will be executed **before** the application starts. @@ -64,9 +60,7 @@ If you check, the function is decorated with an `@asynccontextmanager`. That converts the function into something called an "**async context manager**". -```Python hl_lines="1 13" -{!../../docs_src/events/tutorial003.py!} -``` +{* ../../docs_src/events/tutorial003.py hl[1,13] *} A **context manager** in Python is something that you can use in a `with` statement, for example, `open()` can be used as a context manager: @@ -88,9 +82,7 @@ In our code example above, we don't use it directly, but we pass it to FastAPI f The `lifespan` parameter of the `FastAPI` app takes an **async context manager**, so we can pass our new `lifespan` async context manager to it. -```Python hl_lines="22" -{!../../docs_src/events/tutorial003.py!} -``` +{* ../../docs_src/events/tutorial003.py hl[22] *} ## Alternative Events (deprecated) @@ -112,9 +104,7 @@ These functions can be declared with `async def` or normal `def`. To add a function that should be run before the application starts, declare it with the event `"startup"`: -```Python hl_lines="8" -{!../../docs_src/events/tutorial001.py!} -``` +{* ../../docs_src/events/tutorial001.py hl[8] *} In this case, the `startup` event handler function will initialize the items "database" (just a `dict`) with some values. @@ -126,9 +116,7 @@ And your application won't start receiving requests until all the `startup` even To add a function that should be run when the application is shutting down, declare it with the event `"shutdown"`: -```Python hl_lines="6" -{!../../docs_src/events/tutorial002.py!} -``` +{* ../../docs_src/events/tutorial002.py hl[6] *} Here, the `shutdown` event handler function will write a text line `"Application shutdown"` to a file `log.txt`. diff --git a/docs/en/docs/advanced/generate-clients.md b/docs/en/docs/advanced/generate-clients.md index 7872103c30280..3b9dc83f04723 100644 --- a/docs/en/docs/advanced/generate-clients.md +++ b/docs/en/docs/advanced/generate-clients.md @@ -32,21 +32,7 @@ There are also several other companies offering similar services that you can se Let's start with a simple FastAPI application: -//// tab | Python 3.9+ - -```Python hl_lines="7-9 12-13 16-17 21" -{!> ../../docs_src/generate_clients/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9-11 14-15 18 19 23" -{!> ../../docs_src/generate_clients/tutorial001.py!} -``` - -//// +{* ../../docs_src/generate_clients/tutorial001_py39.py hl[7:9,12:13,16:17,21] *} Notice that the *path operations* define the models they use for request payload and response payload, using the models `Item` and `ResponseMessage`. @@ -151,21 +137,7 @@ In many cases your FastAPI app will be bigger, and you will probably use tags to For example, you could have a section for **items** and another section for **users**, and they could be separated by tags: -//// tab | Python 3.9+ - -```Python hl_lines="21 26 34" -{!> ../../docs_src/generate_clients/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="23 28 36" -{!> ../../docs_src/generate_clients/tutorial002.py!} -``` - -//// +{* ../../docs_src/generate_clients/tutorial002_py39.py hl[21,26,34] *} ### Generate a TypeScript Client with Tags @@ -212,21 +184,7 @@ For example, here it is using the first tag (you will probably have only one tag You can then pass that custom function to **FastAPI** as the `generate_unique_id_function` parameter: -//// tab | Python 3.9+ - -```Python hl_lines="6-7 10" -{!> ../../docs_src/generate_clients/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8-9 12" -{!> ../../docs_src/generate_clients/tutorial003.py!} -``` - -//// +{* ../../docs_src/generate_clients/tutorial003_py39.py hl[6:7,10] *} ### Generate a TypeScript Client with Custom Operation IDs @@ -248,13 +206,7 @@ But for the generated client we could **modify** the OpenAPI operation IDs right We could download the OpenAPI JSON to a file `openapi.json` and then we could **remove that prefixed tag** with a script like this: -//// tab | Python - -```Python -{!> ../../docs_src/generate_clients/tutorial004.py!} -``` - -//// +{* ../../docs_src/generate_clients/tutorial004.py *} //// tab | Node.js diff --git a/docs/en/docs/advanced/middleware.md b/docs/en/docs/advanced/middleware.md index 3faf3fbf91dca..1d40b1c8fc568 100644 --- a/docs/en/docs/advanced/middleware.md +++ b/docs/en/docs/advanced/middleware.md @@ -43,7 +43,7 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") **FastAPI** includes several middlewares for common use cases, we'll see next how to use them. -/// note | "Technical Details" +/// note | Technical Details For the next examples, you could also use `from starlette.middleware.something import SomethingMiddleware`. diff --git a/docs/en/docs/advanced/openapi-callbacks.md b/docs/en/docs/advanced/openapi-callbacks.md index 82069a950073f..ca9065a896d2d 100644 --- a/docs/en/docs/advanced/openapi-callbacks.md +++ b/docs/en/docs/advanced/openapi-callbacks.md @@ -31,9 +31,7 @@ It will have a *path operation* that will receive an `Invoice` body, and a query This part is pretty normal, most of the code is probably already familiar to you: -```Python hl_lines="9-13 36-53" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[9:13,36:53] *} /// tip @@ -92,9 +90,7 @@ Temporarily adopting this point of view (of the *external developer*) can help y First create a new `APIRouter` that will contain one or more callbacks. -```Python hl_lines="3 25" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[3,25] *} ### Create the callback *path operation* @@ -105,9 +101,7 @@ It should look just like a normal FastAPI *path operation*: * It should probably have a declaration of the body it should receive, e.g. `body: InvoiceEvent`. * And it could also have a declaration of the response it should return, e.g. `response_model=InvoiceEventReceived`. -```Python hl_lines="16-18 21-22 28-32" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[16:18,21:22,28:32] *} There are 2 main differences from a normal *path operation*: @@ -175,9 +169,7 @@ At this point you have the *callback path operation(s)* needed (the one(s) that Now use the parameter `callbacks` in *your API's path operation decorator* to pass the attribute `.routes` (that's actually just a `list` of routes/*path operations*) from that callback router: -```Python hl_lines="35" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[35] *} /// tip diff --git a/docs/en/docs/advanced/openapi-webhooks.md b/docs/en/docs/advanced/openapi-webhooks.md index eaaa48a37ee23..97aaa41af96f6 100644 --- a/docs/en/docs/advanced/openapi-webhooks.md +++ b/docs/en/docs/advanced/openapi-webhooks.md @@ -32,9 +32,7 @@ Webhooks are available in OpenAPI 3.1.0 and above, supported by FastAPI `0.99.0` When you create a **FastAPI** application, there is a `webhooks` attribute that you can use to define *webhooks*, the same way you would define *path operations*, for example with `@app.webhooks.post()`. -```Python hl_lines="9-13 36-53" -{!../../docs_src/openapi_webhooks/tutorial001.py!} -``` +{* ../../docs_src/openapi_webhooks/tutorial001.py hl[9:13,36:53] *} The webhooks that you define will end up in the **OpenAPI** schema and the automatic **docs UI**. diff --git a/docs/en/docs/advanced/path-operation-advanced-configuration.md b/docs/en/docs/advanced/path-operation-advanced-configuration.md index a61e3f19b5ba3..c4814ebd2f368 100644 --- a/docs/en/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/en/docs/advanced/path-operation-advanced-configuration.md @@ -12,9 +12,7 @@ You can set the OpenAPI `operationId` to be used in your *path operation* with t You would have to make sure that it is unique for each operation. -```Python hl_lines="6" -{!../../docs_src/path_operation_advanced_configuration/tutorial001.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial001.py hl[6] *} ### Using the *path operation function* name as the operationId @@ -22,9 +20,7 @@ If you want to use your APIs' function names as `operationId`s, you can iterate You should do it after adding all your *path operations*. -```Python hl_lines="2 12-21 24" -{!../../docs_src/path_operation_advanced_configuration/tutorial002.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial002.py hl[2, 12:21, 24] *} /// tip @@ -44,9 +40,7 @@ Even if they are in different modules (Python files). To exclude a *path operation* from the generated OpenAPI schema (and thus, from the automatic documentation systems), use the parameter `include_in_schema` and set it to `False`: -```Python hl_lines="6" -{!../../docs_src/path_operation_advanced_configuration/tutorial003.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial003.py hl[6] *} ## Advanced description from docstring @@ -56,9 +50,7 @@ Adding an `\f` (an escaped "form feed" character) causes **FastAPI** to truncate It won't show up in the documentation, but other tools (such as Sphinx) will be able to use the rest. -```Python hl_lines="19-29" -{!../../docs_src/path_operation_advanced_configuration/tutorial004.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial004.py hl[19:29] *} ## Additional Responses @@ -74,7 +66,7 @@ There's a whole chapter here in the documentation about it, you can read it at [ When you declare a *path operation* in your application, **FastAPI** automatically generates the relevant metadata about that *path operation* to be included in the OpenAPI schema. -/// note | "Technical details" +/// note | Technical details In the OpenAPI specification it is called the Operation Object. @@ -100,9 +92,7 @@ You can extend the OpenAPI schema for a *path operation* using the parameter `op This `openapi_extra` can be helpful, for example, to declare [OpenAPI Extensions](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions): -```Python hl_lines="6" -{!../../docs_src/path_operation_advanced_configuration/tutorial005.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial005.py hl[6] *} If you open the automatic API docs, your extension will show up at the bottom of the specific *path operation*. @@ -149,9 +139,7 @@ For example, you could decide to read and validate the request with your own cod You could do that with `openapi_extra`: -```Python hl_lines="19-36 39-40" -{!../../docs_src/path_operation_advanced_configuration/tutorial006.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial006.py hl[19:36, 39:40] *} In this example, we didn't declare any Pydantic model. In fact, the request body is not even parsed as JSON, it is read directly as `bytes`, and the function `magic_data_reader()` would be in charge of parsing it in some way. @@ -167,17 +155,13 @@ For example, in this application we don't use FastAPI's integrated functionality //// tab | Pydantic v2 -```Python hl_lines="17-22 24" -{!> ../../docs_src/path_operation_advanced_configuration/tutorial007.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[17:22, 24] *} //// //// tab | Pydantic v1 -```Python hl_lines="17-22 24" -{!> ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py hl[17:22, 24] *} //// @@ -195,17 +179,13 @@ And then in our code, we parse that YAML content directly, and then we are again //// tab | Pydantic v2 -```Python hl_lines="26-33" -{!> ../../docs_src/path_operation_advanced_configuration/tutorial007.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[26:33] *} //// //// tab | Pydantic v1 -```Python hl_lines="26-33" -{!> ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py hl[26:33] *} //// diff --git a/docs/en/docs/advanced/response-change-status-code.md b/docs/en/docs/advanced/response-change-status-code.md index fc041f7de5fc1..6d3f9f3e8674d 100644 --- a/docs/en/docs/advanced/response-change-status-code.md +++ b/docs/en/docs/advanced/response-change-status-code.md @@ -20,9 +20,7 @@ You can declare a parameter of type `Response` in your *path operation function* And then you can set the `status_code` in that *temporal* response object. -```Python hl_lines="1 9 12" -{!../../docs_src/response_change_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_change_status_code/tutorial001.py hl[1,9,12] *} And then you can return any object you need, as you normally would (a `dict`, a database model, etc). diff --git a/docs/en/docs/advanced/response-cookies.md b/docs/en/docs/advanced/response-cookies.md index 4467779ba65b8..f6d17f35d6e05 100644 --- a/docs/en/docs/advanced/response-cookies.md +++ b/docs/en/docs/advanced/response-cookies.md @@ -6,9 +6,7 @@ You can declare a parameter of type `Response` in your *path operation function* And then you can set cookies in that *temporal* response object. -```Python hl_lines="1 8-9" -{!../../docs_src/response_cookies/tutorial002.py!} -``` +{* ../../docs_src/response_cookies/tutorial002.py hl[1, 8:9] *} And then you can return any object you need, as you normally would (a `dict`, a database model, etc). @@ -26,9 +24,7 @@ To do that, you can create a response as described in [Return a Response Directl Then set Cookies in it, and then return it: -```Python hl_lines="10-12" -{!../../docs_src/response_cookies/tutorial001.py!} -``` +{* ../../docs_src/response_cookies/tutorial001.py hl[10:12] *} /// tip @@ -42,7 +38,7 @@ And also that you are not sending any data that should have been filtered by a ` ### More info -/// note | "Technical Details" +/// note | Technical Details You could also use `from starlette.responses import Response` or `from starlette.responses import JSONResponse`. diff --git a/docs/en/docs/advanced/response-directly.md b/docs/en/docs/advanced/response-directly.md index 8246b96740602..691b1e7cdde76 100644 --- a/docs/en/docs/advanced/response-directly.md +++ b/docs/en/docs/advanced/response-directly.md @@ -34,11 +34,9 @@ For example, you cannot put a Pydantic model in a `JSONResponse` without first c For those cases, you can use the `jsonable_encoder` to convert your data before passing it to a response: -```Python hl_lines="6-7 21-22" -{!../../docs_src/response_directly/tutorial001.py!} -``` +{* ../../docs_src/response_directly/tutorial001.py hl[6:7,21:22] *} -/// note | "Technical Details" +/// note | Technical Details You could also use `from starlette.responses import JSONResponse`. @@ -56,9 +54,7 @@ Let's say that you want to return an ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="2 5 9 13 48 66 107 109-117 123-126 130-136 141 157" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="4 8 12 46 64 105 107-115 121-124 128-134 139 155" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[5,9,13,47,65,106,108:116,122:125,129:135,140,156] *} Now let's review those changes step by step. @@ -136,71 +72,7 @@ The first change is that now we are declaring the OAuth2 security scheme with tw The `scopes` parameter receives a `dict` with each scope as a key and the description as the value: -//// tab | Python 3.10+ - -```Python hl_lines="63-66" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="63-66" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="64-67" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="62-65" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="63-66" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="63-66" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[63:66] *} Because we are now declaring those scopes, they will show up in the API docs when you log-in/authorize. @@ -226,71 +98,7 @@ But in your application, for security, you should make sure you only add the sco /// -//// tab | Python 3.10+ - -```Python hl_lines="156" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="156" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="157" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="155" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="156" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="156" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[156] *} ## Declare scopes in *path operations* and dependencies @@ -316,73 +124,9 @@ We are doing it here to demonstrate how **FastAPI** handles scopes declared at d /// -//// tab | Python 3.10+ - -```Python hl_lines="5 140 171" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="5 140 171" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="5 141 172" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="4 139 168" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="5 140 169" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="5 140 169" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[5,140,171] *} -/// info | "Technical Details" +/// info | Technical Details `Security` is actually a subclass of `Depends`, and it has just one extra parameter that we'll see later. @@ -406,71 +150,7 @@ We also declare a special parameter of type `SecurityScopes`, imported from `fas This `SecurityScopes` class is similar to `Request` (`Request` was used to get the request object directly). -//// tab | Python 3.10+ - -```Python hl_lines="9 106" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9 106" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 107" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="8 105" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9 106" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9 106" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[9,106] *} ## Use the `scopes` @@ -484,71 +164,7 @@ We create an `HTTPException` that we can reuse (`raise`) later at several points In this exception, we include the scopes required (if any) as a string separated by spaces (using `scope_str`). We put that string containing the scopes in the `WWW-Authenticate` header (this is part of the spec). -//// tab | Python 3.10+ - -```Python hl_lines="106 108-116" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="106 108-116" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="107 109-117" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="105 107-115" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="106 108-116" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="106 108-116" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[106,108:116] *} ## Verify the `username` and data shape @@ -564,71 +180,7 @@ Instead of, for example, a `dict`, or something else, as it could break the appl We also verify that we have a user with that username, and if not, we raise that same exception we created before. -//// tab | Python 3.10+ - -```Python hl_lines="47 117-128" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="47 117-128" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="48 118-129" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="46 116-127" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="47 117-128" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="47 117-128" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[47,117:128] *} ## Verify the `scopes` @@ -636,71 +188,7 @@ We now verify that all the scopes required, by this dependency and all the depen For this, we use `security_scopes.scopes`, that contains a `list` with all these scopes as `str`. -//// tab | Python 3.10+ - -```Python hl_lines="129-135" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="129-135" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="130-136" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="128-134" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="129-135" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="129-135" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[129:135] *} ## Dependency tree and scopes diff --git a/docs/en/docs/advanced/settings.md b/docs/en/docs/advanced/settings.md index 01810c438a792..1af19a0454da7 100644 --- a/docs/en/docs/advanced/settings.md +++ b/docs/en/docs/advanced/settings.md @@ -62,9 +62,7 @@ You can use all the same validation features and tools you use for Pydantic mode //// tab | Pydantic v2 -```Python hl_lines="2 5-8 11" -{!> ../../docs_src/settings/tutorial001.py!} -``` +{* ../../docs_src/settings/tutorial001.py hl[2,5:8,11] *} //// @@ -76,9 +74,7 @@ In Pydantic v1 you would import `BaseSettings` directly from `pydantic` instead /// -```Python hl_lines="2 5-8 11" -{!> ../../docs_src/settings/tutorial001_pv1.py!} -``` +{* ../../docs_src/settings/tutorial001_pv1.py hl[2,5:8,11] *} //// @@ -96,9 +92,7 @@ Next it will convert and validate the data. So, when you use that `settings` obj Then you can use the new `settings` object in your application: -```Python hl_lines="18-20" -{!../../docs_src/settings/tutorial001.py!} -``` +{* ../../docs_src/settings/tutorial001.py hl[18:20] *} ### Run the server @@ -132,15 +126,11 @@ You could put those settings in another module file as you saw in [Bigger Applic For example, you could have a file `config.py` with: -```Python -{!../../docs_src/settings/app01/config.py!} -``` +{* ../../docs_src/settings/app01/config.py *} And then use it in a file `main.py`: -```Python hl_lines="3 11-13" -{!../../docs_src/settings/app01/main.py!} -``` +{* ../../docs_src/settings/app01/main.py hl[3,11:13] *} /// tip @@ -158,9 +148,7 @@ This could be especially useful during testing, as it's very easy to override a Coming from the previous example, your `config.py` file could look like: -```Python hl_lines="10" -{!../../docs_src/settings/app02/config.py!} -``` +{* ../../docs_src/settings/app02/config.py hl[10] *} Notice that now we don't create a default instance `settings = Settings()`. @@ -168,35 +156,7 @@ Notice that now we don't create a default instance `settings = Settings()`. Now we create a dependency that returns a new `config.Settings()`. -//// tab | Python 3.9+ - -```Python hl_lines="6 12-13" -{!> ../../docs_src/settings/app02_an_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="6 12-13" -{!> ../../docs_src/settings/app02_an/main.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="5 11-12" -{!> ../../docs_src/settings/app02/main.py!} -``` - -//// +{* ../../docs_src/settings/app02_an_py39/main.py hl[6,12:13] *} /// tip @@ -208,43 +168,13 @@ For now you can assume `get_settings()` is a normal function. And then we can require it from the *path operation function* as a dependency and use it anywhere we need it. -//// tab | Python 3.9+ - -```Python hl_lines="17 19-21" -{!> ../../docs_src/settings/app02_an_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17 19-21" -{!> ../../docs_src/settings/app02_an/main.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="16 18-20" -{!> ../../docs_src/settings/app02/main.py!} -``` - -//// +{* ../../docs_src/settings/app02_an_py39/main.py hl[17,19:21] *} ### Settings and testing Then it would be very easy to provide a different settings object during testing by creating a dependency override for `get_settings`: -```Python hl_lines="9-10 13 21" -{!../../docs_src/settings/app02/test_main.py!} -``` +{* ../../docs_src/settings/app02/test_main.py hl[9:10,13,21] *} In the dependency override we set a new value for the `admin_email` when creating the new `Settings` object, and then we return that new object. @@ -287,9 +217,7 @@ And then update your `config.py` with: //// tab | Pydantic v2 -```Python hl_lines="9" -{!> ../../docs_src/settings/app03_an/config.py!} -``` +{* ../../docs_src/settings/app03_an/config.py hl[9] *} /// tip @@ -301,9 +229,7 @@ The `model_config` attribute is used just for Pydantic configuration. You can re //// tab | Pydantic v1 -```Python hl_lines="9-10" -{!> ../../docs_src/settings/app03_an/config_pv1.py!} -``` +{* ../../docs_src/settings/app03_an/config_pv1.py hl[9:10] *} /// tip @@ -344,35 +270,7 @@ we would create that object for each request, and we would be reading the `.env` But as we are using the `@lru_cache` decorator on top, the `Settings` object will be created only once, the first time it's called. ✔️ -//// tab | Python 3.9+ - -```Python hl_lines="1 11" -{!> ../../docs_src/settings/app03_an_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 11" -{!> ../../docs_src/settings/app03_an/main.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="1 10" -{!> ../../docs_src/settings/app03/main.py!} -``` - -//// +{* ../../docs_src/settings/app03_an_py39/main.py hl[1,11] *} Then for any subsequent call of `get_settings()` in the dependencies for the next requests, instead of executing the internal code of `get_settings()` and creating a new `Settings` object, it will return the same object that was returned on the first call, again and again. diff --git a/docs/en/docs/advanced/sub-applications.md b/docs/en/docs/advanced/sub-applications.md index befa9908a43de..48e329fc13d35 100644 --- a/docs/en/docs/advanced/sub-applications.md +++ b/docs/en/docs/advanced/sub-applications.md @@ -10,9 +10,7 @@ If you need to have two independent FastAPI applications, with their own indepen First, create the main, top-level, **FastAPI** application, and its *path operations*: -```Python hl_lines="3 6-8" -{!../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[3, 6:8] *} ### Sub-application @@ -20,9 +18,7 @@ Then, create your sub-application, and its *path operations*. This sub-application is just another standard FastAPI application, but this is the one that will be "mounted": -```Python hl_lines="11 14-16" -{!../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[11, 14:16] *} ### Mount the sub-application @@ -30,9 +26,7 @@ In your top-level application, `app`, mount the sub-application, `subapi`. In this case, it will be mounted at the path `/subapi`: -```Python hl_lines="11 19" -{!../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[11, 19] *} ### Check the automatic API docs diff --git a/docs/en/docs/advanced/templates.md b/docs/en/docs/advanced/templates.md index d688c5cb7a039..d9b0ca6f14fc4 100644 --- a/docs/en/docs/advanced/templates.md +++ b/docs/en/docs/advanced/templates.md @@ -27,9 +27,7 @@ $ pip install jinja2 * Declare a `Request` parameter in the *path operation* that will return a template. * Use the `templates` you created to render and return a `TemplateResponse`, pass the name of the template, the request object, and a "context" dictionary with key-value pairs to be used inside of the Jinja2 template. -```Python hl_lines="4 11 15-18" -{!../../docs_src/templates/tutorial001.py!} -``` +{* ../../docs_src/templates/tutorial001.py hl[4,11,15:18] *} /// note @@ -45,7 +43,7 @@ By declaring `response_class=HTMLResponse` the docs UI will be able to know that /// -/// note | "Technical Details" +/// note | Technical Details You could also use `from starlette.templating import Jinja2Templates`. diff --git a/docs/en/docs/advanced/testing-dependencies.md b/docs/en/docs/advanced/testing-dependencies.md index 1cc4313a1e17f..17b4f98145659 100644 --- a/docs/en/docs/advanced/testing-dependencies.md +++ b/docs/en/docs/advanced/testing-dependencies.md @@ -28,57 +28,7 @@ To override a dependency for testing, you put as a key the original dependency ( And then **FastAPI** will call that override instead of the original dependency. -//// tab | Python 3.10+ - -```Python hl_lines="26-27 30" -{!> ../../docs_src/dependency_testing/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="28-29 32" -{!> ../../docs_src/dependency_testing/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="29-30 33" -{!> ../../docs_src/dependency_testing/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="24-25 28" -{!> ../../docs_src/dependency_testing/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="28-29 32" -{!> ../../docs_src/dependency_testing/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependency_testing/tutorial001_an_py310.py hl[26:27,30] *} /// tip diff --git a/docs/en/docs/advanced/testing-events.md b/docs/en/docs/advanced/testing-events.md index f48907c7c3de1..0c554c4ece5e2 100644 --- a/docs/en/docs/advanced/testing-events.md +++ b/docs/en/docs/advanced/testing-events.md @@ -2,6 +2,4 @@ When you need your event handlers (`startup` and `shutdown`) to run in your tests, you can use the `TestClient` with a `with` statement: -```Python hl_lines="9-12 20-24" -{!../../docs_src/app_testing/tutorial003.py!} -``` +{* ../../docs_src/app_testing/tutorial003.py hl[9:12,20:24] *} diff --git a/docs/en/docs/advanced/testing-websockets.md b/docs/en/docs/advanced/testing-websockets.md index ab08c90fe876c..60dfdc3432cb9 100644 --- a/docs/en/docs/advanced/testing-websockets.md +++ b/docs/en/docs/advanced/testing-websockets.md @@ -4,9 +4,7 @@ You can use the same `TestClient` to test WebSockets. For this, you use the `TestClient` in a `with` statement, connecting to the WebSocket: -```Python hl_lines="27-31" -{!../../docs_src/app_testing/tutorial002.py!} -``` +{* ../../docs_src/app_testing/tutorial002.py hl[27:31] *} /// note diff --git a/docs/en/docs/advanced/using-request-directly.md b/docs/en/docs/advanced/using-request-directly.md index 917d77a95f3c3..2f88c8f2062e4 100644 --- a/docs/en/docs/advanced/using-request-directly.md +++ b/docs/en/docs/advanced/using-request-directly.md @@ -29,9 +29,7 @@ Let's imagine you want to get the client's IP address/host inside of your *path For that you need to access the request directly. -```Python hl_lines="1 7-8" -{!../../docs_src/using_request_directly/tutorial001.py!} -``` +{* ../../docs_src/using_request_directly/tutorial001.py hl[1,7:8] *} By declaring a *path operation function* parameter with the type being the `Request` **FastAPI** will know to pass the `Request` in that parameter. @@ -49,7 +47,7 @@ The same way, you can declare any other parameter as normally, and additionally, You can read more details about the `Request` object in the official Starlette documentation site. -/// note | "Technical Details" +/// note | Technical Details You could also use `from starlette.requests import Request`. diff --git a/docs/en/docs/advanced/websockets.md b/docs/en/docs/advanced/websockets.md index 8947f32e7d2c9..ee8e901dfbc19 100644 --- a/docs/en/docs/advanced/websockets.md +++ b/docs/en/docs/advanced/websockets.md @@ -38,19 +38,15 @@ In production you would have one of the options above. But it's the simplest way to focus on the server-side of WebSockets and have a working example: -```Python hl_lines="2 6-38 41-43" -{!../../docs_src/websockets/tutorial001.py!} -``` +{* ../../docs_src/websockets/tutorial001.py hl[2,6:38,41:43] *} ## Create a `websocket` In your **FastAPI** application, create a `websocket`: -```Python hl_lines="1 46-47" -{!../../docs_src/websockets/tutorial001.py!} -``` +{* ../../docs_src/websockets/tutorial001.py hl[1,46:47] *} -/// note | "Technical Details" +/// note | Technical Details You could also use `from starlette.websockets import WebSocket`. @@ -62,9 +58,7 @@ You could also use `from starlette.websockets import WebSocket`. In your WebSocket route you can `await` for messages and send messages. -```Python hl_lines="48-52" -{!../../docs_src/websockets/tutorial001.py!} -``` +{* ../../docs_src/websockets/tutorial001.py hl[48:52] *} You can receive and send binary, text, and JSON data. @@ -115,57 +109,7 @@ In WebSocket endpoints you can import from `fastapi` and use: They work the same way as for other FastAPI endpoints/*path operations*: -//// tab | Python 3.10+ - -```Python hl_lines="68-69 82" -{!> ../../docs_src/websockets/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="68-69 82" -{!> ../../docs_src/websockets/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="69-70 83" -{!> ../../docs_src/websockets/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="66-67 79" -{!> ../../docs_src/websockets/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="68-69 81" -{!> ../../docs_src/websockets/tutorial002.py!} -``` - -//// +{* ../../docs_src/websockets/tutorial002_an_py310.py hl[68:69,82] *} /// info @@ -210,21 +154,7 @@ With that you can connect the WebSocket and then send and receive messages: When a WebSocket connection is closed, the `await websocket.receive_text()` will raise a `WebSocketDisconnect` exception, which you can then catch and handle like in this example. -//// tab | Python 3.9+ - -```Python hl_lines="79-81" -{!> ../../docs_src/websockets/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="81-83" -{!> ../../docs_src/websockets/tutorial003.py!} -``` - -//// +{* ../../docs_src/websockets/tutorial003_py39.py hl[79:81] *} To try it out: diff --git a/docs/en/docs/advanced/wsgi.md b/docs/en/docs/advanced/wsgi.md index 3974d491c3a44..296eb136475df 100644 --- a/docs/en/docs/advanced/wsgi.md +++ b/docs/en/docs/advanced/wsgi.md @@ -12,9 +12,7 @@ Then wrap the WSGI (e.g. Flask) app with the middleware. And then mount that under a path. -```Python hl_lines="2-3 23" -{!../../docs_src/wsgi/tutorial001.py!} -``` +{* ../../docs_src/wsgi/tutorial001.py hl[2:3,3] *} ## Check it diff --git a/docs/en/docs/alternatives.md b/docs/en/docs/alternatives.md index f596232d3fa35..326f0dbe1a718 100644 --- a/docs/en/docs/alternatives.md +++ b/docs/en/docs/alternatives.md @@ -36,7 +36,7 @@ Django REST Framework was created by Tom Christie. The same creator of Starlette /// -/// check | "Inspired **FastAPI** to" +/// check | Inspired **FastAPI** to Have an automatic API documentation web user interface. @@ -56,7 +56,7 @@ This decoupling of parts, and being a "microframework" that could be extended to Given the simplicity of Flask, it seemed like a good match for building APIs. The next thing to find was a "Django REST Framework" for Flask. -/// check | "Inspired **FastAPI** to" +/// check | Inspired **FastAPI** to Be a micro-framework. Making it easy to mix and match the tools and parts needed. @@ -98,7 +98,7 @@ def read_url(): See the similarities in `requests.get(...)` and `@app.get(...)`. -/// check | "Inspired **FastAPI** to" +/// check | Inspired **FastAPI** to * Have a simple and intuitive API. * Use HTTP method names (operations) directly, in a straightforward and intuitive way. @@ -118,7 +118,7 @@ At some point, Swagger was given to the Linux Foundation, to be renamed OpenAPI. That's why when talking about version 2.0 it's common to say "Swagger", and for version 3+ "OpenAPI". -/// check | "Inspired **FastAPI** to" +/// check | Inspired **FastAPI** to Adopt and use an open standard for API specifications, instead of a custom schema. @@ -147,7 +147,7 @@ These features are what Marshmallow was built to provide. It is a great library, But it was created before there existed Python type hints. So, to define every schema you need to use specific utils and classes provided by Marshmallow. -/// check | "Inspired **FastAPI** to" +/// check | Inspired **FastAPI** to Use code to define "schemas" that provide data types and validation, automatically. @@ -169,7 +169,7 @@ Webargs was created by the same Marshmallow developers. /// -/// check | "Inspired **FastAPI** to" +/// check | Inspired **FastAPI** to Have automatic validation of incoming request data. @@ -199,7 +199,7 @@ APISpec was created by the same Marshmallow developers. /// -/// check | "Inspired **FastAPI** to" +/// check | Inspired **FastAPI** to Support the open standard for APIs, OpenAPI. @@ -231,7 +231,7 @@ Flask-apispec was created by the same Marshmallow developers. /// -/// check | "Inspired **FastAPI** to" +/// check | Inspired **FastAPI** to Generate the OpenAPI schema automatically, from the same code that defines serialization and validation. @@ -251,7 +251,7 @@ But as TypeScript data is not preserved after compilation to JavaScript, it cann It can't handle nested models very well. So, if the JSON body in the request is a JSON object that has inner fields that in turn are nested JSON objects, it cannot be properly documented and validated. -/// check | "Inspired **FastAPI** to" +/// check | Inspired **FastAPI** to Use Python types to have great editor support. @@ -263,7 +263,7 @@ Have a powerful dependency injection system. Find a way to minimize code repetit It was one of the first extremely fast Python frameworks based on `asyncio`. It was made to be very similar to Flask. -/// note | "Technical Details" +/// note | Technical Details It used `uvloop` instead of the default Python `asyncio` loop. That's what made it so fast. @@ -271,7 +271,7 @@ It clearly inspired Uvicorn and Starlette, that are currently faster than Sanic /// -/// check | "Inspired **FastAPI** to" +/// check | Inspired **FastAPI** to Find a way to have a crazy performance. @@ -287,7 +287,7 @@ It is designed to have functions that receive two parameters, one "request" and So, data validation, serialization, and documentation, have to be done in code, not automatically. Or they have to be implemented as a framework on top of Falcon, like Hug. This same distinction happens in other frameworks that are inspired by Falcon's design, of having one request object and one response object as parameters. -/// check | "Inspired **FastAPI** to" +/// check | Inspired **FastAPI** to Find ways to get great performance. @@ -313,7 +313,7 @@ The dependency injection system requires pre-registration of the dependencies an Routes are declared in a single place, using functions declared in other places (instead of using decorators that can be placed right on top of the function that handles the endpoint). This is closer to how Django does it than to how Flask (and Starlette) does it. It separates in the code things that are relatively tightly coupled. -/// check | "Inspired **FastAPI** to" +/// check | Inspired **FastAPI** to Define extra validations for data types using the "default" value of model attributes. This improves editor support, and it was not available in Pydantic before. @@ -341,7 +341,7 @@ Hug was created by Timothy Crosley, the same creator of Platform.sh * Porter * Coherence +* Render diff --git a/docs/en/docs/how-to/conditional-openapi.md b/docs/en/docs/how-to/conditional-openapi.md index 6cd0385a2a2fe..bd6cad9a89ca8 100644 --- a/docs/en/docs/how-to/conditional-openapi.md +++ b/docs/en/docs/how-to/conditional-openapi.md @@ -29,9 +29,7 @@ You can easily use the same Pydantic settings to configure your generated OpenAP For example: -```Python hl_lines="6 11" -{!../../docs_src/conditional_openapi/tutorial001.py!} -``` +{* ../../docs_src/conditional_openapi/tutorial001.py hl[6,11] *} Here we declare the setting `openapi_url` with the same default of `"/openapi.json"`. diff --git a/docs/en/docs/how-to/custom-docs-ui-assets.md b/docs/en/docs/how-to/custom-docs-ui-assets.md index 16c873d1152a5..f717c98faafc0 100644 --- a/docs/en/docs/how-to/custom-docs-ui-assets.md +++ b/docs/en/docs/how-to/custom-docs-ui-assets.md @@ -18,9 +18,7 @@ The first step is to disable the automatic docs, as by default, those use the de To disable them, set their URLs to `None` when creating your `FastAPI` app: -```Python hl_lines="8" -{!../../docs_src/custom_docs_ui/tutorial001.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial001.py hl[8] *} ### Include the custom docs @@ -36,9 +34,7 @@ You can reuse FastAPI's internal functions to create the HTML pages for the docs And similarly for ReDoc... -```Python hl_lines="2-6 11-19 22-24 27-33" -{!../../docs_src/custom_docs_ui/tutorial001.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial001.py hl[2:6,11:19,22:24,27:33] *} /// tip @@ -54,9 +50,7 @@ Swagger UI will handle it behind the scenes for you, but it needs this "redirect Now, to be able to test that everything works, create a *path operation*: -```Python hl_lines="36-38" -{!../../docs_src/custom_docs_ui/tutorial001.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial001.py hl[36:38] *} ### Test it @@ -124,9 +118,7 @@ After that, your file structure could look like: * Import `StaticFiles`. * "Mount" a `StaticFiles()` instance in a specific path. -```Python hl_lines="7 11" -{!../../docs_src/custom_docs_ui/tutorial002.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[7,11] *} ### Test the static files @@ -158,9 +150,7 @@ The same as when using a custom CDN, the first step is to disable the automatic To disable them, set their URLs to `None` when creating your `FastAPI` app: -```Python hl_lines="9" -{!../../docs_src/custom_docs_ui/tutorial002.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[9] *} ### Include the custom docs for static files @@ -176,9 +166,7 @@ Again, you can reuse FastAPI's internal functions to create the HTML pages for t And similarly for ReDoc... -```Python hl_lines="2-6 14-22 25-27 30-36" -{!../../docs_src/custom_docs_ui/tutorial002.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[2:6,14:22,25:27,30:36] *} /// tip @@ -194,9 +182,7 @@ Swagger UI will handle it behind the scenes for you, but it needs this "redirect Now, to be able to test that everything works, create a *path operation*: -```Python hl_lines="39-41" -{!../../docs_src/custom_docs_ui/tutorial002.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[39:41] *} ### Test Static Files UI diff --git a/docs/en/docs/how-to/custom-request-and-route.md b/docs/en/docs/how-to/custom-request-and-route.md index a62ebf1d57067..9b4160d758c9d 100644 --- a/docs/en/docs/how-to/custom-request-and-route.md +++ b/docs/en/docs/how-to/custom-request-and-route.md @@ -42,9 +42,7 @@ If there's no `gzip` in the header, it will not try to decompress the body. That way, the same route class can handle gzip compressed or uncompressed requests. -```Python hl_lines="8-15" -{!../../docs_src/custom_request_and_route/tutorial001.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial001.py hl[8:15] *} ### Create a custom `GzipRoute` class @@ -56,11 +54,9 @@ This method returns a function. And that function is what will receive a request Here we use it to create a `GzipRequest` from the original request. -```Python hl_lines="18-26" -{!../../docs_src/custom_request_and_route/tutorial001.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial001.py hl[18:26] *} -/// note | "Technical Details" +/// note | Technical Details A `Request` has a `request.scope` attribute, that's just a Python `dict` containing the metadata related to the request. @@ -96,26 +92,18 @@ We can also use this same approach to access the request body in an exception ha All we need to do is handle the request inside a `try`/`except` block: -```Python hl_lines="13 15" -{!../../docs_src/custom_request_and_route/tutorial002.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial002.py hl[13,15] *} If an exception occurs, the`Request` instance will still be in scope, so we can read and make use of the request body when handling the error: -```Python hl_lines="16-18" -{!../../docs_src/custom_request_and_route/tutorial002.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial002.py hl[16:18] *} ## Custom `APIRoute` class in a router You can also set the `route_class` parameter of an `APIRouter`: -```Python hl_lines="26" -{!../../docs_src/custom_request_and_route/tutorial003.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial003.py hl[26] *} In this example, the *path operations* under the `router` will use the custom `TimedRoute` class, and will have an extra `X-Response-Time` header in the response with the time it took to generate the response: -```Python hl_lines="13-20" -{!../../docs_src/custom_request_and_route/tutorial003.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial003.py hl[13:20] *} diff --git a/docs/en/docs/how-to/extending-openapi.md b/docs/en/docs/how-to/extending-openapi.md index 8c77907255cd2..26c742c203cec 100644 --- a/docs/en/docs/how-to/extending-openapi.md +++ b/docs/en/docs/how-to/extending-openapi.md @@ -45,23 +45,18 @@ First, write all your **FastAPI** application as normally: {* ../../docs_src/extending_openapi/tutorial001.py hl[1,4,7:9] *} - ### Generate the OpenAPI schema Then, use the same utility function to generate the OpenAPI schema, inside a `custom_openapi()` function: - - {* ../../docs_src/extending_openapi/tutorial001.py hl[2,15:21] *} - ### Modify the OpenAPI schema Now you can add the ReDoc extension, adding a custom `x-logo` to the `info` "object" in the OpenAPI schema: {* ../../docs_src/extending_openapi/tutorial001.py hl[22:24] *} - ### Cache the OpenAPI schema You can use the property `.openapi_schema` as a "cache", to store your generated schema. @@ -70,19 +65,14 @@ That way, your application won't have to generate the schema every time a user o It will be generated only once, and then the same cached schema will be used for the next requests. - {* ../../docs_src/extending_openapi/tutorial001.py hl[13:14,25:26] *} - ### Override the method Now you can replace the `.openapi()` method with your new function. - - {* ../../docs_src/extending_openapi/tutorial001.py hl[29] *} - ### Check it Once you go to http://127.0.0.1:8000/redoc you will see that you are using your custom logo (in this example, **FastAPI**'s logo): diff --git a/docs/en/docs/how-to/graphql.md b/docs/en/docs/how-to/graphql.md index 5d8f879d174ac..a6219e481d650 100644 --- a/docs/en/docs/how-to/graphql.md +++ b/docs/en/docs/how-to/graphql.md @@ -35,10 +35,8 @@ Depending on your use case, you might prefer to use a different library, but if Here's a small preview of how you could integrate Strawberry with FastAPI: - {* ../../docs_src/graphql/tutorial001.py hl[3,22,25:26] *} - You can learn more about Strawberry in the Strawberry documentation. And also the docs about Strawberry with FastAPI. diff --git a/docs/en/docs/img/sponsors/render-banner.svg b/docs/en/docs/img/sponsors/render-banner.svg new file mode 100644 index 0000000000000..b8b1ed2e9b6f3 --- /dev/null +++ b/docs/en/docs/img/sponsors/render-banner.svg @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/en/docs/img/sponsors/render.svg b/docs/en/docs/img/sponsors/render.svg new file mode 100644 index 0000000000000..4a830482da88d --- /dev/null +++ b/docs/en/docs/img/sponsors/render.svg @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/en/docs/management-tasks.md b/docs/en/docs/management-tasks.md index 7e7aa3bafc677..05cd5d27d0bec 100644 --- a/docs/en/docs/management-tasks.md +++ b/docs/en/docs/management-tasks.md @@ -171,7 +171,7 @@ Esto es un consejo. Those don't have to be translated, but if they are, they need to be written as: ``` -/// tip | "consejo" +/// tip | consejo Esto es un consejo. @@ -181,7 +181,7 @@ Esto es un consejo. Which looks like: -/// tip | "consejo" +/// tip | consejo Esto es un consejo. diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index ea6896f2293ce..a786985d2d2c0 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,177 @@ hide: ## Latest Changes +## 0.115.6 + +### Fixes + +* 🐛 Preserve traceback when exception is raised in sync dependency with `yield`. PR [#5823](https://github.com/fastapi/fastapi/pull/5823) by [@sombek](https://github.com/sombek). + +### Refactors + +* ♻️ Update tests and internals for compatibility with Pydantic >=2.10. PR [#12971](https://github.com/fastapi/fastapi/pull/12971) by [@tamird](https://github.com/tamird). + +### Docs + +* 📝 Update includes format in docs with an automated script. PR [#12950](https://github.com/fastapi/fastapi/pull/12950) by [@tiangolo](https://github.com/tiangolo). +* 📝 Update includes for `docs/de/docs/advanced/using-request-directly.md`. PR [#12685](https://github.com/fastapi/fastapi/pull/12685) by [@alissadb](https://github.com/alissadb). +* 📝 Update includes for `docs/de/docs/how-to/conditional-openapi.md`. PR [#12689](https://github.com/fastapi/fastapi/pull/12689) by [@alissadb](https://github.com/alissadb). + +### Translations + +* 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/async.md`. PR [#12990](https://github.com/fastapi/fastapi/pull/12990) by [@ILoveSorasakiHina](https://github.com/ILoveSorasakiHina). +* 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/tutorial/query-param-models.md`. PR [#12932](https://github.com/fastapi/fastapi/pull/12932) by [@Vincy1230](https://github.com/Vincy1230). +* 🌐 Add Korean translation for `docs/ko/docs/advanced/testing-dependencies.md`. PR [#12992](https://github.com/fastapi/fastapi/pull/12992) by [@Limsunoh](https://github.com/Limsunoh). +* 🌐 Add Korean translation for `docs/ko/docs/advanced/websockets.md`. PR [#12991](https://github.com/fastapi/fastapi/pull/12991) by [@kwang1215](https://github.com/kwang1215). +* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/response-model.md`. PR [#12933](https://github.com/fastapi/fastapi/pull/12933) by [@AndreBBM](https://github.com/AndreBBM). +* 🌐 Add Korean translation for `docs/ko/docs/advanced/middlewares.md`. PR [#12753](https://github.com/fastapi/fastapi/pull/12753) by [@nahyunkeem](https://github.com/nahyunkeem). +* 🌐 Add Korean translation for `docs/ko/docs/advanced/openapi-webhooks.md`. PR [#12752](https://github.com/fastapi/fastapi/pull/12752) by [@saeye](https://github.com/saeye). +* 🌐 Add Chinese translation for `docs/zh/docs/tutorial/query-param-models.md`. PR [#12931](https://github.com/fastapi/fastapi/pull/12931) by [@Vincy1230](https://github.com/Vincy1230). +* 🌐 Add Russian translation for `docs/ru/docs/tutorial/query-param-models.md`. PR [#12445](https://github.com/fastapi/fastapi/pull/12445) by [@gitgernit](https://github.com/gitgernit). +* 🌐 Add Korean translation for `docs/ko/docs/tutorial/query-param-models.md`. PR [#12940](https://github.com/fastapi/fastapi/pull/12940) by [@jts8257](https://github.com/jts8257). +* 🔥 Remove obsolete tutorial translation to Chinese for `docs/zh/docs/tutorial/sql-databases.md`, it references files that are no longer on the repo. PR [#12949](https://github.com/fastapi/fastapi/pull/12949) by [@tiangolo](https://github.com/tiangolo). + +### Internal + +* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12954](https://github.com/fastapi/fastapi/pull/12954) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). + +## 0.115.5 + +### Refactors + +* ♻️ Update internal checks to support Pydantic 2.10. PR [#12914](https://github.com/fastapi/fastapi/pull/12914) by [@tiangolo](https://github.com/tiangolo). + +### Docs + +* 📝 Update includes for `docs/en/docs/tutorial/body.md`. PR [#12757](https://github.com/fastapi/fastapi/pull/12757) by [@gsheni](https://github.com/gsheni). +* 📝 Update includes in `docs/en/docs/advanced/testing-dependencies.md`. PR [#12647](https://github.com/fastapi/fastapi/pull/12647) by [@AyushSinghal1794](https://github.com/AyushSinghal1794). +* 📝 Update includes for `docs/en/docs/tutorial/metadata.md`. PR [#12773](https://github.com/fastapi/fastapi/pull/12773) by [@Nimitha-jagadeesha](https://github.com/Nimitha-jagadeesha). +* 📝 Update `docs/en/docs/tutorial/dependencies/dependencies-with-yield.md`. PR [#12045](https://github.com/fastapi/fastapi/pull/12045) by [@xuvjso](https://github.com/xuvjso). +* 📝 Update includes for `docs/en/docs/tutorial/dependencies/global-dependencies.md`. PR [#12653](https://github.com/fastapi/fastapi/pull/12653) by [@vishnuvskvkl](https://github.com/vishnuvskvkl). +* 📝 Update includes for `docs/en/docs/tutorial/body-updates.md`. PR [#12712](https://github.com/fastapi/fastapi/pull/12712) by [@davioc](https://github.com/davioc). +* 📝 Remove mention of Celery in the project generators. PR [#12742](https://github.com/fastapi/fastapi/pull/12742) by [@david-caro](https://github.com/david-caro). +* 📝 Update includes in `docs/en/docs/tutorial/header-param-models.md`. PR [#12814](https://github.com/fastapi/fastapi/pull/12814) by [@zhaohan-dong](https://github.com/zhaohan-dong). +* 📝 Update `contributing.md` docs, include note to not translate this page. PR [#12841](https://github.com/fastapi/fastapi/pull/12841) by [@tiangolo](https://github.com/tiangolo). +* 📝 Update includes in `docs/en/docs/tutorial/request-forms.md`. PR [#12648](https://github.com/fastapi/fastapi/pull/12648) by [@vishnuvskvkl](https://github.com/vishnuvskvkl). +* 📝 Update includes in `docs/en/docs/tutorial/request-form-models.md`. PR [#12649](https://github.com/fastapi/fastapi/pull/12649) by [@vishnuvskvkl](https://github.com/vishnuvskvkl). +* 📝 Update includes in `docs/en/docs/tutorial/security/oauth2-jwt.md`. PR [#12650](https://github.com/fastapi/fastapi/pull/12650) by [@OCE1960](https://github.com/OCE1960). +* 📝 Update includes in `docs/vi/docs/tutorial/first-steps.md`. PR [#12754](https://github.com/fastapi/fastapi/pull/12754) by [@MxPy](https://github.com/MxPy). +* 📝 Update includes for `docs/pt/docs/advanced/wsgi.md`. PR [#12769](https://github.com/fastapi/fastapi/pull/12769) by [@Nimitha-jagadeesha](https://github.com/Nimitha-jagadeesha). +* 📝 Update includes for `docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md`. PR [#12815](https://github.com/fastapi/fastapi/pull/12815) by [@handabaldeep](https://github.com/handabaldeep). +* 📝 Update includes for `docs/en/docs/tutorial/dependencies/classes-as-dependencies.md`. PR [#12813](https://github.com/fastapi/fastapi/pull/12813) by [@handabaldeep](https://github.com/handabaldeep). +* ✏️ Fix error in `docs/en/docs/tutorial/middleware.md`. PR [#12819](https://github.com/fastapi/fastapi/pull/12819) by [@alejsdev](https://github.com/alejsdev). +* 📝 Update includes for `docs/en/docs/tutorial/security/get-current-user.md`. PR [#12645](https://github.com/fastapi/fastapi/pull/12645) by [@OCE1960](https://github.com/OCE1960). +* 📝 Update includes for `docs/en/docs/tutorial/security/first-steps.md`. PR [#12643](https://github.com/fastapi/fastapi/pull/12643) by [@OCE1960](https://github.com/OCE1960). +* 📝 Update includes in `docs/de/docs/advanced/additional-responses.md`. PR [#12821](https://github.com/fastapi/fastapi/pull/12821) by [@zhaohan-dong](https://github.com/zhaohan-dong). +* 📝 Update includes in `docs/en/docs/advanced/generate-clients.md`. PR [#12642](https://github.com/fastapi/fastapi/pull/12642) by [@AyushSinghal1794](https://github.com/AyushSinghal1794). +* 📝 Fix admonition double quotes with new syntax. PR [#12835](https://github.com/fastapi/fastapi/pull/12835) by [@tiangolo](https://github.com/tiangolo). +* 📝 Update includes in `docs/zh/docs/advanced/additional-responses.md`. PR [#12828](https://github.com/fastapi/fastapi/pull/12828) by [@zhaohan-dong](https://github.com/zhaohan-dong). +* 📝 Update includes in `docs/en/docs/tutorial/path-params-numeric-validations.md`. PR [#12825](https://github.com/fastapi/fastapi/pull/12825) by [@zhaohan-dong](https://github.com/zhaohan-dong). +* 📝 Update includes for `docs/en/docs/advanced/testing-websockets.md`. PR [#12761](https://github.com/fastapi/fastapi/pull/12761) by [@hamidrasti](https://github.com/hamidrasti). +* 📝 Update includes for `docs/en/docs/advanced/using-request-directly.md`. PR [#12760](https://github.com/fastapi/fastapi/pull/12760) by [@hamidrasti](https://github.com/hamidrasti). +* 📝 Update includes for `docs/advanced/wsgi.md`. PR [#12758](https://github.com/fastapi/fastapi/pull/12758) by [@hamidrasti](https://github.com/hamidrasti). +* 📝 Update includes in `docs/de/docs/tutorial/middleware.md`. PR [#12729](https://github.com/fastapi/fastapi/pull/12729) by [@paintdog](https://github.com/paintdog). +* 📝 Update includes for `docs/en/docs/tutorial/schema-extra-example.md`. PR [#12822](https://github.com/fastapi/fastapi/pull/12822) by [@tiangolo](https://github.com/tiangolo). +* 📝 Update includes in `docs/fr/docs/advanced/additional-responses.md`. PR [#12634](https://github.com/fastapi/fastapi/pull/12634) by [@fegmorte](https://github.com/fegmorte). +* 📝 Update includes in `docs/fr/docs/advanced/path-operation-advanced-configuration.md`. PR [#12633](https://github.com/fastapi/fastapi/pull/12633) by [@kantandane](https://github.com/kantandane). +* 📝 Update includes in `docs/fr/docs/advanced/response-directly.md`. PR [#12632](https://github.com/fastapi/fastapi/pull/12632) by [@kantandane](https://github.com/kantandane). +* 📝 Update includes for `docs/en/docs/tutorial/header-params.md`. PR [#12640](https://github.com/fastapi/fastapi/pull/12640) by [@vishnuvskvkl](https://github.com/vishnuvskvkl). +* 📝 Update includes in `docs/en/docs/tutorial/cookie-param-models.md`. PR [#12639](https://github.com/fastapi/fastapi/pull/12639) by [@vishnuvskvkl](https://github.com/vishnuvskvkl). +* 📝 Update includes for `docs/en/docs/tutorial/extra-models.md`. PR [#12638](https://github.com/fastapi/fastapi/pull/12638) by [@vishnuvskvkl](https://github.com/vishnuvskvkl). +* 📝 Update includes for `docs/en/docs/tutorial/cors.md`. PR [#12637](https://github.com/fastapi/fastapi/pull/12637) by [@vishnuvskvkl](https://github.com/vishnuvskvkl). +* 📝 Update includes for `docs/en/docs/tutorial/dependencies/sub-dependencies.md`. PR [#12810](https://github.com/fastapi/fastapi/pull/12810) by [@handabaldeep](https://github.com/handabaldeep). +* 📝 Update includes in `docs/en/docs/tutorial/body-nested-models.md`. PR [#12812](https://github.com/fastapi/fastapi/pull/12812) by [@zhaohan-dong](https://github.com/zhaohan-dong). +* 📝 Update includes in `docs/en/docs/tutorial/path-operation-configuration.md`. PR [#12809](https://github.com/fastapi/fastapi/pull/12809) by [@AlexWendland](https://github.com/AlexWendland). +* 📝 Update includes in `docs/en/docs/tutorial/request-files.md`. PR [#12818](https://github.com/fastapi/fastapi/pull/12818) by [@zhaohan-dong](https://github.com/zhaohan-dong). +* 📝 Update includes for `docs/en/docs/tutorial/query-param-models.md`. PR [#12817](https://github.com/fastapi/fastapi/pull/12817) by [@handabaldeep](https://github.com/handabaldeep). +* 📝 Update includes in `docs/en/docs/tutorial/path-params.md`. PR [#12811](https://github.com/fastapi/fastapi/pull/12811) by [@AlexWendland](https://github.com/AlexWendland). +* 📝 Update includes in `docs/en/docs/tutorial/response-model.md`. PR [#12621](https://github.com/fastapi/fastapi/pull/12621) by [@kantandane](https://github.com/kantandane). +* 📝 Update includes in `docs/en/docs/advanced/websockets.md`. PR [#12606](https://github.com/fastapi/fastapi/pull/12606) by [@vishnuvskvkl](https://github.com/vishnuvskvkl). +* 📝 Updates include for `docs/en/docs/tutorial/cookie-params.md`. PR [#12808](https://github.com/fastapi/fastapi/pull/12808) by [@handabaldeep](https://github.com/handabaldeep). +* 📝 Update includes in `docs/en/docs/tutorial/middleware.md`. PR [#12807](https://github.com/fastapi/fastapi/pull/12807) by [@AlexWendland](https://github.com/AlexWendland). +* 📝 Update includes in `docs/en/docs/advanced/sub-applications.md`. PR [#12806](https://github.com/fastapi/fastapi/pull/12806) by [@zhaohan-dong](https://github.com/zhaohan-dong). +* 📝 Update includes in `docs/en/docs/advanced/response-headers.md`. PR [#12805](https://github.com/fastapi/fastapi/pull/12805) by [@zhaohan-dong](https://github.com/zhaohan-dong). +* 📝 Update includes in `docs/fr/docs/tutorial/first-steps.md`. PR [#12594](https://github.com/fastapi/fastapi/pull/12594) by [@kantandane](https://github.com/kantandane). +* 📝 Update includes in `docs/en/docs/advanced/response-cookies.md`. PR [#12804](https://github.com/fastapi/fastapi/pull/12804) by [@zhaohan-dong](https://github.com/zhaohan-dong). +* 📝 Update includes in `docs/en/docs/advanced/path-operation-advanced-configuration.md`. PR [#12802](https://github.com/fastapi/fastapi/pull/12802) by [@zhaohan-dong](https://github.com/zhaohan-dong). +* 📝 Update includes for `docs/en/docs/advanced/response-directly.md`. PR [#12803](https://github.com/fastapi/fastapi/pull/12803) by [@handabaldeep](https://github.com/handabaldeep). +* 📝 Update includes in `docs/zh/docs/tutorial/background-tasks.md`. PR [#12798](https://github.com/fastapi/fastapi/pull/12798) by [@zhaohan-dong](https://github.com/zhaohan-dong). +* 📝 Update includes for `docs/de/docs/tutorial/body-multiple-params.md`. PR [#12699](https://github.com/fastapi/fastapi/pull/12699) by [@alissadb](https://github.com/alissadb). +* 📝 Update includes in `docs/em/docs/tutorial/body-updates.md`. PR [#12799](https://github.com/fastapi/fastapi/pull/12799) by [@AlexWendland](https://github.com/AlexWendland). +* 📝 Update includes `docs/en/docs/advanced/response-change-status-code.md`. PR [#12801](https://github.com/fastapi/fastapi/pull/12801) by [@handabaldeep](https://github.com/handabaldeep). +* 📝 Update includes `docs/en/docs/advanced/openapi-callbacks.md`. PR [#12800](https://github.com/fastapi/fastapi/pull/12800) by [@handabaldeep](https://github.com/handabaldeep). +* 📝 Update includes in `docs/fr/docs/tutorial/body-multiple-params.md`. PR [#12598](https://github.com/fastapi/fastapi/pull/12598) by [@kantandane](https://github.com/kantandane). +* 📝 Update includes in `docs/en/docs/tutorial/body-multiple-params.md`. PR [#12593](https://github.com/fastapi/fastapi/pull/12593) by [@Tashanam-Shahbaz](https://github.com/Tashanam-Shahbaz). +* 📝 Update includes in `docs/pt/docs/tutorial/background-tasks.md`. PR [#12736](https://github.com/fastapi/fastapi/pull/12736) by [@bhunao](https://github.com/bhunao). +* 📝 Update includes for `docs/en/docs/advanced/custom-response.md`. PR [#12797](https://github.com/fastapi/fastapi/pull/12797) by [@handabaldeep](https://github.com/handabaldeep). +* 📝 Update includes for `docs/pt/docs/python-types.md`. PR [#12671](https://github.com/fastapi/fastapi/pull/12671) by [@ceb10n](https://github.com/ceb10n). +* 📝 Update includes for `docs/de/docs/python-types.md`. PR [#12660](https://github.com/fastapi/fastapi/pull/12660) by [@alissadb](https://github.com/alissadb). +* 📝 Update includes for `docs/de/docs/advanced/dataclasses.md`. PR [#12658](https://github.com/fastapi/fastapi/pull/12658) by [@alissadb](https://github.com/alissadb). +* 📝 Update includes in `docs/fr/docs/tutorial/path-params.md`. PR [#12592](https://github.com/fastapi/fastapi/pull/12592) by [@kantandane](https://github.com/kantandane). +* 📝 Update includes for `docs/de/docs/how-to/configure-swagger-ui.md`. PR [#12690](https://github.com/fastapi/fastapi/pull/12690) by [@alissadb](https://github.com/alissadb). +* 📝 Update includes in `docs/en/docs/advanced/security/oauth2-scopes.md`. PR [#12572](https://github.com/fastapi/fastapi/pull/12572) by [@krishnamadhavan](https://github.com/krishnamadhavan). +* 📝 Update includes for `docs/en/docs/how-to/conditional-openapi.md`. PR [#12624](https://github.com/fastapi/fastapi/pull/12624) by [@rabinlamadong](https://github.com/rabinlamadong). +* 📝 Update includes in `docs/en/docs/tutorial/dependencies/index.md`. PR [#12615](https://github.com/fastapi/fastapi/pull/12615) by [@bharara](https://github.com/bharara). +* 📝 Update includes in `docs/en/docs/tutorial/response-status-code.md`. PR [#12620](https://github.com/fastapi/fastapi/pull/12620) by [@kantandane](https://github.com/kantandane). +* 📝 Update includes in `docs/en/docs/how-to/custom-docs-ui-assets.md`. PR [#12623](https://github.com/fastapi/fastapi/pull/12623) by [@rabinlamadong](https://github.com/rabinlamadong). +* 📝 Update includes in `docs/en/docs/advanced/openapi-webhooks.md`. PR [#12605](https://github.com/fastapi/fastapi/pull/12605) by [@salmantec](https://github.com/salmantec). +* 📝 Update includes in `docs/en/docs/advanced/events.md`. PR [#12604](https://github.com/fastapi/fastapi/pull/12604) by [@salmantec](https://github.com/salmantec). +* 📝 Update includes in `docs/en/docs/advanced/dataclasses.md`. PR [#12603](https://github.com/fastapi/fastapi/pull/12603) by [@salmantec](https://github.com/salmantec). +* 📝 Update includes in `docs/es/docs/tutorial/cookie-params.md`. PR [#12602](https://github.com/fastapi/fastapi/pull/12602) by [@antonyare93](https://github.com/antonyare93). +* 📝 Update includes in `docs/fr/docs/tutorial/path-params-numeric-validations.md`. PR [#12601](https://github.com/fastapi/fastapi/pull/12601) by [@kantandane](https://github.com/kantandane). +* 📝 Update includes in `docs/fr/docs/tutorial/background-tasks.md`. PR [#12600](https://github.com/fastapi/fastapi/pull/12600) by [@kantandane](https://github.com/kantandane). +* 📝 Update includes in `docs/en/docs/tutorial/encoder.md`. PR [#12597](https://github.com/fastapi/fastapi/pull/12597) by [@tonyjly](https://github.com/tonyjly). +* 📝 Update includes in `docs/en/docs/how-to/custom-docs-ui-assets.md`. PR [#12557](https://github.com/fastapi/fastapi/pull/12557) by [@philipokiokio](https://github.com/philipokiokio). +* 🎨 Adjust spacing. PR [#12635](https://github.com/fastapi/fastapi/pull/12635) by [@alejsdev](https://github.com/alejsdev). +* 📝 Update includes in `docs/en/docs/how-to/custom-request-and-route.md`. PR [#12560](https://github.com/fastapi/fastapi/pull/12560) by [@philipokiokio](https://github.com/philipokiokio). + +### Translations + +* 🌐 Add Korean translation for `docs/ko/docs/advanced/testing-websockets.md`. PR [#12739](https://github.com/fastapi/fastapi/pull/12739) by [@Limsunoh](https://github.com/Limsunoh). +* 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/environment-variables.md`. PR [#12785](https://github.com/fastapi/fastapi/pull/12785) by [@Vincy1230](https://github.com/Vincy1230). +* 🌐 Add Chinese translation for `docs/zh/docs/environment-variables.md`. PR [#12784](https://github.com/fastapi/fastapi/pull/12784) by [@Vincy1230](https://github.com/Vincy1230). +* 🌐 Add Korean translation for `ko/docs/advanced/response-headers.md`. PR [#12740](https://github.com/fastapi/fastapi/pull/12740) by [@kwang1215](https://github.com/kwang1215). +* 🌐 Add Chinese translation for `docs/zh/docs/virtual-environments.md`. PR [#12790](https://github.com/fastapi/fastapi/pull/12790) by [@Vincy1230](https://github.com/Vincy1230). +* 🌐 Add Korean translation for `/docs/ko/docs/environment-variables.md`. PR [#12526](https://github.com/fastapi/fastapi/pull/12526) by [@Tolerblanc](https://github.com/Tolerblanc). +* 🌐 Add Korean translation for `docs/ko/docs/history-design-future.md`. PR [#12646](https://github.com/fastapi/fastapi/pull/12646) by [@saeye](https://github.com/saeye). +* 🌐 Add Korean translation for `docs/ko/docs/advanced/advanced-dependencies.md`. PR [#12675](https://github.com/fastapi/fastapi/pull/12675) by [@kim-sangah](https://github.com/kim-sangah). +* 🌐 Add Korean translation for `docs/ko/docs/how-to/conditional-openapi.md`. PR [#12731](https://github.com/fastapi/fastapi/pull/12731) by [@sptcnl](https://github.com/sptcnl). +* 🌐 Add Korean translation for `docs/ko/docs/advanced/using_request_directly.md`. PR [#12738](https://github.com/fastapi/fastapi/pull/12738) by [@kwang1215](https://github.com/kwang1215). +* 🌐 Add Korean translation for `docs/ko/docs/advanced/testing-events.md`. PR [#12741](https://github.com/fastapi/fastapi/pull/12741) by [@9zimin9](https://github.com/9zimin9). +* 🌐 Add Korean translation for `docs/ko/docs/security/index.md`. PR [#12743](https://github.com/fastapi/fastapi/pull/12743) by [@kim-sangah](https://github.com/kim-sangah). +* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/path-operation-advanced-configuration.md`. PR [#12762](https://github.com/fastapi/fastapi/pull/12762) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). +* 🌐 Add Korean translation for `docs/ko/docs/advanced/wsgi.md`. PR [#12659](https://github.com/fastapi/fastapi/pull/12659) by [@Limsunoh](https://github.com/Limsunoh). +* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/websockets.md`. PR [#12703](https://github.com/fastapi/fastapi/pull/12703) by [@devfernandoa](https://github.com/devfernandoa). +* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/security/simple-oauth2.md`. PR [#12520](https://github.com/fastapi/fastapi/pull/12520) by [@LidiaDomingos](https://github.com/LidiaDomingos). +* 🌐 Add Korean translation for `docs/ko/docs/advanced/response-directly.md`. PR [#12674](https://github.com/fastapi/fastapi/pull/12674) by [@9zimin9](https://github.com/9zimin9). +* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/middleware.md`. PR [#12704](https://github.com/fastapi/fastapi/pull/12704) by [@devluisrodrigues](https://github.com/devluisrodrigues). +* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/openapi-callbacks.md`. PR [#12705](https://github.com/fastapi/fastapi/pull/12705) by [@devfernandoa](https://github.com/devfernandoa). +* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/request-files.md`. PR [#12706](https://github.com/fastapi/fastapi/pull/12706) by [@devluisrodrigues](https://github.com/devluisrodrigues). +* 🌐 Add Portuguese Translation for `docs/pt/docs/advanced/custom-response.md`. PR [#12631](https://github.com/fastapi/fastapi/pull/12631) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). +* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/metadata.md`. PR [#12538](https://github.com/fastapi/fastapi/pull/12538) by [@LinkolnR](https://github.com/LinkolnR). +* 🌐 Add Korean translation for `docs/ko/docs/tutorial/metadata.md`. PR [#12541](https://github.com/fastapi/fastapi/pull/12541) by [@kwang1215](https://github.com/kwang1215). +* 🌐 Add Korean Translation for `docs/ko/docs/advanced/response-cookies.md`. PR [#12546](https://github.com/fastapi/fastapi/pull/12546) by [@kim-sangah](https://github.com/kim-sangah). +* 🌐 Add Korean translation for `docs/ko/docs/fastapi-cli.md`. PR [#12515](https://github.com/fastapi/fastapi/pull/12515) by [@dhdld](https://github.com/dhdld). +* 🌐 Add Korean Translation for `docs/ko/docs/advanced/response-change-status-code.md`. PR [#12547](https://github.com/fastapi/fastapi/pull/12547) by [@9zimin9](https://github.com/9zimin9). + +### Internal + +* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12907](https://github.com/fastapi/fastapi/pull/12907) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). +* 🔨 Update docs preview script to show previous version and English version. PR [#12856](https://github.com/fastapi/fastapi/pull/12856) by [@tiangolo](https://github.com/tiangolo). +* ⬆ Bump tiangolo/latest-changes from 0.3.1 to 0.3.2. PR [#12794](https://github.com/fastapi/fastapi/pull/12794) by [@dependabot[bot]](https://github.com/apps/dependabot). +* ⬆ Bump pypa/gh-action-pypi-publish from 1.12.0 to 1.12.2. PR [#12788](https://github.com/fastapi/fastapi/pull/12788) by [@dependabot[bot]](https://github.com/apps/dependabot). +* ⬆ Bump pypa/gh-action-pypi-publish from 1.11.0 to 1.12.0. PR [#12781](https://github.com/fastapi/fastapi/pull/12781) by [@dependabot[bot]](https://github.com/apps/dependabot). +* ⬆ Bump cloudflare/wrangler-action from 3.11 to 3.12. PR [#12777](https://github.com/fastapi/fastapi/pull/12777) by [@dependabot[bot]](https://github.com/apps/dependabot). +* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12766](https://github.com/fastapi/fastapi/pull/12766) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). +* ⬆ Bump pypa/gh-action-pypi-publish from 1.10.3 to 1.11.0. PR [#12721](https://github.com/fastapi/fastapi/pull/12721) by [@dependabot[bot]](https://github.com/apps/dependabot). +* ⬆ Update pre-commit requirement from <4.0.0,>=2.17.0 to >=2.17.0,<5.0.0. PR [#12749](https://github.com/fastapi/fastapi/pull/12749) by [@dependabot[bot]](https://github.com/apps/dependabot). +* ⬆ Bump typer from 0.12.3 to 0.12.5. PR [#12748](https://github.com/fastapi/fastapi/pull/12748) by [@dependabot[bot]](https://github.com/apps/dependabot). +* ⬆ Update flask requirement from <3.0.0,>=1.1.2 to >=1.1.2,<4.0.0. PR [#12747](https://github.com/fastapi/fastapi/pull/12747) by [@dependabot[bot]](https://github.com/apps/dependabot). +* ⬆ Bump pillow from 10.4.0 to 11.0.0. PR [#12746](https://github.com/fastapi/fastapi/pull/12746) by [@dependabot[bot]](https://github.com/apps/dependabot). +* ⬆ Update pytest requirement from <8.0.0,>=7.1.3 to >=7.1.3,<9.0.0. PR [#12745](https://github.com/fastapi/fastapi/pull/12745) by [@dependabot[bot]](https://github.com/apps/dependabot). +* 🔧 Update sponsors: add Render. PR [#12733](https://github.com/fastapi/fastapi/pull/12733) by [@tiangolo](https://github.com/tiangolo). +* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12707](https://github.com/fastapi/fastapi/pull/12707) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). + ## 0.115.4 ### Refactors diff --git a/docs/en/docs/tutorial/background-tasks.md b/docs/en/docs/tutorial/background-tasks.md index 92427e36e81d5..34685fcc40416 100644 --- a/docs/en/docs/tutorial/background-tasks.md +++ b/docs/en/docs/tutorial/background-tasks.md @@ -79,8 +79,6 @@ If you need to perform heavy background computation and you don't necessarily ne They tend to require more complex configurations, a message/job queue manager, like RabbitMQ or Redis, but they allow you to run background tasks in multiple processes, and especially, in multiple servers. -To see an example, check the [Project Generators](../project-generation.md){.internal-link target=_blank}, they all include Celery already configured. - But if you need to access variables and objects from the same **FastAPI** app, or you need to perform small background tasks (like sending an email notification), you can simply just use `BackgroundTasks`. ## Recap diff --git a/docs/en/docs/tutorial/bigger-applications.md b/docs/en/docs/tutorial/bigger-applications.md index 4ec9b15bdb50c..605ced0d3c9fc 100644 --- a/docs/en/docs/tutorial/bigger-applications.md +++ b/docs/en/docs/tutorial/bigger-applications.md @@ -440,7 +440,7 @@ With `app.include_router()` we can add each `APIRouter` to the main `FastAPI` ap It will include all the routes from that router as part of it. -/// note | "Technical Details" +/// note | Technical Details It will actually internally create a *path operation* for each *path operation* that was declared in the `APIRouter`. @@ -503,7 +503,7 @@ Here we do it... just to show that we can 🤷: and it will work correctly, together with all the other *path operations* added with `app.include_router()`. -/// info | "Very Technical Details" +/// info | Very Technical Details **Note**: this is a very technical detail that you probably can **just skip**. diff --git a/docs/en/docs/tutorial/body-fields.md b/docs/en/docs/tutorial/body-fields.md index 7f7e34fcc17e2..3ce30cbf6119c 100644 --- a/docs/en/docs/tutorial/body-fields.md +++ b/docs/en/docs/tutorial/body-fields.md @@ -23,7 +23,7 @@ You can then use `Field` with model attributes: `Field` works the same way as `Query`, `Path` and `Body`, it has all the same parameters, etc. -/// note | "Technical Details" +/// note | Technical Details Actually, `Query`, `Path` and others you'll see next create objects of subclasses of a common `Param` class, which is itself a subclass of Pydantic's `FieldInfo` class. diff --git a/docs/en/docs/tutorial/body-multiple-params.md b/docs/en/docs/tutorial/body-multiple-params.md index eebbb3fe45c7b..9fced965260e3 100644 --- a/docs/en/docs/tutorial/body-multiple-params.md +++ b/docs/en/docs/tutorial/body-multiple-params.md @@ -8,57 +8,9 @@ First, of course, you can mix `Path`, `Query` and request body parameter declara And you can also declare body parameters as optional, by setting the default to `None`: -//// tab | Python 3.10+ +{* ../../docs_src/body_multiple_params/tutorial001_an_py310.py hl[18:20] *} -```Python hl_lines="18-20" -{!> ../../docs_src/body_multiple_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="18-20" -{!> ../../docs_src/body_multiple_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="19-21" -{!> ../../docs_src/body_multiple_params/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="17-19" -{!> ../../docs_src/body_multiple_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="19-21" -{!> ../../docs_src/body_multiple_params/tutorial001.py!} -``` - -//// +## Multiple body parameters /// note @@ -81,21 +33,8 @@ In the previous example, the *path operations* would expect a JSON body with the But you can also declare multiple body parameters, e.g. `item` and `user`: -//// tab | Python 3.10+ - -```Python hl_lines="20" -{!> ../../docs_src/body_multiple_params/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial002_py310.py hl[20] *} -//// tab | Python 3.8+ - -```Python hl_lines="22" -{!> ../../docs_src/body_multiple_params/tutorial002.py!} -``` - -//// In this case, **FastAPI** will notice that there is more than one body parameter in the function (there are two parameters that are Pydantic models). @@ -136,57 +75,8 @@ If you declare it as is, because it is a singular value, **FastAPI** will assume But you can instruct **FastAPI** to treat it as another body key using `Body`: -//// tab | Python 3.10+ - -```Python hl_lines="23" -{!> ../../docs_src/body_multiple_params/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="23" -{!> ../../docs_src/body_multiple_params/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24" -{!> ../../docs_src/body_multiple_params/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// +{* ../../docs_src/body_multiple_params/tutorial003_an_py310.py hl[23] *} -```Python hl_lines="20" -{!> ../../docs_src/body_multiple_params/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="22" -{!> ../../docs_src/body_multiple_params/tutorial003.py!} -``` - -//// In this case, **FastAPI** will expect a body like: @@ -226,57 +116,8 @@ q: str | None = None For example: -//// tab | Python 3.10+ - -```Python hl_lines="28" -{!> ../../docs_src/body_multiple_params/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="28" -{!> ../../docs_src/body_multiple_params/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="29" -{!> ../../docs_src/body_multiple_params/tutorial004_an.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[28] *} -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="26" -{!> ../../docs_src/body_multiple_params/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="28" -{!> ../../docs_src/body_multiple_params/tutorial004.py!} -``` - -//// /// info @@ -298,57 +139,8 @@ item: Item = Body(embed=True) as in: -//// tab | Python 3.10+ - -```Python hl_lines="17" -{!> ../../docs_src/body_multiple_params/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="17" -{!> ../../docs_src/body_multiple_params/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18" -{!> ../../docs_src/body_multiple_params/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="15" -{!> ../../docs_src/body_multiple_params/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="17" -{!> ../../docs_src/body_multiple_params/tutorial005.py!} -``` +{* ../../docs_src/body_multiple_params/tutorial005_an_py310.py hl[17] *} -//// In this case **FastAPI** will expect a body like: diff --git a/docs/en/docs/tutorial/body-nested-models.md b/docs/en/docs/tutorial/body-nested-models.md index 38f3eb136825e..b473062de6633 100644 --- a/docs/en/docs/tutorial/body-nested-models.md +++ b/docs/en/docs/tutorial/body-nested-models.md @@ -6,21 +6,7 @@ With **FastAPI**, you can define, validate, document, and use arbitrarily deeply You can define an attribute to be a subtype. For example, a Python `list`: -//// tab | Python 3.10+ - -```Python hl_lines="12" -{!> ../../docs_src/body_nested_models/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial001_py310.py hl[12] *} This will make `tags` be a list, although it doesn't declare the type of the elements of the list. @@ -34,9 +20,7 @@ In Python 3.9 and above you can use the standard `list` to declare these type an But in Python versions before 3.9 (3.6 and above), you first need to import `List` from standard Python's `typing` module: -```Python hl_lines="1" -{!> ../../docs_src/body_nested_models/tutorial002.py!} -``` +{* ../../docs_src/body_nested_models/tutorial002.py hl[1] *} ### Declare a `list` with a type parameter @@ -65,29 +49,7 @@ Use that same standard syntax for model attributes with internal types. So, in our example, we can make `tags` be specifically a "list of strings": -//// tab | Python 3.10+ - -```Python hl_lines="12" -{!> ../../docs_src/body_nested_models/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial002_py310.py hl[12] *} ## Set types @@ -97,29 +59,7 @@ And Python has a special data type for sets of unique items, the `set`. Then we can declare `tags` as a set of strings: -//// tab | Python 3.10+ - -```Python hl_lines="12" -{!> ../../docs_src/body_nested_models/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 14" -{!> ../../docs_src/body_nested_models/tutorial003.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial003_py310.py hl[12] *} With this, even if you receive a request with duplicate data, it will be converted to a set of unique items. @@ -141,57 +81,13 @@ All that, arbitrarily nested. For example, we can define an `Image` model: -//// tab | Python 3.10+ - -```Python hl_lines="7-9" -{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9-11" -{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9-11" -{!> ../../docs_src/body_nested_models/tutorial004.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[7:9] *} ### Use the submodel as a type And then we can use it as the type of an attribute: -//// tab | Python 3.10+ - -```Python hl_lines="18" -{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial004.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[18] *} This would mean that **FastAPI** would expect a body similar to: @@ -224,29 +120,7 @@ To see all the options you have, checkout ../../docs_src/body_nested_models/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="4 10" -{!> ../../docs_src/body_nested_models/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4 10" -{!> ../../docs_src/body_nested_models/tutorial005.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial005_py310.py hl[2,8] *} The string will be checked to be a valid URL, and documented in JSON Schema / OpenAPI as such. @@ -254,29 +128,7 @@ The string will be checked to be a valid URL, and documented in JSON Schema / Op You can also use Pydantic models as subtypes of `list`, `set`, etc.: -//// tab | Python 3.10+ - -```Python hl_lines="18" -{!> ../../docs_src/body_nested_models/tutorial006_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial006_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial006.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial006_py310.py hl[18] *} This will expect (convert, validate, document, etc.) a JSON body like: @@ -314,29 +166,7 @@ Notice how the `images` key now has a list of image objects. You can define arbitrarily deeply nested models: -//// tab | Python 3.10+ - -```Python hl_lines="7 12 18 21 25" -{!> ../../docs_src/body_nested_models/tutorial007_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9 14 20 23 27" -{!> ../../docs_src/body_nested_models/tutorial007_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 14 20 23 27" -{!> ../../docs_src/body_nested_models/tutorial007.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial007_py310.py hl[7,12,18,21,25] *} /// info @@ -360,21 +190,7 @@ images: list[Image] as in: -//// tab | Python 3.9+ - -```Python hl_lines="13" -{!> ../../docs_src/body_nested_models/tutorial008_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="15" -{!> ../../docs_src/body_nested_models/tutorial008.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial008_py39.py hl[13] *} ## Editor support everywhere @@ -404,21 +220,7 @@ That's what we are going to see here. In this case, you would accept any `dict` as long as it has `int` keys with `float` values: -//// tab | Python 3.9+ - -```Python hl_lines="7" -{!> ../../docs_src/body_nested_models/tutorial009_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/body_nested_models/tutorial009.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial009_py39.py hl[7] *} /// tip diff --git a/docs/en/docs/tutorial/body-updates.md b/docs/en/docs/tutorial/body-updates.md index 3ac2e391497fb..df5b960db6f33 100644 --- a/docs/en/docs/tutorial/body-updates.md +++ b/docs/en/docs/tutorial/body-updates.md @@ -6,29 +6,7 @@ To update an item you can use the ../../docs_src/body_updates/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="30-35" -{!> ../../docs_src/body_updates/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="30-35" -{!> ../../docs_src/body_updates/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial001_py310.py hl[28:33] *} `PUT` is used to receive data that should replace the existing data. @@ -84,29 +62,7 @@ That would generate a `dict` with only the data that was set when creating the ` Then you can use this to generate a `dict` with only the data that was set (sent in the request), omitting default values: -//// tab | Python 3.10+ - -```Python hl_lines="32" -{!> ../../docs_src/body_updates/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="34" -{!> ../../docs_src/body_updates/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="34" -{!> ../../docs_src/body_updates/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial002_py310.py hl[32] *} ### Using Pydantic's `update` parameter @@ -122,29 +78,7 @@ The examples here use `.copy()` for compatibility with Pydantic v1, but you shou Like `stored_item_model.model_copy(update=update_data)`: -//// tab | Python 3.10+ - -```Python hl_lines="33" -{!> ../../docs_src/body_updates/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="35" -{!> ../../docs_src/body_updates/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="35" -{!> ../../docs_src/body_updates/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial002_py310.py hl[33] *} ### Partial updates recap @@ -161,29 +95,7 @@ In summary, to apply partial updates you would: * Save the data to your DB. * Return the updated model. -//// tab | Python 3.10+ - -```Python hl_lines="28-35" -{!> ../../docs_src/body_updates/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="30-37" -{!> ../../docs_src/body_updates/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="30-37" -{!> ../../docs_src/body_updates/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial002_py310.py hl[28:35] *} /// tip diff --git a/docs/en/docs/tutorial/body.md b/docs/en/docs/tutorial/body.md index 9c97f64cb0a45..aba5593a5943a 100644 --- a/docs/en/docs/tutorial/body.md +++ b/docs/en/docs/tutorial/body.md @@ -126,7 +126,7 @@ It improves editor support for Pydantic models, with: Inside of the function, you can access all the attributes of the model object directly: -{!> ../../docs_src/body/tutorial002_py310.py!} +{* ../../docs_src/body/tutorial002_py310.py *} ## Request body + path parameters diff --git a/docs/en/docs/tutorial/cookie-param-models.md b/docs/en/docs/tutorial/cookie-param-models.md index 62cafbb23d13f..55a812852ed0e 100644 --- a/docs/en/docs/tutorial/cookie-param-models.md +++ b/docs/en/docs/tutorial/cookie-param-models.md @@ -20,57 +20,7 @@ This same technique applies to `Query`, `Cookie`, and `Header`. 😎 Declare the **cookie** parameters that you need in a **Pydantic model**, and then declare the parameter as `Cookie`: -//// tab | Python 3.10+ - -```Python hl_lines="9-12 16" -{!> ../../docs_src/cookie_param_models/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9-12 16" -{!> ../../docs_src/cookie_param_models/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10-13 17" -{!> ../../docs_src/cookie_param_models/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7-10 14" -{!> ../../docs_src/cookie_param_models/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9-12 16" -{!> ../../docs_src/cookie_param_models/tutorial001.py!} -``` - -//// +{* ../../docs_src/cookie_param_models/tutorial001_an_py310.py hl[9:12,16] *} **FastAPI** will **extract** the data for **each field** from the **cookies** received in the request and give you the Pydantic model you defined. @@ -100,35 +50,7 @@ Your API now has the power to control its own ../../docs_src/cookie_param_models/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/cookie_param_models/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/cookie_param_models/tutorial002.py!} -``` - -//// +{* ../../docs_src/cookie_param_models/tutorial002_an_py39.py hl[10] *} If a client tries to send some **extra cookies**, they will receive an **error** response. diff --git a/docs/en/docs/tutorial/cookie-params.md b/docs/en/docs/tutorial/cookie-params.md index 8804f854f4432..5341406d51cf1 100644 --- a/docs/en/docs/tutorial/cookie-params.md +++ b/docs/en/docs/tutorial/cookie-params.md @@ -6,57 +6,7 @@ You can define Cookie parameters the same way you define `Query` and `Path` para First import `Cookie`: -//// tab | Python 3.10+ - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/cookie_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[3] *} ## Declare `Cookie` parameters @@ -64,59 +14,9 @@ Then declare the cookie parameters using the same structure as with `Path` and ` You can define the default value as well as all the extra validation or annotation parameters: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/cookie_params/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/cookie_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[9] *} -/// note | "Technical Details" +/// note | Technical Details `Cookie` is a "sister" class of `Path` and `Query`. It also inherits from the same common `Param` class. diff --git a/docs/en/docs/tutorial/cors.md b/docs/en/docs/tutorial/cors.md index 8dfc9bad9504e..cf31cfcf5d5a2 100644 --- a/docs/en/docs/tutorial/cors.md +++ b/docs/en/docs/tutorial/cors.md @@ -46,9 +46,8 @@ You can also specify whether your backend allows: * Specific HTTP methods (`POST`, `PUT`) or all of them with the wildcard `"*"`. * Specific HTTP headers or all of them with the wildcard `"*"`. -```Python hl_lines="2 6-11 13-19" -{!../../docs_src/cors/tutorial001.py!} -``` +{* ../../docs_src/cors/tutorial001.py hl[2,6:11,13:19] *} + The default parameters used by the `CORSMiddleware` implementation are restrictive by default, so you'll need to explicitly enable particular origins, methods, or headers, in order for browsers to be permitted to use them in a Cross-Domain context. @@ -78,7 +77,7 @@ Any request with an `Origin` header. In this case the middleware will pass the r For more info about CORS, check the Mozilla CORS documentation. -/// note | "Technical Details" +/// note | Technical Details You could also use `from starlette.middleware.cors import CORSMiddleware`. diff --git a/docs/en/docs/tutorial/debugging.md b/docs/en/docs/tutorial/debugging.md index 6c01778538438..90dd908f783bb 100644 --- a/docs/en/docs/tutorial/debugging.md +++ b/docs/en/docs/tutorial/debugging.md @@ -6,9 +6,7 @@ You can connect the debugger in your editor, for example with Visual Studio Code In your FastAPI application, import and run `uvicorn` directly: -```Python hl_lines="1 15" -{!../../docs_src/debugging/tutorial001.py!} -``` +{* ../../docs_src/debugging/tutorial001.py hl[1,15] *} ### About `__name__ == "__main__"` diff --git a/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md index defd61a0dd053..9c7bb1fd3818f 100644 --- a/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md @@ -6,57 +6,7 @@ Before diving deeper into the **Dependency Injection** system, let's upgrade the In the previous example, we were returning a `dict` from our dependency ("dependable"): -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="11" -{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="12" -{!> ../../docs_src/dependencies/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="11" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[9] *} But then we get a `dict` in the parameter `commons` of the *path operation function*. @@ -119,165 +69,15 @@ That also applies to callables with no parameters at all. The same as it would b Then, we can change the dependency "dependable" `common_parameters` from above to the class `CommonQueryParams`: -//// tab | Python 3.10+ - -```Python hl_lines="11-15" -{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="11-15" -{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="12-16" -{!> ../../docs_src/dependencies/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9-13" -{!> ../../docs_src/dependencies/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="11-15" -{!> ../../docs_src/dependencies/tutorial002.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[11:15] *} Pay attention to the `__init__` method used to create the instance of the class: -//// tab | Python 3.10+ - -```Python hl_lines="12" -{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="12" -{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="13" -{!> ../../docs_src/dependencies/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/dependencies/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="12" -{!> ../../docs_src/dependencies/tutorial002.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[12] *} ...it has the same parameters as our previous `common_parameters`: -//// tab | Python 3.10+ - -```Python hl_lines="8" -{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/dependencies/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="6" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8] *} Those parameters are what **FastAPI** will use to "solve" the dependency. @@ -293,57 +93,7 @@ In both cases the data will be converted, validated, documented on the OpenAPI s Now you can declare your dependency using this class. -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20" -{!> ../../docs_src/dependencies/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial002.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[19] *} **FastAPI** calls the `CommonQueryParams` class. This creates an "instance" of that class and the instance will be passed as the parameter `commons` to your function. @@ -437,57 +187,7 @@ commons = Depends(CommonQueryParams) ...as in: -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20" -{!> ../../docs_src/dependencies/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial003.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial003_an_py310.py hl[19] *} But declaring the type is encouraged as that way your editor will know what will be passed as the parameter `commons`, and then it can help you with code completion, type checks, etc: @@ -575,57 +275,7 @@ You declare the dependency as the type of the parameter, and you use `Depends()` The same example would then look like: -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20" -{!> ../../docs_src/dependencies/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial004.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial004_an_py310.py hl[19] *} ...and **FastAPI** will know what to do. diff --git a/docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index e89d520be3657..88ad99403db85 100644 --- a/docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -14,35 +14,7 @@ The *path operation decorator* receives an optional argument `dependencies`. It should be a `list` of `Depends()`: -//// tab | Python 3.9+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18" -{!> ../../docs_src/dependencies/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8 non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial006.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[19] *} These dependencies will be executed/solved the same way as normal dependencies. But their value (if they return any) won't be passed to your *path operation function*. @@ -72,69 +44,13 @@ You can use the same dependency *functions* you use normally. They can declare request requirements (like headers) or other sub-dependencies: -//// tab | Python 3.9+ - -```Python hl_lines="8 13" -{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="7 12" -{!> ../../docs_src/dependencies/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8 non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="6 11" -{!> ../../docs_src/dependencies/tutorial006.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[8,13] *} ### Raise exceptions These dependencies can `raise` exceptions, the same as normal dependencies: -//// tab | Python 3.9+ - -```Python hl_lines="10 15" -{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 14" -{!> ../../docs_src/dependencies/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8 non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="8 13" -{!> ../../docs_src/dependencies/tutorial006.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[10,15] *} ### Return values @@ -142,35 +58,7 @@ And they can return values or not, the values won't be used. So, you can reuse a normal dependency (that returns a value) you already use somewhere else, and even though the value won't be used, the dependency will be executed: -//// tab | Python 3.9+ - -```Python hl_lines="11 16" -{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10 15" -{!> ../../docs_src/dependencies/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8 non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9 14" -{!> ../../docs_src/dependencies/tutorial006.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[11,16] *} ## Dependencies for a group of *path operations* diff --git a/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md index 97da668aa0a76..2b97ba39ea501 100644 --- a/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md @@ -10,7 +10,7 @@ Make sure to use `yield` one single time per dependency. /// -/// note | "Technical Details" +/// note | Technical Details Any function that is valid to use with: @@ -29,21 +29,15 @@ For example, you could use this to create a database session and close it after Only the code prior to and including the `yield` statement is executed before creating a response: -```Python hl_lines="2-4" -{!../../docs_src/dependencies/tutorial007.py!} -``` +{* ../../docs_src/dependencies/tutorial007.py hl[2:4] *} The yielded value is what is injected into *path operations* and other dependencies: -```Python hl_lines="4" -{!../../docs_src/dependencies/tutorial007.py!} -``` +{* ../../docs_src/dependencies/tutorial007.py hl[4] *} -The code following the `yield` statement is executed after the response has been delivered: +The code following the `yield` statement is executed after creating the response but before sending it: -```Python hl_lines="5-6" -{!../../docs_src/dependencies/tutorial007.py!} -``` +{* ../../docs_src/dependencies/tutorial007.py hl[5:6] *} /// tip @@ -63,9 +57,7 @@ So, you can look for that specific exception inside the dependency with `except In the same way, you can use `finally` to make sure the exit steps are executed, no matter if there was an exception or not. -```Python hl_lines="3 5" -{!../../docs_src/dependencies/tutorial007.py!} -``` +{* ../../docs_src/dependencies/tutorial007.py hl[3,5] *} ## Sub-dependencies with `yield` @@ -75,35 +67,7 @@ You can have sub-dependencies and "trees" of sub-dependencies of any size and sh For example, `dependency_c` can have a dependency on `dependency_b`, and `dependency_b` on `dependency_a`: -//// tab | Python 3.9+ - -```Python hl_lines="6 14 22" -{!> ../../docs_src/dependencies/tutorial008_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="5 13 21" -{!> ../../docs_src/dependencies/tutorial008_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="4 12 20" -{!> ../../docs_src/dependencies/tutorial008.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial008_an_py39.py hl[6,14,22] *} And all of them can use `yield`. @@ -111,35 +75,7 @@ In this case `dependency_c`, to execute its exit code, needs the value from `dep And, in turn, `dependency_b` needs the value from `dependency_a` (here named `dep_a`) to be available for its exit code. -//// tab | Python 3.9+ - -```Python hl_lines="18-19 26-27" -{!> ../../docs_src/dependencies/tutorial008_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17-18 25-26" -{!> ../../docs_src/dependencies/tutorial008_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="16-17 24-25" -{!> ../../docs_src/dependencies/tutorial008.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial008_an_py39.py hl[18:19,26:27] *} The same way, you could have some dependencies with `yield` and some other dependencies with `return`, and have some of those depend on some of the others. @@ -149,7 +85,7 @@ You can have any combinations of dependencies that you want. **FastAPI** will make sure everything is run in the correct order. -/// note | "Technical Details" +/// note | Technical Details This works thanks to Python's Context Managers. @@ -171,35 +107,7 @@ But it's there for you if you need it. 🤓 /// -//// tab | Python 3.9+ - -```Python hl_lines="18-22 31" -{!> ../../docs_src/dependencies/tutorial008b_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17-21 30" -{!> ../../docs_src/dependencies/tutorial008b_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="16-20 29" -{!> ../../docs_src/dependencies/tutorial008b.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial008b_an_py39.py hl[18:22,31] *} An alternative you could use to catch exceptions (and possibly also raise another `HTTPException`) is to create a [Custom Exception Handler](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}. @@ -207,35 +115,7 @@ An alternative you could use to catch exceptions (and possibly also raise anothe If you catch an exception using `except` in a dependency with `yield` and you don't raise it again (or raise a new exception), FastAPI won't be able to notice there was an exception, the same way that would happen with regular Python: -//// tab | Python 3.9+ - -```Python hl_lines="15-16" -{!> ../../docs_src/dependencies/tutorial008c_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="14-15" -{!> ../../docs_src/dependencies/tutorial008c_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="13-14" -{!> ../../docs_src/dependencies/tutorial008c.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial008c_an_py39.py hl[15:16] *} In this case, the client will see an *HTTP 500 Internal Server Error* response as it should, given that we are not raising an `HTTPException` or similar, but the server will **not have any logs** or any other indication of what was the error. 😱 @@ -245,35 +125,7 @@ If you catch an exception in a dependency with `yield`, unless you are raising a You can re-raise the same exception using `raise`: -//// tab | Python 3.9+ - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial008d_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="16" -{!> ../../docs_src/dependencies/tutorial008d_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="15" -{!> ../../docs_src/dependencies/tutorial008d.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial008d_an_py39.py hl[17] *} Now the client will get the same *HTTP 500 Internal Server Error* response, but the server will have our custom `InternalError` in the logs. 😎 @@ -403,9 +255,7 @@ In Python, you can create Context Managers by ../../docs_src/dependencies/tutorial012_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="16" -{!> ../../docs_src/dependencies/tutorial012_an.py!} -``` - -//// - -//// tab | Python 3.8 non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="15" -{!> ../../docs_src/dependencies/tutorial012.py!} -``` - -//// And all the ideas in the section about [adding `dependencies` to the *path operation decorators*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} still apply, but in this case, to all of the *path operations* in the app. diff --git a/docs/en/docs/tutorial/dependencies/index.md b/docs/en/docs/tutorial/dependencies/index.md index b50edb98ecb58..596ce159961c6 100644 --- a/docs/en/docs/tutorial/dependencies/index.md +++ b/docs/en/docs/tutorial/dependencies/index.md @@ -31,57 +31,7 @@ Let's first focus on the dependency. It is just a function that can take all the same parameters that a *path operation function* can take: -//// tab | Python 3.10+ - -```Python hl_lines="8-9" -{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="8-11" -{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9-12" -{!> ../../docs_src/dependencies/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="6-7" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="8-11" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8:9] *} That's it. @@ -113,113 +63,13 @@ Make sure you [Upgrade the FastAPI version](../../deployment/versions.md#upgradi ### Import `Depends` -//// tab | Python 3.10+ - -```Python hl_lines="3" -{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3" -{!> ../../docs_src/dependencies/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="3" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[3] *} ### Declare the dependency, in the "dependant" The same way you use `Body`, `Query`, etc. with your *path operation function* parameters, use `Depends` with a new parameter: -//// tab | Python 3.10+ - -```Python hl_lines="13 18" -{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="15 20" -{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="16 21" -{!> ../../docs_src/dependencies/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="11 16" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="15 20" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[13,18] *} Although you use `Depends` in the parameters of your function the same way you use `Body`, `Query`, etc, `Depends` works a bit differently. @@ -276,29 +126,7 @@ commons: Annotated[dict, Depends(common_parameters)] But because we are using `Annotated`, we can store that `Annotated` value in a variable and use it in multiple places: -//// tab | Python 3.10+ - -```Python hl_lines="12 16 21" -{!> ../../docs_src/dependencies/tutorial001_02_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="14 18 23" -{!> ../../docs_src/dependencies/tutorial001_02_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="15 19 24" -{!> ../../docs_src/dependencies/tutorial001_02_an.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_02_an_py310.py hl[12,16,21] *} /// tip diff --git a/docs/en/docs/tutorial/dependencies/sub-dependencies.md b/docs/en/docs/tutorial/dependencies/sub-dependencies.md index 2b098d1592db1..1f8ba420a1cb9 100644 --- a/docs/en/docs/tutorial/dependencies/sub-dependencies.md +++ b/docs/en/docs/tutorial/dependencies/sub-dependencies.md @@ -10,57 +10,7 @@ They can be as **deep** as you need them to be. You could create a first dependency ("dependable") like: -//// tab | Python 3.10+ - -```Python hl_lines="8-9" -{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="8-9" -{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9-10" -{!> ../../docs_src/dependencies/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10 non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="6-7" -{!> ../../docs_src/dependencies/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.8 non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="8-9" -{!> ../../docs_src/dependencies/tutorial005.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[8:9] *} It declares an optional query parameter `q` as a `str`, and then it just returns it. @@ -70,57 +20,7 @@ This is quite simple (not very useful), but will help us focus on how the sub-de Then you can create another dependency function (a "dependable") that at the same time declares a dependency of its own (so it is a "dependant" too): -//// tab | Python 3.10+ - -```Python hl_lines="13" -{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="13" -{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="14" -{!> ../../docs_src/dependencies/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10 non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="11" -{!> ../../docs_src/dependencies/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.8 non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="13" -{!> ../../docs_src/dependencies/tutorial005.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[13] *} Let's focus on the parameters declared: @@ -133,57 +33,7 @@ Let's focus on the parameters declared: Then we can use the dependency with: -//// tab | Python 3.10+ - -```Python hl_lines="23" -{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="23" -{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24" -{!> ../../docs_src/dependencies/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10 non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.8 non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="22" -{!> ../../docs_src/dependencies/tutorial005.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[23] *} /// info diff --git a/docs/en/docs/tutorial/encoder.md b/docs/en/docs/tutorial/encoder.md index 039ac671499e7..e2eceafcc1037 100644 --- a/docs/en/docs/tutorial/encoder.md +++ b/docs/en/docs/tutorial/encoder.md @@ -20,21 +20,7 @@ You can use `jsonable_encoder` for that. It receives an object, like a Pydantic model, and returns a JSON compatible version: -//// tab | Python 3.10+ - -```Python hl_lines="4 21" -{!> ../../docs_src/encoder/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="5 22" -{!> ../../docs_src/encoder/tutorial001.py!} -``` - -//// +{* ../../docs_src/encoder/tutorial001_py310.py hl[4,21] *} In this example, it would convert the Pydantic model to a `dict`, and the `datetime` to a `str`. diff --git a/docs/en/docs/tutorial/extra-data-types.md b/docs/en/docs/tutorial/extra-data-types.md index 65f9f1085c554..eb7ccd91d78b8 100644 --- a/docs/en/docs/tutorial/extra-data-types.md +++ b/docs/en/docs/tutorial/extra-data-types.md @@ -55,108 +55,8 @@ Here are some of the additional data types you can use: Here's an example *path operation* with parameters using some of the above types. -//// tab | Python 3.10+ - -```Python hl_lines="1 3 12-16" -{!> ../../docs_src/extra_data_types/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="1 3 12-16" -{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 3 13-17" -{!> ../../docs_src/extra_data_types/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="1 2 11-15" -{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="1 2 12-16" -{!> ../../docs_src/extra_data_types/tutorial001.py!} -``` - -//// +{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[1,3,12:16] *} Note that the parameters inside the function have their natural data type, and you can, for example, perform normal date manipulations, like: -//// tab | Python 3.10+ - -```Python hl_lines="18-19" -{!> ../../docs_src/extra_data_types/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="18-19" -{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="19-20" -{!> ../../docs_src/extra_data_types/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="17-18" -{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="18-19" -{!> ../../docs_src/extra_data_types/tutorial001.py!} -``` - -//// +{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[18:19] *} diff --git a/docs/en/docs/tutorial/extra-models.md b/docs/en/docs/tutorial/extra-models.md index 4e6f69f31ece6..5fac3f69e0037 100644 --- a/docs/en/docs/tutorial/extra-models.md +++ b/docs/en/docs/tutorial/extra-models.md @@ -20,21 +20,8 @@ If you don't know, you will learn what a "password hash" is in the [security cha Here's a general idea of how the models could look like with their password fields and the places where they are used: -//// tab | Python 3.10+ +{* ../../docs_src/extra_models/tutorial001_py310.py hl[7,9,14,20,22,27:28,31:33,38:39] *} -```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" -{!> ../../docs_src/extra_models/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" -{!> ../../docs_src/extra_models/tutorial001.py!} -``` - -//// /// info @@ -176,21 +163,7 @@ All the data conversion, validation, documentation, etc. will still work as norm That way, we can declare just the differences between the models (with plaintext `password`, with `hashed_password` and without password): -//// tab | Python 3.10+ - -```Python hl_lines="7 13-14 17-18 21-22" -{!> ../../docs_src/extra_models/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 15-16 19-20 23-24" -{!> ../../docs_src/extra_models/tutorial002.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial002_py310.py hl[7,13:14,17:18,21:22] *} ## `Union` or `anyOf` @@ -206,21 +179,8 @@ When defining a ../../docs_src/extra_models/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial003_py310.py hl[1,14:15,18:20,33] *} -//// tab | Python 3.8+ - -```Python hl_lines="1 14-15 18-20 33" -{!> ../../docs_src/extra_models/tutorial003.py!} -``` - -//// ### `Union` in Python 3.10 @@ -242,21 +202,8 @@ The same way, you can declare responses of lists of objects. For that, use the standard Python `typing.List` (or just `list` in Python 3.9 and above): -//// tab | Python 3.9+ - -```Python hl_lines="18" -{!> ../../docs_src/extra_models/tutorial004_py39.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial004_py39.py hl[18] *} -//// tab | Python 3.8+ - -```Python hl_lines="1 20" -{!> ../../docs_src/extra_models/tutorial004.py!} -``` - -//// ## Response with arbitrary `dict` @@ -266,21 +213,8 @@ This is useful if you don't know the valid field/attribute names (that would be In this case, you can use `typing.Dict` (or just `dict` in Python 3.9 and above): -//// tab | Python 3.9+ - -```Python hl_lines="6" -{!> ../../docs_src/extra_models/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 8" -{!> ../../docs_src/extra_models/tutorial005.py!} -``` +{* ../../docs_src/extra_models/tutorial005_py39.py hl[6] *} -//// ## Recap diff --git a/docs/en/docs/tutorial/first-steps.md b/docs/en/docs/tutorial/first-steps.md index 1c20b945ace39..783295933b0e8 100644 --- a/docs/en/docs/tutorial/first-steps.md +++ b/docs/en/docs/tutorial/first-steps.md @@ -159,7 +159,7 @@ You could also use it to generate code automatically, for clients that communica `FastAPI` is a Python class that provides all the functionality for your API. -/// note | "Technical Details" +/// note | Technical Details `FastAPI` is a class that inherits directly from `Starlette`. @@ -245,7 +245,7 @@ The `@app.get("/")` tells **FastAPI** that the function right below is in charge * the path `/` * using a get operation -/// info | "`@decorator` Info" +/// info | `@decorator` Info That `@something` syntax in Python is called a "decorator". diff --git a/docs/en/docs/tutorial/handling-errors.md b/docs/en/docs/tutorial/handling-errors.md index 38c15761b8c91..4d969747f69c2 100644 --- a/docs/en/docs/tutorial/handling-errors.md +++ b/docs/en/docs/tutorial/handling-errors.md @@ -25,9 +25,7 @@ To return HTTP responses with errors to the client you use `HTTPException`. ### Import `HTTPException` -```Python hl_lines="1" -{!../../docs_src/handling_errors/tutorial001.py!} -``` +{* ../../docs_src/handling_errors/tutorial001.py hl[1] *} ### Raise an `HTTPException` in your code @@ -41,9 +39,7 @@ The benefit of raising an exception over `return`ing a value will be more eviden In this example, when the client requests an item by an ID that doesn't exist, raise an exception with a status code of `404`: -```Python hl_lines="11" -{!../../docs_src/handling_errors/tutorial001.py!} -``` +{* ../../docs_src/handling_errors/tutorial001.py hl[11] *} ### The resulting response @@ -81,9 +77,7 @@ You probably won't need to use it directly in your code. But in case you needed it for an advanced scenario, you can add custom headers: -```Python hl_lines="14" -{!../../docs_src/handling_errors/tutorial002.py!} -``` +{* ../../docs_src/handling_errors/tutorial002.py hl[14] *} ## Install custom exception handlers @@ -95,9 +89,7 @@ And you want to handle this exception globally with FastAPI. You could add a custom exception handler with `@app.exception_handler()`: -```Python hl_lines="5-7 13-18 24" -{!../../docs_src/handling_errors/tutorial003.py!} -``` +{* ../../docs_src/handling_errors/tutorial003.py hl[5:7,13:18,24] *} Here, if you request `/unicorns/yolo`, the *path operation* will `raise` a `UnicornException`. @@ -109,7 +101,7 @@ So, you will receive a clean error, with an HTTP status code of `418` and a JSON {"message": "Oops! yolo did something. There goes a rainbow..."} ``` -/// note | "Technical Details" +/// note | Technical Details You could also use `from starlette.requests import Request` and `from starlette.responses import JSONResponse`. @@ -135,9 +127,7 @@ To override it, import the `RequestValidationError` and use it with `@app.except The exception handler will receive a `Request` and the exception. -```Python hl_lines="2 14-16" -{!../../docs_src/handling_errors/tutorial004.py!} -``` +{* ../../docs_src/handling_errors/tutorial004.py hl[2,14:16] *} Now, if you go to `/items/foo`, instead of getting the default JSON error with: @@ -188,11 +178,9 @@ 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" +/// note | Technical Details You could also use `from starlette.responses import PlainTextResponse`. @@ -206,9 +194,7 @@ The `RequestValidationError` contains the `body` it received with invalid data. You could use it while developing your app to log the body and debug it, return it to the user, etc. -```Python hl_lines="14" -{!../../docs_src/handling_errors/tutorial005.py!} -``` +{* ../../docs_src/handling_errors/tutorial005.py hl[14] *} Now try sending an invalid item like: @@ -264,8 +250,6 @@ from starlette.exceptions import HTTPException as StarletteHTTPException If you want to use the exception along with the same default exception handlers from **FastAPI**, you can import and reuse the default exception handlers from `fastapi.exception_handlers`: -```Python hl_lines="2-5 15 21" -{!../../docs_src/handling_errors/tutorial006.py!} -``` +{* ../../docs_src/handling_errors/tutorial006.py hl[2:5,15,21] *} In this example you are just `print`ing the error with a very expressive message, but you get the idea. You can use the exception and then just reuse the default exception handlers. diff --git a/docs/en/docs/tutorial/header-param-models.md b/docs/en/docs/tutorial/header-param-models.md index 78517e4984da7..73950a668074e 100644 --- a/docs/en/docs/tutorial/header-param-models.md +++ b/docs/en/docs/tutorial/header-param-models.md @@ -14,71 +14,7 @@ This is supported since FastAPI version `0.115.0`. 🤓 Declare the **header parameters** that you need in a **Pydantic model**, and then declare the parameter as `Header`: -//// tab | Python 3.10+ - -```Python hl_lines="9-14 18" -{!> ../../docs_src/header_param_models/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9-14 18" -{!> ../../docs_src/header_param_models/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10-15 19" -{!> ../../docs_src/header_param_models/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7-12 16" -{!> ../../docs_src/header_param_models/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9-14 18" -{!> ../../docs_src/header_param_models/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7-12 16" -{!> ../../docs_src/header_param_models/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/header_param_models/tutorial001_an_py310.py hl[9:14,18] *} **FastAPI** will **extract** the data for **each field** from the **headers** in the request and give you the Pydantic model you defined. @@ -96,71 +32,7 @@ In some special use cases (probably not very common), you might want to **restri You can use Pydantic's model configuration to `forbid` any `extra` fields: -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/header_param_models/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/header_param_models/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/header_param_models/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="8" -{!> ../../docs_src/header_param_models/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/header_param_models/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/header_param_models/tutorial002.py!} -``` - -//// +{* ../../docs_src/header_param_models/tutorial002_an_py310.py hl[10] *} If a client tries to send some **extra headers**, they will receive an **error** response. diff --git a/docs/en/docs/tutorial/header-params.md b/docs/en/docs/tutorial/header-params.md index 293de897f79c0..49ad7aa25b24e 100644 --- a/docs/en/docs/tutorial/header-params.md +++ b/docs/en/docs/tutorial/header-params.md @@ -6,57 +6,7 @@ You can define Header parameters the same way you define `Query`, `Path` and `Co First import `Header`: -//// tab | Python 3.10+ - -```Python hl_lines="3" -{!> ../../docs_src/header_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/header_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3" -{!> ../../docs_src/header_params/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/header_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="3" -{!> ../../docs_src/header_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/header_params/tutorial001_an_py310.py hl[3] *} ## Declare `Header` parameters @@ -64,59 +14,9 @@ Then declare the header parameters using the same structure as with `Path`, `Que You can define the default value as well as all the extra validation or annotation parameters: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/header_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/header_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/header_params/tutorial001_an.py!} -``` +{* ../../docs_src/header_params/tutorial001_an_py310.py hl[9] *} -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/header_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/header_params/tutorial001.py!} -``` - -//// - -/// note | "Technical Details" +/// note | Technical Details `Header` is a "sister" class of `Path`, `Query` and `Cookie`. It also inherits from the same common `Param` class. @@ -146,57 +46,7 @@ So, you can use `user_agent` as you normally would in Python code, instead of ne If for some reason you need to disable automatic conversion of underscores to hyphens, set the parameter `convert_underscores` of `Header` to `False`: -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/header_params/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="11" -{!> ../../docs_src/header_params/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="12" -{!> ../../docs_src/header_params/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="8" -{!> ../../docs_src/header_params/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/header_params/tutorial002.py!} -``` - -//// +{* ../../docs_src/header_params/tutorial002_an_py310.py hl[10] *} /// warning @@ -214,71 +64,7 @@ You will receive all the values from the duplicate header as a Python `list`. For example, to declare a header of `X-Token` that can appear more than once, you can write: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/header_params/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/header_params/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/header_params/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/header_params/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/header_params/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/header_params/tutorial003.py!} -``` - -//// +{* ../../docs_src/header_params/tutorial003_an_py310.py hl[9] *} If you communicate with that *path operation* sending two HTTP headers like: diff --git a/docs/en/docs/tutorial/metadata.md b/docs/en/docs/tutorial/metadata.md index 715bb999a5277..6bd48caaf3faf 100644 --- a/docs/en/docs/tutorial/metadata.md +++ b/docs/en/docs/tutorial/metadata.md @@ -18,9 +18,7 @@ You can set the following fields that are used in the OpenAPI specification and You can set them as follows: -```Python hl_lines="3-16 19-32" -{!../../docs_src/metadata/tutorial001.py!} -``` +{* ../../docs_src/metadata/tutorial001.py hl[3:16, 19:32] *} /// tip @@ -38,9 +36,7 @@ Since OpenAPI 3.1.0 and FastAPI 0.99.0, you can also set the `license_info` with For example: -```Python hl_lines="31" -{!../../docs_src/metadata/tutorial001_1.py!} -``` +{* ../../docs_src/metadata/tutorial001_1.py hl[31] *} ## Metadata for tags @@ -62,9 +58,7 @@ Let's try that in an example with tags for `users` and `items`. Create metadata for your tags and pass it to the `openapi_tags` parameter: -```Python hl_lines="3-16 18" -{!../../docs_src/metadata/tutorial004.py!} -``` +{* ../../docs_src/metadata/tutorial004.py hl[3:16,18] *} Notice that you can use Markdown inside of the descriptions, for example "login" will be shown in bold (**login**) and "fancy" will be shown in italics (_fancy_). @@ -78,9 +72,7 @@ You don't have to add metadata for all the tags that you use. Use the `tags` parameter with your *path operations* (and `APIRouter`s) to assign them to different tags: -```Python hl_lines="21 26" -{!../../docs_src/metadata/tutorial004.py!} -``` +{* ../../docs_src/metadata/tutorial004.py hl[21,26] *} /// info @@ -108,9 +100,7 @@ But you can configure it with the parameter `openapi_url`. For example, to set it to be served at `/api/v1/openapi.json`: -```Python hl_lines="3" -{!../../docs_src/metadata/tutorial002.py!} -``` +{* ../../docs_src/metadata/tutorial002.py hl[3] *} If you want to disable the OpenAPI schema completely you can set `openapi_url=None`, that will also disable the documentation user interfaces that use it. @@ -127,6 +117,4 @@ You can configure the two documentation user interfaces included: For example, to set Swagger UI to be served at `/documentation` and disable ReDoc: -```Python hl_lines="3" -{!../../docs_src/metadata/tutorial003.py!} -``` +{* ../../docs_src/metadata/tutorial003.py hl[3] *} diff --git a/docs/en/docs/tutorial/middleware.md b/docs/en/docs/tutorial/middleware.md index 7c4954c7b704e..53c47a0857155 100644 --- a/docs/en/docs/tutorial/middleware.md +++ b/docs/en/docs/tutorial/middleware.md @@ -11,7 +11,7 @@ A "middleware" is a function that works with every **request** before it is proc * It can do something to that **response** or run any needed code. * Then it returns the **response**. -/// note | "Technical Details" +/// note | Technical Details If you have dependencies with `yield`, the exit code will run *after* the middleware. @@ -31,9 +31,7 @@ The middleware function receives: * Then it returns the `response` generated by the corresponding *path operation*. * You can then further modify the `response` before returning it. -```Python hl_lines="8-9 11 14" -{!../../docs_src/middleware/tutorial001.py!} -``` +{* ../../docs_src/middleware/tutorial001.py hl[8:9,11,14] *} /// tip @@ -43,7 +41,7 @@ But if you have custom headers that you want a client in a browser to be able to /// -/// note | "Technical Details" +/// note | Technical Details You could also use `from starlette.requests import Request`. @@ -59,9 +57,7 @@ And also after the `response` is generated, before returning it. For example, you could add a custom header `X-Process-Time` containing the time in seconds that it took to process the request and generate a response: -```Python hl_lines="10 12-13" -{!../../docs_src/middleware/tutorial001.py!} -``` +{* ../../docs_src/middleware/tutorial001.py hl[10,12:13] *} /// tip diff --git a/docs/en/docs/tutorial/path-operation-configuration.md b/docs/en/docs/tutorial/path-operation-configuration.md index 4ca6ebf1334bd..f2b5fd7957bc1 100644 --- a/docs/en/docs/tutorial/path-operation-configuration.md +++ b/docs/en/docs/tutorial/path-operation-configuration.md @@ -16,33 +16,11 @@ You can pass directly the `int` code, like `404`. But if you don't remember what each number code is for, you can use the shortcut constants in `status`: -//// tab | Python 3.10+ - -```Python hl_lines="1 15" -{!> ../../docs_src/path_operation_configuration/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="3 17" -{!> ../../docs_src/path_operation_configuration/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3 17" -{!> ../../docs_src/path_operation_configuration/tutorial001.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial001_py310.py hl[1,15] *} That status code will be used in the response and will be added to the OpenAPI schema. -/// note | "Technical Details" +/// note | Technical Details You could also use `from starlette import status`. @@ -54,29 +32,7 @@ You could also use `from starlette import status`. You can add tags to your *path operation*, pass the parameter `tags` with a `list` of `str` (commonly just one `str`): -//// tab | Python 3.10+ - -```Python hl_lines="15 20 25" -{!> ../../docs_src/path_operation_configuration/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="17 22 27" -{!> ../../docs_src/path_operation_configuration/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17 22 27" -{!> ../../docs_src/path_operation_configuration/tutorial002.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial002_py310.py hl[15,20,25] *} They will be added to the OpenAPI schema and used by the automatic documentation interfaces: @@ -90,37 +46,13 @@ In these cases, it could make sense to store the tags in an `Enum`. **FastAPI** supports that the same way as with plain strings: -```Python hl_lines="1 8-10 13 18" -{!../../docs_src/path_operation_configuration/tutorial002b.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial002b.py hl[1,8:10,13,18] *} ## Summary and description You can add a `summary` and `description`: -//// tab | Python 3.10+ - -```Python hl_lines="18-19" -{!> ../../docs_src/path_operation_configuration/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="20-21" -{!> ../../docs_src/path_operation_configuration/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20-21" -{!> ../../docs_src/path_operation_configuration/tutorial003.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial003_py310.py hl[18:19] *} ## Description from docstring @@ -128,29 +60,7 @@ As descriptions tend to be long and cover multiple lines, you can declare the *p You can write Markdown in the docstring, it will be interpreted and displayed correctly (taking into account docstring indentation). -//// tab | Python 3.10+ - -```Python hl_lines="17-25" -{!> ../../docs_src/path_operation_configuration/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="19-27" -{!> ../../docs_src/path_operation_configuration/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="19-27" -{!> ../../docs_src/path_operation_configuration/tutorial004.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial004_py310.py hl[17:25] *} It will be used in the interactive docs: @@ -160,29 +70,7 @@ It will be used in the interactive docs: You can specify the response description with the parameter `response_description`: -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/path_operation_configuration/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="21" -{!> ../../docs_src/path_operation_configuration/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="21" -{!> ../../docs_src/path_operation_configuration/tutorial005.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial005_py310.py hl[19] *} /// info @@ -204,9 +92,7 @@ So, if you don't provide one, **FastAPI** will automatically generate one of "Su If you need to mark a *path operation* as deprecated, but without removing it, pass the parameter `deprecated`: -```Python hl_lines="16" -{!../../docs_src/path_operation_configuration/tutorial006.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial006.py hl[16] *} It will be clearly marked as deprecated in the interactive docs: diff --git a/docs/en/docs/tutorial/path-params-numeric-validations.md b/docs/en/docs/tutorial/path-params-numeric-validations.md index 9ddf49ea94648..9440bcc03b00a 100644 --- a/docs/en/docs/tutorial/path-params-numeric-validations.md +++ b/docs/en/docs/tutorial/path-params-numeric-validations.md @@ -6,57 +6,7 @@ In the same way that you can declare more validations and metadata for query par First, import `Path` from `fastapi`, and import `Annotated`: -//// tab | Python 3.10+ - -```Python hl_lines="1 3" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="1 3" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3-4" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="3" -{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[1,3] *} /// info @@ -74,57 +24,7 @@ You can declare all the same parameters as for `Query`. For example, to declare a `title` metadata value for the path parameter `item_id` you can type: -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="8" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[10] *} /// note @@ -162,29 +62,13 @@ Prefer to use the `Annotated` version if possible. /// -```Python hl_lines="7" -{!> ../../docs_src/path_params_numeric_validations/tutorial002.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial002.py hl[7] *} //// But keep in mind that if you use `Annotated`, you won't have this problem, it won't matter as you're not using the function parameter default values for `Query()` or `Path()`. -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/path_params_numeric_validations/tutorial002_an.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py *} ## Order the parameters as you need, tricks @@ -209,29 +93,13 @@ Pass `*`, as the first parameter of the function. Python won't do anything with that `*`, but it will know that all the following parameters should be called as keyword arguments (key-value pairs), also known as kwargs. Even if they don't have a default value. -```Python hl_lines="7" -{!../../docs_src/path_params_numeric_validations/tutorial003.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *} ### Better with `Annotated` Keep in mind that if you use `Annotated`, as you are not using function parameter default values, you won't have this problem, and you probably won't need to use `*`. -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/path_params_numeric_validations/tutorial003_an.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py hl[10] *} ## Number validations: greater than or equal @@ -239,35 +107,7 @@ With `Query` and `Path` (and others you'll see later) you can declare number con Here, with `ge=1`, `item_id` will need to be an integer number "`g`reater than or `e`qual" to `1`. -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/path_params_numeric_validations/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="8" -{!> ../../docs_src/path_params_numeric_validations/tutorial004.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py hl[10] *} ## Number validations: greater than and less than or equal @@ -276,35 +116,7 @@ The same applies for: * `gt`: `g`reater `t`han * `le`: `l`ess than or `e`qual -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/path_params_numeric_validations/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/path_params_numeric_validations/tutorial005.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py hl[10] *} ## Number validations: floats, greater than and less than @@ -316,35 +128,7 @@ So, `0.5` would be a valid value. But `0.0` or `0` would not. And the same for lt. -//// tab | Python 3.9+ - -```Python hl_lines="13" -{!> ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="12" -{!> ../../docs_src/path_params_numeric_validations/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="11" -{!> ../../docs_src/path_params_numeric_validations/tutorial006.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py hl[13] *} ## Recap @@ -365,7 +149,7 @@ All of them share the same parameters for additional validation and metadata you /// -/// note | "Technical Details" +/// note | Technical Details When you import `Query`, `Path` and others from `fastapi`, they are actually functions. diff --git a/docs/en/docs/tutorial/path-params.md b/docs/en/docs/tutorial/path-params.md index fd9e745856fc4..7e83d3ae57e7f 100644 --- a/docs/en/docs/tutorial/path-params.md +++ b/docs/en/docs/tutorial/path-params.md @@ -2,9 +2,7 @@ You can declare path "parameters" or "variables" with the same syntax used by Python format strings: -```Python hl_lines="6-7" -{!../../docs_src/path_params/tutorial001.py!} -``` +{* ../../docs_src/path_params/tutorial001.py hl[6:7] *} The value of the path parameter `item_id` will be passed to your function as the argument `item_id`. @@ -18,9 +16,7 @@ So, if you run this example and go to ../../docs_src/query_param_models/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="8-12 16" -{!> ../../docs_src/query_param_models/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10-14 18" -{!> ../../docs_src/query_param_models/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9-13 17" -{!> ../../docs_src/query_param_models/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="8-12 16" -{!> ../../docs_src/query_param_models/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9-13 17" -{!> ../../docs_src/query_param_models/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/query_param_models/tutorial001_an_py310.py hl[9:13,17] *} **FastAPI** will **extract** the data for **each field** from the **query parameters** in the request and give you the Pydantic model you defined. @@ -96,71 +32,7 @@ In some special use cases (probably not very common), you might want to **restri You can use Pydantic's model configuration to `forbid` any `extra` fields: -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/query_param_models/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_param_models/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/query_param_models/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/query_param_models/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_param_models/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="11" -{!> ../../docs_src/query_param_models/tutorial002.py!} -``` - -//// +{* ../../docs_src/query_param_models/tutorial002_an_py310.py hl[10] *} If a client tries to send some **extra** data in the **query parameters**, they will receive an **error** response. diff --git a/docs/en/docs/tutorial/query-params-str-validations.md b/docs/en/docs/tutorial/query-params-str-validations.md index 12778d7feaafc..1bf16334d2a74 100644 --- a/docs/en/docs/tutorial/query-params-str-validations.md +++ b/docs/en/docs/tutorial/query-params-str-validations.md @@ -4,21 +4,7 @@ Let's take this application as example: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial001.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial001_py310.py hl[7] *} The query parameter `q` is of type `Union[str, None]` (or `str | None` in Python 3.10), that means that it's of type `str` but could also be `None`, and indeed, the default value is `None`, so FastAPI will know it's not required. @@ -123,21 +109,7 @@ Now let's jump to the fun stuff. 🎉 Now that we have this `Annotated` where we can put more information (in this case some additional validation), add `Query` inside of `Annotated`, and set the parameter `max_length` to `50`: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial002_an.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial002_an_py310.py hl[9] *} Notice that the default value is still `None`, so the parameter is still optional. @@ -167,21 +139,7 @@ For new code and whenever possible, use `Annotated` as explained above. There ar This is how you would use `Query()` as the default value of your function parameter, setting the parameter `max_length` to 50: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial002.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial002_py310.py hl[7] *} As in this case (without using `Annotated`) we have to replace the default value `None` in the function with `Query()`, we now need to set the default value with the parameter `Query(default=None)`, it serves the same purpose of defining that default value (at least for FastAPI). @@ -281,113 +239,13 @@ Because `Annotated` can have more than one metadata annotation, you could now ev You can also add a parameter `min_length`: -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial003.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial003_an_py310.py hl[10] *} ## Add regular expressions You can define a regular expression `pattern` that the parameter should match: -//// tab | Python 3.10+ - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="12" -{!> ../../docs_src/query_params_str_validations/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial004.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial004_an_py310.py hl[11] *} This specific regular expression pattern checks that the received parameter value: @@ -405,11 +263,9 @@ Before Pydantic version 2 and before FastAPI 0.100.0, the parameter was called ` You could still see some code using it: -//// tab | Python 3.10+ Pydantic v1 +//// tab | Pydantic v1 -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial004_an_py310_regex.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial004_regex_an_py310.py hl[11] *} //// @@ -421,35 +277,7 @@ You can, of course, use default values other than `None`. Let's say that you want to declare the `q` query parameter to have a `min_length` of `3`, and to have a default value of `"fixedquery"`: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial005.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial005_an_py39.py hl[9] *} /// note @@ -491,77 +319,13 @@ q: Union[str, None] = Query(default=None, min_length=3) So, when you need to declare a value as required while using `Query`, you can simply not declare a default value: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial006.py!} -``` - -/// tip - -Notice that, even though in this case the `Query()` is used as the function parameter default value, we don't pass the `default=None` to `Query()`. - -Still, probably better to use the `Annotated` version. 😉 - -/// - -//// +{* ../../docs_src/query_params_str_validations/tutorial006_an_py39.py hl[9] *} ### Required with Ellipsis (`...`) There's an alternative way to explicitly declare that a value is required. You can set the default to the literal value `...`: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial006b_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial006b.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial006b_an_py39.py hl[9] *} /// info @@ -579,57 +343,7 @@ You can declare that a parameter can accept `None`, but that it's still required To do that, you can declare that `None` is a valid type but still use `...` as the default: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial006c_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial006c_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial006c_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial006c.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial006c_an_py310.py hl[9] *} /// tip @@ -649,71 +363,7 @@ When you define a query parameter explicitly with `Query` you can also declare i For example, to declare a query parameter `q` that can appear multiple times in the URL, you can write: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial011_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial011_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial011_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial011_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial011_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial011.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial011_an_py310.py hl[9] *} Then, with a URL like: @@ -748,49 +398,7 @@ The interactive API docs will update accordingly, to allow multiple values: And you can also define a default `list` of values if none are provided: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial012_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial012_an.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial012_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial012.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial012_an_py39.py hl[9] *} If you go to: @@ -813,35 +421,7 @@ the default of `q` will be: `["foo", "bar"]` and your response will be: You can also use `list` directly instead of `List[str]` (or `list[str]` in Python 3.9+): -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial013_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial013_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial013.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial013_an_py39.py hl[9] *} /// note @@ -867,111 +447,11 @@ Some of them might not show all the extra information declared yet, although in You can add a `title`: -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial007_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial007_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial007_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial007_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial007.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial007_an_py310.py hl[10] *} And a `description`: -//// tab | Python 3.10+ - -```Python hl_lines="14" -{!> ../../docs_src/query_params_str_validations/tutorial008_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="14" -{!> ../../docs_src/query_params_str_validations/tutorial008_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="15" -{!> ../../docs_src/query_params_str_validations/tutorial008_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial008_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="13" -{!> ../../docs_src/query_params_str_validations/tutorial008.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial008_an_py310.py hl[14] *} ## Alias parameters @@ -991,57 +471,7 @@ But you still need it to be exactly `item-query`... Then you can declare an `alias`, and that alias is what will be used to find the parameter value: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial009_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial009_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial009_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial009_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial009.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial009_an_py310.py hl[9] *} ## Deprecating parameters @@ -1051,57 +481,7 @@ You have to leave it there a while because there are clients using it, but you w Then pass the parameter `deprecated=True` to `Query`: -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/query_params_str_validations/tutorial010_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="19" -{!> ../../docs_src/query_params_str_validations/tutorial010_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20" -{!> ../../docs_src/query_params_str_validations/tutorial010_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="16" -{!> ../../docs_src/query_params_str_validations/tutorial010_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="18" -{!> ../../docs_src/query_params_str_validations/tutorial010.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial010_an_py310.py hl[19] *} The docs will show it like this: @@ -1111,57 +491,7 @@ The docs will show it like this: To exclude a query parameter from the generated OpenAPI schema (and thus, from the automatic documentation systems), set the parameter `include_in_schema` of `Query` to `False`: -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial014_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial014_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial014_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial014_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial014.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial014_an_py310.py hl[10] *} ## Recap diff --git a/docs/en/docs/tutorial/query-params.md b/docs/en/docs/tutorial/query-params.md index 0d31d453d5ce4..c8477387c8fda 100644 --- a/docs/en/docs/tutorial/query-params.md +++ b/docs/en/docs/tutorial/query-params.md @@ -2,9 +2,7 @@ When you declare other function parameters that are not part of the path parameters, they are automatically interpreted as "query" parameters. -```Python hl_lines="9" -{!../../docs_src/query_params/tutorial001.py!} -``` +{* ../../docs_src/query_params/tutorial001.py hl[9] *} The query is the set of key-value pairs that go after the `?` in a URL, separated by `&` characters. @@ -63,21 +61,7 @@ The parameter values in your function will be: The same way, you can declare optional query parameters, by setting their default to `None`: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/query_params/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params/tutorial002.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial002_py310.py hl[7] *} In this case, the function parameter `q` will be optional, and will be `None` by default. @@ -91,21 +75,7 @@ Also notice that **FastAPI** is smart enough to notice that the path parameter ` You can also declare `bool` types, and they will be converted: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/query_params/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params/tutorial003.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial003_py310.py hl[7] *} In this case, if you go to: @@ -148,21 +118,7 @@ And you don't have to declare them in any specific order. They will be detected by name: -//// tab | Python 3.10+ - -```Python hl_lines="6 8" -{!> ../../docs_src/query_params/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8 10" -{!> ../../docs_src/query_params/tutorial004.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial004_py310.py hl[6,8] *} ## Required query parameters @@ -172,9 +128,7 @@ If you don't want to add a specific value but just make it optional, set the def But when you want to make a query parameter required, you can just not declare any default value: -```Python hl_lines="6-7" -{!../../docs_src/query_params/tutorial005.py!} -``` +{* ../../docs_src/query_params/tutorial005.py hl[6:7] *} Here the query parameter `needy` is a required query parameter of type `str`. @@ -220,21 +174,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy And of course, you can define some parameters as required, some as having a default value, and some entirely optional: -//// tab | Python 3.10+ - -```Python hl_lines="8" -{!> ../../docs_src/query_params/tutorial006_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params/tutorial006.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial006_py310.py hl[8] *} In this case, there are 3 query parameters: diff --git a/docs/en/docs/tutorial/request-files.md b/docs/en/docs/tutorial/request-files.md index f3f1eb103e7e6..0d57f35660df9 100644 --- a/docs/en/docs/tutorial/request-files.md +++ b/docs/en/docs/tutorial/request-files.md @@ -20,69 +20,13 @@ This is because uploaded files are sent as "form data". Import `File` and `UploadFile` from `fastapi`: -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/request_files/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1" -{!> ../../docs_src/request_files/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/request_files/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[3] *} ## Define `File` Parameters Create file parameters the same way you would for `Body` or `Form`: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/request_files/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/request_files/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/request_files/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[9] *} /// info @@ -110,35 +54,7 @@ But there are several cases in which you might benefit from using `UploadFile`. Define a file parameter with a type of `UploadFile`: -//// tab | Python 3.9+ - -```Python hl_lines="14" -{!> ../../docs_src/request_files/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="13" -{!> ../../docs_src/request_files/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="12" -{!> ../../docs_src/request_files/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[14] *} Using `UploadFile` has several advantages over `bytes`: @@ -181,13 +97,13 @@ If you are inside of a normal `def` *path operation function*, you can access th contents = myfile.file.read() ``` -/// note | "`async` Technical Details" +/// note | `async` Technical Details When you use the `async` methods, **FastAPI** runs the file methods in a threadpool and awaits for them. /// -/// note | "Starlette Technical Details" +/// note | Starlette Technical Details **FastAPI**'s `UploadFile` inherits directly from **Starlette**'s `UploadFile`, but adds some necessary parts to make it compatible with **Pydantic** and the other parts of FastAPI. @@ -199,7 +115,7 @@ The way HTML forms (`
`) sends the data to the server normally uses **FastAPI** will make sure to read that data from the right place instead of JSON. -/// note | "Technical Details" +/// note | Technical Details Data from forms is normally encoded using the "media type" `application/x-www-form-urlencoded` when it doesn't include files. @@ -221,91 +137,13 @@ This is not a limitation of **FastAPI**, it's part of the HTTP protocol. You can make a file optional by using standard type annotations and setting a default value of `None`: -//// tab | Python 3.10+ - -```Python hl_lines="9 17" -{!> ../../docs_src/request_files/tutorial001_02_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9 17" -{!> ../../docs_src/request_files/tutorial001_02_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10 18" -{!> ../../docs_src/request_files/tutorial001_02_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7 15" -{!> ../../docs_src/request_files/tutorial001_02_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9 17" -{!> ../../docs_src/request_files/tutorial001_02.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *} ## `UploadFile` with Additional Metadata You can also use `File()` with `UploadFile`, for example, to set additional metadata: -//// tab | Python 3.9+ - -```Python hl_lines="9 15" -{!> ../../docs_src/request_files/tutorial001_03_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8 14" -{!> ../../docs_src/request_files/tutorial001_03_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7 13" -{!> ../../docs_src/request_files/tutorial001_03.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_03_an_py39.py hl[9,15] *} ## Multiple File Uploads @@ -315,53 +153,11 @@ They would be associated to the same "form field" sent using "form data". To use that, declare a list of `bytes` or `UploadFile`: -//// tab | Python 3.9+ - -```Python hl_lines="10 15" -{!> ../../docs_src/request_files/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11 16" -{!> ../../docs_src/request_files/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="8 13" -{!> ../../docs_src/request_files/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="10 15" -{!> ../../docs_src/request_files/tutorial002.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial002_an_py39.py hl[10,15] *} You will receive, as declared, a `list` of `bytes` or `UploadFile`s. -/// note | "Technical Details" +/// note | Technical Details You could also use `from starlette.responses import HTMLResponse`. @@ -373,49 +169,7 @@ You could also use `from starlette.responses import HTMLResponse`. And the same way as before, you can use `File()` to set additional parameters, even for `UploadFile`: -//// tab | Python 3.9+ - -```Python hl_lines="11 18-20" -{!> ../../docs_src/request_files/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="12 19-21" -{!> ../../docs_src/request_files/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9 16" -{!> ../../docs_src/request_files/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="11 18" -{!> ../../docs_src/request_files/tutorial003.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial003_an_py39.py hl[11,18:20] *} ## Recap diff --git a/docs/en/docs/tutorial/request-form-models.md b/docs/en/docs/tutorial/request-form-models.md index f1142877ad447..79046a3f692db 100644 --- a/docs/en/docs/tutorial/request-form-models.md +++ b/docs/en/docs/tutorial/request-form-models.md @@ -24,35 +24,7 @@ This is supported since FastAPI version `0.113.0`. 🤓 You just need to declare a **Pydantic model** with the fields you want to receive as **form fields**, and then declare the parameter as `Form`: -//// tab | Python 3.9+ - -```Python hl_lines="9-11 15" -{!> ../../docs_src/request_form_models/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8-10 14" -{!> ../../docs_src/request_form_models/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7-9 13" -{!> ../../docs_src/request_form_models/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_form_models/tutorial001_an_py39.py hl[9:11,15] *} **FastAPI** will **extract** the data for **each field** from the **form data** in the request and give you the Pydantic model you defined. @@ -76,35 +48,7 @@ This is supported since FastAPI version `0.114.0`. 🤓 You can use Pydantic's model configuration to `forbid` any `extra` fields: -//// tab | Python 3.9+ - -```Python hl_lines="12" -{!> ../../docs_src/request_form_models/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/request_form_models/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/request_form_models/tutorial002.py!} -``` - -//// +{* ../../docs_src/request_form_models/tutorial002_an_py39.py hl[12] *} If a client tries to send some extra data, they will receive an **error** response. diff --git a/docs/en/docs/tutorial/request-forms-and-files.md b/docs/en/docs/tutorial/request-forms-and-files.md index d60fc4c00b155..21e4bbd301044 100644 --- a/docs/en/docs/tutorial/request-forms-and-files.md +++ b/docs/en/docs/tutorial/request-forms-and-files.md @@ -16,69 +16,13 @@ $ pip install python-multipart ## Import `File` and `Form` -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1" -{!> ../../docs_src/request_forms_and_files/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/request_forms_and_files/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[3] *} ## Define `File` and `Form` parameters Create file and form parameters the same way you would for `Body` or `Query`: -//// tab | Python 3.9+ - -```Python hl_lines="10-12" -{!> ../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9-11" -{!> ../../docs_src/request_forms_and_files/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="8" -{!> ../../docs_src/request_forms_and_files/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[10:12] *} The files and form fields will be uploaded as form data and you will receive the files and form fields. diff --git a/docs/en/docs/tutorial/request-forms.md b/docs/en/docs/tutorial/request-forms.md index 2ccc6886e72df..3c6a0ddaaa8a7 100644 --- a/docs/en/docs/tutorial/request-forms.md +++ b/docs/en/docs/tutorial/request-forms.md @@ -18,69 +18,13 @@ $ pip install python-multipart Import `Form` from `fastapi`: -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/request_forms/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1" -{!> ../../docs_src/request_forms/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/request_forms/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[3] *} ## Define `Form` parameters Create form parameters the same way you would for `Body` or `Query`: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/request_forms/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/request_forms/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/request_forms/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[9] *} For example, in one of the ways the OAuth2 specification can be used (called "password flow") it is required to send a `username` and `password` as form fields. @@ -106,7 +50,7 @@ The way HTML forms (`
`) sends the data to the server normally uses **FastAPI** will make sure to read that data from the right place instead of JSON. -/// note | "Technical Details" +/// note | Technical Details Data from forms is normally encoded using the "media type" `application/x-www-form-urlencoded`. diff --git a/docs/en/docs/tutorial/response-model.md b/docs/en/docs/tutorial/response-model.md index 36ccfc4ce5ba0..e7837086fb949 100644 --- a/docs/en/docs/tutorial/response-model.md +++ b/docs/en/docs/tutorial/response-model.md @@ -4,29 +4,7 @@ You can declare the type used for the response by annotating the *path operation You can use **type annotations** the same way you would for input data in function **parameters**, you can use Pydantic models, lists, dictionaries, scalar values like integers, booleans, etc. -//// tab | Python 3.10+ - -```Python hl_lines="16 21" -{!> ../../docs_src/response_model/tutorial001_01_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="18 23" -{!> ../../docs_src/response_model/tutorial001_01_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18 23" -{!> ../../docs_src/response_model/tutorial001_01.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial001_01_py310.py hl[16,21] *} FastAPI will use this return type to: @@ -59,29 +37,7 @@ You can use the `response_model` parameter in any of the *path operations*: * `@app.delete()` * etc. -//// tab | Python 3.10+ - -```Python hl_lines="17 22 24-27" -{!> ../../docs_src/response_model/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="17 22 24-27" -{!> ../../docs_src/response_model/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17 22 24-27" -{!> ../../docs_src/response_model/tutorial001.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial001_py310.py hl[17,22,24:27] *} /// note @@ -113,21 +69,7 @@ You can also use `response_model=None` to disable creating a response model for Here we are declaring a `UserIn` model, it will contain a plaintext password: -//// tab | Python 3.10+ - -```Python hl_lines="7 9" -{!> ../../docs_src/response_model/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 11" -{!> ../../docs_src/response_model/tutorial002.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial002_py310.py hl[7,9] *} /// info @@ -149,21 +91,7 @@ $ pip install "pydantic[email]" And we are using this model to declare our input and the same model to declare our output: -//// tab | Python 3.10+ - -```Python hl_lines="16" -{!> ../../docs_src/response_model/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18" -{!> ../../docs_src/response_model/tutorial002.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial002_py310.py hl[16] *} Now, whenever a browser is creating a user with a password, the API will return the same password in the response. @@ -181,57 +109,15 @@ Never store the plain password of a user or send it in a response like this, unl We can instead create an input model with the plaintext password and an output model without it: -//// tab | Python 3.10+ - -```Python hl_lines="9 11 16" -{!> ../../docs_src/response_model/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 11 16" -{!> ../../docs_src/response_model/tutorial003.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_py310.py hl[9,11,16] *} Here, even though our *path operation function* is returning the same input user that contains the password: -//// tab | Python 3.10+ - -```Python hl_lines="24" -{!> ../../docs_src/response_model/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24" -{!> ../../docs_src/response_model/tutorial003.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_py310.py hl[24] *} ...we declared the `response_model` to be our model `UserOut`, that doesn't include the password: -//// tab | Python 3.10+ - -```Python hl_lines="22" -{!> ../../docs_src/response_model/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="22" -{!> ../../docs_src/response_model/tutorial003.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_py310.py hl[22] *} So, **FastAPI** will take care of filtering out all the data that is not declared in the output model (using Pydantic). @@ -255,21 +141,7 @@ But in most of the cases where we need to do something like this, we want the mo And in those cases, we can use classes and inheritance to take advantage of function **type annotations** to get better support in the editor and tools, and still get the FastAPI **data filtering**. -//// tab | Python 3.10+ - -```Python hl_lines="7-10 13-14 18" -{!> ../../docs_src/response_model/tutorial003_01_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9-13 15-16 20" -{!> ../../docs_src/response_model/tutorial003_01.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_01_py310.py hl[7:10,13:14,18] *} With this, we get tooling support, from editors and mypy as this code is correct in terms of types, but we also get the data filtering from FastAPI. @@ -311,9 +183,7 @@ There might be cases where you return something that is not a valid Pydantic fie The most common case would be [returning a Response directly as explained later in the advanced docs](../advanced/response-directly.md){.internal-link target=_blank}. -```Python hl_lines="8 10-11" -{!> ../../docs_src/response_model/tutorial003_02.py!} -``` +{* ../../docs_src/response_model/tutorial003_02.py hl[8,10:11] *} This simple case is handled automatically by FastAPI because the return type annotation is the class (or a subclass of) `Response`. @@ -323,9 +193,7 @@ And tools will also be happy because both `RedirectResponse` and `JSONResponse` You can also use a subclass of `Response` in the type annotation: -```Python hl_lines="8-9" -{!> ../../docs_src/response_model/tutorial003_03.py!} -``` +{* ../../docs_src/response_model/tutorial003_03.py hl[8:9] *} This will also work because `RedirectResponse` is a subclass of `Response`, and FastAPI will automatically handle this simple case. @@ -335,21 +203,7 @@ But when you return some other arbitrary object that is not a valid Pydantic typ The same would happen if you had something like a union between different types where one or more of them are not valid Pydantic types, for example this would fail 💥: -//// tab | Python 3.10+ - -```Python hl_lines="8" -{!> ../../docs_src/response_model/tutorial003_04_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/response_model/tutorial003_04.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_04_py310.py hl[8] *} ...this fails because the type annotation is not a Pydantic type and is not just a single `Response` class or subclass, it's a union (any of the two) between a `Response` and a `dict`. @@ -361,21 +215,7 @@ But you might want to still keep the return type annotation in the function to g In this case, you can disable the response model generation by setting `response_model=None`: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/response_model/tutorial003_05_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/response_model/tutorial003_05.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_05_py310.py hl[7] *} This will make FastAPI skip the response model generation and that way you can have any return type annotations you need without it affecting your FastAPI application. 🤓 @@ -383,29 +223,7 @@ This will make FastAPI skip the response model generation and that way you can h Your response model could have default values, like: -//// tab | Python 3.10+ - -```Python hl_lines="9 11-12" -{!> ../../docs_src/response_model/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="11 13-14" -{!> ../../docs_src/response_model/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11 13-14" -{!> ../../docs_src/response_model/tutorial004.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial004_py310.py hl[9,11:12] *} * `description: Union[str, None] = None` (or `str | None = None` in Python 3.10) has a default of `None`. * `tax: float = 10.5` has a default of `10.5`. @@ -419,29 +237,7 @@ For example, if you have models with many optional attributes in a NoSQL databas You can set the *path operation decorator* parameter `response_model_exclude_unset=True`: -//// tab | Python 3.10+ - -```Python hl_lines="22" -{!> ../../docs_src/response_model/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="24" -{!> ../../docs_src/response_model/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24" -{!> ../../docs_src/response_model/tutorial004.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial004_py310.py hl[22] *} and those default values won't be included in the response, only the values actually set. @@ -538,21 +334,7 @@ This also applies to `response_model_by_alias` that works similarly. /// -//// tab | Python 3.10+ - -```Python hl_lines="29 35" -{!> ../../docs_src/response_model/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="31 37" -{!> ../../docs_src/response_model/tutorial005.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial005_py310.py hl[29,35] *} /// tip @@ -566,21 +348,7 @@ It is equivalent to `set(["name", "description"])`. If you forget to use a `set` and use a `list` or `tuple` instead, FastAPI will still convert it to a `set` and it will work correctly: -//// tab | Python 3.10+ - -```Python hl_lines="29 35" -{!> ../../docs_src/response_model/tutorial006_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="31 37" -{!> ../../docs_src/response_model/tutorial006.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial006_py310.py hl[29,35] *} ## Recap diff --git a/docs/en/docs/tutorial/response-status-code.md b/docs/en/docs/tutorial/response-status-code.md index 73af62aed7186..711042a4667da 100644 --- a/docs/en/docs/tutorial/response-status-code.md +++ b/docs/en/docs/tutorial/response-status-code.md @@ -8,9 +8,7 @@ The same way you can specify a response model, you can also declare the HTTP sta * `@app.delete()` * etc. -```Python hl_lines="6" -{!../../docs_src/response_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_status_code/tutorial001.py hl[6] *} /// note @@ -76,9 +74,7 @@ To know more about each status code and which code is for what, check the
-/// note | "Technical Details" +/// note | Technical Details You could also use `from starlette import status`. diff --git a/docs/en/docs/tutorial/schema-extra-example.md b/docs/en/docs/tutorial/schema-extra-example.md index 5896b54d98373..32a1f5ca21f47 100644 --- a/docs/en/docs/tutorial/schema-extra-example.md +++ b/docs/en/docs/tutorial/schema-extra-example.md @@ -8,35 +8,15 @@ Here are several ways to do it. You can declare `examples` for a Pydantic model that will be added to the generated JSON Schema. -//// tab | Python 3.10+ Pydantic v2 - -```Python hl_lines="13-24" -{!> ../../docs_src/schema_extra_example/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.10+ Pydantic v1 - -```Python hl_lines="13-23" -{!> ../../docs_src/schema_extra_example/tutorial001_py310_pv1.py!} -``` - -//// - -//// tab | Python 3.8+ Pydantic v2 +//// tab | Pydantic v2 -```Python hl_lines="15-26" -{!> ../../docs_src/schema_extra_example/tutorial001.py!} -``` +{* ../../docs_src/schema_extra_example/tutorial001_py310.py hl[13:24] *} //// -//// tab | Python 3.8+ Pydantic v1 +//// tab | Pydantic v1 -```Python hl_lines="15-25" -{!> ../../docs_src/schema_extra_example/tutorial001_pv1.py!} -``` +{* ../../docs_src/schema_extra_example/tutorial001_pv1_py310.py hl[13:23] *} //// @@ -80,21 +60,7 @@ You can read more at the end of this page. When using `Field()` with Pydantic models, you can also declare additional `examples`: -//// tab | Python 3.10+ - -```Python hl_lines="2 8-11" -{!> ../../docs_src/schema_extra_example/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4 10-13" -{!> ../../docs_src/schema_extra_example/tutorial002.py!} -``` - -//// +{* ../../docs_src/schema_extra_example/tutorial002_py310.py hl[2,8:11] *} ## `examples` in JSON Schema - OpenAPI @@ -114,57 +80,7 @@ you can also declare a group of `examples` with additional information that will Here we pass `examples` containing one example of the data expected in `Body()`: -//// tab | Python 3.10+ - -```Python hl_lines="22-29" -{!> ../../docs_src/schema_extra_example/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="22-29" -{!> ../../docs_src/schema_extra_example/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="23-30" -{!> ../../docs_src/schema_extra_example/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="18-25" -{!> ../../docs_src/schema_extra_example/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="20-27" -{!> ../../docs_src/schema_extra_example/tutorial003.py!} -``` - -//// +{* ../../docs_src/schema_extra_example/tutorial003_an_py310.py hl[22:29] *} ### Example in the docs UI @@ -176,57 +92,7 @@ With any of the methods above it would look like this in the `/docs`: You can of course also pass multiple `examples`: -//// tab | Python 3.10+ - -```Python hl_lines="23-38" -{!> ../../docs_src/schema_extra_example/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="23-38" -{!> ../../docs_src/schema_extra_example/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24-39" -{!> ../../docs_src/schema_extra_example/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="19-34" -{!> ../../docs_src/schema_extra_example/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="21-36" -{!> ../../docs_src/schema_extra_example/tutorial004.py!} -``` - -//// +{* ../../docs_src/schema_extra_example/tutorial004_an_py310.py hl[23:38] *} When you do this, the examples will be part of the internal **JSON Schema** for that body data. @@ -267,57 +133,7 @@ Each specific example `dict` in the `examples` can contain: You can use it like this: -//// tab | Python 3.10+ - -```Python hl_lines="23-49" -{!> ../../docs_src/schema_extra_example/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="23-49" -{!> ../../docs_src/schema_extra_example/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24-50" -{!> ../../docs_src/schema_extra_example/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="19-45" -{!> ../../docs_src/schema_extra_example/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="21-47" -{!> ../../docs_src/schema_extra_example/tutorial005.py!} -``` - -//// +{* ../../docs_src/schema_extra_example/tutorial005_an_py310.py hl[23:49] *} ### OpenAPI Examples in the Docs UI diff --git a/docs/en/docs/tutorial/security/first-steps.md b/docs/en/docs/tutorial/security/first-steps.md index ead2aa799224f..8f6578e12b067 100644 --- a/docs/en/docs/tutorial/security/first-steps.md +++ b/docs/en/docs/tutorial/security/first-steps.md @@ -20,35 +20,7 @@ Let's first just use the code and see how it works, and then we'll come back to Copy the example in a file `main.py`: -//// tab | Python 3.9+ - -```Python -{!> ../../docs_src/security/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python -{!> ../../docs_src/security/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python -{!> ../../docs_src/security/tutorial001.py!} -``` - -//// +{* ../../docs_src/security/tutorial001_an_py39.py *} ## Run it @@ -88,7 +60,7 @@ You will see something like this: -/// check | "Authorize button!" +/// check | Authorize button! You already have a shiny new "Authorize" button. @@ -160,35 +132,7 @@ In that case, **FastAPI** also provides you with the tools to build it. When we create an instance of the `OAuth2PasswordBearer` class we pass in the `tokenUrl` parameter. This parameter contains the URL that the client (the frontend running in the user's browser) will use to send the `username` and `password` in order to get a token. -//// tab | Python 3.9+ - -```Python hl_lines="8" -{!> ../../docs_src/security/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="7" -{!> ../../docs_src/security/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="6" -{!> ../../docs_src/security/tutorial001.py!} -``` - -//// +{* ../../docs_src/security/tutorial001_an_py39.py hl[8] *} /// tip @@ -226,41 +170,13 @@ So, it can be used with `Depends`. Now you can pass that `oauth2_scheme` in a dependency with `Depends`. -//// tab | Python 3.9+ - -```Python hl_lines="12" -{!> ../../docs_src/security/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/security/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/security/tutorial001.py!} -``` - -//// +{* ../../docs_src/security/tutorial001_an_py39.py hl[12] *} This dependency will provide a `str` that is assigned to the parameter `token` of the *path operation function*. **FastAPI** will know that it can use this dependency to define a "security scheme" in the OpenAPI schema (and the automatic API docs). -/// info | "Technical Details" +/// info | Technical Details **FastAPI** will know that it can use the class `OAuth2PasswordBearer` (declared in a dependency) to define the security scheme in OpenAPI because it inherits from `fastapi.security.oauth2.OAuth2`, which in turn inherits from `fastapi.security.base.SecurityBase`. diff --git a/docs/en/docs/tutorial/security/get-current-user.md b/docs/en/docs/tutorial/security/get-current-user.md index 0698066216af2..5de3a8e7df133 100644 --- a/docs/en/docs/tutorial/security/get-current-user.md +++ b/docs/en/docs/tutorial/security/get-current-user.md @@ -2,35 +2,7 @@ In the previous chapter the security system (which is based on the dependency injection system) was giving the *path operation function* a `token` as a `str`: -//// tab | Python 3.9+ - -```Python hl_lines="12" -{!> ../../docs_src/security/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/security/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/security/tutorial001.py!} -``` - -//// +{* ../../docs_src/security/tutorial001_an_py39.py hl[12] *} But that is still not that useful. @@ -42,57 +14,7 @@ First, let's create a Pydantic user model. The same way we use Pydantic to declare bodies, we can use it anywhere else: -//// tab | Python 3.10+ - -```Python hl_lines="5 12-16" -{!> ../../docs_src/security/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="5 12-16" -{!> ../../docs_src/security/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="5 13-17" -{!> ../../docs_src/security/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="3 10-14" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="5 12-16" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// +{* ../../docs_src/security/tutorial002_an_py310.py hl[5,12:6] *} ## Create a `get_current_user` dependency @@ -104,169 +26,19 @@ Remember that dependencies can have sub-dependencies? The same as we were doing before in the *path operation* directly, our new dependency `get_current_user` will receive a `token` as a `str` from the sub-dependency `oauth2_scheme`: -//// tab | Python 3.10+ - -```Python hl_lines="25" -{!> ../../docs_src/security/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="25" -{!> ../../docs_src/security/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="26" -{!> ../../docs_src/security/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="23" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="25" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// +{* ../../docs_src/security/tutorial002_an_py310.py hl[25] *} ## Get the user `get_current_user` will use a (fake) utility function we created, that takes a token as a `str` and returns our Pydantic `User` model: -//// tab | Python 3.10+ - -```Python hl_lines="19-22 26-27" -{!> ../../docs_src/security/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="19-22 26-27" -{!> ../../docs_src/security/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20-23 27-28" -{!> ../../docs_src/security/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="17-20 24-25" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="19-22 26-27" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// +{* ../../docs_src/security/tutorial002_an_py310.py hl[19:22,26:27] *} ## Inject the current user So now we can use the same `Depends` with our `get_current_user` in the *path operation*: -//// tab | Python 3.10+ - -```Python hl_lines="31" -{!> ../../docs_src/security/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="31" -{!> ../../docs_src/security/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="32" -{!> ../../docs_src/security/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="29" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="31" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// +{* ../../docs_src/security/tutorial002_an_py310.py hl[31] *} Notice that we declare the type of `current_user` as the Pydantic model `User`. @@ -320,57 +92,7 @@ And all of them (or any portion of them that you want) can take advantage of re- And all these thousands of *path operations* can be as small as 3 lines: -//// tab | Python 3.10+ - -```Python hl_lines="30-32" -{!> ../../docs_src/security/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="30-32" -{!> ../../docs_src/security/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="31-33" -{!> ../../docs_src/security/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="28-30" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="30-32" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// +{* ../../docs_src/security/tutorial002_an_py310.py hl[30:32] *} ## Recap diff --git a/docs/en/docs/tutorial/security/oauth2-jwt.md b/docs/en/docs/tutorial/security/oauth2-jwt.md index 6ae1507dcbb5e..8644db45c20b1 100644 --- a/docs/en/docs/tutorial/security/oauth2-jwt.md +++ b/docs/en/docs/tutorial/security/oauth2-jwt.md @@ -116,57 +116,7 @@ And another utility to verify if a received password matches the hash stored. And another one to authenticate and return a user. -//// tab | Python 3.10+ - -```Python hl_lines="8 49 56-57 60-61 70-76" -{!> ../../docs_src/security/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="8 49 56-57 60-61 70-76" -{!> ../../docs_src/security/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8 50 57-58 61-62 71-77" -{!> ../../docs_src/security/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7 48 55-56 59-60 69-75" -{!> ../../docs_src/security/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="8 49 56-57 60-61 70-76" -{!> ../../docs_src/security/tutorial004.py!} -``` - -//// +{* ../../docs_src/security/tutorial004_an_py310.py hl[8,49,56:57,60:61,70:76] *} /// note @@ -202,57 +152,7 @@ Define a Pydantic Model that will be used in the token endpoint for the response Create a utility function to generate a new access token. -//// tab | Python 3.10+ - -```Python hl_lines="4 7 13-15 29-31 79-87" -{!> ../../docs_src/security/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="4 7 13-15 29-31 79-87" -{!> ../../docs_src/security/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4 7 14-16 30-32 80-88" -{!> ../../docs_src/security/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="3 6 12-14 28-30 78-86" -{!> ../../docs_src/security/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="4 7 13-15 29-31 79-87" -{!> ../../docs_src/security/tutorial004.py!} -``` - -//// +{* ../../docs_src/security/tutorial004_an_py310.py hl[4,7,13:15,29:31,79:87] *} ## Update the dependencies @@ -262,57 +162,7 @@ Decode the received token, verify it, and return the current user. If the token is invalid, return an HTTP error right away. -//// tab | Python 3.10+ - -```Python hl_lines="90-107" -{!> ../../docs_src/security/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="90-107" -{!> ../../docs_src/security/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="91-108" -{!> ../../docs_src/security/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="89-106" -{!> ../../docs_src/security/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="90-107" -{!> ../../docs_src/security/tutorial004.py!} -``` - -//// +{* ../../docs_src/security/tutorial004_an_py310.py hl[90:107] *} ## Update the `/token` *path operation* @@ -320,57 +170,7 @@ Create a `timedelta` with the expiration time of the token. Create a real JWT access token and return it. -//// tab | Python 3.10+ - -```Python hl_lines="118-133" -{!> ../../docs_src/security/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="118-133" -{!> ../../docs_src/security/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="119-134" -{!> ../../docs_src/security/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="115-130" -{!> ../../docs_src/security/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="116-131" -{!> ../../docs_src/security/tutorial004.py!} -``` - -//// +{* ../../docs_src/security/tutorial004_an_py310.py hl[118:133] *} ### Technical details about the JWT "subject" `sub` diff --git a/docs/en/docs/tutorial/security/simple-oauth2.md b/docs/en/docs/tutorial/security/simple-oauth2.md index dc15bef204db5..1b70aa8111ec0 100644 --- a/docs/en/docs/tutorial/security/simple-oauth2.md +++ b/docs/en/docs/tutorial/security/simple-oauth2.md @@ -52,57 +52,7 @@ Now let's use the utilities provided by **FastAPI** to handle this. First, import `OAuth2PasswordRequestForm`, and use it as a dependency with `Depends` in the *path operation* for `/token`: -//// tab | Python 3.10+ - -```Python hl_lines="4 78" -{!> ../../docs_src/security/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="4 78" -{!> ../../docs_src/security/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4 79" -{!> ../../docs_src/security/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="2 74" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="4 76" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// +{* ../../docs_src/security/tutorial003_an_py310.py hl[4,78] *} `OAuth2PasswordRequestForm` is a class dependency that declares a form body with: @@ -150,57 +100,7 @@ If there is no such user, we return an error saying "Incorrect username or passw For the error, we use the exception `HTTPException`: -//// tab | Python 3.10+ - -```Python hl_lines="3 79-81" -{!> ../../docs_src/security/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="3 79-81" -{!> ../../docs_src/security/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3 80-82" -{!> ../../docs_src/security/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="1 75-77" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="3 77-79" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// +{* ../../docs_src/security/tutorial003_an_py310.py hl[3,79:81] *} ### Check the password @@ -226,57 +126,7 @@ If your database is stolen, the thief won't have your users' plaintext passwords So, the thief won't be able to try to use those same passwords in another system (as many users use the same password everywhere, this would be dangerous). -//// tab | Python 3.10+ - -```Python hl_lines="82-85" -{!> ../../docs_src/security/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="82-85" -{!> ../../docs_src/security/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="83-86" -{!> ../../docs_src/security/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="78-81" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="80-83" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// +{* ../../docs_src/security/tutorial003_an_py310.py hl[82:85] *} #### About `**user_dict` @@ -318,57 +168,7 @@ But for now, let's focus on the specific details we need. /// -//// tab | Python 3.10+ - -```Python hl_lines="87" -{!> ../../docs_src/security/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="87" -{!> ../../docs_src/security/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="88" -{!> ../../docs_src/security/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="83" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="85" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// +{* ../../docs_src/security/tutorial003_an_py310.py hl[87] *} /// tip @@ -394,57 +194,7 @@ Both of these dependencies will just return an HTTP error if the user doesn't ex So, in our endpoint, we will only get a user if the user exists, was correctly authenticated, and is active: -//// tab | Python 3.10+ - -```Python hl_lines="58-66 69-74 94" -{!> ../../docs_src/security/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="58-66 69-74 94" -{!> ../../docs_src/security/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="59-67 70-75 95" -{!> ../../docs_src/security/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="56-64 67-70 88" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="58-66 69-72 90" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// +{* ../../docs_src/security/tutorial003_an_py310.py hl[58:66,69:74,94] *} /// info diff --git a/docs/en/docs/tutorial/static-files.md b/docs/en/docs/tutorial/static-files.md index 46affd4f2f97a..1d277a51cb312 100644 --- a/docs/en/docs/tutorial/static-files.md +++ b/docs/en/docs/tutorial/static-files.md @@ -9,7 +9,7 @@ You can serve static files automatically from a directory using `StaticFiles`. {* ../../docs_src/static_files/tutorial001.py hl[2,6] *} -/// note | "Technical Details" +/// note | Technical Details You could also use `from starlette.staticfiles import StaticFiles`. diff --git a/docs/en/docs/tutorial/testing.md b/docs/en/docs/tutorial/testing.md index 7f609a5958964..35940d9204959 100644 --- a/docs/en/docs/tutorial/testing.md +++ b/docs/en/docs/tutorial/testing.md @@ -30,9 +30,7 @@ Use the `TestClient` object the same way as you do with `httpx`. Write simple `assert` statements with the standard Python expressions that you need to check (again, standard `pytest`). -```Python hl_lines="2 12 15-18" -{!../../docs_src/app_testing/tutorial001.py!} -``` +{* ../../docs_src/app_testing/tutorial001.py hl[2,12,15:18] *} /// tip @@ -44,7 +42,7 @@ This allows you to use `pytest` directly without complications. /// -/// note | "Technical Details" +/// note | Technical Details You could also use `from starlette.testclient import TestClient`. @@ -78,9 +76,7 @@ Let's say you have a file structure as described in [Bigger Applications](bigger In the file `main.py` you have your **FastAPI** app: -```Python -{!../../docs_src/app_testing/main.py!} -``` +{* ../../docs_src/app_testing/main.py *} ### Testing file @@ -96,9 +92,8 @@ Then you could have a file `test_main.py` with your tests. It could live on the Because this file is in the same package, you can use relative imports to import the object `app` from the `main` module (`main.py`): -```Python hl_lines="3" -{!../../docs_src/app_testing/test_main.py!} -``` +{* ../../docs_src/app_testing/test_main.py hl[3] *} + ...and have the code for the tests just like before. @@ -182,9 +177,8 @@ Prefer to use the `Annotated` version if possible. You could then update `test_main.py` with the extended tests: -```Python -{!> ../../docs_src/app_testing/app_b/test_main.py!} -``` +{* ../../docs_src/app_testing/app_b/test_main.py *} + Whenever you need the client to pass information in the request and you don't know how to, you can search (Google) how to do it in `httpx`, or even how to do it with `requests`, as HTTPX's design is based on Requests' design. diff --git a/docs/en/overrides/main.html b/docs/en/overrides/main.html index 462907e7c8541..70a05831f60c8 100644 --- a/docs/en/overrides/main.html +++ b/docs/en/overrides/main.html @@ -82,6 +82,12 @@ + {% endblock %} diff --git a/docs/es/docs/advanced/additional-status-codes.md b/docs/es/docs/advanced/additional-status-codes.md index 4a0625c255119..b72798c2b35a1 100644 --- a/docs/es/docs/advanced/additional-status-codes.md +++ b/docs/es/docs/advanced/additional-status-codes.md @@ -14,9 +14,7 @@ Pero también quieres que acepte nuevos ítems. Cuando los ítems no existan ant Para conseguir esto importa `JSONResponse` y devuelve ahí directamente tu contenido, asignando el `status_code` que quieras: -```Python hl_lines="4 25" -{!../../docs_src/additional_status_codes/tutorial001.py!} -``` +{* ../../docs_src/additional_status_codes/tutorial001.py hl[4,25] *} /// warning | Advertencia diff --git a/docs/es/docs/advanced/path-operation-advanced-configuration.md b/docs/es/docs/advanced/path-operation-advanced-configuration.md index f6813f0ff5fb7..600e2e0747141 100644 --- a/docs/es/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/es/docs/advanced/path-operation-advanced-configuration.md @@ -2,7 +2,7 @@ ## OpenAPI operationId -/// warning | "Advertencia" +/// warning | Advertencia Si no eres una persona "experta" en OpenAPI, probablemente no necesitas leer esto. @@ -12,9 +12,7 @@ Puedes asignar el `operationId` de OpenAPI para ser usado en tu *operación de p En este caso tendrías que asegurarte de que sea único para cada operación. -```Python hl_lines="6" -{!../../docs_src/path_operation_advanced_configuration/tutorial001.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial001.py hl[6] *} ### Usando el nombre de la *función de la operación de path* en el operationId @@ -22,9 +20,7 @@ Si quieres usar tus nombres de funciones de API como `operationId`s, puedes iter Deberías hacerlo después de adicionar todas tus *operaciones de path*. -```Python hl_lines="2 12 13 14 15 16 17 18 19 20 21 24" -{!../../docs_src/path_operation_advanced_configuration/tutorial002.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial002.py hl[2,12,13,14,15,16,17,18,19,20,21,24] *} /// tip | Consejo @@ -44,9 +40,7 @@ Incluso si están en diferentes módulos (archivos Python). Para excluir una *operación de path* del esquema OpenAPI generado (y por tanto del la documentación generada automáticamente), usa el parámetro `include_in_schema` y asigna el valor como `False`; -```Python hl_lines="6" -{!../../docs_src/path_operation_advanced_configuration/tutorial003.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial003.py hl[6] *} ## Descripción avanzada desde el docstring @@ -56,6 +50,4 @@ Agregar un `\f` (un carácter de "form feed" escapado) hace que **FastAPI** trun No será mostrado en la documentación, pero otras herramientas (como Sphinx) serán capaces de usar el resto. -```Python hl_lines="19 20 21 22 23 24 25 26 27 28 29" -{!../../docs_src/path_operation_advanced_configuration/tutorial004.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial004.py hl[19,20,21,22,23,24,25,26,27,28,29] *} diff --git a/docs/es/docs/advanced/response-change-status-code.md b/docs/es/docs/advanced/response-change-status-code.md index ddfd05a77fdbf..6a44ea94eeb28 100644 --- a/docs/es/docs/advanced/response-change-status-code.md +++ b/docs/es/docs/advanced/response-change-status-code.md @@ -20,9 +20,7 @@ Puedes declarar un parámetro de tipo `Response` en tu *función de la operació Y luego puedes establecer el `status_code` en ese objeto de respuesta *temporal*. -```Python hl_lines="1 9 12" -{!../../docs_src/response_change_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_change_status_code/tutorial001.py hl[1,9,12] *} Y luego puedes retornar cualquier objeto que necesites, como normalmente lo harías (un `dict`, un modelo de base de datos, etc). diff --git a/docs/es/docs/advanced/response-directly.md b/docs/es/docs/advanced/response-directly.md index 8800d25108f5e..3cab11d99d8f0 100644 --- a/docs/es/docs/advanced/response-directly.md +++ b/docs/es/docs/advanced/response-directly.md @@ -34,9 +34,7 @@ Por ejemplo, no puedes poner un modelo Pydantic en una `JSONResponse` sin primer Para esos casos, puedes usar el `jsonable_encoder` para convertir tus datos antes de pasarlos a la respuesta: -```Python hl_lines="4 6 20 21" -{!../../docs_src/response_directly/tutorial001.py!} -``` +{* ../../docs_src/response_directly/tutorial001.py hl[4,6,20,21] *} /// note | Detalles Técnicos @@ -56,9 +54,7 @@ Digamos que quieres devolver una respuesta documentación de Strawberry. diff --git a/docs/es/docs/python-types.md b/docs/es/docs/python-types.md index 156907ad12d48..de502314e67ea 100644 --- a/docs/es/docs/python-types.md +++ b/docs/es/docs/python-types.md @@ -22,9 +22,8 @@ Si eres un experto en Python y ya lo sabes todo sobre los type hints, salta al s Comencemos con un ejemplo simple: -```Python -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py *} + Llamar este programa nos muestra el siguiente output: @@ -38,9 +37,8 @@ La función hace lo siguiente: * Convierte la primera letra de cada uno en una letra mayúscula con `title()`. * Las concatena con un espacio en la mitad. -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py hl[2] *} + ### Edítalo @@ -82,9 +80,8 @@ Eso es todo. Esos son los "type hints": -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial002.py!} -``` +{* ../../docs_src/python_types/tutorial002.py hl[1] *} + No es lo mismo a declarar valores por defecto, como sería con: @@ -112,9 +109,8 @@ Con esto puedes moverte hacia abajo viendo las opciones hasta que encuentras una Mira esta función que ya tiene type hints: -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial003.py!} -``` +{* ../../docs_src/python_types/tutorial003.py hl[1] *} + Como el editor conoce el tipo de las variables no solo obtienes auto-completado, si no que también obtienes chequeo de errores: @@ -122,9 +118,8 @@ Como el editor conoce el tipo de las variables no solo obtienes auto-completado, Ahora que sabes que tienes que arreglarlo convierte `age` a un string con `str(age)`: -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial004.py!} -``` +{* ../../docs_src/python_types/tutorial004.py hl[2] *} + ## Declarando tipos @@ -143,9 +138,8 @@ Por ejemplo, puedes usar: * `bool` * `bytes` -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial005.py!} -``` +{* ../../docs_src/python_types/tutorial005.py hl[1] *} + ### Tipos con sub-tipos @@ -161,9 +155,8 @@ Por ejemplo, vamos a definir una variable para que sea una `list` compuesta de ` De `typing`, importa `List` (con una `L` mayúscula): -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial006.py!} -``` +{* ../../docs_src/python_types/tutorial006.py hl[1] *} + Declara la variable con la misma sintaxis de los dos puntos (`:`). @@ -171,9 +164,8 @@ Pon `List` como el tipo. Como la lista es un tipo que permite tener un "sub-tipo" pones el sub-tipo en corchetes `[]`: -```Python hl_lines="4" -{!../../docs_src/python_types/tutorial006.py!} -``` +{* ../../docs_src/python_types/tutorial006.py hl[4] *} + Esto significa: la variable `items` es una `list` y cada uno de los ítems en esta lista es un `str`. @@ -191,9 +183,8 @@ El editor aún sabe que es un `str` y provee soporte para ello. Harías lo mismo para declarar `tuple`s y `set`s: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial007.py!} -``` +{* ../../docs_src/python_types/tutorial007.py hl[1,4] *} + Esto significa: @@ -208,9 +199,8 @@ El primer sub-tipo es para los keys del `dict`. El segundo sub-tipo es para los valores del `dict`: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial008.py!} -``` +{* ../../docs_src/python_types/tutorial008.py hl[1,4] *} + Esto significa: @@ -224,15 +214,13 @@ También puedes declarar una clase como el tipo de una variable. Digamos que tienes una clase `Person`con un nombre: -```Python hl_lines="1-3" -{!../../docs_src/python_types/tutorial009.py!} -``` +{* ../../docs_src/python_types/tutorial009.py hl[1:3] *} + Entonces puedes declarar una variable que sea de tipo `Person`: -```Python hl_lines="6" -{!../../docs_src/python_types/tutorial009.py!} -``` +{* ../../docs_src/python_types/tutorial009.py hl[6] *} + Una vez más tendrás todo el soporte del editor: @@ -252,9 +240,8 @@ Y obtienes todo el soporte del editor con el objeto resultante. Tomado de la documentación oficial de Pydantic: -```Python -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py *} + /// info | Información diff --git a/docs/es/docs/tutorial/cookie-params.md b/docs/es/docs/tutorial/cookie-params.md index e858e34e8ad08..9a3b1a00bef51 100644 --- a/docs/es/docs/tutorial/cookie-params.md +++ b/docs/es/docs/tutorial/cookie-params.md @@ -6,57 +6,7 @@ Puedes definir parámetros de Cookie de la misma manera que defines parámetros Primero importa `Cookie`: -//// tab | Python 3.10+ - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Consejo - -Es preferible utilizar la versión `Annotated` si es posible. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/cookie_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Consejo - -Es preferible utilizar la versión `Annotated` si es posible. - -/// - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[3]*} ## Declarar parámetros de `Cookie` @@ -64,59 +14,9 @@ Luego declara los parámetros de cookie usando la misma estructura que con `Path El primer valor es el valor por defecto, puedes pasar todos los parámetros adicionales de validación o anotación: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/cookie_params/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Consejo - -Es preferible utilizar la versión `Annotated` si es posible. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/cookie_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Consejo - -Es preferible utilizar la versión `Annotated` si es posible. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[9]*} -/// note | "Detalles Técnicos" +/// note | Detalles Técnicos `Cookie` es una clase "hermana" de `Path` y `Query`. También hereda de la misma clase común `Param`. diff --git a/docs/es/docs/tutorial/first-steps.md b/docs/es/docs/tutorial/first-steps.md index 68df00e64e72f..4cc4cc11dccda 100644 --- a/docs/es/docs/tutorial/first-steps.md +++ b/docs/es/docs/tutorial/first-steps.md @@ -2,9 +2,7 @@ Un archivo muy simple de FastAPI podría verse así: -```Python -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py *} Copia eso a un archivo `main.py`. @@ -133,9 +131,7 @@ También podrías usarlo para generar código automáticamente, para los cliente ### Paso 1: importa `FastAPI` -```Python hl_lines="1" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[1] *} `FastAPI` es una clase de Python que provee toda la funcionalidad para tu API. @@ -149,9 +145,7 @@ También puedes usar toda la funcionalidad de Objets d'opération. @@ -86,7 +78,7 @@ Il inclut les `tags`, `parameters`, `requestBody`, `responses`, etc. Ce schéma OpenAPI spécifique aux *operations* est normalement généré automatiquement par **FastAPI**, mais vous pouvez également l'étendre. -/// tip | "Astuce" +/// tip | Astuce Si vous avez seulement besoin de déclarer des réponses supplémentaires, un moyen plus pratique de le faire est d'utiliser les [réponses supplémentaires dans OpenAPI](additional-responses.md){.internal-link target=_blank}. @@ -98,9 +90,7 @@ Vous pouvez étendre le schéma OpenAPI pour une *opération de chemin* en utili Cet `openapi_extra` peut être utile, par exemple, pour déclarer [OpenAPI Extensions](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions) : -```Python hl_lines="6" -{!../../docs_src/path_operation_advanced_configuration/tutorial005.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial005.py hl[6] *} Si vous ouvrez la documentation automatique de l'API, votre extension apparaîtra au bas du *chemin* spécifique. @@ -147,9 +137,7 @@ Par exemple, vous pouvez décider de lire et de valider la requête avec votre p Vous pouvez le faire avec `openapi_extra` : -```Python hl_lines="20-37 39-40" -{!../../docs_src/path_operation_advanced_configuration/tutorial006.py !} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial006.py hl[20:37,39:40] *} Dans cet exemple, nous n'avons déclaré aucun modèle Pydantic. En fait, le corps de la requête n'est même pas parsé en tant que JSON, il est lu directement en tant que `bytes`, et la fonction `magic_data_reader()` serait chargé de l'analyser d'une manière ou d'une autre. @@ -163,9 +151,7 @@ Et vous pouvez le faire même si le type de données dans la requête n'est pas Dans cet exemple, nous n'utilisons pas les fonctionnalités de FastAPI pour extraire le schéma JSON des modèles Pydantic ni la validation automatique pour JSON. En fait, nous déclarons le type de contenu de la requête en tant que YAML, et non JSON : -```Python hl_lines="17-22 24" -{!../../docs_src/path_operation_advanced_configuration/tutorial007.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[17:22,24] *} Néanmoins, bien que nous n'utilisions pas la fonctionnalité par défaut, nous utilisons toujours un modèle Pydantic pour générer manuellement le schéma JSON pour les données que nous souhaitons recevoir en YAML. @@ -173,11 +159,9 @@ 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" +/// tip | Astuce Ici, nous réutilisons le même modèle Pydantic. diff --git a/docs/fr/docs/advanced/response-directly.md b/docs/fr/docs/advanced/response-directly.md index 80876bc18b03c..4ff883c770706 100644 --- a/docs/fr/docs/advanced/response-directly.md +++ b/docs/fr/docs/advanced/response-directly.md @@ -14,7 +14,7 @@ Cela peut être utile, par exemple, pour retourner des en-têtes personnalisés En fait, vous pouvez retourner n'importe quelle `Response` ou n'importe quelle sous-classe de celle-ci. -/// note | "Remarque" +/// note | Remarque `JSONResponse` est elle-même une sous-classe de `Response`. @@ -34,11 +34,9 @@ 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" +/// note | Détails techniques Vous pouvez aussi utiliser `from starlette.responses import JSONResponse`. @@ -56,9 +54,7 @@ Disons que vous voulez retourner une réponse schéma
, vous devez utiliser des utilitaires et des classes spécifiques fournies par Marshmallow. -/// check | "A inspiré **FastAPI** à" +/// check | A inspiré **FastAPI** à Utilisez du code pour définir des "schémas" qui fournissent automatiquement les types de données et la validation. @@ -189,7 +189,7 @@ Webargs a été créé par les développeurs de Marshmallow. /// -/// check | "A inspiré **FastAPI** à" +/// check | A inspiré **FastAPI** à Disposer d'une validation automatique des données des requêtes entrantes. @@ -219,7 +219,7 @@ APISpec a été créé par les développeurs de Marshmallow. /// -/// check | "A inspiré **FastAPI** à" +/// check | A inspiré **FastAPI** à Supporter la norme ouverte pour les API, OpenAPI. @@ -252,7 +252,7 @@ Flask-apispec a été créé par les développeurs de Marshmallow. /// -/// check | "A inspiré **FastAPI** à" +/// check | A inspiré **FastAPI** à Générer le schéma OpenAPI automatiquement, à partir du même code qui définit la sérialisation et la validation. @@ -273,7 +273,7 @@ Mais comme les données TypeScript ne sont pas préservées après la compilatio Il ne peut pas très bien gérer les modèles imbriqués. Ainsi, si le corps JSON de la requête est un objet JSON comportant des champs internes qui sont à leur tour des objets JSON imbriqués, il ne peut pas être correctement documenté et validé. -/// check | "A inspiré **FastAPI** à" +/// check | A inspiré **FastAPI** à Utiliser les types Python pour bénéficier d'un excellent support de l'éditeur. @@ -285,7 +285,7 @@ Disposer d'un puissant système d'injection de dépendances. Trouver un moyen de C'était l'un des premiers frameworks Python extrêmement rapides basés sur `asyncio`. Il a été conçu pour être très similaire à Flask. -/// note | "Détails techniques" +/// note | Détails techniques Il utilisait `uvloop` au lieu du système par défaut de Python `asyncio`. C'est ce qui l'a rendu si rapide. @@ -293,7 +293,7 @@ Il a clairement inspiré Uvicorn et Starlette, qui sont actuellement plus rapide /// -/// check | "A inspiré **FastAPI** à" +/// check | A inspiré **FastAPI** à Trouvez un moyen d'avoir une performance folle. @@ -313,7 +313,7 @@ pas possible de déclarer des paramètres de requête et des corps avec des indi Ainsi, la validation, la sérialisation et la documentation des données doivent être effectuées dans le code, et non pas automatiquement. Ou bien elles doivent être implémentées comme un framework au-dessus de Falcon, comme Hug. Cette même distinction se retrouve dans d'autres frameworks qui s'inspirent de la conception de Falcon, qui consiste à avoir un objet de requête et un objet de réponse comme paramètres. -/// check | "A inspiré **FastAPI** à" +/// check | A inspiré **FastAPI** à Trouver des moyens d'obtenir de bonnes performances. @@ -343,7 +343,7 @@ d'utiliser des décorateurs qui peuvent être placés juste au-dessus de la fonc méthode est plus proche de celle de Django que de celle de Flask (et Starlette). Il sépare dans le code des choses qui sont relativement fortement couplées. -/// check | "A inspiré **FastAPI** à" +/// check | A inspiré **FastAPI** à Définir des validations supplémentaires pour les types de données utilisant la valeur "par défaut" des attributs du modèle. Ceci améliore le support de l'éditeur, et n'était pas disponible dans Pydantic auparavant. @@ -372,7 +372,7 @@ Hug a été créé par Timothy Crosley, le créateur de - -```console -$ python -m venv env -``` - - - -Cela va créer un répertoire `./env/` avec les binaires Python et vous pourrez alors installer des paquets pour cet environnement isolé. - -### Activer l'environnement - -Activez le nouvel environnement avec : - -//// tab | Linux, macOS - -
- -```console -$ source ./env/bin/activate -``` - -
- -//// - -//// tab | Windows PowerShell - -
- -```console -$ .\env\Scripts\Activate.ps1 -``` - -
- -//// - -//// tab | Windows Bash - -Ou si vous utilisez Bash pour Windows (par exemple
Git Bash): - -
- -```console -$ source ./env/Scripts/activate -``` - -
- -//// - -Pour vérifier que cela a fonctionné, utilisez : - -//// tab | Linux, macOS, Windows Bash - -
- -```console -$ which pip - -some/directory/fastapi/env/bin/pip -``` - -
- -//// - -//// tab | Windows PowerShell - -
- -```console -$ Get-Command pip - -some/directory/fastapi/env/bin/pip -``` - -
- -//// - -Si celui-ci montre le binaire `pip` à `env/bin/pip`, alors ça a fonctionné. 🎉 - - - -/// tip - -Chaque fois que vous installez un nouveau paquet avec `pip` sous cet environnement, activez à nouveau l'environnement. - -Cela permet de s'assurer que si vous utilisez un programme terminal installé par ce paquet (comme `flit`), vous utilisez celui de votre environnement local et pas un autre qui pourrait être installé globalement. - -/// - -### Flit - -**FastAPI** utilise Flit pour build, packager et publier le projet. - -Après avoir activé l'environnement comme décrit ci-dessus, installez `flit` : - -
- -```console -$ pip install flit - ----> 100% -``` - -
- -Réactivez maintenant l'environnement pour vous assurer que vous utilisez le "flit" que vous venez d'installer (et non un environnement global). - -Et maintenant, utilisez `flit` pour installer les dépendances de développement : - -//// tab | Linux, macOS - -
- -```console -$ flit install --deps develop --symlink - ----> 100% -``` - -
- -//// - -//// tab | Windows - -Si vous êtes sous Windows, utilisez `--pth-file` au lieu de `--symlink` : - -
- -```console -$ flit install --deps develop --pth-file - ----> 100% -``` - -
- -//// - -Il installera toutes les dépendances et votre FastAPI local dans votre environnement local. - -#### Utiliser votre FastAPI local - -Si vous créez un fichier Python qui importe et utilise FastAPI, et que vous l'exécutez avec le Python de votre environnement local, il utilisera votre code source FastAPI local. - -Et si vous mettez à jour le code source local de FastAPI, tel qu'il est installé avec `--symlink` (ou `--pth-file` sous Windows), lorsque vous exécutez à nouveau ce fichier Python, il utilisera la nouvelle version de FastAPI que vous venez d'éditer. - -De cette façon, vous n'avez pas à "installer" votre version locale pour pouvoir tester chaque changement. - -### Formatage - -Il existe un script que vous pouvez exécuter qui formatera et nettoiera tout votre code : - -
- -```console -$ bash scripts/format.sh -``` - -
- -Il effectuera également un tri automatique de touts vos imports. - -Pour qu'il puisse les trier correctement, vous devez avoir FastAPI installé localement dans votre environnement, avec la commande dans la section ci-dessus en utilisant `--symlink` (ou `--pth-file` sous Windows). - -### Formatage des imports - -Il existe un autre script qui permet de formater touts les imports et de s'assurer que vous n'avez pas d'imports inutilisés : - -
- -```console -$ bash scripts/format-imports.sh -``` - -
- -Comme il exécute une commande après l'autre et modifie et inverse de nombreux fichiers, il prend un peu plus de temps à s'exécuter, il pourrait donc être plus facile d'utiliser fréquemment `scripts/format.sh` et `scripts/format-imports.sh` seulement avant de commit. - -## Documentation - -Tout d'abord, assurez-vous que vous configurez votre environnement comme décrit ci-dessus, qui installera toutes les exigences. - -La documentation utilise MkDocs. - -Et il y a des outils/scripts supplémentaires en place pour gérer les traductions dans `./scripts/docs.py`. - -/// tip - -Vous n'avez pas besoin de voir le code dans `./scripts/docs.py`, vous l'utilisez simplement dans la ligne de commande. - -/// - -Toute la documentation est au format Markdown dans le répertoire `./docs/fr/`. - -De nombreux tutoriels comportent des blocs de code. - -Dans la plupart des cas, ces blocs de code sont de véritables applications complètes qui peuvent être exécutées telles quelles. - -En fait, ces blocs de code ne sont pas écrits à l'intérieur du Markdown, ce sont des fichiers Python dans le répertoire `./docs_src/`. - -Et ces fichiers Python sont inclus/injectés dans la documentation lors de la génération du site. - -### Documentation pour les tests - -La plupart des tests sont en fait effectués par rapport aux exemples de fichiers sources dans la documentation. - -Cela permet de s'assurer que : - -* La documentation est à jour. -* Les exemples de documentation peuvent être exécutés tels quels. -* La plupart des fonctionnalités sont couvertes par la documentation, assurées par la couverture des tests. - -Au cours du développement local, un script build le site et vérifie les changements éventuels, puis il est rechargé en direct : - -
- -```console -$ python ./scripts/docs.py live - -[INFO] Serving on http://127.0.0.1:8008 -[INFO] Start watching changes -[INFO] Start detecting changes -``` - -
- -Il servira la documentation sur `http://127.0.0.1:8008`. - -De cette façon, vous pouvez modifier la documentation/les fichiers sources et voir les changements en direct. - -#### Typer CLI (facultatif) - -Les instructions ici vous montrent comment utiliser le script à `./scripts/docs.py` avec le programme `python` directement. - -Mais vous pouvez également utiliser Typer CLI, et vous obtiendrez l'auto-complétion dans votre terminal pour les commandes après l'achèvement de l'installation. - -Si vous installez Typer CLI, vous pouvez installer la complétion avec : - -
- -```console -$ typer --install-completion - -zsh completion installed in /home/user/.bashrc. -Completion will take effect once you restart the terminal. -``` - -
- -### Apps et documentation en même temps - -Si vous exécutez les exemples avec, par exemple : - -
- -```console -$ uvicorn tutorial001:app --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -
- -Comme Uvicorn utilisera par défaut le port `8000`, la documentation sur le port `8008` n'entrera pas en conflit. - -### Traductions - -L'aide aux traductions est TRÈS appréciée ! Et cela ne peut se faire sans l'aide de la communauté. 🌎 🚀 - -Voici les étapes à suivre pour aider à la traduction. - -#### Conseils et lignes directrices - -* Vérifiez les pull requests existantes pour votre langue et ajouter des reviews demandant des changements ou les approuvant. - -/// tip - -Vous pouvez ajouter des commentaires avec des suggestions de changement aux pull requests existantes. - -Consultez les documents concernant l'ajout d'un review de pull request pour l'approuver ou demander des modifications. - -/// - -* Vérifiez dans issues pour voir s'il y a une personne qui coordonne les traductions pour votre langue. - -* Ajoutez une seule pull request par page traduite. Il sera ainsi beaucoup plus facile pour les autres de l'examiner. - -Pour les langues que je ne parle pas, je vais attendre plusieurs autres reviews de la traduction avant de merge. - -* Vous pouvez également vérifier s'il existe des traductions pour votre langue et y ajouter une review, ce qui m'aidera à savoir si la traduction est correcte et je pourrai la fusionner. - -* Utilisez les mêmes exemples en Python et ne traduisez que le texte des documents. Vous n'avez pas besoin de changer quoi que ce soit pour que cela fonctionne. - -* Utilisez les mêmes images, noms de fichiers et liens. Vous n'avez pas besoin de changer quoi que ce soit pour que cela fonctionne. - -* Pour vérifier le code à 2 lettres de la langue que vous souhaitez traduire, vous pouvez utiliser le tableau Liste des codes ISO 639-1. - -#### Langue existante - -Disons que vous voulez traduire une page pour une langue qui a déjà des traductions pour certaines pages, comme l'espagnol. - -Dans le cas de l'espagnol, le code à deux lettres est `es`. Ainsi, le répertoire des traductions espagnoles se trouve à l'adresse `docs/es/`. - -/// tip - -La langue principale ("officielle") est l'anglais, qui se trouve à l'adresse "docs/en/". - -/// - -Maintenant, lancez le serveur en live pour les documents en espagnol : - -
- -```console -// Use the command "live" and pass the language code as a CLI argument -$ python ./scripts/docs.py live es - -[INFO] Serving on http://127.0.0.1:8008 -[INFO] Start watching changes -[INFO] Start detecting changes -``` - -
- -Vous pouvez maintenant aller sur http://127.0.0.1:8008 et voir vos changements en direct. - -Si vous regardez le site web FastAPI docs, vous verrez que chaque langue a toutes les pages. Mais certaines pages ne sont pas traduites et sont accompagnées d'une notification concernant la traduction manquante. - -Mais si vous le gérez localement de cette manière, vous ne verrez que les pages déjà traduites. - -Disons maintenant que vous voulez ajouter une traduction pour la section [Features](features.md){.internal-link target=_blank}. - -* Copiez le fichier à : - -``` -docs/en/docs/features.md -``` - -* Collez-le exactement au même endroit mais pour la langue que vous voulez traduire, par exemple : - -``` -docs/es/docs/features.md -``` - -/// tip - -Notez que le seul changement dans le chemin et le nom du fichier est le code de langue, qui passe de `en` à `es`. - -/// - -* Ouvrez maintenant le fichier de configuration de MkDocs pour l'anglais à - -``` -docs/en/docs/mkdocs.yml -``` - -* Trouvez l'endroit où cette `docs/features.md` se trouve dans le fichier de configuration. Quelque part comme : - -```YAML hl_lines="8" -site_name: FastAPI -# More stuff -nav: -- FastAPI: index.md -- Languages: - - en: / - - es: /es/ -- features.md -``` - -* Ouvrez le fichier de configuration MkDocs pour la langue que vous éditez, par exemple : - -``` -docs/es/docs/mkdocs.yml -``` - -* Ajoutez-le à l'endroit exact où il se trouvait pour l'anglais, par exemple : - -```YAML hl_lines="8" -site_name: FastAPI -# More stuff -nav: -- FastAPI: index.md -- Languages: - - en: / - - es: /es/ -- features.md -``` - -Assurez-vous que s'il y a d'autres entrées, la nouvelle entrée avec votre traduction est exactement dans le même ordre que dans la version anglaise. - -Si vous allez sur votre navigateur, vous verrez que maintenant les documents montrent votre nouvelle section. 🎉 - -Vous pouvez maintenant tout traduire et voir à quoi cela ressemble au fur et à mesure que vous enregistrez le fichier. - -#### Nouvelle langue - -Disons que vous voulez ajouter des traductions pour une langue qui n'est pas encore traduite, pas même quelques pages. - -Disons que vous voulez ajouter des traductions pour le Créole, et que ce n'est pas encore dans les documents. - -En vérifiant le lien ci-dessus, le code pour "Créole" est `ht`. - -L'étape suivante consiste à exécuter le script pour générer un nouveau répertoire de traduction : - -
- -```console -// Use the command new-lang, pass the language code as a CLI argument -$ python ./scripts/docs.py new-lang ht - -Successfully initialized: docs/ht -Updating ht -Updating en -``` - -
- -Vous pouvez maintenant vérifier dans votre éditeur de code le répertoire nouvellement créé `docs/ht/`. - -/// tip - -Créez une première demande d'extraction à l'aide de cette fonction, afin de configurer la nouvelle langue avant d'ajouter des traductions. - -Ainsi, d'autres personnes peuvent vous aider à rédiger d'autres pages pendant que vous travaillez sur la première. 🚀 - -/// - -Commencez par traduire la page principale, `docs/ht/index.md`. - -Vous pouvez ensuite continuer avec les instructions précédentes, pour une "langue existante". - -##### Nouvelle langue non prise en charge - -Si, lors de l'exécution du script du serveur en direct, vous obtenez une erreur indiquant que la langue n'est pas prise en charge, quelque chose comme : - -``` - raise TemplateNotFound(template) -jinja2.exceptions.TemplateNotFound: partials/language/xx.html -``` - -Cela signifie que le thème ne supporte pas cette langue (dans ce cas, avec un faux code de 2 lettres de `xx`). - -Mais ne vous inquiétez pas, vous pouvez définir la langue du thème en anglais et ensuite traduire le contenu des documents. - -Si vous avez besoin de faire cela, modifiez le fichier `mkdocs.yml` pour votre nouvelle langue, il aura quelque chose comme : - -```YAML hl_lines="5" -site_name: FastAPI -# More stuff -theme: - # More stuff - language: xx -``` - -Changez cette langue de `xx` (de votre code de langue) à `fr`. - -Vous pouvez ensuite relancer le serveur live. - -#### Prévisualisez le résultat - -Lorsque vous utilisez le script à `./scripts/docs.py` avec la commande `live`, il n'affiche que les fichiers et les traductions disponibles pour la langue courante. - -Mais une fois que vous avez terminé, vous pouvez tester le tout comme il le ferait en ligne. - -Pour ce faire, il faut d'abord construire tous les documents : - -
- -```console -// Use the command "build-all", this will take a bit -$ python ./scripts/docs.py build-all - -Updating es -Updating en -Building docs for: en -Building docs for: es -Successfully built docs for: es -Copying en index.md to README.md -``` - -
- -Cela génère tous les documents à `./docs_build/` pour chaque langue. Cela inclut l'ajout de tout fichier dont la traduction est manquante, avec une note disant que "ce fichier n'a pas encore de traduction". Mais vous n'avez rien à faire avec ce répertoire. - -Ensuite, il construit tous ces sites MkDocs indépendants pour chaque langue, les combine, et génère le résultat final à `./site/`. - -Ensuite, vous pouvez servir cela avec le commandement `serve`: - -
- -```console -// Use the command "serve" after running "build-all" -$ python ./scripts/docs.py serve - -Warning: this is a very simple server. For development, use mkdocs serve instead. -This is here only to preview a site with translations already built. -Make sure you run the build-all command first. -Serving at: http://127.0.0.1:8008 -``` - -
- -## Tests - -Il existe un script que vous pouvez exécuter localement pour tester tout le code et générer des rapports de couverture en HTML : - -
- -```console -$ bash scripts/test-cov-html.sh -``` - -
- -Cette commande génère un répertoire `./htmlcov/`, si vous ouvrez le fichier `./htmlcov/index.html` dans votre navigateur, vous pouvez explorer interactivement les régions de code qui sont couvertes par les tests, et remarquer s'il y a une région manquante. diff --git a/docs/fr/docs/deployment/docker.md b/docs/fr/docs/deployment/docker.md index 0f3b647001ea3..05b597a2df3fa 100644 --- a/docs/fr/docs/deployment/docker.md +++ b/docs/fr/docs/deployment/docker.md @@ -17,7 +17,7 @@ Cette image est dotée d'un mécanisme d'"auto-tuning", de sorte qu'il vous suff Mais vous pouvez toujours changer et mettre à jour toutes les configurations avec des variables d'environnement ou des fichiers de configuration. -/// tip | "Astuce" +/// tip | Astuce Pour voir toutes les configurations et options, rendez-vous sur la page de l'image Docker : tiangolo/uvicorn-gunicorn-fastapi. diff --git a/docs/fr/docs/deployment/manually.md b/docs/fr/docs/deployment/manually.md index 6a737fdef05be..7c29242a9f25d 100644 --- a/docs/fr/docs/deployment/manually.md +++ b/docs/fr/docs/deployment/manually.md @@ -39,7 +39,7 @@ $ pip install "uvicorn[standard]" -/// tip | "Astuce" +/// tip | Astuce En ajoutant `standard`, Uvicorn va installer et utiliser quelques dépendances supplémentaires recommandées. diff --git a/docs/fr/docs/deployment/versions.md b/docs/fr/docs/deployment/versions.md index 8ea79a1726184..9d84274e27345 100644 --- a/docs/fr/docs/deployment/versions.md +++ b/docs/fr/docs/deployment/versions.md @@ -48,7 +48,7 @@ des changements non rétrocompatibles. FastAPI suit également la convention que tout changement de version "PATCH" est pour des corrections de bogues et des changements rétrocompatibles. -/// tip | "Astuce" +/// tip | Astuce Le "PATCH" est le dernier chiffre, par exemple, dans `0.2.3`, la version PATCH est `3`. @@ -62,7 +62,7 @@ fastapi>=0.45.0,<0.46.0 Les changements non rétrocompatibles et les nouvelles fonctionnalités sont ajoutés dans les versions "MINOR". -/// tip | "Astuce" +/// tip | Astuce Le "MINOR" est le numéro au milieu, par exemple, dans `0.2.3`, la version MINOR est `2`. diff --git a/docs/fr/docs/python-types.md b/docs/fr/docs/python-types.md index 8a0f1f3f474d9..99ca908277211 100644 --- a/docs/fr/docs/python-types.md +++ b/docs/fr/docs/python-types.md @@ -161,7 +161,7 @@ Les listes étant un type contenant des types internes, mettez ces derniers entr {*../../docs_src/python_types/tutorial006.py hl[4] *} -/// tip | "Astuce" +/// tip | Astuce Ces types internes entre crochets sont appelés des "paramètres de type". diff --git a/docs/fr/docs/tutorial/background-tasks.md b/docs/fr/docs/tutorial/background-tasks.md index d971d293dc9ec..2065ca58ed58e 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 index dafd869e32d8c..0541acc74e37f 100644 --- a/docs/fr/docs/tutorial/body-multiple-params.md +++ b/docs/fr/docs/tutorial/body-multiple-params.md @@ -8,57 +8,7 @@ Tout d'abord, sachez que vous pouvez mélanger les déclarations des paramètres Vous pouvez également déclarer des paramètres body comme étant optionnels, en leur assignant une valeur par défaut à `None` : -//// tab | Python 3.10+ - -```Python hl_lines="18-20" -{!> ../../docs_src/body_multiple_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="18-20" -{!> ../../docs_src/body_multiple_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="19-21" -{!> ../../docs_src/body_multiple_params/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Préférez utiliser la version `Annotated` si possible. - -/// - -```Python hl_lines="17-19" -{!> ../../docs_src/body_multiple_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Préférez utiliser la version `Annotated` si possible. - -/// - -```Python hl_lines="19-21" -{!> ../../docs_src/body_multiple_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial001_an_py310.py hl[18:20] *} /// note @@ -81,21 +31,7 @@ Dans l'exemple précédent, les opérations de routage attendaient un body JSON Mais vous pouvez également déclarer plusieurs paramètres provenant de body, par exemple `item` et `user` simultanément : -//// tab | Python 3.10+ - -```Python hl_lines="20" -{!> ../../docs_src/body_multiple_params/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="22" -{!> ../../docs_src/body_multiple_params/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial002_py310.py hl[20] *} Dans ce cas, **FastAPI** détectera qu'il y a plus d'un paramètre dans le body (chacun correspondant à un modèle Pydantic). @@ -135,57 +71,8 @@ Par exemple, en étendant le modèle précédent, vous pouvez vouloir ajouter un Si vous le déclarez tel quel, comme c'est une valeur [scalaire](https://docs.github.com/fr/graphql/reference/scalars), **FastAPI** supposera qu'il s'agit d'un paramètre de requête (`Query`). Mais vous pouvez indiquer à **FastAPI** de la traiter comme une variable de body en utilisant `Body` : -//// tab | Python 3.10+ - -```Python hl_lines="23" -{!> ../../docs_src/body_multiple_params/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="23" -{!> ../../docs_src/body_multiple_params/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24" -{!> ../../docs_src/body_multiple_params/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Préférez utiliser la version `Annotated` si possible. - -/// - -```Python hl_lines="20" -{!> ../../docs_src/body_multiple_params/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Préférez utiliser la version `Annotated` si possible. - -/// - -```Python hl_lines="22" -{!> ../../docs_src/body_multiple_params/tutorial003.py!} -``` -//// +{* ../../docs_src/body_multiple_params/tutorial003_an_py310.py hl[23] *} Dans ce cas, **FastAPI** s'attendra à un body semblable à : @@ -225,57 +112,7 @@ q: str | None = None Par exemple : -//// tab | Python 3.10+ - -```Python hl_lines="27" -{!> ../../docs_src/body_multiple_params/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="27" -{!> ../../docs_src/body_multiple_params/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="28" -{!> ../../docs_src/body_multiple_params/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Préférez utiliser la version `Annotated` si possible. - -/// - -```Python hl_lines="25" -{!> ../../docs_src/body_multiple_params/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Préférez utiliser la version `Annotated` si possible. - -/// - -```Python hl_lines="27" -{!> ../../docs_src/body_multiple_params/tutorial004.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[27] *} /// info @@ -297,57 +134,7 @@ item: Item = Body(embed=True) Voici un exemple complet : -//// tab | Python 3.10+ - -```Python hl_lines="17" -{!> ../../docs_src/body_multiple_params/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="17" -{!> ../../docs_src/body_multiple_params/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18" -{!> ../../docs_src/body_multiple_params/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Préférez utiliser la version `Annotated` si possible. - -/// - -```Python hl_lines="15" -{!> ../../docs_src/body_multiple_params/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Préférez utiliser la version `Annotated` si possible. - -/// - -```Python hl_lines="17" -{!> ../../docs_src/body_multiple_params/tutorial005.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial005_an_py310.py hl[17] *} Dans ce cas **FastAPI** attendra un body semblable à : diff --git a/docs/fr/docs/tutorial/body.md b/docs/fr/docs/tutorial/body.md index c4d493a458222..760b6d80ae3d9 100644 --- a/docs/fr/docs/tutorial/body.md +++ b/docs/fr/docs/tutorial/body.md @@ -107,7 +107,7 @@ Mais vous auriez le même support de l'éditeur avec -/// tip | "Astuce" +/// tip | Astuce Si vous utilisez PyCharm comme éditeur, vous pouvez utiliser le Plugin Pydantic PyCharm Plugin. diff --git a/docs/fr/docs/tutorial/first-steps.md b/docs/fr/docs/tutorial/first-steps.md index e9511b02995a9..7581453620d7c 100644 --- a/docs/fr/docs/tutorial/first-steps.md +++ b/docs/fr/docs/tutorial/first-steps.md @@ -2,9 +2,7 @@ Le fichier **FastAPI** le plus simple possible pourrait ressembler à cela : -```Python -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py *} Copiez ce code dans un fichier nommé `main.py`. @@ -134,13 +132,11 @@ 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" +/// note | Détails techniques `FastAPI` est une classe héritant directement de `Starlette`. @@ -150,9 +146,7 @@ Vous pouvez donc aussi utiliser toutes les fonctionnalités de opération get
-/// info | "`@décorateur` Info" +/// info | `@décorateur` Info Cette syntaxe `@something` en Python est appelée un "décorateur". @@ -286,7 +276,7 @@ Tout comme celles les plus exotiques : * `@app.patch()` * `@app.trace()` -/// tip | "Astuce" +/// tip | Astuce Vous êtes libres d'utiliser chaque opération (méthode HTTP) comme vous le désirez. @@ -306,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. @@ -320,9 +308,7 @@ 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 @@ -332,9 +318,7 @@ Si vous ne connaissez pas la différence, allez voir la section [Concurrence : * ### É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/path-params-numeric-validations.md b/docs/fr/docs/tutorial/path-params-numeric-validations.md index 82e317ff799be..3f3280e640c3f 100644 --- a/docs/fr/docs/tutorial/path-params-numeric-validations.md +++ b/docs/fr/docs/tutorial/path-params-numeric-validations.md @@ -6,57 +6,7 @@ De la même façon que vous pouvez déclarer plus de validations et de métadonn Tout d'abord, importez `Path` de `fastapi`, et importez `Annotated` : -//// tab | Python 3.10+ - -```Python hl_lines="1 3" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="1 3" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3-4" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Préférez utiliser la version `Annotated` si possible. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Préférez utiliser la version `Annotated` si possible. - -/// - -```Python hl_lines="3" -{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[1,3] *} /// info @@ -74,57 +24,7 @@ Vous pouvez déclarer les mêmes paramètres que pour `Query`. Par exemple, pour déclarer une valeur de métadonnée `title` pour le paramètre de chemin `item_id`, vous pouvez écrire : -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Préférez utiliser la version `Annotated` si possible. - -/// - -```Python hl_lines="8" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Préférez utiliser la version `Annotated` si possible. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[10] *} /// note @@ -154,37 +54,11 @@ Cela n'a pas d'importance pour **FastAPI**. Il détectera les paramètres par le Ainsi, vous pouvez déclarer votre fonction comme suit : -//// tab | Python 3.8 non-Annotated - -/// tip - -Préférez utiliser la version `Annotated` si possible. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/path_params_numeric_validations/tutorial002.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial002.py hl[7] *} Mais gardez à l'esprit que si vous utilisez `Annotated`, vous n'aurez pas ce problème, cela n'aura pas d'importance car vous n'utilisez pas les valeurs par défaut des paramètres de fonction pour `Query()` ou `Path()`. -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/path_params_numeric_validations/tutorial002_an.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py hl[10] *} ## Ordonnez les paramètres comme vous le souhaitez (astuces) @@ -209,29 +83,13 @@ Passez `*`, comme premier paramètre de la fonction. Python ne fera rien avec ce `*`, mais il saura que tous les paramètres suivants doivent être appelés comme arguments "mots-clés" (paires clé-valeur), également connus sous le nom de kwargs. Même s'ils n'ont pas de valeur par défaut. -```Python hl_lines="7" -{!../../docs_src/path_params_numeric_validations/tutorial003.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *} # Avec `Annotated` Gardez à l'esprit que si vous utilisez `Annotated`, comme vous n'utilisez pas les valeurs par défaut des paramètres de fonction, vous n'aurez pas ce problème, et vous n'aurez probablement pas besoin d'utiliser `*`. -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/path_params_numeric_validations/tutorial003_an.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py hl[10] *} ## Validations numériques : supérieur ou égal @@ -239,35 +97,7 @@ Avec `Query` et `Path` (et d'autres que vous verrez plus tard) vous pouvez décl Ici, avec `ge=1`, `item_id` devra être un nombre entier "`g`reater than or `e`qual" à `1`. -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/path_params_numeric_validations/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="8" -{!> ../../docs_src/path_params_numeric_validations/tutorial004.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py hl[10] *} ## Validations numériques : supérieur ou égal et inférieur ou égal @@ -276,35 +106,7 @@ La même chose s'applique pour : * `gt` : `g`reater `t`han * `le` : `l`ess than or `e`qual -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/path_params_numeric_validations/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Préférez utiliser la version `Annotated` si possible. - -/// - -```Python hl_lines="8" -{!> ../../docs_src/path_params_numeric_validations/tutorial004.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py hl[10] *} ## Validations numériques : supérieur et inférieur ou égal @@ -313,35 +115,7 @@ La même chose s'applique pour : * `gt` : `g`reater `t`han * `le` : `l`ess than or `e`qual -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/path_params_numeric_validations/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Préférez utiliser la version `Annotated` si possible. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/path_params_numeric_validations/tutorial005.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py hl[10] *} ## Validations numériques : flottants, supérieur et inférieur @@ -353,35 +127,7 @@ Ainsi, `0.5` serait une valeur valide. Mais `0.0` ou `0` ne le serait pas. Et la même chose pour lt. -//// tab | Python 3.9+ - -```Python hl_lines="13" -{!> ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="12" -{!> ../../docs_src/path_params_numeric_validations/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Préférez utiliser la version `Annotated` si possible. - -/// - -```Python hl_lines="11" -{!> ../../docs_src/path_params_numeric_validations/tutorial006.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py hl[13] *} ## Pour résumer @@ -402,7 +148,7 @@ Tous partagent les mêmes paramètres pour des validations supplémentaires et d /// -/// note | "Détails techniques" +/// note | Détails techniques Lorsque vous importez `Query`, `Path` et d'autres de `fastapi`, ce sont en fait des fonctions. diff --git a/docs/fr/docs/tutorial/path-params.md b/docs/fr/docs/tutorial/path-params.md index 34012c278b734..71c96b18eefdd 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,13 +20,11 @@ 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" +/// 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. @@ -43,7 +39,7 @@ Si vous exécutez cet exemple et allez sur http://127.0.0.1:8000/items/4.2. -/// check | "vérifier" +/// check | vérifier Donc, avec ces mêmes déclarations de type Python, **FastAPI** vous fournit de la validation de données. @@ -131,9 +127,7 @@ Et vous avez un second chemin : `/users/{user_id}` pour récupérer de la donné Les *fonctions de chemin* étant évaluées dans l'ordre, il faut s'assurer que la fonction correspondant à `/users/me` est déclarée avant celle de `/users/{user_id}` : -```Python hl_lines="6 11" -{!../../docs_src/path_params/tutorial003.py!} -``` +{* ../../docs_src/path_params/tutorial003.py hl[6,11] *} Sinon, le chemin `/users/{user_id}` correspondrait aussi à `/users/me`, la fonction "croyant" qu'elle a reçu un paramètre `user_id` avec pour valeur `"me"`. @@ -149,9 +143,7 @@ En héritant de `str` la documentation sera capable de savoir que les valeurs do Créez ensuite des attributs de classe avec des valeurs fixes, qui seront les valeurs autorisées pour cette énumération. -```Python hl_lines="1 6-9" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[1,6:9] *} /// info @@ -159,7 +151,7 @@ Créez ensuite des attributs de classe avec des valeurs fixes, qui seront les va /// -/// tip | "Astuce" +/// tip | Astuce Pour ceux qui se demandent, "AlexNet", "ResNet", et "LeNet" sont juste des noms de modèles de Machine Learning. @@ -169,9 +161,7 @@ Pour ceux qui se demandent, "AlexNet", "ResNet", et "LeNet" sont juste des noms Créez ensuite un *paramètre de chemin* avec une annotation de type désignant l'énumération créée précédemment (`ModelName`) : -```Python hl_lines="16" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[16] *} ### Documentation @@ -187,19 +177,15 @@ 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" +/// tip | Astuce Vous pouvez aussi accéder la valeur `"lenet"` avec `ModelName.lenet.value`. @@ -211,9 +197,7 @@ Vous pouvez retourner des *membres d'énumération* dans vos *fonctions de chemi Ils seront convertis vers leurs valeurs correspondantes (chaînes de caractères ici) avant d'être transmis au client : -```Python hl_lines="18 21 23" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[18,21,23] *} Le client recevra une réponse JSON comme celle-ci : @@ -252,11 +236,9 @@ 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" +/// tip | Astuce Vous pourriez avoir besoin que le paramètre contienne `/home/johndoe/myfile.txt`, avec un slash au début (`/`). diff --git a/docs/fr/docs/tutorial/query-params-str-validations.md b/docs/fr/docs/tutorial/query-params-str-validations.md index a3cf763024d8c..c54c0c717165d 100644 --- a/docs/fr/docs/tutorial/query-params-str-validations.md +++ b/docs/fr/docs/tutorial/query-params-str-validations.md @@ -106,7 +106,7 @@ Disons que vous déclarez le paramètre `q` comme ayant une longueur minimale de {* ../../docs_src/query_params_str_validations/tutorial005.py hl[7] *} -/// note | "Rappel" +/// note | Rappel Avoir une valeur par défaut rend le paramètre optionnel. @@ -171,7 +171,7 @@ Donc la réponse de cette URL serait : } ``` -/// tip | "Astuce" +/// tip | Astuce Pour déclarer un paramètre de requête de type `list`, comme dans l'exemple ci-dessus, il faut explicitement utiliser `Query`, sinon cela sera interprété comme faisant partie du corps de la requête. diff --git a/docs/fr/docs/tutorial/query-params.md b/docs/fr/docs/tutorial/query-params.md index 798f84fa3e0f6..b87c26c782c3e 100644 --- a/docs/fr/docs/tutorial/query-params.md +++ b/docs/fr/docs/tutorial/query-params.md @@ -65,7 +65,7 @@ De la même façon, vous pouvez définir des paramètres de requête comme optio Ici, le paramètre `q` sera optionnel, et aura `None` comme valeur par défaut. -/// check | "Remarque" +/// check | Remarque On peut voir que **FastAPI** est capable de détecter que le paramètre de chemin `item_id` est un paramètre de chemin et que `q` n'en est pas un, c'est donc un paramètre de requête. @@ -187,7 +187,7 @@ Ici, on a donc 3 paramètres de requête : * `skip`, un `int` avec comme valeur par défaut `0`. * `limit`, un `int` optionnel. -/// tip | "Astuce" +/// tip | Astuce Vous pouvez utiliser les `Enum`s de la même façon qu'avec les [Paramètres de chemin](path-params.md#valeurs-predefinies){.internal-link target=_blank}. diff --git a/docs/id/docs/tutorial/index.md b/docs/id/docs/tutorial/index.md index f0dee3d730478..c01ec9a8965a8 100644 --- a/docs/id/docs/tutorial/index.md +++ b/docs/id/docs/tutorial/index.md @@ -52,7 +52,7 @@ $ pip install "fastapi[all]" ...yang juga termasuk `uvicorn`, yang dapat kamu gunakan sebagai server yang menjalankan kodemu. -/// note | "Catatan" +/// note | Catatan Kamu juga dapat meng-installnya bagian demi bagian. diff --git a/docs/ja/docs/advanced/additional-status-codes.md b/docs/ja/docs/advanced/additional-status-codes.md index 904d539e77e55..33457f591ce96 100644 --- a/docs/ja/docs/advanced/additional-status-codes.md +++ b/docs/ja/docs/advanced/additional-status-codes.md @@ -14,11 +14,9 @@ これを達成するには、 `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 | "注意" +/// warning | 注意 上記の例のように `Response` を明示的に返す場合、それは直接返されます。 @@ -28,7 +26,7 @@ /// -/// note | "技術詳細" +/// note | 技術詳細 `from starlette.responses import JSONResponse` を利用することもできます。 diff --git a/docs/ja/docs/advanced/custom-response.md b/docs/ja/docs/advanced/custom-response.md index 88269700e00ee..1b2cd914d404c 100644 --- a/docs/ja/docs/advanced/custom-response.md +++ b/docs/ja/docs/advanced/custom-response.md @@ -12,7 +12,7 @@ そしてもし、`Response` が、`JSONResponse` や `UJSONResponse` の場合のようにJSONメディアタイプ (`application/json`) ならば、データは *path operationデコレータ* に宣言したPydantic `response_model` により自動的に変換 (もしくはフィルタ) されます。 -/// note | "備考" +/// note | 備考 メディアタイプを指定せずにレスポンスクラスを利用すると、FastAPIは何もコンテンツがないことを期待します。そのため、生成されるOpenAPIドキュメントにレスポンスフォーマットが記載されません。 @@ -24,11 +24,9 @@ 使いたい `Response` クラス (サブクラス) をインポートし、 *path operationデコレータ* に宣言します。 -```Python hl_lines="2 7" -{!../../docs_src/custom_response/tutorial001b.py!} -``` +{* ../../docs_src/custom_response/tutorial001b.py hl[2,7] *} -/// info | "情報" +/// info | 情報 パラメータ `response_class` は、レスポンスの「メディアタイプ」を定義するために利用することもできます。 @@ -38,7 +36,7 @@ /// -/// tip | "豆知識" +/// tip | 豆知識 `ORJSONResponse` は、現在はFastAPIのみで利用可能で、Starletteでは利用できません。 @@ -51,11 +49,9 @@ * `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 | "情報" +/// info | 情報 パラメータ `response_class` は、レスポンスの「メディアタイプ」を定義するために利用されます。 @@ -71,17 +67,15 @@ 上記と同じ例において、 `HTMLResponse` を返すと、このようになります: -```Python hl_lines="2 7 19" -{!../../docs_src/custom_response/tutorial003.py!} -``` +{* ../../docs_src/custom_response/tutorial003.py hl[2,7,19] *} -/// warning | "注意" +/// warning | 注意 *path operation関数* から直接返される `Response` は、OpenAPIにドキュメントされず (例えば、 `Content-Type` がドキュメントされない) 、自動的な対話的ドキュメントからも閲覧できません。 /// -/// info | "情報" +/// info | 情報 もちろん、実際の `Content-Type` ヘッダーやステータスコードなどは、返された `Response` オブジェクトに由来しています。 @@ -97,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` を生成して返しています。 @@ -115,7 +107,7 @@ `Response` を使って他の何かを返せますし、カスタムのサブクラスも作れることを覚えておいてください。 -/// note | "技術詳細" +/// note | 技術詳細 `from starlette.responses import HTMLResponse` も利用できます。 @@ -138,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` @@ -150,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` @@ -168,17 +156,15 @@ FastAPI (実際にはStarlette) は自動的にContent-Lengthヘッダーを含 `ujson`を使った、代替のJSONレスポンスです。 -/// warning | "注意" +/// warning | 注意 `ujson` は、いくつかのエッジケースの取り扱いについて、Pythonにビルトインされた実装よりも作りこまれていません。 /// -```Python hl_lines="2 7" -{!../../docs_src/custom_response/tutorial001.py!} -``` +{* ../../docs_src/custom_response/tutorial001.py hl[2,7] *} -/// tip | "豆知識" +/// tip | 豆知識 `ORJSONResponse` のほうが高速な代替かもしれません。 @@ -188,17 +174,13 @@ FastAPI (実際にはStarlette) は自動的にContent-Lengthヘッダーを含 HTTPリダイレクトを返します。デフォルトでは307ステータスコード (Temporary Redirect) となります。 -```Python hl_lines="2 9" -{!../../docs_src/custom_response/tutorial006.py!} -``` +{* ../../docs_src/custom_response/tutorial006.py 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` をファイルライクなオブジェクトとともに使う @@ -206,11 +188,9 @@ 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 | "豆知識" +/// tip | 豆知識 ここでは `async` や `await` をサポートしていない標準の `open()` を使っているので、通常の `def` でpath operationを宣言していることに注意してください。 @@ -229,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] *} ## デフォルトレスポンスクラス @@ -241,11 +219,9 @@ 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 | "豆知識" +/// tip | 豆知識 前に見たように、 *path operation* の中で `response_class` をオーバーライドできます。 diff --git a/docs/ja/docs/advanced/index.md b/docs/ja/docs/advanced/index.md index da3c2a2bf656f..22eaf6eb80d76 100644 --- a/docs/ja/docs/advanced/index.md +++ b/docs/ja/docs/advanced/index.md @@ -6,7 +6,7 @@ 以降のセクションでは、チュートリアルでは説明しきれなかったオプションや設定、および機能について説明します。 -/// tip | "豆知識" +/// tip | 豆知識 以降のセクションは、 **必ずしも"応用編"ではありません**。 diff --git a/docs/ja/docs/advanced/path-operation-advanced-configuration.md b/docs/ja/docs/advanced/path-operation-advanced-configuration.md index 2dab4aec1585e..05188d5b25d7e 100644 --- a/docs/ja/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/ja/docs/advanced/path-operation-advanced-configuration.md @@ -2,7 +2,7 @@ ## OpenAPI operationId -/// warning | "注意" +/// warning | 注意 あなたがOpenAPIの「エキスパート」でなければ、これは必要ないかもしれません。 @@ -12,9 +12,7 @@ `operation_id` は各オペレーションで一意にする必要があります。 -```Python hl_lines="6" -{!../../docs_src/path_operation_advanced_configuration/tutorial001.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial001.py hl[6] *} ### *path operation関数* の名前をoperationIdとして使用する @@ -22,17 +20,15 @@ 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 | "豆知識" +/// tip | 豆知識 `app.openapi()` を手動でコールする場合、その前に`operationId`を更新する必要があります。 /// -/// warning | "注意" +/// warning | 注意 この方法をとる場合、各 *path operation関数* が一意な名前である必要があります。 @@ -44,9 +40,7 @@ APIの関数名を `operationId` として利用したい場合、すべてのAP 生成されるOpenAPIスキーマ (つまり、自動ドキュメント生成の仕組み) から *path operation* を除外するには、 `include_in_schema` パラメータを `False` にします。 -```Python hl_lines="6" -{!../../docs_src/path_operation_advanced_configuration/tutorial003.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial003.py hl[6] *} ## docstringによる説明の高度な設定 @@ -56,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 167d15589f4fa..42412d5070ad7 100644 --- a/docs/ja/docs/advanced/response-directly.md +++ b/docs/ja/docs/advanced/response-directly.md @@ -14,7 +14,7 @@ 実際は、`Response` やそのサブクラスを返すことができます。 -/// tip | "豆知識" +/// tip | 豆知識 `JSONResponse` それ自体は、 `Response` のサブクラスです。 @@ -34,11 +34,9 @@ このようなケースでは、レスポンスにデータを含める前に `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 | "技術詳細" +/// note | 技術詳細 また、`from starlette.responses import JSONResponse` も利用できます。 @@ -56,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 f7bcb6af3497d..43009eba85467 100644 --- a/docs/ja/docs/advanced/websockets.md +++ b/docs/ja/docs/advanced/websockets.md @@ -38,19 +38,15 @@ $ 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 | "技術詳細" +/// note | 技術詳細 `from starlette.websockets import WebSocket` を使用しても構いません. @@ -62,9 +58,7 @@ $ pip install websockets WebSocketルートでは、 `await` を使ってメッセージの送受信ができます。 -```Python hl_lines="48-52" -{!../../docs_src/websockets/tutorial001.py!} -``` +{* ../../docs_src/websockets/tutorial001.py hl[48:52] *} バイナリやテキストデータ、JSONデータを送受信できます。 @@ -115,11 +109,9 @@ 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の接続を直接閉じる方がよいでしょう。 @@ -150,7 +142,7 @@ $ uvicorn main:app --reload * パスで使用される「Item ID」 * クエリパラメータとして使用される「Token」 -/// tip | "豆知識" +/// tip | 豆知識 クエリ `token` は依存パッケージによって処理されることに注意してください。 @@ -164,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] *} 試してみるには、 @@ -180,7 +170,7 @@ WebSocket接続が閉じられると、 `await websocket.receive_text()` は例 Client #1596980209979 left the chat ``` -/// tip | "豆知識" +/// tip | 豆知識 上記のアプリは、複数の WebSocket 接続に対してメッセージを処理し、ブロードキャストする方法を示すための最小限のシンプルな例です。 diff --git a/docs/ja/docs/alternatives.md b/docs/ja/docs/alternatives.md index 343ae4ed87d60..8129a7002be04 100644 --- a/docs/ja/docs/alternatives.md +++ b/docs/ja/docs/alternatives.md @@ -30,13 +30,13 @@ Mozilla、Red Hat、Eventbrite など多くの企業で利用されています これは**自動的なAPIドキュメント生成**の最初の例であり、これは**FastAPI**に向けた「調査」を触発した最初のアイデアの一つでした。 -/// note | "備考" +/// note | 備考 Django REST Framework は Tom Christie によって作成されました。StarletteとUvicornの生みの親であり、**FastAPI**のベースとなっています。 /// -/// check | "**FastAPI**へ与えたインスピレーション" +/// check | **FastAPI**へ与えたインスピレーション 自動でAPIドキュメントを生成するWebユーザーインターフェースを持っている点。 @@ -56,7 +56,7 @@ Flask は「マイクロフレームワーク」であり、データベース Flaskのシンプルさを考えると、APIを構築するのに適しているように思えました。次に見つけるべきは、Flask 用の「Django REST Framework」でした。 -/// check | "**FastAPI**へ与えたインスピレーション" +/// check | **FastAPI**へ与えたインスピレーション マイクロフレームワークであること。ツールやパーツを目的に合うように簡単に組み合わせられる点。 @@ -98,7 +98,7 @@ def read_url(): `requests.get(...)` と`@app.get(...)` には類似点が見受けられます。 -/// check | "**FastAPI**へ与えたインスピレーション" +/// check | **FastAPI**へ与えたインスピレーション * シンプルで直感的なAPIを持っている点。 * HTTPメソッド名を直接利用し、単純で直感的である。 @@ -118,7 +118,7 @@ def read_url(): そのため、バージョン2.0では「Swagger」、バージョン3以上では「OpenAPI」と表記するのが一般的です。 -/// check | "**FastAPI**へ与えたインスピレーション" +/// check | **FastAPI**へ与えたインスピレーション 独自のスキーマの代わりに、API仕様のオープンな標準を採用しました。 @@ -147,7 +147,7 @@ APIが必要とするもう一つの大きな機能はデータのバリデー しかし、それはPythonの型ヒントが存在する前に作られたものです。そのため、すべてのスキーマを定義するためには、Marshmallowが提供する特定のユーティリティやクラスを使用する必要があります。 -/// check | "**FastAPI**へ与えたインスピレーション" +/// check | **FastAPI**へ与えたインスピレーション コードで「スキーマ」を定義し、データの型やバリデーションを自動で提供する点。 @@ -163,13 +163,13 @@ WebargsはFlaskをはじめとするいくつかのフレームワークの上 素晴らしいツールで、私も**FastAPI**を持つ前はよく使っていました。 -/// info | "情報" +/// info | 情報 Webargsは、Marshmallowと同じ開発者により作られました。 /// -/// check | "**FastAPI**へ与えたインスピレーション" +/// check | **FastAPI**へ与えたインスピレーション 受信したデータに対する自動的なバリデーションを持っている点。 @@ -193,13 +193,13 @@ Flask, Starlette, Responderなどにおいてはそのように動作します エディタでは、この問題を解決することはできません。また、パラメータやMarshmallowスキーマを変更したときに、YAMLのdocstringを変更するのを忘れてしまうと、生成されたスキーマが古くなってしまいます。 -/// info | "情報" +/// info | 情報 APISpecは、Marshmallowと同じ開発者により作成されました。 /// -/// check | "**FastAPI**へ与えたインスピレーション" +/// check | **FastAPI**へ与えたインスピレーション OpenAPIという、APIについてのオープンな標準をサポートしている点。 @@ -225,13 +225,13 @@ Flask、Flask-apispec、Marshmallow、Webargsの組み合わせは、**FastAPI** そして、これらのフルスタックジェネレーターは、[**FastAPI** Project Generators](project-generation.md){.internal-link target=_blank}の元となっていました。 -/// info | "情報" +/// info | 情報 Flask-apispecはMarshmallowと同じ開発者により作成されました。 /// -/// check | "**FastAPI**へ与えたインスピレーション" +/// check | **FastAPI**へ与えたインスピレーション シリアライゼーションとバリデーションを定義したコードから、OpenAPIスキーマを自動的に生成する点。 @@ -251,7 +251,7 @@ Angular 2にインスピレーションを受けた、統合された依存性 入れ子になったモデルをうまく扱えません。そのため、リクエストのJSONボディが内部フィールドを持つJSONオブジェクトで、それが順番にネストされたJSONオブジェクトになっている場合、適切にドキュメント化やバリデーションをすることができません。 -/// check | "**FastAPI**へ与えたインスピレーション" +/// check | **FastAPI**へ与えたインスピレーション 素晴らしいエディターの補助を得るために、Pythonの型ヒントを利用している点。 @@ -263,7 +263,7 @@ Angular 2にインスピレーションを受けた、統合された依存性 `asyncio`に基づいた、Pythonのフレームワークの中でも非常に高速なものの一つです。Flaskと非常に似た作りになっています。 -/// note | "技術詳細" +/// note | 技術詳細 Pythonの`asyncio`ループの代わりに、`uvloop`が利用されています。それにより、非常に高速です。 @@ -271,7 +271,7 @@ Pythonの`asyncio`ループの代わりに、`uvloop`が利用されています /// -/// check | "**FastAPI**へ与えたインスピレーション" +/// check | **FastAPI**へ与えたインスピレーション 物凄い性能を出す方法を見つけた点。 @@ -289,7 +289,7 @@ Pythonのウェブフレームワーク標準規格 (WSGI) を使用していま そのため、データのバリデーション、シリアライゼーション、ドキュメント化は、自動的にできずコードの中で行わなければなりません。あるいは、HugのようにFalconの上にフレームワークとして実装されなければなりません。このような分断は、パラメータとして1つのリクエストオブジェクトと1つのレスポンスオブジェクトを持つというFalconのデザインにインスピレーションを受けた他のフレームワークでも起こります。 -/// check | "**FastAPI**へ与えたインスピレーション" +/// check | **FastAPI**へ与えたインスピレーション 素晴らしい性能を得るための方法を見つけた点。 @@ -315,7 +315,7 @@ Pydanticのようなデータのバリデーション、シリアライゼーシ ルーティングは一つの場所で宣言され、他の場所で宣言された関数を使用します (エンドポイントを扱う関数のすぐ上に配置できるデコレータを使用するのではなく) 。これはFlask (やStarlette) よりも、Djangoに近いです。これは、比較的緊密に結合されているものをコードの中で分離しています。 -/// check | "**FastAPI**へ与えたインスピレーション" +/// check | **FastAPI**へ与えたインスピレーション モデルの属性の「デフォルト」値を使用したデータ型の追加バリデーションを定義します。これはエディタの補助を改善するもので、以前はPydanticでは利用できませんでした。 @@ -337,13 +337,13 @@ OpenAPIやJSON Schemaのような標準に基づいたものではありませ 以前のPythonの同期型Webフレームワーク標準 (WSGI) をベースにしているため、Websocketなどは扱えませんが、それでも高性能です。 -/// info | "情報" +/// info | 情報 HugはTimothy Crosleyにより作成されました。彼は`isort`など、Pythonのファイル内のインポートの並び替えを自動的におこうなう素晴らしいツールの開発者です。 /// -/// check | "**FastAPI**へ与えたインスピレーション" +/// check | **FastAPI**へ与えたインスピレーション HugはAPIStarに部分的なインスピレーションを与えており、私が発見した中ではAPIStarと同様に最も期待の持てるツールの一つでした。 @@ -377,7 +377,7 @@ Hugは、**FastAPI**がヘッダーやクッキーを設定するために関数 今ではAPIStarはOpenAPI仕様を検証するためのツールセットであり、ウェブフレームワークではありません。 -/// info | "情報" +/// info | 情報 APIStarはTom Christieにより開発されました。以下の開発者でもあります: @@ -387,7 +387,7 @@ APIStarはTom Christieにより開発されました。以下の開発者でも /// -/// check | "**FastAPI**へ与えたインスピレーション" +/// check | **FastAPI**へ与えたインスピレーション 存在そのもの。 @@ -411,7 +411,7 @@ Pydanticは、Pythonの型ヒントを元にデータのバリデーション、 Marshmallowに匹敵しますが、ベンチマークではMarshmallowよりも高速です。また、Pythonの型ヒントを元にしているので、エディタの補助が素晴らしいです。 -/// check | "**FastAPI**での使用用途" +/// check | **FastAPI**での使用用途 データのバリデーション、データのシリアライゼーション、自動的なモデルの (JSON Schemaに基づいた) ドキュメント化の全てを扱えます。 @@ -447,7 +447,7 @@ Starletteは基本的なWebマイクロフレームワークの機能をすべ これは **FastAPI** が追加する主な機能の一つで、すべての機能は Pythonの型ヒントに基づいています (Pydanticを使用しています) 。これに加えて、依存性注入の仕組み、セキュリティユーティリティ、OpenAPIスキーマ生成などがあります。 -/// note | "技術詳細" +/// note | 技術詳細 ASGIはDjangoのコアチームメンバーにより開発された新しい「標準」です。まだ「Pythonの標準 (PEP) 」ではありませんが、現在そうなるように進めています。 @@ -455,7 +455,7 @@ ASGIはDjangoのコアチームメンバーにより開発された新しい「 /// -/// check | "**FastAPI**での使用用途" +/// check | **FastAPI**での使用用途 webに関するコアな部分を全て扱います。その上に機能を追加します。 @@ -473,7 +473,7 @@ Uvicornは非常に高速なASGIサーバーで、uvloopとhttptoolsにより構 Starletteや**FastAPI**のサーバーとして推奨されています。 -/// check | "**FastAPI**が推奨する理由" +/// check | **FastAPI**が推奨する理由 **FastAPI**アプリケーションを実行するメインのウェブサーバーである点。 diff --git a/docs/ja/docs/async.md b/docs/ja/docs/async.md index ce9dac56fece1..d1da1f82d2382 100644 --- a/docs/ja/docs/async.md +++ b/docs/ja/docs/async.md @@ -21,7 +21,7 @@ async def read_results(): return results ``` -/// note | "備考" +/// note | 備考 `async def` を使用して作成された関数の内部でしか `await` は使用できません。 @@ -358,7 +358,7 @@ async def read_burgers(): ## 非常に発展的な技術的詳細 -/// warning | "注意" +/// warning | 注意 恐らくスキップしても良いでしょう。 diff --git a/docs/ja/docs/contributing.md b/docs/ja/docs/contributing.md deleted file mode 100644 index 86926b2132719..0000000000000 --- a/docs/ja/docs/contributing.md +++ /dev/null @@ -1,498 +0,0 @@ -# 開発 - 貢献 - -まず、[FastAPIを応援 - ヘルプの入手](help-fastapi.md){.internal-link target=_blank}の基本的な方法を見て、ヘルプを得た方がいいかもしれません。 - -## 開発 - -すでにリポジトリをクローンし、コードを詳しく調べる必要があるとわかっている場合に、環境構築のためのガイドラインをいくつか紹介します。 - -### `venv`を使用した仮想環境 - -Pythonの`venv`モジュールを使用して、ディレクトリに仮想環境を作成します: - -
- -```console -$ python -m venv env -``` - -
- -これにより、Pythonバイナリを含む`./env/`ディレクトリが作成され、その隔離された環境にパッケージのインストールが可能になります。 - -### 仮想環境の有効化 - -新しい環境を有効化するには: - -//// tab | Linux, macOS - -
- -```console -$ source ./env/bin/activate -``` - -
- -//// - -//// tab | Windows PowerShell - -
- -```console -$ .\env\Scripts\Activate.ps1 -``` - -
- -//// - -//// tab | Windows Bash - -もしwindows用のBash (例えば、Git Bash)を使っているなら: - -
- -```console -$ source ./env/Scripts/activate -``` - -
- -//// - -動作の確認には、下記を実行します: - -//// tab | Linux, macOS, Windows Bash - -
- -```console -$ which pip - -some/directory/fastapi/env/bin/pip -``` - -
- -//// - -//// tab | Windows PowerShell - -
- -```console -$ Get-Command pip - -some/directory/fastapi/env/bin/pip -``` - -
- -//// - -`env/bin/pip`に`pip`バイナリが表示される場合は、正常に機能しています。🎉 - - -/// tip | "豆知識" - -この環境で`pip`を使って新しいパッケージをインストールするたびに、仮想環境を再度有効化します。 - -これにより、そのパッケージによってインストールされたターミナルのプログラム を使用する場合、ローカル環境のものを使用し、グローバルにインストールされたものは使用されなくなります。 - -/// - -### pip - -上記のように環境を有効化した後: - -
- -```console -$ pip install -r requirements.txt - ----> 100% -``` - -
- -これで、すべての依存関係とFastAPIを、ローカル環境にインストールします。 - -#### ローカル環境でFastAPIを使う - -FastAPIをインポートして使用するPythonファイルを作成し、ローカル環境で実行すると、ローカルのFastAPIソースコードが使用されます。 - -そして、`-e` でインストールされているローカルのFastAPIソースコードを更新した場合、そのPythonファイルを再度実行すると、更新したばかりの新しいバージョンのFastAPIが使用されます。 - -これにより、ローカルバージョンを「インストール」しなくても、すべての変更をテストできます。 - -### コードの整形 - -すべてのコードを整形してクリーンにするスクリプトがあります: - -
- -```console -$ bash scripts/format.sh -``` - -
- -また、すべてのインポートを自動でソートします。 - -正しく並べ替えるには、上記セクションのコマンドで `-e` を使い、FastAPIをローカル環境にインストールしている必要があります。 - -### インポートの整形 - -他にも、すべてのインポートを整形し、未使用のインポートがないことを確認するスクリプトがあります: - -
- -```console -$ bash scripts/format-imports.sh -``` - -
- -多くのファイルを編集したり、リバートした後、これらのコマンドを実行すると、少し時間がかかります。なので`scripts/format.sh`を頻繁に使用し、`scripts/format-imports.sh`をコミット前に実行する方が楽でしょう。 - -## ドキュメント - -まず、上記のように環境をセットアップしてください。すべての必要なパッケージがインストールされます。 - -ドキュメントは、MkDocsを使っています。 - -そして、翻訳を処理するためのツール/スクリプトが、`./scripts/docs.py`に用意されています。 - -/// tip | "豆知識" - -`./scripts/docs.py`のコードを見る必要はなく、コマンドラインからただ使うだけです。 - -/// - -すべてのドキュメントが、Markdown形式で`./docs/en/`ディレクトリにあります。 - -多くのチュートリアルには、コードブロックがあります。 - -ほとんどの場合、これらのコードブロックは、実際にそのまま実行できる完全なアプリケーションです。 - -実際、これらのコードブロックはMarkdown内には記述されておらず、`./docs_src/`ディレクトリのPythonファイルです。 - -そして、これらのPythonファイルは、サイトの生成時にドキュメントに含まれるか/挿入されます。 - -### ドキュメントのテスト - -ほとんどのテストは、実際にドキュメント内のサンプルソースファイルに対して実行されます。 - -これにより、次のことが確認できます: - -* ドキュメントが最新であること。 -* ドキュメントの例が、そのまま実行できること。 -* ほとんどの機能がドキュメントでカバーされており、テスト範囲で保証されていること。 - -ローカル開発中に、サイトを構築して変更がないかチェックするスクリプトがあり、ライブリロードされます: - -
- -```console -$ python ./scripts/docs.py live - -[INFO] Serving on http://127.0.0.1:8008 -[INFO] Start watching changes -[INFO] Start detecting changes -``` - -
- -ドキュメントは、`http://127.0.0.1:8008`で提供します。 - -そうすることで、ドキュメント/ソースファイルを編集し、変更をライブで見ることができます。 - -#### Typer CLI (任意) - -ここでは、`./scripts/docs.py`のスクリプトを`python`プログラムで直接使う方法を説明します。 - -ですがTyper CLIを使用して、インストール完了後にターミナルでの自動補完もできます。 - -Typer CLIをインストールする場合、次のコマンドで補完をインストールできます: - -
- -```console -$ typer --install-completion - -zsh completion installed in /home/user/.bashrc. -Completion will take effect once you restart the terminal. -``` - -
- -### アプリとドキュメントを同時に - -以下の様にサンプルを実行すると: - -
- -```console -$ uvicorn tutorial001:app --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -
- -Uvicornはデフォルトでポート`8000`を使用するため、ポート`8008`のドキュメントは衝突しません。 - -### 翻訳 - -翻訳のヘルプをとても歓迎しています!これはコミュニティの助けなしでは成し遂げられません。 🌎🚀 - -翻訳を支援するための手順は次のとおりです。 - -#### 豆知識とガイドライン - -* あなたの言語の今あるプルリクエストを確認し、変更や承認をするレビューを追加します。 - -/// tip | "豆知識" - -すでにあるプルリクエストに修正提案つきのコメントを追加できます。 - -修正提案の承認のためにプルリクエストのレビューの追加のドキュメントを確認してください。 - -/// - -* issuesをチェックして、あなたの言語に対応する翻訳があるかどうかを確認してください。 - -* 翻訳したページごとに1つのプルリクエストを追加します。これにより、他のユーザーがレビューしやすくなります。 - -私が話さない言語については、他の何人かが翻訳をレビューするのを待って、マージします。 - -* 自分の言語の翻訳があるかどうか確認し、レビューを追加できます。これにより、翻訳が正しく、マージできることがわかります。 - -* 同じPythonの例を使用し、ドキュメント内のテキストのみを翻訳してください。何も変更する必要はありません。 - -* 同じ画像、ファイル名、リンクを使用します。何も変更する必要はありません。 - -* 翻訳する言語の2文字のコードを確認するには、表 ISO 639-1コードのリストが使用できます。 - -#### すでにある言語 - -スペイン語の様に、既に一部のページが翻訳されている言語の翻訳を追加したいとしましょう。 - -スペイン語の場合、2文字のコードは`es`です。したがって、スペイン語のディレクトリは`docs/es/`です。 - -/// tip | "豆知識" - -メイン (「公式」) 言語は英語で、`docs/en/`にあります。 - -/// - -次に、ドキュメントのライブサーバーをスペイン語で実行します: - -
- -```console -// コマンド"live"を使用し、言語コードをCLIに引数で渡します。 -$ python ./scripts/docs.py live es - -[INFO] Serving on http://127.0.0.1:8008 -[INFO] Start watching changes -[INFO] Start detecting changes -``` - -
- -これでhttp://127.0.0.1:8008 を開いて、変更を確認できます。 - -FastAPI docs Webサイトを見ると、すべての言語にすべてのページがあります。しかし、一部のページは翻訳されておらず、翻訳の欠落ページについて通知があります。 - -しかし、このようにローカルで実行すると、翻訳済みのページのみが表示されます。 - -ここで、セクション[Features](features.md){.internal-link target=_blank}の翻訳を追加するとします。 - -* 下記のファイルをコピーします: - -``` -docs/en/docs/features.md -``` - -* 翻訳したい言語のまったく同じところに貼り付けます。例えば: - -``` -docs/es/docs/features.md -``` - -/// tip | "豆知識" - -パスとファイル名の変更は、`en`から`es`への言語コードだけであることに注意してください。 - -/// - -* ここで、英語のMkDocs構成ファイルを開きます: - -``` -docs/en/docs/mkdocs.yml -``` - -* 設定ファイルの中で、`docs/features.md`が記述されている箇所を見つけます: - -```YAML hl_lines="8" -site_name: FastAPI -# More stuff -nav: -- FastAPI: index.md -- Languages: - - en: / - - es: /es/ -- features.md -``` - -* 編集している言語のMkDocs構成ファイルを開きます。例えば: - -``` -docs/es/docs/mkdocs.yml -``` - -* 英語とまったく同じ場所に追加します。例えば: - -```YAML hl_lines="8" -site_name: FastAPI -# More stuff -nav: -- FastAPI: index.md -- Languages: - - en: / - - es: /es/ -- features.md -``` - -他のエントリがある場合は、翻訳を含む新しいエントリが英語版とまったく同じ順序になっていることを確認してください。 - -ブラウザにアクセスすれば、ドキュメントに新しいセクションが表示されています。 🎉 - -これですべて翻訳して、ファイルを保存した状態を確認できます。 - -#### 新しい言語 - -まだ翻訳されていない言語の翻訳を追加したいとしましょう。 - -クレオール語の翻訳を追加したいのですが、それはまだドキュメントにありません。 - -上記のリンクを確認すると、「クレオール語」のコードは`ht`です。 - -次のステップは、スクリプトを実行して新しい翻訳ディレクトリを生成することです: - -
- -```console -// コマンド「new-lang」を使用して、言語コードをCLIに引数で渡します -$ python ./scripts/docs.py new-lang ht - -Successfully initialized: docs/ht -Updating ht -Updating en -``` - -
- -これで、新しく作成された`docs/ht/`ディレクトリをコードエディターから確認できます。 - -/// tip | "豆知識" - -翻訳を追加する前に、これだけで最初のプルリクエストを作成し、新しい言語の設定をセットアップします。 - -そうすることで、最初のページで作業している間、誰かの他のページの作業を助けることができます。 🚀 - -/// - -まず、メインページの`docs/ht/index.md`を翻訳します。 - -その後、「既存の言語」で、さきほどの手順を続行してください。 - -##### まだサポートされていない新しい言語 - -ライブサーバースクリプトを実行するときに、サポートされていない言語に関するエラーが発生した場合は、次のように表示されます: - -``` - raise TemplateNotFound(template) -jinja2.exceptions.TemplateNotFound: partials/language/xx.html -``` - -これは、テーマがその言語をサポートしていないことを意味します (この場合は、`xx`の2文字の偽のコード) 。 - -ただし、心配しないでください。テーマ言語を英語に設定して、ドキュメントの内容を翻訳できます。 - -その必要がある場合は、新しい言語の`mkdocs.yml`を次のように編集してください: - -```YAML hl_lines="5" -site_name: FastAPI -# More stuff -theme: - # More stuff - language: xx -``` - -その言語を`xx` (あなたの言語コード) から`en`に変更します。 - -その後、ライブサーバーを再起動します。 - -#### 結果のプレビュー - -`./scripts/docs.py`のスクリプトを`live`コマンドで使用すると、現在の言語で利用可能なファイルと翻訳のみが表示されます。 - -しかし一度実行したら、オンラインで表示されるのと同じように、すべてをテストできます。 - -このために、まずすべてのドキュメントをビルドします: - -
- -```console -// 「build-all」コマンドは少し時間がかかります。 -$ python ./scripts/docs.py build-all - -Updating es -Updating en -Building docs for: en -Building docs for: es -Successfully built docs for: es -Copying en index.md to README.md -``` - -
- -これで、言語ごとにすべてのドキュメントが`./docs_build/`に作成されます。 - -これには、翻訳が欠落しているファイルを追加することと、「このファイルにはまだ翻訳がない」というメモが含まれます。ただし、そのディレクトリで何もする必要はありません。 - -次に、言語ごとにこれらすべての個別のMkDocsサイトを構築し、それらを組み合わせて、`./site/`に最終結果を出力します。 - -これは、コマンド`serve`で提供できます: - -
- -```console -// 「build-all」コマンドの実行の後に、「serve」コマンドを使います -$ python ./scripts/docs.py serve - -Warning: this is a very simple server. For development, use mkdocs serve instead. -This is here only to preview a site with translations already built. -Make sure you run the build-all command first. -Serving at: http://127.0.0.1:8008 -``` - -
- -## テスト - -すべてのコードをテストし、HTMLでカバレッジレポートを生成するためにローカルで実行できるスクリプトがあります: - -
- -```console -$ bash scripts/test-cov-html.sh -``` - -
- -このコマンドは`./htmlcov/`ディレクトリを生成します。ブラウザでファイル`./htmlcov/index.html`を開くと、テストでカバーされているコードの領域をインタラクティブに探索できます。それによりテストが不足しているかどうか気付くことができます。 diff --git a/docs/ja/docs/deployment/manually.md b/docs/ja/docs/deployment/manually.md index c17e637284700..4ea6bd8ffe7e3 100644 --- a/docs/ja/docs/deployment/manually.md +++ b/docs/ja/docs/deployment/manually.md @@ -20,7 +20,7 @@ $ pip install "uvicorn[standard]" //// -/// tip | "豆知識" +/// tip | 豆知識 `standard` を加えることで、Uvicornがインストールされ、いくつかの推奨される依存関係を利用するようになります。 diff --git a/docs/ja/docs/deployment/versions.md b/docs/ja/docs/deployment/versions.md index 941ddb71b4533..7575fc4f70c47 100644 --- a/docs/ja/docs/deployment/versions.md +++ b/docs/ja/docs/deployment/versions.md @@ -42,7 +42,7 @@ PoetryやPipenvなど、他のインストール管理ツールを使用して FastAPIでは「パッチ」バージョンはバグ修正と非破壊的な変更に留めるという規約に従っています。 -/// tip | "豆知識" +/// tip | 豆知識 「パッチ」は最後の数字を指します。例えば、`0.2.3` ではパッチバージョンは `3` です。 @@ -56,7 +56,7 @@ fastapi>=0.45.0,<0.46.0 破壊的な変更と新機能実装は「マイナー」バージョンで加えられます。 -/// tip | "豆知識" +/// tip | 豆知識 「マイナー」は真ん中の数字です。例えば、`0.2.3` ではマイナーバージョンは `2` です。 diff --git a/docs/ja/docs/features.md b/docs/ja/docs/features.md index 73c0192c703b4..4024590cf0e16 100644 --- a/docs/ja/docs/features.md +++ b/docs/ja/docs/features.md @@ -62,7 +62,7 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -/// info | "情報" +/// info | 情報 `**second_user_data` は以下を意味します: diff --git a/docs/ja/docs/how-to/conditional-openapi.md b/docs/ja/docs/how-to/conditional-openapi.md index 053d481f7a2ed..bfaa9e6d754b3 100644 --- a/docs/ja/docs/how-to/conditional-openapi.md +++ b/docs/ja/docs/how-to/conditional-openapi.md @@ -29,9 +29,7 @@ 例えば、 -```Python hl_lines="6 11" -{!../../docs_src/conditional_openapi/tutorial001.py!} -``` +{* ../../docs_src/conditional_openapi/tutorial001.py hl[6,11] *} ここでは `openapi_url` の設定を、デフォルトの `"/openapi.json"` のまま宣言しています。 diff --git a/docs/ja/docs/python-types.md b/docs/ja/docs/python-types.md index 7af6ce0c0b148..a847ce5d54be3 100644 --- a/docs/ja/docs/python-types.md +++ b/docs/ja/docs/python-types.md @@ -12,7 +12,7 @@ しかしたとえまったく **FastAPI** を使用しない場合でも、それらについて少し学ぶことで利点を得ることができるでしょう。 -/// note | "備考" +/// note | 備考 もしあなたがPythonの専門家で、すでに型ヒントについてすべて知っているのであれば、次の章まで読み飛ばしてください。 @@ -22,9 +22,8 @@ 簡単な例から始めてみましょう: -```Python -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py *} + このプログラムを実行すると以下が出力されます: @@ -38,9 +37,8 @@ John Doe * `title()`を用いて、それぞれの最初の文字を大文字に変換します。 * 真ん中にスペースを入れて連結します。 -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py hl[2] *} + ### 編集 @@ -82,9 +80,8 @@ John Doe それが「型ヒント」です: -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial002.py!} -``` +{* ../../docs_src/python_types/tutorial002.py hl[1] *} + これは、以下のようにデフォルト値を宣言するのと同じではありません: @@ -112,9 +109,8 @@ John Doe この関数を見てください。すでに型ヒントを持っています: -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial003.py!} -``` +{* ../../docs_src/python_types/tutorial003.py hl[1] *} + エディタは変数の型を知っているので、補完だけでなく、エラーチェックをすることもできます。 @@ -122,9 +118,8 @@ John Doe これで`age`を`str(age)`で文字列に変換して修正する必要があることがわかります: -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial004.py!} -``` +{* ../../docs_src/python_types/tutorial004.py hl[2] *} + ## 型の宣言 @@ -143,9 +138,8 @@ John Doe * `bool` * `bytes` -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial005.py!} -``` +{* ../../docs_src/python_types/tutorial005.py hl[1] *} + ### 型パラメータを持つジェネリック型 @@ -161,9 +155,8 @@ John Doe `typing`から`List`をインポートします(大文字の`L`を含む): -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial006.py!} -``` +{* ../../docs_src/python_types/tutorial006.py hl[1] *} + 同じようにコロン(`:`)の構文で変数を宣言します。 @@ -171,11 +164,10 @@ John Doe リストはいくつかの内部の型を含む型なので、それらを角括弧で囲んでいます。 -```Python hl_lines="4" -{!../../docs_src/python_types/tutorial006.py!} -``` +{* ../../docs_src/python_types/tutorial006.py hl[4] *} + -/// tip | "豆知識" +/// tip | 豆知識 角括弧内の内部の型は「型パラメータ」と呼ばれています。 @@ -199,9 +191,8 @@ John Doe `tuple`と`set`の宣言も同様です: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial007.py!} -``` +{* ../../docs_src/python_types/tutorial007.py hl[1,4] *} + つまり: @@ -217,9 +208,8 @@ John Doe 2番目の型パラメータは`dict`の値です。 -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial008.py!} -``` +{* ../../docs_src/python_types/tutorial008.py hl[1,4] *} + つまり: @@ -256,15 +246,13 @@ John Doe 例えば、`Person`クラスという名前のクラスがあるとしましょう: -```Python hl_lines="1 2 3" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[1,2,3] *} + 変数の型を`Person`として宣言することができます: -```Python hl_lines="6" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[6] *} + そして、再び、すべてのエディタのサポートを得ることができます: @@ -284,11 +272,10 @@ John Doe Pydanticの公式ドキュメントから引用: -```Python -{!../../docs_src/python_types/tutorial011.py!} -``` +{* ../../docs_src/python_types/tutorial011.py *} + -/// info | "情報" +/// info | 情報 Pydanticについてより学びたい方はドキュメントを参照してください. @@ -320,7 +307,7 @@ Pydanticについてより学びたい方は`mypy`のチートシートを参照してください diff --git a/docs/ja/docs/tutorial/background-tasks.md b/docs/ja/docs/tutorial/background-tasks.md index 6f93408175ba6..650a079fb63ab 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 1d386040aa985..0466320f1167d 100644 --- a/docs/ja/docs/tutorial/body-fields.md +++ b/docs/ja/docs/tutorial/body-fields.md @@ -6,11 +6,9 @@ まず、以下のようにインポートします: -```Python hl_lines="4" -{!../../docs_src/body_fields/tutorial001.py!} -``` +{* ../../docs_src/body_fields/tutorial001.py hl[4] *} -/// warning | "注意" +/// warning | 注意 `Field`は他の全てのもの(`Query`、`Path`、`Body`など)とは違い、`fastapi`からではなく、`pydantic`から直接インポートされていることに注意してください。 @@ -20,13 +18,11 @@ 以下のように`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 | "技術詳細" +/// note | 技術詳細 実際には次に見る`Query`や`Path`などは、共通の`Param`クラスのサブクラスのオブジェクトを作成しますが、それ自体はPydanticの`FieldInfo`クラスのサブクラスです。 @@ -38,7 +34,7 @@ /// -/// tip | "豆知識" +/// tip | 豆知識 型、デフォルト値、`Field`を持つ各モデルの属性が、`Path`や`Query`、`Body`の代わりに`Field`を持つ、*path operation 関数の*パラメータと同じ構造になっていることに注目してください。 diff --git a/docs/ja/docs/tutorial/body-multiple-params.md b/docs/ja/docs/tutorial/body-multiple-params.md index 647143ee54fda..cbfdda4b211a5 100644 --- a/docs/ja/docs/tutorial/body-multiple-params.md +++ b/docs/ja/docs/tutorial/body-multiple-params.md @@ -8,11 +8,9 @@ また、デフォルトの`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 | "備考" +/// note | 備考 この場合、ボディから取得する`item`はオプションであることに注意してください。デフォルト値は`None`です。 @@ -33,9 +31,7 @@ しかし、`item`と`user`のように複数のボディパラメータを宣言することもできます: -```Python hl_lines="22" -{!../../docs_src/body_multiple_params/tutorial002.py!} -``` +{* ../../docs_src/body_multiple_params/tutorial002.py hl[22] *} この場合、**FastAPI**は関数内に複数のボディパラメータ(Pydanticモデルである2つのパラメータ)があることに気付きます。 @@ -56,7 +52,7 @@ } ``` -/// note | "備考" +/// note | 備考 以前と同じように`item`が宣言されていたにもかかわらず、`item`はキー`item`を持つボディの内部にあることが期待されていることに注意してください。 @@ -77,9 +73,7 @@ しかし、`Body`を使用して、**FastAPI** に別のボディキーとして扱うように指示することができます: -```Python hl_lines="23" -{!../../docs_src/body_multiple_params/tutorial003.py!} -``` +{* ../../docs_src/body_multiple_params/tutorial003.py hl[23] *} この場合、**FastAPI** は以下のようなボディを期待します: @@ -114,11 +108,9 @@ q: str = None 以下において: -```Python hl_lines="27" -{!../../docs_src/body_multiple_params/tutorial004.py!} -``` +{* ../../docs_src/body_multiple_params/tutorial004.py hl[27] *} -/// info | "情報" +/// info | 情報 `Body`もまた、後述する `Query` や `Path` などと同様に、すべての検証パラメータとメタデータパラメータを持っています。 @@ -138,9 +130,7 @@ item: Item = Body(..., embed=True) 以下において: -```Python hl_lines="17" -{!../../docs_src/body_multiple_params/tutorial005.py!} -``` +{* ../../docs_src/body_multiple_params/tutorial005.py hl[17] *} この場合、**FastAPI** は以下のようなボディを期待します: diff --git a/docs/ja/docs/tutorial/body-nested-models.md b/docs/ja/docs/tutorial/body-nested-models.md index 8703a40e7d6ff..a1680d10f2525 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,7 +146,7 @@ Pydanticモデルを`list`や`set`などのサブタイプとして使用する } ``` -/// info | "情報" +/// info | 情報 `images`キーが画像オブジェクトのリストを持つようになったことに注目してください。 @@ -172,11 +156,9 @@ Pydanticモデルを`list`や`set`などのサブタイプとして使用する 深くネストされた任意のモデルを定義することができます: -```Python hl_lines="9 14 20 23 27" -{!../../docs_src/body_nested_models/tutorial007.py!} -``` +{* ../../docs_src/body_nested_models/tutorial007.py hl[9,14,20,23,27] *} -/// info | "情報" +/// info | 情報 `Offer`は`Item`のリストであり、オプションの`Image`のリストを持っていることに注目してください。 @@ -192,9 +174,7 @@ images: List[Image] 以下のように: -```Python hl_lines="15" -{!../../docs_src/body_nested_models/tutorial008.py!} -``` +{* ../../docs_src/body_nested_models/tutorial008.py hl[15] *} ## あらゆる場所でのエディタサポート @@ -224,11 +204,9 @@ 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 | "豆知識" +/// tip | 豆知識 JSONはキーとして`str`しかサポートしていないことに注意してください。 diff --git a/docs/ja/docs/tutorial/body-updates.md b/docs/ja/docs/tutorial/body-updates.md index fde9f4f5e4349..ffbe52e1db200 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,7 +32,7 @@ つまり、更新したいデータだけを送信して、残りはそのままにしておくことができます。 -/// note | "備考" +/// note | 備考 `PATCH`は`PUT`よりもあまり使われておらず、知られていません。 @@ -56,9 +54,7 @@ これを使うことで、デフォルト値を省略して、設定された(リクエストで送られた)データのみを含む`dict`を生成することができます: -```Python hl_lines="34" -{!../../docs_src/body_updates/tutorial002.py!} -``` +{* ../../docs_src/body_updates/tutorial002.py hl[34] *} ### Pydanticの`update`パラメータ @@ -66,9 +62,7 @@ `stored_item_model.copy(update=update_data)`のように: -```Python hl_lines="35" -{!../../docs_src/body_updates/tutorial002.py!} -``` +{* ../../docs_src/body_updates/tutorial002.py hl[35] *} ### 部分的更新のまとめ @@ -85,11 +79,9 @@ * データを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 | "豆知識" +/// tip | 豆知識 実際には、HTTPの`PUT`操作でも同じテクニックを使用することができます。 @@ -97,7 +89,7 @@ /// -/// note | "備考" +/// note | 備考 入力モデルがまだ検証されていることに注目してください。 diff --git a/docs/ja/docs/tutorial/body.md b/docs/ja/docs/tutorial/body.md index 888d4388accea..8376959d5b2ca 100644 --- a/docs/ja/docs/tutorial/body.md +++ b/docs/ja/docs/tutorial/body.md @@ -8,7 +8,7 @@ APIはほとんどの場合 **レスポンス** ボディを送らなければ **リクエスト** ボディを宣言するために Pydantic モデルを使用します。そして、その全てのパワーとメリットを利用します。 -/// info | "情報" +/// info | 情報 データを送るには、`POST` (もっともよく使われる)、`PUT`、`DELETE` または `PATCH` を使うべきです。 @@ -22,9 +22,7 @@ GET リクエストでボディを送信することは、仕様では未定義 ます初めに、 `pydantic` から `BaseModel` をインポートする必要があります: -```Python hl_lines="2" -{!../../docs_src/body/tutorial001.py!} -``` +{* ../../docs_src/body/tutorial001.py hl[2] *} ## データモデルの作成 @@ -32,9 +30,7 @@ GET リクエストでボディを送信することは、仕様では未定義 すべての属性にpython標準の型を使用します: -```Python hl_lines="5-9" -{!../../docs_src/body/tutorial001.py!} -``` +{* ../../docs_src/body/tutorial001.py hl[5:9] *} クエリパラメータの宣言と同様に、モデル属性がデフォルト値をもつとき、必須な属性ではなくなります。それ以外は必須になります。オプショナルな属性にしたい場合は `None` を使用してください。 @@ -62,9 +58,7 @@ GET リクエストでボディを送信することは、仕様では未定義 *パスオペレーション* に加えるために、パスパラメータやクエリパラメータと同じ様に宣言します: -```Python hl_lines="16" -{!../../docs_src/body/tutorial001.py!} -``` +{* ../../docs_src/body/tutorial001.py hl[16] *} ...そして、作成したモデル `Item` で型を宣言します。 @@ -113,7 +107,7 @@ GET リクエストでボディを送信することは、仕様では未定義 -/// tip | "豆知識" +/// tip | 豆知識 PyCharmエディタを使用している場合は、Pydantic PyCharm Pluginが使用可能です。 @@ -131,9 +125,7 @@ GET リクエストでボディを送信することは、仕様では未定義 関数内部で、モデルの全ての属性に直接アクセスできます: -```Python hl_lines="19" -{!../../docs_src/body/tutorial002.py!} -``` +{* ../../docs_src/body/tutorial002.py hl[19] *} ## リクエストボディ + パスパラメータ @@ -141,9 +133,7 @@ GET リクエストでボディを送信することは、仕様では未定義 **FastAPI** はパスパラメータである関数パラメータは**パスから受け取り**、Pydanticモデルによって宣言された関数パラメータは**リクエストボディから受け取る**ということを認識します。 -```Python hl_lines="15-16" -{!../../docs_src/body/tutorial003.py!} -``` +{* ../../docs_src/body/tutorial003.py hl[15:16] *} ## リクエストボディ + パスパラメータ + クエリパラメータ @@ -151,9 +141,7 @@ GET リクエストでボディを送信することは、仕様では未定義 **FastAPI** はそれぞれを認識し、適切な場所からデータを取得します。 -```Python hl_lines="16" -{!../../docs_src/body/tutorial004.py!} -``` +{* ../../docs_src/body/tutorial004.py hl[16] *} 関数パラメータは以下の様に認識されます: @@ -161,7 +149,7 @@ GET リクエストでボディを送信することは、仕様では未定義 * パラメータが**単数型** (`int`、`float`、`str`、`bool` など)の場合は**クエリ**パラメータとして解釈されます。 * パラメータが **Pydantic モデル**型で宣言された場合、リクエスト**ボディ**として解釈されます。 -/// note | "備考" +/// note | 備考 FastAPIは、`= None`があるおかげで、`q`がオプショナルだとわかります。 diff --git a/docs/ja/docs/tutorial/cookie-params.md b/docs/ja/docs/tutorial/cookie-params.md index 1f45db17c2a9c..13af6d3c77d3c 100644 --- a/docs/ja/docs/tutorial/cookie-params.md +++ b/docs/ja/docs/tutorial/cookie-params.md @@ -6,9 +6,7 @@ まず、`Cookie`をインポートします: -```Python hl_lines="3" -{!../../docs_src/cookie_params/tutorial001.py!} -``` +{* ../../docs_src/cookie_params/tutorial001.py hl[3] *} ## `Cookie`のパラメータを宣言 @@ -16,11 +14,9 @@ 最初の値がデフォルト値で、追加の検証パラメータや注釈パラメータをすべて渡すことができます: -```Python hl_lines="9" -{!../../docs_src/cookie_params/tutorial001.py!} -``` +{* ../../docs_src/cookie_params/tutorial001.py hl[9] *} -/// note | "技術詳細" +/// note | 技術詳細 `Cookie`は`Path`と`Query`の「姉妹」クラスです。また、同じ共通の`Param`クラスを継承しています。 @@ -28,7 +24,7 @@ /// -/// info | "情報" +/// info | 情報 クッキーを宣言するには、`Cookie`を使う必要があります。なぜなら、そうしないとパラメータがクエリのパラメータとして解釈されてしまうからです。 diff --git a/docs/ja/docs/tutorial/cors.md b/docs/ja/docs/tutorial/cors.md index 9530c51bfe81d..f7bd59b709ff3 100644 --- a/docs/ja/docs/tutorial/cors.md +++ b/docs/ja/docs/tutorial/cors.md @@ -46,9 +46,7 @@ * 特定のHTTPメソッド (`POST`、`PUT`) またはワイルドカード `"*"` を使用してすべて許可。 * 特定のHTTPヘッダー、またはワイルドカード `"*"`を使用してすべて許可。 -```Python hl_lines="2 6-11 13-19" -{!../../docs_src/cors/tutorial001.py!} -``` +{* ../../docs_src/cors/tutorial001.py hl[2,6:11,13:19] *} `CORSMiddleware` 実装のデフォルトのパラメータはCORSに関して制限を与えるものになっているので、ブラウザにドメインを跨いで特定のオリジン、メソッド、またはヘッダーを使用可能にするためには、それらを明示的に有効にする必要があります @@ -78,7 +76,7 @@ CORSについてより詳しい情報は、Mozilla CORS documentation を参照して下さい。 -/// note | "技術詳細" +/// note | 技術詳細 `from starlette.middleware.cors import CORSMiddleware` も使用できます。 diff --git a/docs/ja/docs/tutorial/debugging.md b/docs/ja/docs/tutorial/debugging.md index be0ff81d48a1f..6c29679efd6e7 100644 --- a/docs/ja/docs/tutorial/debugging.md +++ b/docs/ja/docs/tutorial/debugging.md @@ -6,9 +6,7 @@ Visual Studio CodeやPyCharmなどを使用して、エディター上でデバ FastAPIアプリケーション上で、`uvicorn` を直接インポートして実行します: -```Python hl_lines="1 15" -{!../../docs_src/debugging/tutorial001.py!} -``` +{* ../../docs_src/debugging/tutorial001.py hl[1,15] *} ### `__name__ == "__main__"` について @@ -74,7 +72,7 @@ from myapp import app は実行されません。 -/// info | "情報" +/// info | 情報 より詳しい情報は、公式Pythonドキュメントを参照してください。 diff --git a/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md index fb23a7b2b982f..80153529e5cab 100644 --- a/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md @@ -6,9 +6,7 @@ 前の例では、依存関係("dependable")から`dict`を返していました: -```Python hl_lines="9" -{!../../docs_src/dependencies/tutorial001.py!} -``` +{* ../../docs_src/dependencies/tutorial001.py hl[9] *} しかし、*path operation関数*のパラメータ`commons`に`dict`が含まれています。 @@ -71,21 +69,15 @@ FastAPIが実際にチェックしているのは、それが「呼び出し可 そこで、上で紹介した依存関係の`common_parameters`を`CommonQueryParams`クラスに変更します: -```Python hl_lines="11 12 13 14 15" -{!../../docs_src/dependencies/tutorial002.py!} -``` +{* ../../docs_src/dependencies/tutorial002.py hl[11,12,13,14,15] *} クラスのインスタンスを作成するために使用される`__init__`メソッドに注目してください: -```Python hl_lines="12" -{!../../docs_src/dependencies/tutorial002.py!} -``` +{* ../../docs_src/dependencies/tutorial002.py hl[12] *} ...以前の`common_parameters`と同じパラメータを持っています: -```Python hl_lines="8" -{!../../docs_src/dependencies/tutorial001.py!} -``` +{* ../../docs_src/dependencies/tutorial001.py hl[8] *} これらのパラメータは **FastAPI** が依存関係を「解決」するために使用するものです。 @@ -101,9 +93,7 @@ FastAPIが実際にチェックしているのは、それが「呼び出し可 これで、このクラスを使用して依存関係を宣言することができます。 -```Python hl_lines="19" -{!../../docs_src/dependencies/tutorial002.py!} -``` +{* ../../docs_src/dependencies/tutorial002.py hl[19] *} **FastAPI** は`CommonQueryParams`クラスを呼び出します。これにより、そのクラスの「インスタンス」が作成され、インスタンスはパラメータ`commons`として関数に渡されます。 @@ -143,9 +133,7 @@ commons = Depends(CommonQueryParams) 以下にあるように: -```Python hl_lines="19" -{!../../docs_src/dependencies/tutorial003.py!} -``` +{* ../../docs_src/dependencies/tutorial003.py hl[19] *} しかし、型を宣言することは推奨されています。そうすれば、エディタは`commons`のパラメータとして何が渡されるかを知ることができ、コードの補完や型チェックなどを行うのに役立ちます: @@ -179,13 +167,11 @@ commons: CommonQueryParams = Depends() 同じ例では以下のようになります: -```Python hl_lines="19" -{!../../docs_src/dependencies/tutorial004.py!} -``` +{* ../../docs_src/dependencies/tutorial004.py hl[19] *} ...そして **FastAPI** は何をすべきか知っています。 -/// tip | "豆知識" +/// tip | 豆知識 役に立つというよりも、混乱するようであれば無視してください。それをする*必要*はありません。 diff --git a/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index 59f21c3df7aee..0fb15ae02c5f3 100644 --- a/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -14,13 +14,11 @@ それは`Depends()`の`list`であるべきです: -```Python hl_lines="17" -{!../../docs_src/dependencies/tutorial006.py!} -``` +{* ../../docs_src/dependencies/tutorial006.py hl[17] *} これらの依存関係は、通常の依存関係と同様に実行・解決されます。しかし、それらの値(何かを返す場合)は*path operation関数*には渡されません。 -/// tip | "豆知識" +/// tip | 豆知識 エディタによっては、未使用の関数パラメータをチェックしてエラーとして表示するものもあります。 @@ -38,17 +36,13 @@ これらはリクエストの要件(ヘッダのようなもの)やその他のサブ依存関係を宣言することができます: -```Python hl_lines="6 11" -{!../../docs_src/dependencies/tutorial006.py!} -``` +{* ../../docs_src/dependencies/tutorial006.py hl[6,11] *} ### 例外の発生 これらの依存関係は通常の依存関係と同じように、例外を`raise`発生させることができます: -```Python hl_lines="8 13" -{!../../docs_src/dependencies/tutorial006.py!} -``` +{* ../../docs_src/dependencies/tutorial006.py hl[8,13] *} ### 戻り値 @@ -56,9 +50,7 @@ つまり、すでにどこかで使っている通常の依存関係(値を返すもの)を再利用することができ、値は使われなくても依存関係は実行されます: -```Python hl_lines="9 14" -{!../../docs_src/dependencies/tutorial006.py!} -``` +{* ../../docs_src/dependencies/tutorial006.py hl[9,14] *} ## *path operations*のグループに対する依存関係 diff --git a/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md index 7ef1caf0d42ea..35a69de0dfe2d 100644 --- a/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md @@ -4,13 +4,13 @@ FastAPIは、いくつかのしてカスタムの独自ヘッダーを追加できます。 @@ -43,7 +41,7 @@ /// -/// note | "技術詳細" +/// note | 技術詳細 `from starlette.requests import Request` を使用することもできます。 @@ -59,9 +57,7 @@ 例えば、リクエストの処理とレスポンスの生成にかかった秒数を含むカスタムヘッダー `X-Process-Time` を追加できます: -```Python hl_lines="10 12-13" -{!../../docs_src/middleware/tutorial001.py!} -``` +{* ../../docs_src/middleware/tutorial001.py hl[10,12:13] *} ## その他のミドルウェア diff --git a/docs/ja/docs/tutorial/path-operation-configuration.md b/docs/ja/docs/tutorial/path-operation-configuration.md index 7eceb377d5bc5..0cc38cb2559de 100644 --- a/docs/ja/docs/tutorial/path-operation-configuration.md +++ b/docs/ja/docs/tutorial/path-operation-configuration.md @@ -2,7 +2,7 @@ *path operationデコレータ*を設定するためのパラメータがいくつかあります。 -/// warning | "注意" +/// warning | 注意 これらのパラメータは*path operation関数*ではなく、*path operationデコレータ*に直接渡されることに注意してください。 @@ -16,13 +16,11 @@ しかし、それぞれの番号コードが何のためのものか覚えていない場合は、`status`のショートカット定数を使用することができます: -```Python hl_lines="3 17" -{!../../docs_src/path_operation_configuration/tutorial001.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial001.py hl[3,17] *} そのステータスコードはレスポンスで使用され、OpenAPIスキーマに追加されます。 -/// note | "技術詳細" +/// note | 技術詳細 また、`from starlette import status`を使用することもできます。 @@ -34,9 +32,7 @@ `tags`パラメータを`str`の`list`(通常は1つの`str`)と一緒に渡すと、*path operation*にタグを追加できます: -```Python hl_lines="17 22 27" -{!../../docs_src/path_operation_configuration/tutorial002.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial002.py hl[17,22,27] *} これらはOpenAPIスキーマに追加され、自動ドキュメントのインターフェースで使用されます: @@ -46,9 +42,7 @@ `summary`と`description`を追加できます: -```Python hl_lines="20-21" -{!../../docs_src/path_operation_configuration/tutorial003.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial003.py hl[20:21] *} ## docstringを用いた説明 @@ -56,9 +50,7 @@ docstringにMarkdownを記述すれば、正しく解釈されて表示されます。(docstringのインデントを考慮して) -```Python hl_lines="19-27" -{!../../docs_src/path_operation_configuration/tutorial004.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial004.py hl[19:27] *} これは対話的ドキュメントで使用されます: @@ -68,17 +60,15 @@ docstringにdeprecatedとしてマークする必要があるが、それを削除しない場合は、`deprecated`パラメータを渡します: -```Python hl_lines="16" -{!../../docs_src/path_operation_configuration/tutorial006.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial006.py hl[16] *} 対話的ドキュメントでは非推奨と明記されます: diff --git a/docs/ja/docs/tutorial/path-params-numeric-validations.md b/docs/ja/docs/tutorial/path-params-numeric-validations.md index 42fbb2ee2c3b6..13a71f72f96f8 100644 --- a/docs/ja/docs/tutorial/path-params-numeric-validations.md +++ b/docs/ja/docs/tutorial/path-params-numeric-validations.md @@ -6,9 +6,7 @@ まず初めに、`fastapi`から`Path`をインポートします: -```Python hl_lines="1" -{!../../docs_src/path_params_numeric_validations/tutorial001.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial001.py hl[1] *} ## メタデータの宣言 @@ -16,11 +14,9 @@ 例えば、パスパラメータ`item_id`に対して`title`のメタデータを宣言するには以下のようにします: -```Python hl_lines="8" -{!../../docs_src/path_params_numeric_validations/tutorial001.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial001.py hl[8] *} -/// note | "備考" +/// note | 備考 パスの一部でなければならないので、パスパラメータは常に必須です。 @@ -46,9 +42,7 @@ Pythonは「デフォルト」を持たない値の前に「デフォルト」 そのため、以下のように関数を宣言することができます: -```Python hl_lines="8" -{!../../docs_src/path_params_numeric_validations/tutorial002.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial002.py hl[8] *} ## 必要に応じてパラメータを並び替えるトリック @@ -58,9 +52,7 @@ Pythonは「デフォルト」を持たない値の前に「デフォルト」 Pythonはその`*`で何かをすることはありませんが、それ以降のすべてのパラメータがキーワード引数(キーと値のペア)として呼ばれるべきものであると知っているでしょう。それはkwargsとしても知られています。たとえデフォルト値がなくても。 -```Python hl_lines="8" -{!../../docs_src/path_params_numeric_validations/tutorial003.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[8] *} ## 数値の検証: 以上 @@ -68,9 +60,7 @@ Pythonはその`*`で何かをすることはありませんが、それ以降 ここで、`ge=1`の場合、`item_id`は`1`「より大きい`g`か、同じ`e`」整数でなれけばなりません。 -```Python hl_lines="8" -{!../../docs_src/path_params_numeric_validations/tutorial004.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial004.py hl[8] *} ## 数値の検証: より大きいと小なりイコール @@ -79,9 +69,7 @@ Pythonはその`*`で何かをすることはありませんが、それ以降 * `gt`: より大きい(`g`reater `t`han) * `le`: 小なりイコール(`l`ess than or `e`qual) -```Python hl_lines="9" -{!../../docs_src/path_params_numeric_validations/tutorial005.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial005.py hl[9] *} ## 数値の検証: 浮動小数点、 大なり小なり @@ -93,9 +81,7 @@ Pythonはその`*`で何かをすることはありませんが、それ以降 これはltも同じです。 -```Python hl_lines="11" -{!../../docs_src/path_params_numeric_validations/tutorial006.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial006.py hl[11] *} ## まとめ @@ -108,7 +94,7 @@ Pythonはその`*`で何かをすることはありませんが、それ以降 * `lt`: より小さい(`l`ess `t`han) * `le`: 以下(`l`ess than or `e`qual) -/// info | "情報" +/// info | 情報 `Query`、`Path`などは後に共通の`Param`クラスのサブクラスを見ることになります。(使う必要はありません) @@ -116,7 +102,7 @@ Pythonはその`*`で何かをすることはありませんが、それ以降 /// -/// note | "技術詳細" +/// note | 技術詳細 `fastapi`から`Query`、`Path`などをインポートすると、これらは実際には関数です。 diff --git a/docs/ja/docs/tutorial/path-params.md b/docs/ja/docs/tutorial/path-params.md index e1cb67a13a4e4..1893ec12f434d 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,13 +16,11 @@ 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 | 確認 これにより、関数内でのエディターサポート (エラーチェックや補完など) が提供されます。 @@ -38,7 +34,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー {"item_id":3} ``` -/// check | "確認" +/// check | 確認 関数が受け取った(および返した)値は、文字列の `"3"` ではなく、Pythonの `int` としての `3` であることに注意してください。 @@ -69,7 +65,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー http://127.0.0.1:8000/items/4.2 で見られるように、intのかわりに `float` が与えられた場合にも同様なエラーが表示されます。 -/// check | "確認" +/// check | 確認 したがって、Pythonの型宣言を使用することで、**FastAPI**はデータのバリデーションを行います。 @@ -85,7 +81,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー -/// check | "確認" +/// check | 確認 繰り返しになりますが、Python型宣言を使用するだけで、**FastAPI**は対話的なAPIドキュメントを自動的に生成します(Swagger UIを統合)。 @@ -121,9 +117,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー *path operations* は順に評価されるので、 `/users/me` が `/users/{user_id}` よりも先に宣言されているか確認する必要があります: -```Python hl_lines="6 11" -{!../../docs_src/path_params/tutorial003.py!} -``` +{* ../../docs_src/path_params/tutorial003.py hl[6,11] *} それ以外の場合、 `/users/{users_id}` は `/users/me` としてもマッチします。値が「"me"」であるパラメータ `user_id` を受け取ると「考え」ます。 @@ -139,17 +133,15 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー そして、固定値のクラス属性を作ります。すると、その値が使用可能な値となります: -```Python hl_lines="1 6 7 8 9" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[1,6,7,8,9] *} -/// info | "情報" +/// info | 情報 Enumerations (もしくは、enums)はPython 3.4以降で利用できます。 /// -/// tip | "豆知識" +/// tip | 豆知識 "AlexNet"、"ResNet"そして"LeNet"は機械学習モデルの名前です。 @@ -159,9 +151,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー 次に、作成したenumクラスである`ModelName`を使用した型アノテーションをもつ*パスパラメータ*を作成します: -```Python hl_lines="16" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[16] *} ### ドキュメントの確認 @@ -177,19 +167,15 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー これは、作成した列挙型 `ModelName` の*列挙型メンバ*と比較できます: -```Python hl_lines="17" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[17] *} #### *列挙値*の取得 `model_name.value` 、もしくは一般に、 `your_enum_member.value` を使用して実際の値 (この場合は `str`) を取得できます。 -```Python hl_lines="20" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[20] *} -/// tip | "豆知識" +/// tip | 豆知識 `ModelName.lenet.value` でも `"lenet"` 値にアクセスできます。 @@ -201,9 +187,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー それらはクライアントに返される前に適切な値 (この場合は文字列) に変換されます。 -```Python hl_lines="18 21 23" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[18,21,23] *} クライアントは以下の様なJSONレスポンスを得ます: @@ -242,11 +226,9 @@ Starletteのオプションを直接使用することで、以下のURLの様 したがって、以下の様に使用できます: -```Python hl_lines="6" -{!../../docs_src/path_params/tutorial004.py!} -``` +{* ../../docs_src/path_params/tutorial004.py hl[6] *} -/// tip | "豆知識" +/// tip | 豆知識 最初のスラッシュ (`/`)が付いている `/home/johndoe/myfile.txt` をパラメータが含んでいる必要があります。 diff --git a/docs/ja/docs/tutorial/query-params-str-validations.md b/docs/ja/docs/tutorial/query-params-str-validations.md index 9e54a6f557826..22b89e452ff44 100644 --- a/docs/ja/docs/tutorial/query-params-str-validations.md +++ b/docs/ja/docs/tutorial/query-params-str-validations.md @@ -4,13 +4,11 @@ 以下のアプリケーションを例にしてみましょう: -```Python hl_lines="9" -{!../../docs_src/query_params_str_validations/tutorial001.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial001.py hl[9] *} クエリパラメータ `q` は `Optional[str]` 型で、`None` を許容する `str` 型を意味しており、デフォルトは `None` です。そのため、FastAPIはそれが必須ではないと理解します。 -/// note | "備考" +/// note | 備考 FastAPIは、 `q` はデフォルト値が `=None` であるため、必須ではないと理解します。 @@ -26,17 +24,13 @@ FastAPIは、 `q` はデフォルト値が `=None` であるため、必須で そのために、まずは`fastapi`から`Query`をインポートします: -```Python hl_lines="3" -{!../../docs_src/query_params_str_validations/tutorial002.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial002.py hl[3] *} ## デフォルト値として`Query`を使用 パラメータのデフォルト値として使用し、パラメータ`max_length`を50に設定します: -```Python hl_lines="9" -{!../../docs_src/query_params_str_validations/tutorial002.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial002.py hl[9] *} デフォルト値`None`を`Query(default=None)`に置き換える必要があるので、`Query`の最初の引数はデフォルト値を定義するのと同じです。 @@ -54,7 +48,7 @@ q: Optional[str] = None しかし、これはクエリパラメータとして明示的に宣言しています。 -/// info | "情報" +/// info | 情報 FastAPIは以下の部分を気にすることを覚えておいてください: @@ -86,17 +80,13 @@ q: Union[str, None] = Query(default=None, max_length=50) パラメータ`min_length`も追加することができます: -```Python hl_lines="10" -{!../../docs_src/query_params_str_validations/tutorial003.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial003.py hl[10] *} ## 正規表現の追加 パラメータが一致するべき正規表現を定義することができます: -```Python hl_lines="11" -{!../../docs_src/query_params_str_validations/tutorial004.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial004.py hl[11] *} この特定の正規表現は受け取ったパラメータの値をチェックします: @@ -114,11 +104,9 @@ 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 | 備考 デフォルト値を指定すると、パラメータは任意になります。 @@ -146,11 +134,9 @@ q: Union[str, None] = Query(default=None, min_length=3) そのため、`Query`を使用して必須の値を宣言する必要がある場合は、第一引数に`...`を使用することができます: -```Python hl_lines="7" -{!../../docs_src/query_params_str_validations/tutorial006.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial006.py hl[7] *} -/// info | "情報" +/// info | 情報 これまで`...`を見たことがない方へ: これは特殊な単一値です。Pythonの一部であり、"Ellipsis"と呼ばれています。 @@ -164,9 +150,7 @@ q: Union[str, None] = Query(default=None, min_length=3) 例えば、URL内に複数回出現するクエリパラメータ`q`を宣言するには以下のように書きます: -```Python hl_lines="9" -{!../../docs_src/query_params_str_validations/tutorial011.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial011.py hl[9] *} そしてURLは以下です: @@ -187,7 +171,7 @@ http://localhost:8000/items/?q=foo&q=bar } ``` -/// tip | "豆知識" +/// tip | 豆知識 上述の例のように、`list`型のクエリパラメータを宣言するには明示的に`Query`を使用する必要があります。そうしない場合、リクエストボディと解釈されます。 @@ -201,9 +185,7 @@ http://localhost:8000/items/?q=foo&q=bar また、値が指定されていない場合はデフォルトの`list`を定義することもできます。 -```Python hl_lines="9" -{!../../docs_src/query_params_str_validations/tutorial012.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial012.py hl[9] *} 以下のURLを開くと: @@ -226,11 +208,9 @@ http://localhost:8000/items/ `List[str]`の代わりに直接`list`を使うこともできます: -```Python hl_lines="7" -{!../../docs_src/query_params_str_validations/tutorial013.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial013.py hl[7] *} -/// note | "備考" +/// note | 備考 この場合、FastAPIはリストの内容をチェックしないことを覚えておいてください。 @@ -244,7 +224,7 @@ http://localhost:8000/items/ その情報は、生成されたOpenAPIに含まれ、ドキュメントのユーザーインターフェースや外部のツールで使用されます。 -/// note | "備考" +/// note | 備考 ツールによってOpenAPIのサポートのレベルが異なる可能性があることを覚えておいてください。 @@ -254,15 +234,11 @@ http://localhost:8000/items/ `title`を追加できます: -```Python hl_lines="9" -{!../../docs_src/query_params_str_validations/tutorial007.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial007.py hl[9] *} `description`を追加できます: -```Python hl_lines="13" -{!../../docs_src/query_params_str_validations/tutorial008.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial008.py hl[13] *} ## エイリアスパラメータ @@ -282,9 +258,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems それならば、`alias`を宣言することができます。エイリアスはパラメータの値を見つけるのに使用されます: -```Python hl_lines="9" -{!../../docs_src/query_params_str_validations/tutorial009.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial009.py hl[9] *} ## 非推奨パラメータ @@ -294,9 +268,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems その場合、`Query`にパラメータ`deprecated=True`を渡します: -```Python hl_lines="18" -{!../../docs_src/query_params_str_validations/tutorial010.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial010.py hl[18] *} ドキュメントは以下のようになります: diff --git a/docs/ja/docs/tutorial/query-params.md b/docs/ja/docs/tutorial/query-params.md index 6d41d3742dfa8..74e455579e96e 100644 --- a/docs/ja/docs/tutorial/query-params.md +++ b/docs/ja/docs/tutorial/query-params.md @@ -2,9 +2,7 @@ パスパラメータではない関数パラメータを宣言すると、それらは自動的に "クエリ" パラメータとして解釈されます。 -```Python hl_lines="9" -{!../../docs_src/query_params/tutorial001.py!} -``` +{* ../../docs_src/query_params/tutorial001.py hl[9] *} クエリはURL内で `?` の後に続くキーとバリューの組で、 `&` で区切られています。 @@ -63,13 +61,11 @@ http://127.0.0.1:8000/items/?skip=20 同様に、デフォルト値を `None` とすることで、オプショナルなクエリパラメータを宣言できます: -```Python hl_lines="9" -{!../../docs_src/query_params/tutorial002.py!} -``` +{* ../../docs_src/query_params/tutorial002.py hl[9] *} この場合、関数パラメータ `q` はオプショナルとなり、デフォルトでは `None` になります。 -/// check | "確認" +/// check | 確認 パスパラメータ `item_id` はパスパラメータであり、`q` はそれとは違ってクエリパラメータであると判別できるほど**FastAPI** が賢いということにも注意してください。 @@ -79,9 +75,7 @@ http://127.0.0.1:8000/items/?skip=20 `bool` 型も宣言できます。これは以下の様に変換されます: -```Python hl_lines="9" -{!../../docs_src/query_params/tutorial003.py!} -``` +{* ../../docs_src/query_params/tutorial003.py hl[9] *} この場合、以下にアクセスすると: @@ -123,9 +117,7 @@ http://127.0.0.1:8000/items/foo?short=yes 名前で判別されます: -```Python hl_lines="8 10" -{!../../docs_src/query_params/tutorial004.py!} -``` +{* ../../docs_src/query_params/tutorial004.py hl[8,10] *} ## 必須のクエリパラメータ @@ -135,9 +127,7 @@ http://127.0.0.1:8000/items/foo?short=yes しかしクエリパラメータを必須にしたい場合は、ただデフォルト値を宣言しなければよいです: -```Python hl_lines="6-7" -{!../../docs_src/query_params/tutorial005.py!} -``` +{* ../../docs_src/query_params/tutorial005.py hl[6:7] *} ここで、クエリパラメータ `needy` は `str` 型の必須のクエリパラメータです @@ -181,9 +171,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy そして当然、あるパラメータを必須に、別のパラメータにデフォルト値を設定し、また別のパラメータをオプショナルにできます: -```Python hl_lines="10" -{!../../docs_src/query_params/tutorial006.py!} -``` +{* ../../docs_src/query_params/tutorial006.py hl[10] *} この場合、3つのクエリパラメータがあります。: @@ -191,7 +179,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy * `skip`、デフォルト値を `0` とする `int` 。 * `limit`、オプショナルな `int` 。 -/// tip | "豆知識" +/// tip | 豆知識 [パスパラメータ](path-params.md#_8){.internal-link target=_blank}と同様に `Enum` を使用できます。 diff --git a/docs/ja/docs/tutorial/request-forms-and-files.md b/docs/ja/docs/tutorial/request-forms-and-files.md index e03b9166d7ce7..110e3106a6d17 100644 --- a/docs/ja/docs/tutorial/request-forms-and-files.md +++ b/docs/ja/docs/tutorial/request-forms-and-files.md @@ -2,7 +2,7 @@ `File`と`Form`を同時に使うことでファイルとフォームフィールドを定義することができます。 -/// info | "情報" +/// info | 情報 アップロードされたファイルやフォームデータを受信するには、まず`python-multipart`をインストールします。 @@ -12,23 +12,19 @@ ## `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 | "注意" +/// warning | 注意 *path operation*で複数の`File`と`Form`パラメータを宣言することができますが、JSONとして受け取ることを期待している`Body`フィールドを宣言することはできません。なぜなら、リクエストのボディは`application/json`の代わりに`multipart/form-data`を使ってエンコードされているからです。 diff --git a/docs/ja/docs/tutorial/request-forms.md b/docs/ja/docs/tutorial/request-forms.md index eb453c04a6193..eca2cd6dc712f 100644 --- a/docs/ja/docs/tutorial/request-forms.md +++ b/docs/ja/docs/tutorial/request-forms.md @@ -2,7 +2,7 @@ JSONの代わりにフィールドを受け取る場合は、`Form`を使用します。 -/// info | "情報" +/// info | 情報 フォームを使うためには、まず`python-multipart`をインストールします。 @@ -14,17 +14,13 @@ JSONの代わりにフィールドを受け取る場合は、`Form`を使用し `fastapi`から`Form`をインポートします: -```Python hl_lines="1" -{!../../docs_src/request_forms/tutorial001.py!} -``` +{* ../../docs_src/request_forms/tutorial001.py hl[1] *} ## `Form`のパラメータの定義 `Body`や`Query`の場合と同じようにフォームパラメータを作成します: -```Python hl_lines="7" -{!../../docs_src/request_forms/tutorial001.py!} -``` +{* ../../docs_src/request_forms/tutorial001.py hl[7] *} 例えば、OAuth2仕様が使用できる方法の1つ(「パスワードフロー」と呼ばれる)では、フォームフィールドとして`username`と`password`を送信する必要があります。 @@ -32,13 +28,13 @@ JSONの代わりにフィールドを受け取る場合は、`Form`を使用し `Form`では`Body`(および`Query`や`Path`、`Cookie`)と同じメタデータとバリデーションを宣言することができます。 -/// info | "情報" +/// info | 情報 `Form`は`Body`を直接継承するクラスです。 /// -/// tip | "豆知識" +/// tip | 豆知識 フォームのボディを宣言するには、明示的に`Form`を使用する必要があります。なぜなら、これを使わないと、パラメータはクエリパラメータやボディ(JSON)パラメータとして解釈されるからです。 @@ -50,7 +46,7 @@ HTMLフォーム(`
`)がサーバにデータを送信する方 **FastAPI** は、JSONの代わりにそのデータを適切な場所から読み込むようにします。 -/// note | "技術詳細" +/// note | 技術詳細 フォームからのデータは通常、`application/x-www-form-urlencoded`の「media type」を使用してエンコードされます。 @@ -60,7 +56,7 @@ HTMLフォーム(`
`)がサーバにデータを送信する方 /// -/// warning | "注意" +/// warning | 注意 *path operation*で複数の`Form`パラメータを宣言することができますが、JSONとして受け取ることを期待している`Body`フィールドを宣言することはできません。なぜなら、リクエストは`application/json`の代わりに`application/x-www-form-urlencoded`を使ってボディをエンコードするからです。 diff --git a/docs/ja/docs/tutorial/response-model.md b/docs/ja/docs/tutorial/response-model.md index 973f893de771d..b8464a4c73f52 100644 --- a/docs/ja/docs/tutorial/response-model.md +++ b/docs/ja/docs/tutorial/response-model.md @@ -8,11 +8,9 @@ * `@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関数* のパラメータではありません。 @@ -31,7 +29,7 @@ FastAPIは`response_model`を使って以下のことをします: * 出力データをモデルのデータに限定します。これがどのように重要なのか以下で見ていきましょう。 -/// note | "技術詳細" +/// note | 技術詳細 レスポンスモデルは、関数の戻り値のアノテーションではなく、このパラメータで宣言されています。なぜなら、パス関数は実際にはそのレスポンスモデルを返すのではなく、`dict`やデータベースオブジェクト、あるいは他のモデルを返し、`response_model`を使用してフィールドの制限やシリアライズを行うからです。 @@ -41,15 +39,11 @@ FastAPIは`response_model`を使って以下のことをします: ここでは`UserIn`モデルを宣言しています。それには平文のパスワードが含まれています: -```Python hl_lines="9 11" -{!../../docs_src/response_model/tutorial002.py!} -``` +{* ../../docs_src/response_model/tutorial002.py hl[9,11] *} そして、このモデルを使用して入力を宣言し、同じモデルを使って出力を宣言しています: -```Python hl_lines="17 18" -{!../../docs_src/response_model/tutorial002.py!} -``` +{* ../../docs_src/response_model/tutorial002.py hl[17,18] *} これで、ブラウザがパスワードを使ってユーザーを作成する際に、APIがレスポンスで同じパスワードを返すようになりました。 @@ -57,7 +51,7 @@ FastAPIは`response_model`を使って以下のことをします: しかし、同じモデルを別の*path operation*に使用すると、すべてのクライアントにユーザーのパスワードを送信してしまうことになります。 -/// danger | "危険" +/// danger | 危険 ユーザーの平文のパスワードを保存したり、レスポンスで送信したりすることは絶対にしないでください。 @@ -67,21 +61,15 @@ FastAPIは`response_model`を使って以下のことをします: 代わりに、平文のパスワードを持つ入力モデルと、パスワードを持たない出力モデルを作成することができます: -```Python hl_lines="9 11 16" -{!../../docs_src/response_model/tutorial003.py!} -``` +{* ../../docs_src/response_model/tutorial003.py hl[9,11,16] *} ここでは、*path operation関数*がパスワードを含む同じ入力ユーザーを返しているにもかかわらず: -```Python hl_lines="24" -{!../../docs_src/response_model/tutorial003.py!} -``` +{* ../../docs_src/response_model/tutorial003.py hl[24] *} ...`response_model`を`UserOut`と宣言したことで、パスワードが含まれていません: -```Python hl_lines="22" -{!../../docs_src/response_model/tutorial003.py!} -``` +{* ../../docs_src/response_model/tutorial003.py hl[22] *} そのため、**FastAPI** は出力モデルで宣言されていない全てのデータをフィルタリングしてくれます(Pydanticを使用)。 @@ -99,9 +87,7 @@ FastAPIは`response_model`を使って以下のことをします: レスポンスモデルにはデフォルト値を設定することができます: -```Python hl_lines="11 13 14" -{!../../docs_src/response_model/tutorial004.py!} -``` +{* ../../docs_src/response_model/tutorial004.py hl[11,13,14] *} * `description: str = None`は`None`がデフォルト値です。 * `tax: float = 10.5`は`10.5`がデフォルト値です。 @@ -115,9 +101,7 @@ FastAPIは`response_model`を使って以下のことをします: *path operation デコレータ*に`response_model_exclude_unset=True`パラメータを設定することができます: -```Python hl_lines="24" -{!../../docs_src/response_model/tutorial004.py!} -``` +{* ../../docs_src/response_model/tutorial004.py hl[24] *} そして、これらのデフォルト値はレスポンスに含まれず、実際に設定された値のみが含まれます。 @@ -130,13 +114,13 @@ FastAPIは`response_model`を使って以下のことをします: } ``` -/// info | "情報" +/// info | 情報 FastAPIはこれをするために、Pydanticモデルの`.dict()`をその`exclude_unset`パラメータで使用しています。 /// -/// info | "情報" +/// info | 情報 以下も使用することができます: @@ -180,7 +164,7 @@ FastAPIは十分に賢いので(実際には、Pydanticが十分に賢い)`d そのため、それらはJSONレスポンスに含まれることになります。 -/// tip | "豆知識" +/// tip | 豆知識 デフォルト値は`None`だけでなく、なんでも良いことに注意してください。 例えば、リスト(`[]`)や`10.5`の`float`などです。 @@ -195,7 +179,7 @@ FastAPIは十分に賢いので(実際には、Pydanticが十分に賢い)`d これは、Pydanticモデルが1つしかなく、出力からいくつかのデータを削除したい場合のクイックショートカットとして使用することができます。 -/// tip | "豆知識" +/// tip | 豆知識 それでも、これらのパラメータではなく、複数のクラスを使用して、上記のようなアイデアを使うことをおすすめします。 @@ -205,11 +189,9 @@ FastAPIは十分に賢いので(実際には、Pydanticが十分に賢い)`d /// -```Python hl_lines="31 37" -{!../../docs_src/response_model/tutorial005.py!} -``` +{* ../../docs_src/response_model/tutorial005.py hl[31,37] *} -/// tip | "豆知識" +/// tip | 豆知識 `{"name", "description"}`の構文はこれら2つの値をもつ`set`を作成します。 @@ -221,9 +203,7 @@ FastAPIは十分に賢いので(実際には、Pydanticが十分に賢い)`d もし`set`を使用することを忘れて、代わりに`list`や`tuple`を使用しても、FastAPIはそれを`set`に変換して正しく動作します: -```Python hl_lines="31 37" -{!../../docs_src/response_model/tutorial006.py!} -``` +{* ../../docs_src/response_model/tutorial006.py hl[31,37] *} ## まとめ diff --git a/docs/ja/docs/tutorial/response-status-code.md b/docs/ja/docs/tutorial/response-status-code.md index 90b2908871b3b..6d197d543deb3 100644 --- a/docs/ja/docs/tutorial/response-status-code.md +++ b/docs/ja/docs/tutorial/response-status-code.md @@ -8,11 +8,9 @@ * `@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`など)のパラメータであることに注意してください。すべてのパラメータやボディのように、*path operation関数*のものではありません。 @@ -20,7 +18,7 @@ `status_code`パラメータはHTTPステータスコードを含む数値を受け取ります。 -/// info | "情報" +/// info | 情報 `status_code`は代わりに、Pythonの`http.HTTPStatus`のように、`IntEnum`を受け取ることもできます。 @@ -33,7 +31,7 @@ -/// note | "備考" +/// note | 備考 いくつかのレスポンスコード(次のセクションを参照)は、レスポンスにボディがないことを示しています。 @@ -43,7 +41,7 @@ FastAPIはこれを知っていて、レスポンスボディがないというO ## HTTPステータスコードについて -/// note | "備考" +/// note | 備考 すでにHTTPステータスコードが何であるかを知っている場合は、次のセクションにスキップしてください。 @@ -66,7 +64,7 @@ HTTPでは、レスポンスの一部として3桁の数字のステータス * クライアントからの一般的なエラーについては、`400`を使用することができます。 * `500`以上はサーバーエラーのためのものです。これらを直接使うことはほとんどありません。アプリケーションコードやサーバーのどこかで何か問題が発生した場合、これらのステータスコードのいずれかが自動的に返されます。 -/// tip | "豆知識" +/// tip | 豆知識 それぞれのステータスコードとどのコードが何のためのコードなのかについて詳細はMDN HTTP レスポンスステータスコードについてのドキュメントを参照してください。 @@ -76,9 +74,7 @@ HTTPでは、レスポンスの一部として3桁の数字のステータス 先ほどの例をもう一度見てみましょう: -```Python hl_lines="6" -{!../../docs_src/response_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_status_code/tutorial001.py hl[6] *} `201`は「作成完了」のためのステータスコードです。 @@ -86,15 +82,13 @@ HTTPでは、レスポンスの一部として3桁の数字のステータス `fastapi.status`の便利な変数を利用することができます。 -```Python hl_lines="1 6" -{!../../docs_src/response_status_code/tutorial002.py!} -``` +{* ../../docs_src/response_status_code/tutorial002.py hl[1,6] *} それらは便利です。それらは同じ番号を保持しており、その方法ではエディタの自動補完を使用してそれらを見つけることができます。 -/// note | "技術詳細" +/// note | 技術詳細 また、`from starlette import status`を使うこともできます。 diff --git a/docs/ja/docs/tutorial/schema-extra-example.md b/docs/ja/docs/tutorial/schema-extra-example.md index baf1bbedd4a4c..1834e67b27c28 100644 --- a/docs/ja/docs/tutorial/schema-extra-example.md +++ b/docs/ja/docs/tutorial/schema-extra-example.md @@ -10,9 +10,7 @@ JSON Schemaの追加情報を宣言する方法はいくつかあります。 Pydanticのドキュメント: スキーマのカスタマイズで説明されているように、`Config`と`schema_extra`を使ってPydanticモデルの例を宣言することができます: -```Python hl_lines="15 16 17 18 19 20 21 22 23" -{!../../docs_src/schema_extra_example/tutorial001.py!} -``` +{* ../../docs_src/schema_extra_example/tutorial001.py hl[15,16,17,18,19,20,21,22,23] *} その追加情報はそのまま出力され、JSON Schemaに追加されます。 @@ -20,11 +18,9 @@ JSON Schemaの追加情報を宣言する方法はいくつかあります。 後述する`Field`、`Path`、`Query`、`Body`などでは、任意の引数を関数に渡すことでJSON Schemaの追加情報を宣言することもできます: -```Python hl_lines="4 10 11 12 13" -{!../../docs_src/schema_extra_example/tutorial002.py!} -``` +{* ../../docs_src/schema_extra_example/tutorial002.py hl[4,10,11,12,13] *} -/// warning | "注意" +/// warning | 注意 これらの追加引数が渡されても、文書化のためのバリデーションは追加されず、注釈だけが追加されることを覚えておいてください。 @@ -36,9 +32,7 @@ JSON Schemaの追加情報を宣言する方法はいくつかあります。 例えば、`Body`にボディリクエストの`example`を渡すことができます: -```Python hl_lines="21 22 23 24 25 26" -{!../../docs_src/schema_extra_example/tutorial003.py!} -``` +{* ../../docs_src/schema_extra_example/tutorial003.py hl[21,22,23,24,25,26] *} ## ドキュメントのUIの例 diff --git a/docs/ja/docs/tutorial/security/first-steps.md b/docs/ja/docs/tutorial/security/first-steps.md index 51f7bf829a9e2..0ce0f929bee62 100644 --- a/docs/ja/docs/tutorial/security/first-steps.md +++ b/docs/ja/docs/tutorial/security/first-steps.md @@ -20,13 +20,11 @@ `main.py`に、下記の例をコピーします: -```Python -{!../../docs_src/security/tutorial001.py!} -``` +{* ../../docs_src/security/tutorial001.py *} ## 実行 -/// info | "情報" +/// info | 情報 まず`python-multipart`をインストールします。 @@ -56,7 +54,7 @@ $ uvicorn main:app --reload -/// check | "Authorizeボタン!" +/// check | Authorizeボタン! すでにピカピカの新しい「Authorize」ボタンがあります。 @@ -68,7 +66,7 @@ $ uvicorn main:app --reload -/// note | "備考" +/// note | 備考 フォームに何を入力しても、まだうまくいきません。ですが、これから動くようになります。 @@ -114,7 +112,7 @@ OAuth2は、バックエンドやAPIがユーザーを認証するサーバー この例では、**Bearer**トークンを使用して**OAuth2**を**パスワード**フローで使用します。これには`OAuth2PasswordBearer`クラスを使用します。 -/// info | "情報" +/// info | 情報 「bearer」トークンが、唯一の選択肢ではありません。 @@ -128,11 +126,9 @@ OAuth2は、バックエンドやAPIがユーザーを認証するサーバー `OAuth2PasswordBearer` クラスのインスタンスを作成する時に、パラメーター`tokenUrl`を渡します。このパラメーターには、クライアント (ユーザーのブラウザで動作するフロントエンド) がトークンを取得するために`ユーザー名`と`パスワード`を送信するURLを指定します。 -```Python hl_lines="6" -{!../../docs_src/security/tutorial001.py!} -``` +{* ../../docs_src/security/tutorial001.py hl[6] *} -/// tip | "豆知識" +/// tip | 豆知識 ここで、`tokenUrl="token"`は、まだ作成していない相対URL`token`を指します。相対URLなので、`./token`と同じです。 @@ -146,7 +142,7 @@ OAuth2は、バックエンドやAPIがユーザーを認証するサーバー 実際のpath operationもすぐに作ります。 -/// info | "情報" +/// info | 情報 非常に厳格な「Pythonista」であれば、パラメーター名のスタイルが`token_url`ではなく`tokenUrl`であることを気に入らないかもしれません。 @@ -168,15 +164,13 @@ oauth2_scheme(some, parameters) これで`oauth2_scheme`を`Depends`で依存関係に渡すことができます。 -```Python hl_lines="10" -{!../../docs_src/security/tutorial001.py!} -``` +{* ../../docs_src/security/tutorial001.py hl[10] *} この依存関係は、*path operation function*のパラメーター`token`に代入される`str`を提供します。 **FastAPI**は、この依存関係を使用してOpenAPIスキーマ (および自動APIドキュメント) で「セキュリティスキーム」を定義できることを知っています。 -/// info | "技術詳細" +/// info | 技術詳細 **FastAPI**は、`OAuth2PasswordBearer` クラス (依存関係で宣言されている) を使用してOpenAPIのセキュリティスキームを定義できることを知っています。これは`fastapi.security.oauth2.OAuth2`、`fastapi.security.base.SecurityBase`を継承しているからです。 diff --git a/docs/ja/docs/tutorial/security/get-current-user.md b/docs/ja/docs/tutorial/security/get-current-user.md index 0edbd983f3458..9fc46c07c57ad 100644 --- a/docs/ja/docs/tutorial/security/get-current-user.md +++ b/docs/ja/docs/tutorial/security/get-current-user.md @@ -2,9 +2,7 @@ 一つ前の章では、(依存性注入システムに基づいた)セキュリティシステムは、 *path operation関数* に `str` として `token` を与えていました: -```Python hl_lines="10" -{!../../docs_src/security/tutorial001.py!} -``` +{* ../../docs_src/security/tutorial001.py hl[10] *} しかし、それはまだそんなに有用ではありません。 @@ -16,9 +14,7 @@ ボディを宣言するのにPydanticを使用するのと同じやり方で、Pydanticを別のどんなところでも使うことができます: -```Python hl_lines="5 12-16" -{!../../docs_src/security/tutorial002.py!} -``` +{* ../../docs_src/security/tutorial002.py hl[5,12:16] *} ## 依存関係 `get_current_user` を作成 @@ -30,31 +26,25 @@ 以前直接 *path operation* の中でしていたのと同じように、新しい依存関係である `get_current_user` は `str` として `token` を受け取るようになります: -```Python hl_lines="25" -{!../../docs_src/security/tutorial002.py!} -``` +{* ../../docs_src/security/tutorial002.py hl[25] *} ## ユーザーの取得 `get_current_user` は作成した(偽物の)ユーティリティ関数を使って、 `str` としてトークンを受け取り、先ほどのPydanticの `User` モデルを返却します: -```Python hl_lines="19-22 26-27" -{!../../docs_src/security/tutorial002.py!} -``` +{* ../../docs_src/security/tutorial002.py hl[19:22,26:27] *} ## 現在のユーザーの注入 ですので、 `get_current_user` に対して同様に *path operation* の中で `Depends` を利用できます。 -```Python hl_lines="31" -{!../../docs_src/security/tutorial002.py!} -``` +{* ../../docs_src/security/tutorial002.py hl[31] *} Pydanticモデルの `User` として、 `current_user` の型を宣言することに注意してください。 その関数の中ですべての入力補完や型チェックを行う際に役に立ちます。 -/// tip | "豆知識" +/// tip | 豆知識 リクエストボディはPydanticモデルでも宣言できることを覚えているかもしれません。 @@ -62,7 +52,7 @@ Pydanticモデルの `User` として、 `current_user` の型を宣言するこ /// -/// check | "確認" +/// check | 確認 依存関係システムがこのように設計されているおかげで、 `User` モデルを返却する別の依存関係(別の"dependables")を持つことができます。 @@ -103,9 +93,7 @@ Pydanticモデルの `User` として、 `current_user` の型を宣言するこ さらに、こうした何千もの *path operations* は、たった3行で表現できるのです: -```Python hl_lines="30-32" -{!../../docs_src/security/tutorial002.py!} -``` +{* ../../docs_src/security/tutorial002.py hl[30:32] *} ## まとめ diff --git a/docs/ja/docs/tutorial/security/index.md b/docs/ja/docs/tutorial/security/index.md index c68e7e7f2f04d..37b8bb9583810 100644 --- a/docs/ja/docs/tutorial/security/index.md +++ b/docs/ja/docs/tutorial/security/index.md @@ -32,7 +32,7 @@ OAuth 1というものもありましたが、これはOAuth2とは全く異な OAuth2は、通信を暗号化する方法を指定せず、アプリケーションがHTTPSで提供されることを想定しています。 -/// tip | "豆知識" +/// tip | 豆知識 **デプロイ**のセクションでは、TraefikとLet's Encryptを使用して、無料でHTTPSを設定する方法が紹介されています。 @@ -89,7 +89,7 @@ OpenAPIでは、以下のセキュリティスキームを定義しています: * この自動検出メカニズムは、OpenID Connectの仕様で定義されているものです。 -/// tip | "豆知識" +/// tip | 豆知識 Google、Facebook、Twitter、GitHubなど、他の認証/認可プロバイダを統合することも可能で、比較的簡単です。 diff --git a/docs/ja/docs/tutorial/security/oauth2-jwt.md b/docs/ja/docs/tutorial/security/oauth2-jwt.md index b2f51161070c4..4859819cc15d1 100644 --- a/docs/ja/docs/tutorial/security/oauth2-jwt.md +++ b/docs/ja/docs/tutorial/security/oauth2-jwt.md @@ -44,7 +44,7 @@ $ pip install python-jose[cryptography] ここでは、推奨されているものを使用します:pyca/cryptography。 -/// tip | "豆知識" +/// tip | 豆知識 このチュートリアルでは以前、PyJWTを使用していました。 @@ -86,7 +86,7 @@ $ pip install passlib[bcrypt] -/// tip | "豆知識" +/// tip | 豆知識 `passlib`を使用すると、**Django**や**Flask**のセキュリティプラグインなどで作成されたパスワードを読み取れるように設定できます。 @@ -102,7 +102,7 @@ $ pip install passlib[bcrypt] PassLib の「context」を作成します。これは、パスワードのハッシュ化と検証に使用されるものです。 -/// tip | "豆知識" +/// tip | 豆知識 PassLibのcontextには、検証だけが許された非推奨の古いハッシュアルゴリズムを含む、様々なハッシュアルゴリズムを使用した検証機能もあります。 @@ -118,11 +118,9 @@ PassLibのcontextには、検証だけが許された非推奨の古いハッシ さらに、ユーザーを認証して返す関数も作成します。 -```Python hl_lines="7 48 55-56 59-60 69-75" -{!../../docs_src/security/tutorial004.py!} -``` +{* ../../docs_src/security/tutorial004.py hl[7,48,55:56,59:60,69:75] *} -/// note | "備考" +/// note | 備考 新しい(偽の)データベース`fake_users_db`を確認すると、ハッシュ化されたパスワードが次のようになっていることがわかります:`"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"` @@ -156,9 +154,7 @@ JWTトークンの署名に使用するアルゴリズム`"HS256"`を指定し 新しいアクセストークンを生成するユーティリティ関数を作成します。 -```Python hl_lines="6 12-14 28-30 78-86" -{!../../docs_src/security/tutorial004.py!} -``` +{* ../../docs_src/security/tutorial004.py hl[6,12:14,28:30,78:86] *} ## 依存関係の更新 @@ -168,9 +164,7 @@ JWTトークンの署名に使用するアルゴリズム`"HS256"`を指定し トークンが無効な場合は、すぐにHTTPエラーを返します。 -```Python hl_lines="89-106" -{!../../docs_src/security/tutorial004.py!} -``` +{* ../../docs_src/security/tutorial004.py hl[89:106] *} ## `/token` パスオペレーションの更新 @@ -178,9 +172,7 @@ JWTトークンの署名に使用するアルゴリズム`"HS256"`を指定し JWTアクセストークンを作成し、それを返します。 -```Python hl_lines="115-130" -{!../../docs_src/security/tutorial004.py!} -``` +{* ../../docs_src/security/tutorial004.py hl[115:130] *} ### JWTの"subject" `sub` についての技術的な詳細 @@ -219,7 +211,7 @@ IDの衝突を回避するために、ユーザーのJWTトークンを作成す Username: `johndoe` Password: `secret` -/// check | "確認" +/// check | 確認 コードのどこにも平文のパスワード"`secret`"はなく、ハッシュ化されたものしかないことを確認してください。 @@ -244,7 +236,7 @@ Password: `secret` -/// note | "備考" +/// note | 備考 ヘッダーの`Authorization`には、`Bearer`で始まる値があります。 diff --git a/docs/ja/docs/tutorial/static-files.md b/docs/ja/docs/tutorial/static-files.md index e6002a1fb6e25..f63f3f3b1bba0 100644 --- a/docs/ja/docs/tutorial/static-files.md +++ b/docs/ja/docs/tutorial/static-files.md @@ -7,11 +7,9 @@ * `StaticFiles` をインポート。 * `StaticFiles()` インスタンスを生成し、特定のパスに「マウント」。 -```Python hl_lines="2 6" -{!../../docs_src/static_files/tutorial001.py!} -``` +{* ../../docs_src/static_files/tutorial001.py hl[2,6] *} -/// note | "技術詳細" +/// note | 技術詳細 `from starlette.staticfiles import StaticFiles` も使用できます。 diff --git a/docs/ja/docs/tutorial/testing.md b/docs/ja/docs/tutorial/testing.md index 6c5e712e84a6c..fe6c8c6b46057 100644 --- a/docs/ja/docs/tutorial/testing.md +++ b/docs/ja/docs/tutorial/testing.md @@ -18,11 +18,9 @@ チェックしたい Python の標準的な式と共に、シンプルに `assert` 文を記述します。 -```Python hl_lines="2 12 15-18" -{!../../docs_src/app_testing/tutorial001.py!} -``` +{* ../../docs_src/app_testing/tutorial001.py hl[2,12,15:18] *} -/// tip | "豆知識" +/// tip | 豆知識 テスト関数は `async def` ではなく、通常の `def` であることに注意してください。 @@ -32,7 +30,7 @@ /// -/// note | "技術詳細" +/// note | 技術詳細 `from starlette.testclient import TestClient` も使用できます。 @@ -40,7 +38,7 @@ /// -/// tip | "豆知識" +/// tip | 豆知識 FastAPIアプリケーションへのリクエストの送信とは別に、テストで `async` 関数 (非同期データベース関数など) を呼び出したい場合は、高度なチュートリアルの[Async Tests](../advanced/async-tests.md){.internal-link target=_blank} を参照してください。 @@ -56,17 +54,13 @@ FastAPIアプリケーションへのリクエストの送信とは別に、テ **FastAPI** アプリに `main.py` ファイルがあるとします: -```Python -{!../../docs_src/app_testing/main.py!} -``` +{* ../../docs_src/app_testing/main.py *} ### テストファイル 次に、テストを含む `test_main.py` ファイルを作成し、`main` モジュール (`main.py`) から `app` をインポートします: -```Python -{!../../docs_src/app_testing/test_main.py!} -``` +{* ../../docs_src/app_testing/test_main.py *} ## テスト: 例の拡張 @@ -83,29 +77,13 @@ FastAPIアプリケーションへのリクエストの送信とは別に、テ これらの *path operation* には `X-Token` ヘッダーが必要です。 -//// tab | Python 3.10+ - -```Python -{!> ../../docs_src/app_testing/app_b_py310/main.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python -{!> ../../docs_src/app_testing/app_b/main.py!} -``` - -//// +{* ../../docs_src/app_testing/app_b_py310/main.py *} ### 拡張版テストファイル 次に、先程のものに拡張版のテストを加えた、`test_main_b.py` を作成します。 -```Python -{!> ../../docs_src/app_testing/app_b/test_main.py!} -``` +{* ../../docs_src/app_testing/app_b/test_main.py *} リクエストに情報を渡せるクライアントが必要で、その方法がわからない場合はいつでも、`httpx` での実現方法を検索 (Google) できます。 @@ -121,7 +99,7 @@ FastAPIアプリケーションへのリクエストの送信とは別に、テ (`httpx` または `TestClient` を使用して) バックエンドにデータを渡す方法の詳細は、HTTPXのドキュメントを確認してください。 -/// info | "情報" +/// info | 情報 `TestClient` は、Pydanticモデルではなく、JSONに変換できるデータを受け取ることに注意してください。 diff --git a/docs/ko/docs/advanced/advanced-dependencies.md b/docs/ko/docs/advanced/advanced-dependencies.md new file mode 100644 index 0000000000000..7fa043fa3a70a --- /dev/null +++ b/docs/ko/docs/advanced/advanced-dependencies.md @@ -0,0 +1,67 @@ +# 고급 의존성 + +## 매개변수화된 의존성 + +지금까지 본 모든 의존성은 고정된 함수 또는 클래스입니다. + +하지만 여러 개의 함수나 클래스를 선언하지 않고도 의존성에 매개변수를 설정해야 하는 경우가 있을 수 있습니다. + +예를 들어, `q` 쿼리 매개변수가 특정 고정된 내용을 포함하고 있는지 확인하는 의존성을 원한다고 가정해 봅시다. + +이때 해당 고정된 내용을 매개변수화할 수 있길 바랍니다. + +## "호출 가능한" 인스턴스 + +Python에는 클래스의 인스턴스를 "호출 가능"하게 만드는 방법이 있습니다. + +클래스 자체(이미 호출 가능함)가 아니라 해당 클래스의 인스턴스에 대해 호출 가능하게 하는 것입니다. + +이를 위해 `__call__` 메서드를 선언합니다: + +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[12] *} + +이 경우, **FastAPI**는 추가 매개변수와 하위 의존성을 확인하기 위해 `__call__`을 사용하게 되며, +나중에 *경로 연산 함수*에서 매개변수에 값을 전달할 때 이를 호출하게 됩니다. + +## 인스턴스 매개변수화하기 + +이제 `__init__`을 사용하여 의존성을 "매개변수화"할 수 있는 인스턴스의 매개변수를 선언할 수 있습니다: + +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[9] *} + +이 경우, **FastAPI**는 `__init__`에 전혀 관여하지 않으며, 우리는 이 메서드를 코드에서 직접 사용하게 됩니다. + +## 인스턴스 생성하기 + +다음과 같이 이 클래스의 인스턴스를 생성할 수 있습니다: + +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[18] *} + +이렇게 하면 `checker.fixed_content` 속성에 `"bar"`라는 값을 담아 의존성을 "매개변수화"할 수 있습니다. + +## 인스턴스를 의존성으로 사용하기 + +그런 다음, `Depends(FixedContentQueryChecker)` 대신 `Depends(checker)`에서 이 `checker` 인스턴스를 사용할 수 있으며, +클래스 자체가 아닌 인스턴스 `checker`가 의존성이 됩니다. + +의존성을 해결할 때 **FastAPI**는 이 `checker`를 다음과 같이 호출합니다: + +```Python +checker(q="somequery") +``` + +...그리고 이때 반환되는 값을 *경로 연산 함수*의 `fixed_content_included` 매개변수로 전달합니다: + +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[22] *} + +/// tip | 참고 + +이 모든 과정이 복잡하게 느껴질 수 있습니다. 그리고 지금은 이 방법이 얼마나 유용한지 명확하지 않을 수도 있습니다. + +이 예시는 의도적으로 간단하게 만들었지만, 전체 구조가 어떻게 작동하는지 보여줍니다. + +보안 관련 장에서는 이와 같은 방식으로 구현된 편의 함수들이 있습니다. + +이 모든 과정을 이해했다면, 이러한 보안 도구들이 내부적으로 어떻게 작동하는지 이미 파악한 것입니다. + +/// diff --git a/docs/ko/docs/advanced/events.md b/docs/ko/docs/advanced/events.md index 94867c1988e48..ae349e7bec948 100644 --- a/docs/ko/docs/advanced/events.md +++ b/docs/ko/docs/advanced/events.md @@ -4,7 +4,7 @@ 이 함수들은 `async def` 또는 평범하게 `def`으로 선언할 수 있습니다. -/// warning | "경고" +/// warning | 경고 이벤트 핸들러는 주 응용 프로그램에서만 작동합니다. [하위 응용 프로그램 - 마운트](./sub-applications.md){.internal-link target=_blank}에서는 작동하지 않습니다. @@ -14,9 +14,7 @@ 응용 프로그램을 시작하기 전에 실행하려는 함수를 "startup" 이벤트로 선언합니다: -```Python hl_lines="8" -{!../../docs_src/events/tutorial001.py!} -``` +{* ../../docs_src/events/tutorial001.py hl[8] *} 이 경우 `startup` 이벤트 핸들러 함수는 단순히 몇 가지 값으로 구성된 `dict` 형식의 "데이터베이스"를 초기화합니다. @@ -28,19 +26,17 @@ 응용 프로그램이 종료될 때 실행하려는 함수를 추가하려면 `"shutdown"` 이벤트로 선언합니다: -```Python hl_lines="6" -{!../../docs_src/events/tutorial002.py!} -``` +{* ../../docs_src/events/tutorial002.py hl[6] *} 이 예제에서 `shutdown` 이벤트 핸들러 함수는 `"Application shutdown"`이라는 텍스트가 적힌 `log.txt` 파일을 추가할 것입니다. -/// info | "정보" +/// info | 정보 `open()` 함수에서 `mode="a"`는 "추가"를 의미합니다. 따라서 이미 존재하는 파일의 내용을 덮어쓰지 않고 새로운 줄을 추가합니다. /// -/// tip | "팁" +/// tip | 팁 이 예제에서는 파일과 상호작용 하기 위해 파이썬 표준 함수인 `open()`을 사용하고 있습니다. @@ -50,7 +46,7 @@ /// -/// info | "정보" +/// info | 정보 이벤트 핸들러에 관한 내용은 Starlette 이벤트 문서에서 추가로 확인할 수 있습니다. diff --git a/docs/ko/docs/advanced/index.md b/docs/ko/docs/advanced/index.md index cb628fa10b6a3..31704727ca97e 100644 --- a/docs/ko/docs/advanced/index.md +++ b/docs/ko/docs/advanced/index.md @@ -6,7 +6,7 @@ 이어지는 장에서는 여러분이 다른 옵션, 구성 및 추가 기능을 보실 수 있습니다. -/// tip | "팁" +/// tip | 팁 다음 장들이 **반드시 "심화"**인 것은 아닙니다. diff --git a/docs/ko/docs/advanced/middlewares.md b/docs/ko/docs/advanced/middlewares.md new file mode 100644 index 0000000000000..c00aedeaf04c9 --- /dev/null +++ b/docs/ko/docs/advanced/middlewares.md @@ -0,0 +1,96 @@ +# 고급 미들웨어 + +메인 튜토리얼에서 [Custom Middleware](../tutorial/middleware.md){.internal-link target=_blank}를 응용프로그램에 추가하는 방법을 읽으셨습니다. + +그리고 [CORS with the `CORSMiddleware`](){.internal-link target=_blank}하는 방법도 보셨습니다. + +이 섹션에서는 다른 미들웨어들을 사용하는 방법을 알아보겠습니다. + +## ASGI 미들웨어 추가하기 + +**FastAPI**는 Starlette을 기반으로 하고 있으며, ASGI 사양을 구현하므로 ASGI 미들웨어를 사용할 수 있습니다. + +미들웨어가 FastAPI나 Starlette용으로 만들어지지 않아도 ASGI 사양을 준수하는 한 동작할 수 있습니다. + +일반적으로 ASGI 미들웨어는 첫 번째 인수로 ASGI 앱을 받는 클래스들입니다. + +따라서 타사 ASGI 미들웨어 문서에서 일반적으로 다음과 같이 사용하도록 안내할 것입니다. + +```Python +from unicorn import UnicornMiddleware + +app = SomeASGIApp() + +new_app = UnicornMiddleware(app, some_config="rainbow") +``` + +하지만 내부 미들웨어가 서버 오류를 처리하고 사용자 정의 예외 처리기가 제대로 작동하도록 하는 더 간단한 방법을 제공하는 FastAPI(실제로는 Starlette)가 있습니다. + +이를 위해 `app.add_middleware()`를 사용합니다(CORS의 예에서와 같이). + +```Python +from fastapi import FastAPI +from unicorn import UnicornMiddleware + +app = FastAPI() + +app.add_middleware(UnicornMiddleware, some_config="rainbow") +``` + +`app.add_middleware()`는 첫 번째 인수로 미들웨어 클래스와 미들웨어에 전달할 추가 인수를 받습니다. + +## 통합 미들웨어 + +**FastAPI**에는 일반적인 사용 사례를 위한 여러 미들웨어가 포함되어 있으며, 사용 방법은 다음에서 살펴보겠습니다. + +/// note | 기술 세부 사항 + +다음 예제에서는 `from starlette.middleware.something import SomethingMiddleware`를 사용할 수도 있습니다. + +**FastAPI**는 개발자의 편의를 위해 `fastapi.middleware`에 여러 미들웨어를 제공합니다. 그러나 사용 가능한 대부분의 미들웨어는 Starlette에서 직접 제공합니다. + +/// + +## `HTTPSRedirectMiddleware` + +들어오는 모든 요청이 `https` 또는 `wss`여야 합니다. + +`http` 또는 `ws`로 들어오는 모든 요청은 대신 보안 체계로 리디렉션됩니다. + +{* ../../docs_src/advanced_middleware/tutorial001.py hl[2,6] *} + +## `TrustedHostMiddleware` + +HTTP 호스트 헤더 공격을 방지하기 위해 모든 수신 요청에 올바르게 설정된 `Host` 헤더를 갖도록 강제합니다. + +{* ../../docs_src/advanced_middleware/tutorial002.py hl[2,6:8] *} + +다음 인수가 지원됩니다: + +* `allowed_hosts` - 호스트 이름으로 허용해야 하는 도메인 이름 목록입니다. 일치하는 하위 도메인에 대해 `*.example.com`과 같은 와일드카드 도메인이 지원됩니다. 모든 호스트 이름을 허용하려면 `allowed_hosts=[“*”]`를 사용하거나 미들웨어를 생략하세요. + +수신 요청의 유효성이 올바르게 확인되지 않으면 `400`이라는 응답이 전송됩니다. + +## `GZipMiddleware` + +`Accept-Encoding` 헤더에 `“gzip”`이 포함된 모든 요청에 대해 GZip 응답을 처리합니다. + +미들웨어는 표준 응답과 스트리밍 응답을 모두 처리합니다. + +{* ../../docs_src/advanced_middleware/tutorial003.py hl[2,6] *} + +지원되는 인수는 다음과 같습니다: + +* `minimum_size` - 이 최소 크기(바이트)보다 작은 응답은 GZip하지 않습니다. 기본값은 `500`입니다. +* `compresslevel` - GZip 압축 중에 사용됩니다. 1에서 9 사이의 정수입니다. 기본값은 `9`입니다. 값이 낮을수록 압축 속도는 빨라지지만 파일 크기는 커지고, 값이 높을수록 압축 속도는 느려지지만 파일 크기는 작아집니다. + +## 기타 미들웨어 + +다른 많은 ASGI 미들웨어가 있습니다. + +예를 들어: + +유비콘의 `ProxyHeadersMiddleware`> +MessagePack + +사용 가능한 다른 미들웨어를 확인하려면 스타렛의 미들웨어 문서ASGI Awesome List를 참조하세요. diff --git a/docs/ko/docs/advanced/response-change-status-code.md b/docs/ko/docs/advanced/response-change-status-code.md new file mode 100644 index 0000000000000..1ba9aa3ccbfa6 --- /dev/null +++ b/docs/ko/docs/advanced/response-change-status-code.md @@ -0,0 +1,31 @@ +# 응답 - 상태 코드 변경 + +기본 [응답 상태 코드 설정](../tutorial/response-status-code.md){.internal-link target=_blank}이 가능하다는 걸 이미 알고 계실 겁니다. + +하지만 경우에 따라 기본 설정과 다른 상태 코드를 반환해야 할 때가 있습니다. + +## 사용 예 + +예를 들어 기본적으로 HTTP 상태 코드 "OK" `200`을 반환하고 싶다고 가정해 봅시다. + +하지만 데이터가 존재하지 않으면 이를 새로 생성하고, HTTP 상태 코드 "CREATED" `201`을 반환하고자 할 때가 있을 수 있습니다. + +이때도 여전히 `response_model`을 사용하여 반환하는 데이터를 필터링하고 변환하고 싶을 수 있습니다. + +이런 경우에는 `Response` 파라미터를 사용할 수 있습니다. + +## `Response` 파라미터 사용하기 + +*경로 작동 함수*에 `Response` 타입의 파라미터를 선언할 수 있습니다. (쿠키와 헤더에 대해 선언하는 것과 유사하게) + +그리고 이 *임시* 응답 객체에서 `status_code`를 설정할 수 있습니다. + +{* ../../docs_src/response_change_status_code/tutorial001.py hl[1,9,12] *} + +그리고 평소처럼 원하는 객체(`dict`, 데이터베이스 모델 등)를 반환할 수 있습니다. + +`response_model`을 선언했다면 반환된 객체는 여전히 필터링되고 변환됩니다. + +**FastAPI**는 이 *임시* 응답 객체에서 상태 코드(쿠키와 헤더 포함)를 추출하여, `response_model`로 필터링된 반환 값을 최종 응답에 넣습니다. + +또한, 의존성에서도 `Response` 파라미터를 선언하고 그 안에서 상태 코드를 설정할 수 있습니다. 단, 마지막으로 설정된 상태 코드가 우선 적용된다는 점을 유의하세요. diff --git a/docs/ko/docs/advanced/response-cookies.md b/docs/ko/docs/advanced/response-cookies.md new file mode 100644 index 0000000000000..327f20afe7d61 --- /dev/null +++ b/docs/ko/docs/advanced/response-cookies.md @@ -0,0 +1,49 @@ +# 응답 쿠키 + +## `Response` 매개변수 사용하기 + +*경로 작동 함수*에서 `Response` 타입의 매개변수를 선언할 수 있습니다. + +그런 다음 해당 *임시* 응답 객체에서 쿠키를 설정할 수 있습니다. + +{* ../../docs_src/response_cookies/tutorial002.py hl[1,8:9] *} + +그런 다음 필요한 객체(`dict`, 데이터베이스 모델 등)를 반환할 수 있습니다. + +그리고 `response_model`을 선언했다면 반환한 객체를 거르고 변환하는 데 여전히 사용됩니다. + +**FastAPI**는 그 *임시* 응답에서 쿠키(또한 헤더 및 상태 코드)를 추출하고, 반환된 값이 포함된 최종 응답에 이를 넣습니다. 이 값은 `response_model`로 걸러지게 됩니다. + +또한 의존관계에서 `Response` 매개변수를 선언하고, 해당 의존성에서 쿠키(및 헤더)를 설정할 수도 있습니다. + +## `Response`를 직접 반환하기 + +코드에서 `Response`를 직접 반환할 때도 쿠키를 생성할 수 있습니다. + +이를 위해 [Response를 직접 반환하기](response-directly.md){.internal-link target=_blank}에서 설명한 대로 응답을 생성할 수 있습니다. + +그런 다음 쿠키를 설정하고 반환하면 됩니다: +{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *} +/// tip + +`Response` 매개변수를 사용하지 않고 응답을 직접 반환하는 경우, FastAPI는 이를 직접 반환한다는 점에 유의하세요. + +따라서 데이터가 올바른 유형인지 확인해야 합니다. 예: `JSONResponse`를 반환하는 경우, JSON과 호환되는지 확인하세요. + +또한 `response_model`로 걸러져야 할 데이터가 전달되지 않도록 확인하세요. + +/// + +### 추가 정보 + +/// note | 기술적 세부사항 + +`from starlette.responses import Response` 또는 `from starlette.responses import JSONResponse`를 사용할 수도 있습니다. + +**FastAPI**는 개발자의 편의를 위해 `fastapi.responses`로 동일한 `starlette.responses`를 제공합니다. 그러나 대부분의 응답은 Starlette에서 직접 제공됩니다. + +또한 `Response`는 헤더와 쿠키를 설정하는 데 자주 사용되므로, **FastAPI**는 이를 `fastapi.Response`로도 제공합니다. + +/// + +사용 가능한 모든 매개변수와 옵션은 Starlette 문서에서 확인할 수 있습니다. diff --git a/docs/ko/docs/advanced/response-directly.md b/docs/ko/docs/advanced/response-directly.md new file mode 100644 index 0000000000000..08d63c43ce3d1 --- /dev/null +++ b/docs/ko/docs/advanced/response-directly.md @@ -0,0 +1,63 @@ +# 응답을 직접 반환하기 + +**FastAPI**에서 *경로 작업(path operation)*을 생성할 때, 일반적으로 `dict`, `list`, Pydantic 모델, 데이터베이스 모델 등의 데이터를 반환할 수 있습니다. + +기본적으로 **FastAPI**는 [JSON 호환 가능 인코더](../tutorial/encoder.md){.internal-link target=_blank}에 설명된 `jsonable_encoder`를 사용해 해당 반환 값을 자동으로 `JSON`으로 변환합니다. + +그런 다음, JSON 호환 데이터(예: `dict`)를 `JSONResponse`에 넣어 사용자의 응답을 전송하는 방식으로 처리됩니다. + +그러나 *경로 작업*에서 `JSONResponse`를 직접 반환할 수도 있습니다. + +예를 들어, 사용자 정의 헤더나 쿠키를 반환해야 하는 경우에 유용할 수 있습니다. + +## `Response` 반환하기 + +사실, `Response` 또는 그 하위 클래스를 반환할 수 있습니다. + +/// tip + +`JSONResponse` 자체도 `Response`의 하위 클래스입니다. + +/// + +그리고 `Response`를 반환하면 **FastAPI**가 이를 그대로 전달합니다. + +Pydantic 모델로 데이터 변환을 수행하지 않으며, 내용을 다른 형식으로 변환하지 않습니다. + +이로 인해 많은 유연성을 얻을 수 있습니다. 어떤 데이터 유형이든 반환할 수 있고, 데이터 선언이나 유효성 검사를 재정의할 수 있습니다. + +## `Response`에서 `jsonable_encoder` 사용하기 + +**FastAPI**는 반환하는 `Response`에 아무런 변환을 하지 않으므로, 그 내용이 준비되어 있어야 합니다. + +예를 들어, Pydantic 모델을 `dict`로 변환해 `JSONResponse`에 넣지 않으면 JSON 호환 유형으로 변환된 데이터 유형(예: `datetime`, `UUID` 등)이 사용되지 않습니다. + +이러한 경우, 데이터를 응답에 전달하기 전에 `jsonable_encoder`를 사용하여 변환할 수 있습니다: + +{* ../../docs_src/response_directly/tutorial001.py hl[6:7,21:22] *} + +/// note | 기술적 세부 사항 + +`from starlette.responses import JSONResponse`를 사용할 수도 있습니다. + +**FastAPI**는 개발자의 편의를 위해 `starlette.responses`를 `fastapi.responses`로 제공합니다. 그러나 대부분의 가능한 응답은 Starlette에서 직접 제공합니다. + +/// + +## 사용자 정의 `Response` 반환하기 +위 예제는 필요한 모든 부분을 보여주지만, 아직 유용하지는 않습니다. 사실 데이터를 직접 반환하면 **FastAPI**가 이를 `JSONResponse`에 넣고 `dict`로 변환하는 등 모든 작업을 자동으로 처리합니다. + +이제, 사용자 정의 응답을 반환하는 방법을 알아보겠습니다. + +예를 들어 XML 응답을 반환하고 싶다고 가정해보겠습니다. + +XML 내용을 문자열에 넣고, 이를 `Response`에 넣어 반환할 수 있습니다: + +{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *} + +## 참고 사항 +`Response`를 직접 반환할 때, 그 데이터는 자동으로 유효성 검사되거나, 변환(직렬화)되거나, 문서화되지 않습니다. + +그러나 [OpenAPI에서 추가 응답](additional-responses.md){.internal-link target=_blank}에서 설명된 대로 문서화할 수 있습니다. + +이후 단락에서 자동 데이터 변환, 문서화 등을 사용하면서 사용자 정의 `Response`를 선언하는 방법을 확인할 수 있습니다. diff --git a/docs/ko/docs/advanced/response-headers.md b/docs/ko/docs/advanced/response-headers.md new file mode 100644 index 0000000000000..e8abe0be2f106 --- /dev/null +++ b/docs/ko/docs/advanced/response-headers.md @@ -0,0 +1,41 @@ +# 응답 헤더 + +## `Response` 매개변수 사용하기 + +여러분은 *경로 작동 함수*에서 `Response` 타입의 매개변수를 선언할 수 있습니다 (쿠키와 같이 사용할 수 있습니다). + +그런 다음, 여러분은 해당 *임시* 응답 객체에서 헤더를 설정할 수 있습니다. + +{* ../../docs_src/response_headers/tutorial002.py hl[1,7:8] *} + +그 후, 일반적으로 사용하듯이 필요한 객체(`dict`, 데이터베이스 모델 등)를 반환할 수 있습니다. + +`response_model`을 선언한 경우, 반환한 객체를 필터링하고 변환하는 데 여전히 사용됩니다. + +**FastAPI**는 해당 *임시* 응답에서 헤더(쿠키와 상태 코드도 포함)를 추출하여, 여러분이 반환한 값을 포함하는 최종 응답에 `response_model`로 필터링된 값을 넣습니다. + +또한, 종속성에서 `Response` 매개변수를 선언하고 그 안에서 헤더(및 쿠키)를 설정할 수 있습니다. + +## `Response` 직접 반환하기 + +`Response`를 직접 반환할 때에도 헤더를 추가할 수 있습니다. + +[응답을 직접 반환하기](response-directly.md){.internal-link target=_blank}에서 설명한 대로 응답을 생성하고, 헤더를 추가 매개변수로 전달하세요. + +{* ../../docs_src/response_headers/tutorial001.py hl[10:12] *} + +/// note | 기술적 세부사항 + +`from starlette.responses import Response`나 `from starlette.responses import JSONResponse`를 사용할 수도 있습니다. + +**FastAPI**는 `starlette.responses`를 `fastapi.responses`로 개발자의 편의를 위해 직접 제공하지만, 대부분의 응답은 Starlette에서 직접 제공됩니다. + +그리고 `Response`는 헤더와 쿠키를 설정하는 데 자주 사용될 수 있으므로, **FastAPI**는 `fastapi.Response`로도 이를 제공합니다. + +/// + +## 커스텀 헤더 + +‘X-’ 접두어를 사용하여 커스텀 사설 헤더를 추가할 수 있습니다. + +하지만, 여러분이 브라우저에서 클라이언트가 볼 수 있기를 원하는 커스텀 헤더가 있는 경우, CORS 설정에 이를 추가해야 합니다([CORS (Cross-Origin Resource Sharing)](../tutorial/cors.md){.internal-link target=_blank}에서 자세히 알아보세요). `expose_headers` 매개변수를 사용하여 Starlette의 CORS 설명서에 문서화된 대로 설정할 수 있습니다. diff --git a/docs/ko/docs/advanced/testing-dependencies.md b/docs/ko/docs/advanced/testing-dependencies.md new file mode 100644 index 0000000000000..780e19431f586 --- /dev/null +++ b/docs/ko/docs/advanced/testing-dependencies.md @@ -0,0 +1,53 @@ +# 테스트 의존성 오버라이드 + +## 테스트 중 의존성 오버라이드하기 + +테스트를 진행하다 보면 의존성을 오버라이드해야 하는 경우가 있습니다. + +원래 의존성을 실행하고 싶지 않을 수도 있습니다(또는 그 의존성이 가지고 있는 하위 의존성까지도 실행되지 않길 원할 수 있습니다). + +대신, 테스트 동안(특정 테스트에서만) 사용될 다른 의존성을 제공하고, 원래 의존성이 사용되던 곳에서 사용할 수 있는 값을 제공하기를 원할 수 있습니다. + +### 사용 사례: 외부 서비스 + +예를 들어, 외부 인증 제공자를 호출해야 하는 경우를 생각해봅시다. + +토큰을 보내면 인증된 사용자를 반환합니다. + +제공자는 요청당 요금을 부과할 수 있으며, 테스트를 위해 고정된 모의 사용자가 있는 경우보다 호출하는 데 시간이 더 걸릴 수 있습니다. + +외부 제공자를 한 번만 테스트하고 싶을 수도 있지만 테스트를 실행할 때마다 반드시 호출할 필요는 없습니다. + +이 경우 해당 공급자를 호출하는 종속성을 오버라이드하고 테스트에 대해서만 모의 사용자를 반환하는 사용자 지정 종속성을 사용할 수 있습니다. + +### `app.dependency_overrides` 속성 사용하기 + +이런 경우를 위해 **FastAPI** 응용 프로그램에는 `app.dependency_overrides`라는 속성이 있습니다. 이는 간단한 `dict`입니다. + +테스트를 위해 의존성을 오버라이드하려면, 원래 의존성(함수)을 키로 설정하고 오버라이드할 의존성(다른 함수)을 값으로 설정합니다. + +그럼 **FastAPI**는 원래 의존성 대신 오버라이드된 의존성을 호출합니다. + +{* ../../docs_src/dependency_testing/tutorial001_an_py310.py hl[26:27,30] *} + +/// tip | 팁 + +**FastAPI** 애플리케이션 어디에서든 사용된 의존성에 대해 오버라이드를 설정할 수 있습니다. + +원래 의존성은 *경로 동작 함수*, *경로 동작 데코레이터*(반환값을 사용하지 않는 경우), `.include_router()` 호출 등에서 사용될 수 있습니다. + +FastAPI는 여전히 이를 오버라이드할 수 있습니다. + +/// + +그런 다음, `app.dependency_overrides`를 빈 `dict`로 설정하여 오버라이드를 재설정(제거)할 수 있습니다: + +```python +app.dependency_overrides = {} +``` + +/// tip | 팁 + +특정 테스트에서만 의존성을 오버라이드하고 싶다면, 테스트 시작 시(테스트 함수 내부) 오버라이드를 설정하고 테스트 종료 시(테스트 함수 끝부분) 재설정하면 됩니다. + +/// diff --git a/docs/ko/docs/advanced/testing-events.md b/docs/ko/docs/advanced/testing-events.md new file mode 100644 index 0000000000000..502762f23b4b2 --- /dev/null +++ b/docs/ko/docs/advanced/testing-events.md @@ -0,0 +1,5 @@ +# 이벤트 테스트: 시작 - 종료 + +테스트에서 이벤트 핸들러(`startup` 및 `shutdown`)를 실행해야 하는 경우, `with` 문과 함께 `TestClient`를 사용할 수 있습니다. + +{* ../../docs_src/app_testing/tutorial003.py hl[9:12,20:24] *} diff --git a/docs/ko/docs/advanced/testing-websockets.md b/docs/ko/docs/advanced/testing-websockets.md new file mode 100644 index 0000000000000..9f3b4a451b96b --- /dev/null +++ b/docs/ko/docs/advanced/testing-websockets.md @@ -0,0 +1,13 @@ +# WebSocket 테스트하기 + +`TestClient`를 사용하여 WebSocket을 테스트할 수 있습니다. + +이를 위해 `with` 문에서 `TestClient`를 사용하여 WebSocket에 연결합니다: + +{* ../../docs_src/app_testing/tutorial002.py hl[27:31] *} + +/// note | 참고 + +자세한 내용은 Starlette의 WebSocket 테스트에 관한 설명서를 참고하시길 바랍니다. + +/// diff --git a/docs/ko/docs/advanced/using-request-directly.md b/docs/ko/docs/advanced/using-request-directly.md new file mode 100644 index 0000000000000..bfa4fa4db09a6 --- /dev/null +++ b/docs/ko/docs/advanced/using-request-directly.md @@ -0,0 +1,56 @@ +# `Request` 직접 사용하기 + +지금까지 요청에서 필요한 부분을 각 타입으로 선언하여 사용해 왔습니다. + +다음과 같은 곳에서 데이터를 가져왔습니다: + +* 경로의 파라미터로부터. +* 헤더. +* 쿠키. +* 기타 등등. + +이렇게 함으로써, **FastAPI**는 데이터를 검증하고 변환하며, API에 대한 문서를 자동화로 생성합니다. + +하지만 `Request` 객체에 직접 접근해야 하는 상황이 있을 수 있습니다. + +## `Request` 객체에 대한 세부 사항 + +**FastAPI**는 실제로 내부에 **Starlette**을 사용하며, 그 위에 여러 도구를 덧붙인 구조입니다. 따라서 여러분이 필요할 때 Starlette의 `Request` 객체를 직접 사용할 수 있습니다. + +`Request` 객체에서 데이터를 직접 가져오는 경우(예: 본문을 읽기)에는 FastAPI가 해당 데이터를 검증하거나 변환하지 않으며, 문서화(OpenAPI를 통한 문서 자동화(로 생성된) API 사용자 인터페이스)도 되지 않습니다. + +그러나 다른 매개변수(예: Pydantic 모델을 사용한 본문)는 여전히 검증, 변환, 주석 추가 등이 이루어집니다. + +하지만 특정한 경우에는 `Request` 객체에 직접 접근하는 것이 유용할 수 있습니다. + +## `Request` 객체를 직접 사용하기 + +여러분이 클라이언트의 IP 주소/호스트 정보를 *경로 작동 함수* 내부에서 가져와야 한다고 가정해 보겠습니다. + +이를 위해서는 요청에 직접 접근해야 합니다. + +{* ../../docs_src/using_request_directly/tutorial001.py hl[1,7:8] *} + +*경로 작동 함수* 매개변수를 `Request` 타입으로 선언하면 **FastAPI**가 해당 매개변수에 `Request` 객체를 전달하는 것을 알게 됩니다. + +/// tip | 팁 + +이 경우, 요청 매개변수와 함께 경로 매개변수를 선언한 것을 볼 수 있습니다. + +따라서, 경로 매개변수는 추출되고 검증되며 지정된 타입으로 변환되고 OpenAPI로 주석이 추가됩니다. + +이와 같은 방식으로, 다른 매개변수들을 평소처럼 선언하면서, 부가적으로 `Request`도 가져올 수 있습니다. + +/// + +## `Request` 설명서 + +여러분은 `Request` 객체에 대한 더 자세한 내용을 공식 Starlette 설명서 사이트에서 읽어볼 수 있습니다. + +/// note | 기술 세부사항 + +`from starlette.requests import Request`를 사용할 수도 있습니다. + +**FastAPI**는 여러분(개발자)를 위한 편의를 위해 이를 직접 제공하지만, 실제로는 Starlette에서 가져온 것입니다. + +/// diff --git a/docs/ko/docs/advanced/websockets.md b/docs/ko/docs/advanced/websockets.md new file mode 100644 index 0000000000000..fa60a428bd873 --- /dev/null +++ b/docs/ko/docs/advanced/websockets.md @@ -0,0 +1,186 @@ +# WebSockets + +여러분은 **FastAPI**에서 WebSockets를 사용할 수 있습니다. + +## `WebSockets` 설치 + +[가상 환경](../virtual-environments.md){.internal-link target=_blank)를 생성하고 활성화한 다음, `websockets`를 설치하세요: + +
+ +```console +$ pip install websockets + +---> 100% +``` + +
+ +## WebSockets 클라이언트 + +### 프로덕션 환경에서 + +여러분의 프로덕션 시스템에서는 React, Vue.js 또는 Angular와 같은 최신 프레임워크로 생성된 프런트엔드를 사용하고 있을 가능성이 높습니다. + +백엔드와 WebSockets을 사용해 통신하려면 아마도 프런트엔드의 유틸리티를 사용할 것입니다. + +또는 네이티브 코드로 WebSocket 백엔드와 직접 통신하는 네이티브 모바일 응용 프로그램을 가질 수도 있습니다. + +혹은 WebSocket 엔드포인트와 통신할 수 있는 다른 방법이 있을 수도 있습니다. + +--- + +하지만 이번 예제에서는 일부 자바스크립트를 포함한 간단한 HTML 문서를 사용하겠습니다. 모든 것을 긴 문자열 안에 넣습니다. + +물론, 이는 최적의 방법이 아니며 프로덕션 환경에서는 사용하지 않을 것입니다. + +프로덕션 환경에서는 위에서 설명한 옵션 중 하나를 사용하는 것이 좋습니다. + +그러나 이는 WebSockets의 서버 측에 집중하고 동작하는 예제를 제공하는 가장 간단한 방법입니다: + +{* ../../docs_src/websockets/tutorial001.py hl[2,6:38,41:43] *} + +## `websocket` 생성하기 + +**FastAPI** 응용 프로그램에서 `websocket`을 생성합니다: + +{* ../../docs_src/websockets/tutorial001.py hl[1,46:47] *} + +/// note | 기술적 세부사항 + +`from starlette.websockets import WebSocket`을 사용할 수도 있습니다. + +**FastAPI**는 개발자를 위한 편의를 위해 동일한 `WebSocket`을 직접 제공합니다. 하지만 이는 Starlette에서 가져옵니다. + +/// + +## 메시지를 대기하고 전송하기 + +WebSocket 경로에서 메시지를 대기(`await`)하고 전송할 수 있습니다. + +{* ../../docs_src/websockets/tutorial001.py hl[48:52] *} + +여러분은 이진 데이터, 텍스트, JSON 데이터를 받을 수 있고 전송할 수 있습니다. + +## 시도해보기 + +파일 이름이 `main.py`라고 가정하고 응용 프로그램을 실행합니다: + +
+ +```console +$ fastapi dev main.py + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +브라우저에서 http://127.0.0.1:8000을 열어보세요. + +간단한 페이지가 나타날 것입니다: + + + +입력창에 메시지를 입력하고 전송할 수 있습니다: + + + +**FastAPI** WebSocket 응용 프로그램이 응답을 돌려줄 것입니다: + + + +여러 메시지를 전송(그리고 수신)할 수 있습니다: + + + +모든 메시지는 동일한 WebSocket 연결을 사용합니다. + +## `Depends` 및 기타 사용하기 + +WebSocket 엔드포인트에서 `fastapi`에서 다음을 가져와 사용할 수 있습니다: + +* `Depends` +* `Security` +* `Cookie` +* `Header` +* `Path` +* `Query` + +이들은 다른 FastAPI 엔드포인트/*경로 작동*과 동일하게 동작합니다: + +{* ../../docs_src/websockets/tutorial002_an_py310.py hl[68:69,82] *} + +/// info | 정보 + +WebSocket에서는 `HTTPException`을 발생시키는 것이 적합하지 않습니다. 대신 `WebSocketException`을 발생시킵니다. + +명세서에 정의된 유효한 코드를 사용하여 종료 코드를 설정할 수 있습니다. + +/// + +### 종속성을 가진 WebSockets 테스트 + +파일 이름이 `main.py`라고 가정하고 응용 프로그램을 실행합니다: + +
+ +```console +$ fastapi dev main.py + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +브라우저에서 http://127.0.0.1:8000을 열어보세요. + +다음과 같은 값을 설정할 수 있습니다: + +* 경로에 사용된 "Item ID". +* 쿼리 매개변수로 사용된 "Token". + +/// tip | 팁 + +쿼리 `token`은 종속성에 의해 처리됩니다. + +/// + +이제 WebSocket에 연결하고 메시지를 전송 및 수신할 수 있습니다: + + + +## 연결 해제 및 다중 클라이언트 처리 + +WebSocket 연결이 닫히면, `await websocket.receive_text()`가 `WebSocketDisconnect` 예외를 발생시킵니다. 이를 잡아 처리할 수 있습니다: + +{* ../../docs_src/websockets/tutorial003_py39.py hl[79:81] *} + +테스트해보기: + +* 여러 브라우저 탭에서 앱을 엽니다. +* 각 탭에서 메시지를 작성합니다. +* 한 탭을 닫아보세요. + +`WebSocketDisconnect` 예외가 발생하며, 다른 모든 클라이언트가 다음과 같은 메시지를 수신합니다: + +``` +Client #1596980209979 left the chat +``` + +/// tip | 팁 + +위 응용 프로그램은 여러 WebSocket 연결에 메시지를 브로드캐스트하는 방법을 보여주는 간단한 예제입니다. + +그러나 모든 것을 메모리의 단일 리스트로 처리하므로, 프로세스가 실행 중인 동안만 동작하며 단일 프로세스에서만 작동합니다. + +FastAPI와 쉽게 통합할 수 있으면서 더 견고하고 Redis, PostgreSQL 등을 지원하는 도구를 찾고 있다면, encode/broadcaster를 확인하세요. + +/// + +## 추가 정보 + +다음 옵션에 대한 자세한 내용을 보려면 Starlette의 문서를 확인하세요: + +* `WebSocket` 클래스. +* 클래스 기반 WebSocket 처리. diff --git a/docs/ko/docs/advanced/wsgi.md b/docs/ko/docs/advanced/wsgi.md new file mode 100644 index 0000000000000..3e9de3e6cab98 --- /dev/null +++ b/docs/ko/docs/advanced/wsgi.md @@ -0,0 +1,35 @@ +# WSGI 포함하기 - Flask, Django 그 외 + +[서브 응용 프로그램 - 마운트](sub-applications.md){.internal-link target=_blank}, [프록시 뒤편에서](behind-a-proxy.md){.internal-link target=_blank}에서 보았듯이 WSGI 응용 프로그램들을 다음과 같이 마운트 할 수 있습니다. + +`WSGIMiddleware`를 사용하여 WSGI 응용 프로그램(예: Flask, Django 등)을 감쌀 수 있습니다. + +## `WSGIMiddleware` 사용하기 + +`WSGIMiddleware`를 불러와야 합니다. + +그런 다음, WSGI(예: Flask) 응용 프로그램을 미들웨어로 포장합니다. + +그 후, 해당 경로에 마운트합니다. + +{* ../../docs_src/wsgi/tutorial001.py hl[2:3,23] *} + +## 확인하기 + +이제 `/v1/` 경로에 있는 모든 요청은 Flask 응용 프로그램에서 처리됩니다. + +그리고 나머지는 **FastAPI**에 의해 처리됩니다. + +실행하면 http://localhost:8000/v1/으로 이동해서 Flask의 응답을 볼 수 있습니다: + +```txt +Hello, World from Flask! +``` + +그리고 다음으로 이동하면 http://localhost:8000/v2 Flask의 응답을 볼 수 있습니다: + +```JSON +{ + "message": "Hello World" +} +``` diff --git a/docs/ko/docs/async.md b/docs/ko/docs/async.md index dfc2caa789649..fa0d204886e8e 100644 --- a/docs/ko/docs/async.md +++ b/docs/ko/docs/async.md @@ -21,7 +21,7 @@ async def read_results(): return results ``` -/// note | "참고" +/// note | 참고 `async def`로 생성된 함수 내부에서만 `await`를 사용할 수 있습니다. @@ -369,7 +369,7 @@ FastAPI를 사용하지 않더라도, 높은 호환성 및 -/// info | "정보" +/// info | 정보 패키지 종속성을 정의하고 설치하기 위한 방법과 도구는 다양합니다. @@ -231,7 +231,7 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 프로그램이 `/code`에서 시작하고 그 속에 `./app` 디렉터리가 여러분의 코드와 함께 들어있기 때문에, **Uvicorn**은 이를 보고 `app`을 `app.main`으로부터 **불러 올** 것입니다. -/// tip | "팁" +/// tip | 팁 각 코드 라인을 코드의 숫자 버블을 클릭하여 리뷰할 수 있습니다. 👆 @@ -305,7 +305,7 @@ $ docker build -t myimage . -/// tip | "팁" +/// tip | 팁 맨 끝에 있는 `.` 에 주목합시다. 이는 `./`와 동등하며, 도커에게 컨테이너 이미지를 빌드하기 위한 디렉터리를 알려줍니다. @@ -409,7 +409,7 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] **HTTPS**와 **인증서**의 **자동** 취득을 다루는 것은 다른 컨테이너가 될 수 있는데, 예를 들어 Traefik을 사용하는 것입니다. -/// tip | "팁" +/// tip | 팁 Traefik은 도커, 쿠버네티스, 그리고 다른 도구와 통합되어 있어 여러분의 컨테이너를 포함하는 HTTPS를 셋업하고 설정하는 것이 매우 쉽습니다. @@ -441,7 +441,7 @@ Traefik은 도커, 쿠버네티스, 그리고 다른 도구와 통합되어 있 이 요소가 요청들의 **로드**를 읽어들이고 각 워커에게 (바라건대) **균형적으로** 분배한다면, 이 요소는 일반적으로 **로드 밸런서**라고 불립니다. -/// tip | "팁" +/// tip | 팁 HTTPS를 위해 사용된 **TLS 종료 프록시** 요소 또한 **로드 밸런서**가 될 수 있습니다. @@ -524,7 +524,7 @@ HTTPS를 위해 사용된 **TLS 종료 프록시** 요소 또한 **로드 밸런 만약 여러분이 **여러개의 컨테이너**를 가지고 있다면, 아마도 각각의 컨테이너는 **하나의 프로세스**를 가지고 있을 것입니다(예를 들어, **쿠버네티스** 클러스터에서). 그러면 여러분은 복제된 워커 컨테이너를 실행하기 **이전에**, 하나의 컨테이너에 있는 **이전의 단계들을** 수행하는 단일 프로세스를 가지는 **별도의 컨테이너들**을 가지고 싶을 것입니다. -/// info | "정보" +/// info | 정보 만약 여러분이 쿠버네티스를 사용하고 있다면, 아마도 이는 Init Container일 것입니다. @@ -544,7 +544,7 @@ HTTPS를 위해 사용된 **TLS 종료 프록시** 요소 또한 **로드 밸런 * tiangolo/uvicorn-gunicorn-fastapi. -/// warning | "경고" +/// warning | 경고 여러분이 이 베이스 이미지 또는 다른 유사한 이미지를 필요로 하지 **않을** 높은 가능성이 있으며, [위에서 설명된 것처럼: FastAPI를 위한 도커 이미지 빌드하기](#build-a-docker-image-for-fastapi) 처음부터 이미지를 빌드하는 것이 더 나을 수 있습니다. @@ -556,7 +556,7 @@ HTTPS를 위해 사용된 **TLS 종료 프록시** 요소 또한 **로드 밸런 또한 스크립트를 통해 **시작하기 전 사전 단계**를 실행하는 것을 지원합니다. -/// tip | "팁" +/// tip | 팁 모든 설정과 옵션을 보려면, 도커 이미지 페이지로 이동합니다: tiangolo/uvicorn-gunicorn-fastapi. @@ -687,7 +687,7 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 11. `uvicorn` 커맨드를 실행하여, `app.main`에서 불러온 `app` 객체를 사용하도록 합니다. -/// tip | "팁" +/// tip | 팁 버블 숫자를 클릭해 각 줄이 하는 일을 알아볼 수 있습니다. diff --git a/docs/ko/docs/deployment/server-workers.md b/docs/ko/docs/deployment/server-workers.md index 39976faf5b286..b40b25cd8f587 100644 --- a/docs/ko/docs/deployment/server-workers.md +++ b/docs/ko/docs/deployment/server-workers.md @@ -17,7 +17,7 @@ 지금부터 **구니콘**을 **유비콘 워커 프로세스**와 함께 사용하는 방법을 알려드리겠습니다. -/// info | "정보" +/// info | 정보 만약 도커와 쿠버네티스 같은 컨테이너를 사용하고 있다면 다음 챕터 [FastAPI와 컨테이너 - 도커](docker.md){.internal-link target=_blank}에서 더 많은 정보를 얻을 수 있습니다. diff --git a/docs/ko/docs/deployment/versions.md b/docs/ko/docs/deployment/versions.md index f3b3c2d7b83d6..559a892ab94ad 100644 --- a/docs/ko/docs/deployment/versions.md +++ b/docs/ko/docs/deployment/versions.md @@ -43,7 +43,7 @@ fastapi>=0.45.0,<0.46.0 FastAPI는 오류를 수정하고, 일반적인 변경사항을 위해 "패치"버전의 관습을 따릅니다. -/// tip | "팁" +/// tip | 팁 여기서 말하는 "패치"란 버전의 마지막 숫자로, 예를 들어 `0.2.3` 버전에서 "패치"는 `3`을 의미합니다. @@ -57,7 +57,7 @@ fastapi>=0.45.0,<0.46.0 수정된 사항과 새로운 요소들이 "마이너" 버전에 추가되었습니다. -/// tip | "팁" +/// tip | 팁 "마이너"란 버전 넘버의 가운데 숫자로, 예를 들어서 `0.2.3`의 "마이너" 버전은 `2`입니다. diff --git a/docs/ko/docs/environment-variables.md b/docs/ko/docs/environment-variables.md new file mode 100644 index 0000000000000..1e6af3ceba81f --- /dev/null +++ b/docs/ko/docs/environment-variables.md @@ -0,0 +1,298 @@ +# 환경 변수 + +/// tip | 팁 + +만약 "환경 변수"가 무엇이고, 어떻게 사용하는지 알고 계시다면, 이 챕터를 스킵하셔도 좋습니다. + +/// + +환경 변수는 파이썬 코드의 **바깥**인, **운영 체제**에 존재하는 변수입니다. 파이썬 코드나 다른 프로그램에서 읽을 수 있습니다. + +환경 변수는 애플리케이션 **설정**을 처리하거나, 파이썬의 **설치** 과정의 일부로 유용합니다. + +## 환경 변수를 만들고 사용하기 + +파이썬 없이도, **셸 (터미널)** 에서 환경 변수를 **생성** 하고 사용할 수 있습니다. + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +// You could create an env var MY_NAME with +$ export MY_NAME="Wade Wilson" + +// Then you could use it with other programs, like +$ echo "Hello $MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +// Create an env var MY_NAME +$ $Env:MY_NAME = "Wade Wilson" + +// Use it with other programs, like +$ echo "Hello $Env:MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +## 파이썬에서 환경 변수 읽기 + +파이썬 **바깥**인 터미널에서(다른 도구로도 가능) 환경 변수를 생성도 할 수도 있고, 이를 **파이썬에서 읽을 수 있습니다.** + +예를 들어 다음과 같은 `main.py` 파일이 있다고 합시다: + +```Python hl_lines="3" +import os + +name = os.getenv("MY_NAME", "World") +print(f"Hello {name} from Python") +``` + +/// tip | 팁 + +`os.getenv()` 의 두 번째 인자는 반환할 기본값입니다. + +여기서는 `"World"`를 넣었기에 기본값으로써 사용됩니다. 넣지 않으면 `None` 이 기본값으로 사용됩니다. + +/// + +그러면 해당 파이썬 프로그램을 다음과 같이 호출할 수 있습니다: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +// Here we don't set the env var yet +$ python main.py + +// As we didn't set the env var, we get the default value + +Hello World from Python + +// But if we create an environment variable first +$ export MY_NAME="Wade Wilson" + +// And then call the program again +$ python main.py + +// Now it can read the environment variable + +Hello Wade Wilson from Python +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +// Here we don't set the env var yet +$ python main.py + +// As we didn't set the env var, we get the default value + +Hello World from Python + +// But if we create an environment variable first +$ $Env:MY_NAME = "Wade Wilson" + +// And then call the program again +$ python main.py + +// Now it can read the environment variable + +Hello Wade Wilson from Python +``` + +
+ +//// + +환경변수는 코드 바깥에서 설정될 수 있지만, 코드에서 읽을 수 있고, 나머지 파일과 함께 저장(`git`에 커밋)할 필요가 없으므로, 구성이나 **설정** 에 사용하는 것이 일반적입니다. + +**특정 프로그램 호출**에 대해서만 사용할 수 있는 환경 변수를 만들 수도 있습니다. 해당 프로그램에서만 사용할 수 있고, 해당 프로그램이 실행되는 동안만 사용할 수 있습니다. + +그렇게 하려면 프로그램 바로 앞, 같은 줄에 환경 변수를 만들어야 합니다: + +
+ +```console +// Create an env var MY_NAME in line for this program call +$ MY_NAME="Wade Wilson" python main.py + +// Now it can read the environment variable + +Hello Wade Wilson from Python + +// The env var no longer exists afterwards +$ python main.py + +Hello World from Python +``` + +
+ +/// tip | 팁 + +The Twelve-Factor App: Config 에서 좀 더 자세히 알아볼 수 있습니다. + +/// + +## 타입과 검증 + +이 환경변수들은 오직 **텍스트 문자열**로만 처리할 수 있습니다. 텍스트 문자열은 파이썬 외부에 있으며 다른 프로그램 및 나머지 시스템(Linux, Windows, macOS 등 다른 운영 체제)과 호환되어야 합니다. + +즉, 파이썬에서 환경 변수로부터 읽은 **모든 값**은 **`str`**이 되고, 다른 타입으로의 변환이나 검증은 코드에서 수행해야 합니다. + +**애플리케이션 설정**을 처리하기 위한 환경 변수 사용에 대한 자세한 내용은 [고급 사용자 가이드 - 설정 및 환경 변수](./advanced/settings.md){.internal-link target=\_blank} 에서 확인할 수 있습니다. + +## `PATH` 환경 변수 + +**`PATH`**라고 불리는, **특별한** 환경변수가 있습니다. 운영체제(Linux, Windows, macOS 등)에서 실행할 프로그램을 찾기위해 사용됩니다. + +변수 `PATH`의 값은 Linux와 macOS에서는 콜론 `:`, Windows에서는 세미콜론 `;`으로 구분된 디렉토리로 구성된 긴 문자열입니다. + +예를 들어, `PATH` 환경 변수는 다음과 같습니다: + +//// tab | Linux, macOS + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +이는 시스템이 다음 디렉토리에서 프로그램을 찾아야 함을 의미합니다: + +- `/usr/local/bin` +- `/usr/bin` +- `/bin` +- `/usr/sbin` +- `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32 +``` + +이는 시스템이 다음 디렉토리에서 프로그램을 찾아야 함을 의미합니다: + +- `C:\Program Files\Python312\Scripts` +- `C:\Program Files\Python312` +- `C:\Windows\System32` + +//// + +터미널에 **명령어**를 입력하면 운영 체제는 `PATH` 환경 변수에 나열된 **각 디렉토리**에서 프로그램을 **찾습니다.** + +예를 들어 터미널에 `python`을 입력하면 운영 체제는 해당 목록의 **첫 번째 디렉토리**에서 `python`이라는 프로그램을 찾습니다. + +찾으면 **사용합니다**. 그렇지 않으면 **다른 디렉토리**에서 계속 찾습니다. + +### 파이썬 설치와 `PATH` 업데이트 + +파이썬을 설치할 때, 아마 `PATH` 환경 변수를 업데이트 할 것이냐고 물어봤을 겁니다. + +//// tab | Linux, macOS + +파이썬을 설치하고 그것이 `/opt/custompython/bin` 디렉토리에 있다고 가정해 보겠습니다. + +`PATH` 환경 변수를 업데이트하도록 "예"라고 하면 설치 관리자가 `/opt/custompython/bin`을 `PATH` 환경 변수에 추가합니다. + +다음과 같이 보일 수 있습니다: + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/custompython/bin +``` + +이렇게 하면 터미널에 `python`을 입력할 때, 시스템이 `/opt/custompython/bin`(마지막 디렉토리)에서 파이썬 프로그램을 찾아 사용합니다. + +//// + +//// tab | Windows + +파이썬을 설치하고 그것이 `C:\opt\custompython\bin` 디렉토리에 있다고 가정해 보겠습니다. + +`PATH` 환경 변수를 업데이트하도록 "예"라고 하면 설치 관리자가 `C:\opt\custompython\bin`을 `PATH` 환경 변수에 추가합니다. + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32;C:\opt\custompython\bin +``` + +이렇게 하면 터미널에 `python`을 입력할 때, 시스템이 `C:\opt\custompython\bin`(마지막 디렉토리)에서 파이썬 프로그램을 찾아 사용합니다. + +//// + +그래서, 다음과 같이 입력한다면: + +
+ +```console +$ python +``` + +
+ +//// tab | Linux, macOS + +시스템은 `/opt/custompython/bin`에서 `python` 프로그램을 **찾아** 실행합니다. + +다음과 같이 입력하는 것과 거의 같습니다: + +
+ +```console +$ /opt/custompython/bin/python +``` + +
+ +//// + +//// tab | Windows + +시스템은 `C:\opt\custompython\bin\python`에서 `python` 프로그램을 **찾아** 실행합니다. + +다음과 같이 입력하는 것과 거의 같습니다: + +
+ +```console +$ C:\opt\custompython\bin\python +``` + +
+ +//// + +이 정보는 [가상 환경](virtual-environments.md){.internal-link target=\_blank} 에 대해 알아볼 때 유용할 것입니다. + +## 결론 + +이 문서를 읽고 **환경 변수**가 무엇이고 파이썬에서 어떻게 사용하는지 기본적으로 이해하셨을 겁니다. + +또한 환경 변수에 대한 위키피디아(한국어)에서 이에 대해 자세히 알아볼 수 있습니다. + +많은 경우에서, 환경 변수가 어떻게 유용하고 적용 가능한지 바로 명확하게 알 수는 없습니다. 하지만 개발할 때 다양한 시나리오에서 계속 나타나므로 이에 대해 아는 것이 좋습니다. + +예를 들어, 다음 섹션인 [가상 환경](virtual-environments.md)에서 이 정보가 필요합니다. diff --git a/docs/ko/docs/fastapi-cli.md b/docs/ko/docs/fastapi-cli.md new file mode 100644 index 0000000000000..3a976af36aa23 --- /dev/null +++ b/docs/ko/docs/fastapi-cli.md @@ -0,0 +1,83 @@ +# FastAPI CLI + +**FastAPI CLI**는 FastAPI 애플리케이션을 실행하고, 프로젝트를 관리하는 등 다양한 작업을 수행할 수 있는 커맨드 라인 프로그램입니다. + +FastAPI를 설치할 때 (예: `pip install "fastapi[standard]"` 명령어를 사용할 경우), `fastapi-cli`라는 패키지가 포함됩니다. 이 패키지는 터미널에서 사용할 수 있는 `fastapi` 명령어를 제공합니다. + +개발용으로 FastAPI 애플리케이션을 실행하려면 다음과 같이 `fastapi dev` 명령어를 사용할 수 있습니다: + +
+ +```console +$ fastapi dev main.py +INFO Using path main.py +INFO Resolved absolute path /home/user/code/awesomeapp/main.py +INFO Searching for package file structure from directories with __init__.py files +INFO Importing from /home/user/code/awesomeapp + + ╭─ Python module file ─╮ + │ │ + │ 🐍 main.py │ + │ │ + ╰──────────────────────╯ + +INFO Importing module main +INFO Found importable FastAPI app + + ╭─ Importable FastAPI app ─╮ + │ │ + │ from main import app │ + │ │ + ╰──────────────────────────╯ + +INFO Using import string main:app + + ╭────────── FastAPI CLI - Development mode ───────────╮ + │ │ + │ Serving at: http://127.0.0.1:8000 │ + │ │ + │ API docs: http://127.0.0.1:8000/docs │ + │ │ + │ Running in development mode, for production use: │ + │ │ + fastapi run + │ │ + ╰─────────────────────────────────────────────────────╯ + +INFO: Will watch for changes in these directories: ['/home/user/code/awesomeapp'] +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +INFO: Started reloader process [2265862] using WatchFiles +INFO: Started server process [2265873] +INFO: Waiting for application startup. +INFO: Application startup complete. +``` + +
+ +`fastapi`라고 불리는 명령어 프로그램은 **FastAPI CLI**입니다. + +FastAPI CLI는 Python 프로그램의 경로(예: `main.py`)를 인수로 받아, `FastAPI` 인스턴스(일반적으로 `app`으로 명명)를 자동으로 감지하고 올바른 임포트 과정을 결정한 후 이를 실행합니다. + +프로덕션 환경에서는 `fastapi run` 명령어를 사용합니다. 🚀 + +내부적으로, **FastAPI CLI**는 고성능의, 프로덕션에 적합한, ASGI 서버인 Uvicorn을 사용합니다. 😎 + +## `fastapi dev` + +`fastapi dev` 명령을 실행하면 개발 모드가 시작됩니다. + +기본적으로 **자동 재시작(auto-reload)** 기능이 활성화되어, 코드에 변경이 생기면 서버를 자동으로 다시 시작합니다. 하지만 이 기능은 리소스를 많이 사용하며, 비활성화했을 때보다 안정성이 떨어질 수 있습니다. 따라서 개발 환경에서만 사용하는 것이 좋습니다. 또한, 서버는 컴퓨터가 자체적으로 통신할 수 있는 IP 주소(`localhost`)인 `127.0.0.1`에서 연결을 대기합니다. + +## `fastapi run` + +`fastapi run` 명령을 실행하면 기본적으로 프로덕션 모드로 FastAPI가 시작됩니다. + +기본적으로 **자동 재시작(auto-reload)** 기능이 비활성화되어 있습니다. 또한, 사용 가능한 모든 IP 주소인 `0.0.0.0`에서 연결을 대기하므로 해당 컴퓨터와 통신할 수 있는 모든 사람이 공개적으로 액세스할 수 있습니다. 이는 일반적으로 컨테이너와 같은 프로덕션 환경에서 실행하는 방법입니다. + +애플리케이션을 배포하는 방식에 따라 다르지만, 대부분 "종료 프록시(termination proxy)"를 활용해 HTTPS를 처리하는 것이 좋습니다. 배포 서비스 제공자가 이 작업을 대신 처리해줄 수도 있고, 직접 설정해야 할 수도 있습니다. + +/// tip + +자세한 내용은 [deployment documentation](deployment/index.md){.internal-link target=\_blank}에서 확인할 수 있습니다. + +/// diff --git a/docs/ko/docs/features.md b/docs/ko/docs/features.md index b6f6f7af2e086..5e880c2982408 100644 --- a/docs/ko/docs/features.md +++ b/docs/ko/docs/features.md @@ -63,7 +63,7 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -/// info | "정보" +/// info | 정보 `**second_user_data`가 뜻하는 것: diff --git a/docs/ko/docs/history-design-future.md b/docs/ko/docs/history-design-future.md new file mode 100644 index 0000000000000..6680a46e7c420 --- /dev/null +++ b/docs/ko/docs/history-design-future.md @@ -0,0 +1,81 @@ +# 역사, 디자인 그리고 미래 + +어느 날, [한 FastAPI 사용자](https://github.com/fastapi/fastapi/issues/3#issuecomment-454956920)가 이렇게 물었습니다: + +> 이 프로젝트의 역사를 알려 주실 수 있나요? 몇 주 만에 멋진 결과를 낸 것 같아요. [...] + +여기서 그 역사에 대해 간단히 설명하겠습니다. + +--- + +## 대안 + +저는 여러 해 동안 머신러닝, 분산 시스템, 비동기 작업, NoSQL 데이터베이스 같은 복잡한 요구사항을 가진 API를 개발하며 여러 팀을 이끌어 왔습니다. + +이 과정에서 많은 대안을 조사하고, 테스트하며, 사용해야 했습니다. **FastAPI**의 역사는 그 이전에 나왔던 여러 도구의 역사와 밀접하게 연관되어 있습니다. + +[대안](alternatives.md){.internal-link target=_blank} 섹션에서 언급된 것처럼: + +> **FastAPI**는 이전에 나왔던 많은 도구들의 노력 없이는 존재하지 않았을 것입니다. +> +> 이전에 개발된 여러 도구들이 이 프로젝트에 영감을 주었습니다. +> +> 저는 오랫동안 새로운 프레임워크를 만드는 것을 피하고자 했습니다. 처음에는 **FastAPI**가 제공하는 기능들을 다양한 프레임워크와 플러그인, 도구들을 조합해 해결하려 했습니다. +> +> 하지만 결국에는 이 모든 기능을 통합하는 도구가 필요해졌습니다. 이전 도구들로부터 최고의 아이디어들을 모으고, 이를 최적의 방식으로 조합해야만 했습니다. 이는 :term:Python 3.6+ 타입 힌트 와 같은, 이전에는 사용할 수 없었던 언어 기능이 가능했기 때문입니다. + +--- + +## 조사 + +여러 대안을 사용해 보며 다양한 도구에서 배운 점들을 모아 저와 개발팀에게 가장 적합한 방식을 찾았습니다. + +예를 들어, 표준 :term:Python 타입 힌트 에 기반하는 것이 이상적이라는 점이 명확했습니다. + +또한, 이미 존재하는 표준을 활용하는 것이 가장 좋은 접근법이라 판단했습니다. + +그래서 **FastAPI**의 코드를 작성하기 전에 몇 달 동안 OpenAPI, JSON Schema, OAuth2 명세를 연구하며 이들의 관계와 겹치는 부분, 차이점을 이해했습니다. + +--- + +## 디자인 + +그 후, **FastAPI** 사용자가 될 개발자로서 사용하고 싶은 개발자 "API"를 디자인했습니다. + +[Python Developer Survey](https://www.jetbrains.com/research/python-developers-survey-2018/#development-tools)에 따르면 약 80%의 Python 개발자가 PyCharm, VS Code, Jedi 기반 편집기 등에서 개발합니다. 이 과정에서 여러 아이디어를 테스트했습니다. + +대부분의 다른 편집기도 유사하게 동작하기 때문에, **FastAPI**의 이점은 거의 모든 편집기에서 누릴 수 있습니다. + +이 과정을 통해 코드 중복을 최소화하고, 모든 곳에서 자동 완성, 타입 검사, 에러 확인 기능이 제공되는 최적의 방식을 찾아냈습니다. + +이 모든 것은 개발자들에게 최고의 개발 경험을 제공하기 위해 설계되었습니다. + +--- + +## 필요조건 + +여러 대안을 테스트한 후, [Pydantic](https://docs.pydantic.dev/)을 사용하기로 결정했습니다. + +이후 저는 **Pydantic**이 JSON Schema와 완벽히 호환되도록 개선하고, 다양한 제약 조건 선언을 지원하며, 여러 편집기에서의 자동 완성과 타입 검사 기능을 향상하기 위해 기여했습니다. + +또한, 또 다른 주요 필요조건이었던 [Starlette](https://www.starlette.io/)에도 기여했습니다. + +--- + +## 개발 + +**FastAPI**를 개발하기 시작할 즈음에는 대부분의 준비가 이미 완료된 상태였습니다. 설계가 정의되었고, 필요조건과 도구가 준비되었으며, 표준과 명세에 대한 지식도 충분했습니다. + +--- + +## 미래 + +현시점에서 **FastAPI**가 많은 사람들에게 유용하다는 것이 명백해졌습니다. + +여러 용도에 더 적합한 도구로서 기존 대안보다 선호되고 있습니다. +이미 많은 개발자와 팀들이 **FastAPI**에 의존해 프로젝트를 진행 중입니다 (저와 제 팀도 마찬가지입니다). + +하지만 여전히 개선해야 할 점과 추가할 기능들이 많이 남아 있습니다. + +**FastAPI**는 밝은 미래로 나아가고 있습니다. +그리고 [여러분의 도움](help-fastapi.md){.internal-link target=_blank}은 큰 힘이 됩니다. diff --git a/docs/ko/docs/how-to/conditional-openapi.md b/docs/ko/docs/how-to/conditional-openapi.md new file mode 100644 index 0000000000000..79c7f0dd2dff3 --- /dev/null +++ b/docs/ko/docs/how-to/conditional-openapi.md @@ -0,0 +1,61 @@ +# 조건부적인 OpenAPI + +필요한 경우, 설정 및 환경 변수를 사용하여 환경에 따라 조건부로 OpenAPI를 구성하고 완전히 비활성화할 수도 있습니다. + +## 보안, API 및 docs에 대해서 + +프로덕션에서, 문서화된 사용자 인터페이스(UI)를 숨기는 것이 API를 보호하는 방법이 *되어서는 안 됩니다*. + +이는 API에 추가적인 보안을 제공하지 않으며, *경로 작업*은 여전히 동일한 위치에서 사용 할 수 있습니다. + +코드에 보안 결함이 있다면, 그 결함은 여전히 존재할 것입니다. + +문서를 숨기는 것은 API와 상호작용하는 방법을 이해하기 어렵게 만들며, 프로덕션에서 디버깅을 더 어렵게 만들 수 있습니다. 이는 단순히 '모호성에 의한 보안'의 한 형태로 간주될 수 있습니다. + +API를 보호하고 싶다면, 예를 들어 다음과 같은 더 나은 방법들이 있습니다: + +* 요청 본문과 응답에 대해 잘 정의된 Pydantic 모델을 사용하도록 하세요. + +* 종속성을 사용하여 필요한 권한과 역할을 구성하세요. + +* 평문 비밀번호를 절대 저장하지 말고, 오직 암호화된 비밀번호만 저장하세요. + +* Passlib과 JWT 토큰과 같은 잘 알려진 암호화 도구들을 구현하고 사용하세요. + +* 필요한 곳에 OAuth2 범위를 사용하여 더 세분화된 권한 제어를 추가하세요. + +* 등등.... + +그럼에도 불구하고, 특정 환경(예: 프로덕션)에서 또는 환경 변수의 설정에 따라 API 문서를 비활성화해야 하는 매우 특정한 사용 사례가 있을 수 있습니다. + +## 설정 및 환경변수의 조건부 OpenAPI + +동일한 Pydantic 설정을 사용하여 생성된 OpenAPI 및 문서 UI를 쉽게 구성할 수 있습니다. + +예를 들어: + +{* ../../docs_src/conditional_openapi/tutorial001.py hl[6,11] *} + +여기서 `openapi_url` 설정을 기본값인 `"/openapi.json"`으로 선언합니다. + +그런 뒤, 우리는 `FastAPI` 앱을 만들 때 그것을 사용합니다. + +환경 변수 `OPENAPI_URL`을 빈 문자열로 설정하여 OpenAPI(문서 UI 포함)를 비활성화할 수도 있습니다. 예를 들어: + +
+ +```console +$ OPENAPI_URL= uvicorn main:app + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +그리고 `/openapi.json`, `/docs` 또는 `/redoc`의 URL로 이동하면 `404 Not Found`라는 오류가 다음과 같이 표시됩니다: + +```JSON +{ + "detail": "Not Found" +} +``` diff --git a/docs/ko/docs/openapi-webhooks.md b/docs/ko/docs/openapi-webhooks.md new file mode 100644 index 0000000000000..96339aa961b7e --- /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로 이동해 봅시다. + +문서에서 기존 *경로 작업*뿐만 아니라 **웹훅**도 표시된 것을 확인할 수 있습니다: + + diff --git a/docs/ko/docs/python-types.md b/docs/ko/docs/python-types.md index 6d73461898a07..18d4b341e4b78 100644 --- a/docs/ko/docs/python-types.md +++ b/docs/ko/docs/python-types.md @@ -12,7 +12,7 @@ 비록 **FastAPI**를 쓰지 않는다고 하더라도, 조금이라도 알아두면 도움이 될 것입니다. -/// note | "참고" +/// note | 참고 파이썬에 능숙하셔서 타입 힌트에 대해 모두 아신다면, 다음 챕터로 건너뛰세요. @@ -22,9 +22,8 @@ 간단한 예제부터 시작해봅시다: -```Python -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py *} + 이 프로그램을 실행한 결과값: @@ -38,9 +37,8 @@ John Doe * `title()`로 각 첫 문자를 대문자로 변환시킵니다. * 두 단어를 중간에 공백을 두고 연결합니다. -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py hl[2] *} + ### 코드 수정 @@ -82,9 +80,8 @@ John Doe 이게 "타입 힌트"입니다: -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial002.py!} -``` +{* ../../docs_src/python_types/tutorial002.py hl[1] *} + 타입힌트는 다음과 같이 기본 값을 선언하는 것과는 다릅니다: @@ -112,9 +109,8 @@ John Doe 아래 함수를 보면, 이미 타입 힌트가 적용되어 있는 걸 볼 수 있습니다: -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial003.py!} -``` +{* ../../docs_src/python_types/tutorial003.py hl[1] *} + 편집기가 변수의 타입을 알고 있기 때문에, 자동완성 뿐 아니라 에러도 확인할 수 있습니다: @@ -122,9 +118,8 @@ John Doe 이제 고쳐야하는 걸 알기 때문에, `age`를 `str(age)`과 같이 문자열로 바꾸게 됩니다: -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial004.py!} -``` +{* ../../docs_src/python_types/tutorial004.py hl[2] *} + ## 타입 선언 @@ -143,9 +138,8 @@ John Doe * `bool` * `bytes` -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial005.py!} -``` +{* ../../docs_src/python_types/tutorial005.py hl[1] *} + ### 타입 매개변수를 활용한 Generic(제네릭) 타입 @@ -161,9 +155,8 @@ John Doe `typing`에서 `List`(대문자 `L`)를 import 합니다. -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial006.py!} -``` +{* ../../docs_src/python_types/tutorial006.py hl[1] *} + 콜론(`:`) 문법을 이용하여 변수를 선언합니다. @@ -171,11 +164,10 @@ John Doe 이때 배열은 내부 타입을 포함하는 타입이기 때문에 대괄호 안에 넣어줍니다. -```Python hl_lines="4" -{!../../docs_src/python_types/tutorial006.py!} -``` +{* ../../docs_src/python_types/tutorial006.py hl[4] *} + -/// tip | "팁" +/// tip | 팁 대괄호 안의 내부 타입은 "타입 매개변수(type paramters)"라고 합니다. @@ -199,9 +191,8 @@ John Doe `tuple`과 `set`도 동일하게 선언할 수 있습니다. -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial007.py!} -``` +{* ../../docs_src/python_types/tutorial007.py hl[1,4] *} + 이 뜻은 아래와 같습니다: @@ -216,9 +207,8 @@ John Doe 두 번째 매개변수는 `dict`의 값(value)입니다. -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial008.py!} -``` +{* ../../docs_src/python_types/tutorial008.py hl[1,4] *} + 이 뜻은 아래와 같습니다: @@ -255,15 +245,13 @@ John Doe 이름(name)을 가진 `Person` 클래스가 있다고 해봅시다. -```Python hl_lines="1-3" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[1:3] *} + 그렇게 하면 변수를 `Person`이라고 선언할 수 있게 됩니다. -```Python hl_lines="6" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[6] *} + 그리고 역시나 모든 에디터 도움을 받게 되겠죠. @@ -283,11 +271,10 @@ John Doe Pydantic 공식 문서 예시: -```Python -{!../../docs_src/python_types/tutorial011.py!} -``` +{* ../../docs_src/python_types/tutorial011.py *} + -/// info | "정보" +/// info | 정보 Pydantic<에 대해 더 배우고 싶다면 공식 문서를 참고하세요. @@ -319,7 +306,7 @@ Pydantic<에 대해 더 배우고 싶다면 `mypy`에서 제공하는 "cheat sheet"이 좋은 자료가 될 겁니다. diff --git a/docs/ko/docs/security/index.md b/docs/ko/docs/security/index.md new file mode 100644 index 0000000000000..5a6c733f05d6e --- /dev/null +++ b/docs/ko/docs/security/index.md @@ -0,0 +1,19 @@ +# 고급 보안 + +## 추가 기능 + +[자습서 - 사용자 가이드: 보안](../../tutorial/security/index.md){.internal-link target=_blank} 문서에서 다룬 내용 외에도 보안 처리를 위한 몇 가지 추가 기능이 있습니다. + +/// tip + +다음 섹션은 **반드시 "고급"** 기능은 아닙니다. + +그리고 여러분의 사용 사례에 따라, 적합한 해결책이 그 중 하나에 있을 가능성이 있습니다. + +/// + +## 먼저 자습서 읽기 + +다음 섹션은 이미 [자습서 - 사용자 가이드: 보안](../../tutorial/security/index.md){.internal-link target=_blank} 문서를 읽었다고 가정합니다. + +이 섹션들은 모두 동일한 개념을 바탕으로 하며, 추가 기능을 제공합니다. diff --git a/docs/ko/docs/tutorial/background-tasks.md b/docs/ko/docs/tutorial/background-tasks.md index 376c52524db31..a2c4abbd99b7e 100644 --- a/docs/ko/docs/tutorial/background-tasks.md +++ b/docs/ko/docs/tutorial/background-tasks.md @@ -15,9 +15,7 @@ FastAPI에서는 응답을 반환한 후에 실행할 백그라운드 작업을 먼저 아래와 같이 `BackgroundTasks`를 임포트하고, `BackgroundTasks`를 _경로 작동 함수_ 에서 매개변수로 가져오고 정의합니다. -```Python hl_lines="1 13" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *} **FastAPI** 는 `BackgroundTasks` 개체를 생성하고, 매개 변수로 전달합니다. @@ -33,17 +31,13 @@ FastAPI에서는 응답을 반환한 후에 실행할 백그라운드 작업을 그리고 이 작업은 `async`와 `await`를 사용하지 않으므로 일반 `def` 함수로 선언합니다. -```Python hl_lines="6-9" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *} ## 백그라운드 작업 추가 _경로 작동 함수_ 내에서 작업 함수를 `.add_task()` 함수 통해 _백그라운드 작업_ 개체에 전달합니다. -```Python hl_lines="14" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[14] *} `.add_task()` 함수는 다음과 같은 인자를 받습니다 : @@ -57,21 +51,7 @@ _경로 작동 함수_ 내에서 작업 함수를 `.add_task()` 함수 통해 _ **FastAPI**는 각 경우에 수행할 작업과 동일한 개체를 내부적으로 재사용하기에, 모든 백그라운드 작업이 함께 병합되고 나중에 백그라운드에서 실행됩니다. -//// tab | Python 3.6 and above - -```Python hl_lines="13 15 22 25" -{!> ../../docs_src/background_tasks/tutorial002.py!} -``` - -//// - -//// tab | Python 3.10 and above - -```Python hl_lines="11 13 20 23" -{!> ../../docs_src/background_tasks/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/background_tasks/tutorial002.py hl[13,15,22,25] *} 이 예제에서는 응답이 반환된 후에 `log.txt` 파일에 메시지가 기록됩니다. @@ -97,8 +77,6 @@ FastAPI에서 `BackgroundTask`를 단독으로 사용하는 것은 여전히 가 RabbitMQ 또는 Redis와 같은 메시지/작업 큐 시스템 보다 복잡한 구성이 필요한 경향이 있지만, 여러 작업 프로세스를 특히 여러 서버의 백그라운드에서 실행할 수 있습니다. -예제를 보시려면 [프로젝트 생성기](../project-generation.md){.internal-link target=\_blank} 를 참고하세요. 해당 예제에는 이미 구성된 `Celery`가 포함되어 있습니다. - 그러나 동일한 FastAPI 앱에서 변수 및 개체에 접근해야햐는 작은 백그라운드 수행이 필요한 경우 (예 : 알림 이메일 보내기) 간단하게 `BackgroundTasks`를 사용해보세요. ## 요약 diff --git a/docs/ko/docs/tutorial/body-fields.md b/docs/ko/docs/tutorial/body-fields.md index a13159c2713df..4708e7099f612 100644 --- a/docs/ko/docs/tutorial/body-fields.md +++ b/docs/ko/docs/tutorial/body-fields.md @@ -6,59 +6,9 @@ 먼저 이를 임포트해야 합니다: -//// tab | Python 3.10+ +{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[4] *} -```Python hl_lines="4" -{!> ../../docs_src/body_fields/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="4" -{!> ../../docs_src/body_fields/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4" -{!> ../../docs_src/body_fields/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ Annotated가 없는 경우 - -/// tip | "팁" - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="2" -{!> ../../docs_src/body_fields/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ Annotated가 없는 경우 - -/// tip | "팁" - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="4" -{!> ../../docs_src/body_fields/tutorial001.py!} -``` - -//// - -/// warning | "경고" +/// warning | 경고 `Field`는 다른 것들처럼 (`Query`, `Path`, `Body` 등) `fastapi`에서가 아닌 `pydantic`에서 바로 임포트 되는 점에 주의하세요. @@ -68,61 +18,11 @@ 그 다음 모델 어트리뷰트와 함께 `Field`를 사용할 수 있습니다: -//// tab | Python 3.10+ - -```Python hl_lines="11-14" -{!> ../../docs_src/body_fields/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="11-14" -{!> ../../docs_src/body_fields/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="12-15" -{!> ../../docs_src/body_fields/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ Annotated가 없는 경우 - -/// tip | "팁" - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="9-12" -{!> ../../docs_src/body_fields/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ Annotated가 없는 경우 - -/// tip | "팁" - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="11-14" -{!> ../../docs_src/body_fields/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[11:14] *} `Field`는 `Query`, `Path`와 `Body`와 같은 방식으로 동작하며, 모두 같은 매개변수들 등을 가집니다. -/// note | "기술적 세부사항" +/// note | 기술적 세부사항 실제로 `Query`, `Path`등, 여러분이 앞으로 볼 다른 것들은 공통 클래스인 `Param` 클래스의 서브클래스 객체를 만드는데, 그 자체로 Pydantic의 `FieldInfo` 클래스의 서브클래스입니다. @@ -134,7 +34,7 @@ /// -/// tip | "팁" +/// tip | 팁 주목할 점은 타입, 기본 값 및 `Field`로 이루어진 각 모델 어트리뷰트가 `Path`, `Query`와 `Body`대신 `Field`를 사용하는 *경로 작동 함수*의 매개변수와 같은 구조를 가진다는 점 입니다. @@ -146,7 +46,7 @@ 여러분이 예제를 선언할 때 나중에 이 공식 문서에서 별도 정보를 추가하는 방법을 배울 것입니다. -/// warning | "경고" +/// warning | 경고 별도 키가 전달된 `Field` 또한 여러분의 어플리케이션의 OpenAPI 스키마에 나타날 것입니다. 이런 키가 OpenAPI 명세서, [the OpenAPI validator](https://validator.swagger.io/)같은 몇몇 OpenAPI 도구들에 포함되지 못할 수 있으며, 여러분이 생성한 스키마와 호환되지 않을 수 있습니다. diff --git a/docs/ko/docs/tutorial/body-multiple-params.md b/docs/ko/docs/tutorial/body-multiple-params.md index 0a0f34585bcc9..edf892dfabb4d 100644 --- a/docs/ko/docs/tutorial/body-multiple-params.md +++ b/docs/ko/docs/tutorial/body-multiple-params.md @@ -10,11 +10,9 @@ 또한, 기본 값을 `None`으로 설정해 본문 매개변수를 선택사항으로 선언할 수 있습니다. -```Python hl_lines="19-21" -{!../../docs_src/body_multiple_params/tutorial001.py!} -``` +{* ../../docs_src/body_multiple_params/tutorial001.py hl[19:21] *} -/// note | "참고" +/// note | 참고 이 경우에는 본문으로 부터 가져온 ` item`은 기본값이 `None`이기 때문에, 선택사항이라는 점을 유의해야 합니다. @@ -35,9 +33,7 @@ 하지만, 다중 본문 매개변수 역시 선언할 수 있습니다. 예. `item`과 `user`: -```Python hl_lines="22" -{!../../docs_src/body_multiple_params/tutorial002.py!} -``` +{* ../../docs_src/body_multiple_params/tutorial002.py hl[22] *} 이 경우에, **FastAPI**는 이 함수 안에 한 개 이상의 본문 매개변수(Pydantic 모델인 두 매개변수)가 있다고 알 것입니다. @@ -58,7 +54,7 @@ } ``` -/// note | "참고" +/// note | 참고 이전과 같이 `item`이 선언 되었더라도, 본문 내의 `item` 키가 있을 것이라고 예측합니다. @@ -79,9 +75,7 @@ FastAPI는 요청을 자동으로 변환해, 매개변수의 `item`과 `user`를 하지만, **FastAPI**의 `Body`를 사용해 다른 본문 키로 처리하도록 제어할 수 있습니다: -```Python hl_lines="23" -{!../../docs_src/body_multiple_params/tutorial003.py!} -``` +{* ../../docs_src/body_multiple_params/tutorial003.py hl[23] *} 이 경우에는 **FastAPI**는 본문을 이와 같이 예측할 것입니다: @@ -110,9 +104,7 @@ FastAPI는 요청을 자동으로 변환해, 매개변수의 `item`과 `user`를 기본적으로 단일 값은 쿼리 매개변수로 해석되므로, 명시적으로 `Query`를 추가할 필요가 없고, 아래처럼 할 수 있습니다: -```Python hl_lines="27" -{!../../docs_src/body_multiple_params/tutorial004.py!} -``` +{* ../../docs_src/body_multiple_params/tutorial004.py hl[27] *} 이렇게: @@ -120,7 +112,7 @@ FastAPI는 요청을 자동으로 변환해, 매개변수의 `item`과 `user`를 q: Optional[str] = None ``` -/// info | "정보" +/// info | 정보 `Body` 또한 `Query`, `Path` 그리고 이후에 볼 다른 것들처럼 동일한 추가 검증과 메타데이터 매개변수를 갖고 있습니다. @@ -134,9 +126,7 @@ Pydantic 모델 `Item`의 `item`을 본문 매개변수로 오직 한개만 갖 하지만, 만약 모델 내용에 `item `키를 가진 JSON으로 예측하길 원한다면, 추가적인 본문 매개변수를 선언한 것처럼 `Body`의 특별한 매개변수인 `embed`를 사용할 수 있습니다: -```Python hl_lines="17" -{!../../docs_src/body_multiple_params/tutorial005.py!} -``` +{* ../../docs_src/body_multiple_params/tutorial005.py hl[17] *} 아래 처럼: diff --git a/docs/ko/docs/tutorial/body-nested-models.md b/docs/ko/docs/tutorial/body-nested-models.md index 12fb4e0cc1a94..ebd7b3ba6af1c 100644 --- a/docs/ko/docs/tutorial/body-nested-models.md +++ b/docs/ko/docs/tutorial/body-nested-models.md @@ -5,9 +5,7 @@ 어트리뷰트를 서브타입으로 정의할 수 있습니다. 예를 들어 파이썬 `list`는: -```Python hl_lines="14" -{!../../docs_src/body_nested_models/tutorial001.py!} -``` +{* ../../docs_src/body_nested_models/tutorial001.py hl[14] *} 이는 `tags`를 항목 리스트로 만듭니다. 각 항목의 타입을 선언하지 않더라도요. @@ -19,9 +17,7 @@ 먼저, 파이썬 표준 `typing` 모듈에서 `List`를 임포트합니다: -```Python hl_lines="1" -{!../../docs_src/body_nested_models/tutorial002.py!} -``` +{* ../../docs_src/body_nested_models/tutorial002.py hl[1] *} ### 타입 매개변수로 `List` 선언 @@ -42,9 +38,7 @@ my_list: List[str] 마찬가지로 예제에서 `tags`를 구체적으로 "문자열의 리스트"로 만들 수 있습니다: -```Python hl_lines="14" -{!../../docs_src/body_nested_models/tutorial002.py!} -``` +{* ../../docs_src/body_nested_models/tutorial002.py hl[14] *} ## 집합 타입 @@ -54,9 +48,7 @@ my_list: List[str] 그렇다면 `Set`을 임포트 하고 `tags`를 `str`의 `set`으로 선언할 수 있습니다: -```Python hl_lines="1 14" -{!../../docs_src/body_nested_models/tutorial003.py!} -``` +{* ../../docs_src/body_nested_models/tutorial003.py hl[1,14] *} 덕분에 중복 데이터가 있는 요청을 수신하더라도 고유한 항목들의 집합으로 변환됩니다. @@ -78,17 +70,13 @@ Pydantic 모델의 각 어트리뷰트는 타입을 갖습니다. 예를 들어, `Image` 모델을 선언할 수 있습니다: -```Python hl_lines="9-11" -{!../../docs_src/body_nested_models/tutorial004.py!} -``` +{* ../../docs_src/body_nested_models/tutorial004.py hl[9:11] *} ### 서브모듈을 타입으로 사용 그리고 어트리뷰트의 타입으로 사용할 수 있습니다: -```Python hl_lines="20" -{!../../docs_src/body_nested_models/tutorial004.py!} -``` +{* ../../docs_src/body_nested_models/tutorial004.py hl[20] *} 이는 **FastAPI**가 다음과 유사한 본문을 기대한다는 것을 의미합니다: @@ -121,9 +109,7 @@ Pydantic 모델의 각 어트리뷰트는 타입을 갖습니다. 예를 들어 `Image` 모델 안에 `url` 필드를 `str` 대신 Pydantic의 `HttpUrl`로 선언할 수 있습니다: -```Python hl_lines="4 10" -{!../../docs_src/body_nested_models/tutorial005.py!} -``` +{* ../../docs_src/body_nested_models/tutorial005.py hl[4,10] *} 이 문자열이 유효한 URL인지 검사하고 JSON 스키마/OpenAPI로 문서화 됩니다. @@ -131,9 +117,7 @@ Pydantic 모델의 각 어트리뷰트는 타입을 갖습니다. `list`, `set` 등의 서브타입으로 Pydantic 모델을 사용할 수도 있습니다: -```Python hl_lines="20" -{!../../docs_src/body_nested_models/tutorial006.py!} -``` +{* ../../docs_src/body_nested_models/tutorial006.py hl[20] *} 아래와 같은 JSON 본문으로 예상(변환, 검증, 문서화 등을)합니다: @@ -161,7 +145,7 @@ Pydantic 모델의 각 어트리뷰트는 타입을 갖습니다. } ``` -/// info | "정보" +/// info | 정보 `images` 키가 어떻게 이미지 객체 리스트를 갖는지 주목하세요. @@ -171,11 +155,9 @@ Pydantic 모델의 각 어트리뷰트는 타입을 갖습니다. 단독으로 깊게 중첩된 모델을 정의할 수 있습니다: -```Python hl_lines="9 14 20 23 27" -{!../../docs_src/body_nested_models/tutorial007.py!} -``` +{* ../../docs_src/body_nested_models/tutorial007.py hl[9,14,20,23,27] *} -/// info | "정보" +/// info | 정보 `Offer`가 선택사항 `Image` 리스트를 차례로 갖는 `Item` 리스트를 어떻게 가지고 있는지 주목하세요 @@ -191,9 +173,7 @@ images: List[Image] 이를 아래처럼: -```Python hl_lines="15" -{!../../docs_src/body_nested_models/tutorial008.py!} -``` +{* ../../docs_src/body_nested_models/tutorial008.py hl[15] *} ## 어디서나 편집기 지원 @@ -223,11 +203,9 @@ Pydantic 모델 대신에 `dict`를 직접 사용하여 작업할 경우, 이러 이 경우, `float` 값을 가진 `int` 키가 있는 모든 `dict`를 받아들입니다: -```Python hl_lines="15" -{!../../docs_src/body_nested_models/tutorial009.py!} -``` +{* ../../docs_src/body_nested_models/tutorial009.py hl[15] *} -/// tip | "팁" +/// tip | 팁 JSON은 오직 `str`형 키만 지원한다는 것을 염두에 두세요. diff --git a/docs/ko/docs/tutorial/body.md b/docs/ko/docs/tutorial/body.md index 8df8d556e9d0d..b3914fa4b443b 100644 --- a/docs/ko/docs/tutorial/body.md +++ b/docs/ko/docs/tutorial/body.md @@ -8,7 +8,7 @@ **요청** 본문을 선언하기 위해서 모든 강력함과 이점을 갖춘 Pydantic 모델을 사용합니다. -/// info | "정보" +/// info | 정보 데이터를 보내기 위해, (좀 더 보편적인) `POST`, `PUT`, `DELETE` 혹은 `PATCH` 중에 하나를 사용하는 것이 좋습니다. @@ -22,21 +22,7 @@ 먼저 `pydantic`에서 `BaseModel`를 임포트해야 합니다: -//// tab | Python 3.10+ - -```Python hl_lines="2" -{!> ../../docs_src/body/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4" -{!> ../../docs_src/body/tutorial001.py!} -``` - -//// +{* ../../docs_src/body/tutorial001_py310.py hl[2] *} ## 여러분의 데이터 모델 만들기 @@ -44,21 +30,7 @@ 모든 어트리뷰트에 대해 표준 파이썬 타입을 사용합니다: -//// tab | Python 3.10+ - -```Python hl_lines="5-9" -{!> ../../docs_src/body/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="7-11" -{!> ../../docs_src/body/tutorial001.py!} -``` - -//// +{* ../../docs_src/body/tutorial001_py310.py hl[5:9] *} 쿼리 매개변수를 선언할 때와 같이, 모델 어트리뷰트가 기본 값을 가지고 있어도 이는 필수가 아닙니다. 그외에는 필수입니다. 그저 `None`을 사용하여 선택적으로 만들 수 있습니다. @@ -86,21 +58,7 @@ 여러분의 *경로 작동*에 추가하기 위해, 경로 매개변수 그리고 쿼리 매개변수에서 선언했던 것과 같은 방식으로 선언하면 됩니다. -//// tab | Python 3.10+ - -```Python hl_lines="16" -{!> ../../docs_src/body/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18" -{!> ../../docs_src/body/tutorial001.py!} -``` - -//// +{* ../../docs_src/body/tutorial001_py310.py hl[16] *} ...그리고 만들어낸 모델인 `Item`으로 타입을 선언합니다. @@ -149,7 +107,7 @@ -/// tip | "팁" +/// tip | 팁 만약 PyCharm를 편집기로 사용한다면, Pydantic PyCharm Plugin을 사용할 수 있습니다. @@ -167,21 +125,7 @@ 함수 안에서 모델 객체의 모든 어트리뷰트에 직접 접근 가능합니다: -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/body/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="21" -{!> ../../docs_src/body/tutorial002.py!} -``` - -//// +{* ../../docs_src/body/tutorial002_py310.py hl[19] *} ## 요청 본문 + 경로 매개변수 @@ -189,21 +133,7 @@ **FastAPI**는 경로 매개변수와 일치하는 함수 매개변수가 **경로에서 가져와야 한다**는 것을 인지하며, Pydantic 모델로 선언된 그 함수 매개변수는 **요청 본문에서 가져와야 한다**는 것을 인지할 것입니다. -//// tab | Python 3.10+ - -```Python hl_lines="15-16" -{!> ../../docs_src/body/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17-18" -{!> ../../docs_src/body/tutorial003.py!} -``` - -//// +{* ../../docs_src/body/tutorial003_py310.py hl[15:16] *} ## 요청 본문 + 경로 + 쿼리 매개변수 @@ -211,21 +141,7 @@ **FastAPI**는 각각을 인지하고 데이터를 옳바른 위치에 가져올 것입니다. -//// tab | Python 3.10+ - -```Python hl_lines="16" -{!> ../../docs_src/body/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18" -{!> ../../docs_src/body/tutorial004.py!} -``` - -//// +{* ../../docs_src/body/tutorial004_py310.py hl[16] *} 함수 매개변수는 다음을 따라서 인지하게 됩니다: @@ -233,7 +149,7 @@ * 만약 매개변수가 (`int`, `float`, `str`, `bool` 등과 같은) **유일한 타입**으로 되어있으면, **쿼리** 매개변수로 해석될 것입니다. * 만약 매개변수가 **Pydantic 모델** 타입으로 선언되어 있으면, 요청 **본문**으로 해석될 것입니다. -/// note | "참고" +/// note | 참고 FastAPI는 `q`의 값이 필요없음을 알게 될 것입니다. 기본 값이 `= None`이기 때문입니다. diff --git a/docs/ko/docs/tutorial/cookie-params.md b/docs/ko/docs/tutorial/cookie-params.md index 1e21e069da765..fba756d49850d 100644 --- a/docs/ko/docs/tutorial/cookie-params.md +++ b/docs/ko/docs/tutorial/cookie-params.md @@ -6,57 +6,7 @@ 먼저 `Cookie`를 임포트합니다: -//// tab | Python 3.10+ - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ Annotated가 없는 경우 - -/// tip | "팁" - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/cookie_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ Annotated가 없는 경우 - -/// tip | "팁" - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[3] *} ## `Cookie` 매개변수 선언 @@ -64,59 +14,9 @@ 첫 번째 값은 기본값이며, 추가 검증이나 어노테이션 매개변수 모두 전달할 수 있습니다: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/cookie_params/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ Annotated가 없는 경우 - -/// tip | "팁" - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/cookie_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ Annotated가 없는 경우 - -/// tip | "팁" - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[9] *} -/// note | "기술 세부사항" +/// note | 기술 세부사항 `Cookie`는 `Path` 및 `Query`의 "자매"클래스입니다. 이 역시 동일한 공통 `Param` 클래스를 상속합니다. @@ -124,7 +24,7 @@ /// -/// info | "정보" +/// info | 정보 쿠키를 선언하기 위해서는 `Cookie`를 사용해야 합니다. 그렇지 않으면 해당 매개변수를 쿼리 매개변수로 해석하기 때문입니다. diff --git a/docs/ko/docs/tutorial/cors.md b/docs/ko/docs/tutorial/cors.md index 65357ae3f664e..1ef5a7480310b 100644 --- a/docs/ko/docs/tutorial/cors.md +++ b/docs/ko/docs/tutorial/cors.md @@ -46,9 +46,7 @@ * 특정한 HTTP 메소드(`POST`, `PUT`) 또는 와일드카드 `"*"` 를 사용한 모든 HTTP 메소드. * 특정한 HTTP 헤더 또는 와일드카드 `"*"` 를 사용한 모든 HTTP 헤더. -```Python hl_lines="2 6-11 13-19" -{!../../docs_src/cors/tutorial001.py!} -``` +{* ../../docs_src/cors/tutorial001.py hl[2,6:11,13:19] *} `CORSMiddleware` 에서 사용하는 기본 매개변수는 제한적이므로, 브라우저가 교차-도메인 상황에서 특정한 출처, 메소드, 헤더 등을 사용할 수 있도록 하려면 이들을 명시적으로 허용해야 합니다. @@ -78,7 +76,7 @@ CORS에 대한 더 많은 정보를 알고싶다면, Mozilla CORS 문서를 참고하기 바랍니다. -/// note | "기술적 세부 사항" +/// note | 기술적 세부 사항 `from starlette.middleware.cors import CORSMiddleware` 역시 사용할 수 있습니다. diff --git a/docs/ko/docs/tutorial/debugging.md b/docs/ko/docs/tutorial/debugging.md index 27e8f9abff638..e42f1ba880251 100644 --- a/docs/ko/docs/tutorial/debugging.md +++ b/docs/ko/docs/tutorial/debugging.md @@ -6,9 +6,7 @@ FastAPI 애플리케이션에서 `uvicorn`을 직접 임포트하여 실행합니다 -```Python hl_lines="1 15" -{!../../docs_src/debugging/tutorial001.py!} -``` +{* ../../docs_src/debugging/tutorial001.py hl[1,15] *} ### `__name__ == "__main__"` 에 대하여 @@ -74,7 +72,7 @@ from myapp import app 은 실행되지 않습니다. -/// info | "정보" +/// info | 정보 자세한 내용은 공식 Python 문서를 확인하세요 diff --git a/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md index 7430efbb4e7bb..3e5cdcc8c843a 100644 --- a/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md @@ -6,21 +6,7 @@ 이전 예제에서, 우리는 의존성(의존 가능한) 함수에서 `딕셔너리`객체를 반환하고 있었습니다: -//// tab | 파이썬 3.6 이상 - -```Python hl_lines="9" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// - -//// tab | 파이썬 3.10 이상 - -```Python hl_lines="7" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001.py hl[9] *} 우리는 *경로 작동 함수*의 매개변수 `commons`에서 `딕셔너리` 객체를 얻습니다. @@ -81,57 +67,15 @@ FastAPI가 실질적으로 확인하는 것은 "호출 가능성"(함수, 클래 그래서, 우리는 위 예제에서의 `common_paramenters` 의존성을 클래스 `CommonQueryParams`로 바꿀 수 있습니다. -//// tab | 파이썬 3.6 이상 - -```Python hl_lines="11-15" -{!> ../../docs_src/dependencies/tutorial002.py!} -``` - -//// - -//// tab | 파이썬 3.10 이상 - -```Python hl_lines="9-13" -{!> ../../docs_src/dependencies/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial002.py hl[11:15] *} 클래스의 인스턴스를 생성하는 데 사용되는 `__init__` 메서드에 주목하기 바랍니다: -//// tab | 파이썬 3.6 이상 - -```Python hl_lines="12" -{!> ../../docs_src/dependencies/tutorial002.py!} -``` - -//// - -//// tab | 파이썬 3.10 이상 - -```Python hl_lines="10" -{!> ../../docs_src/dependencies/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial002.py hl[12] *} ...이전 `common_parameters`와 동일한 매개변수를 가집니다: -//// tab | 파이썬 3.6 이상 - -```Python hl_lines="9" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// - -//// tab | 파이썬 3.10 이상 - -```Python hl_lines="6" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001.py hl[9] *} 이 매개변수들은 **FastAPI**가 의존성을 "해결"하기 위해 사용할 것입니다 @@ -147,21 +91,7 @@ FastAPI가 실질적으로 확인하는 것은 "호출 가능성"(함수, 클래 이제 아래의 클래스를 이용해서 의존성을 정의할 수 있습니다. -//// tab | 파이썬 3.6 이상 - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial002.py!} -``` - -//// - -//// tab | 파이썬 3.10 이상 - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial002.py hl[19] *} **FastAPI**는 `CommonQueryParams` 클래스를 호출합니다. 이것은 해당 클래스의 "인스턴스"를 생성하고 그 인스턴스는 함수의 매개변수 `commons`로 전달됩니다. @@ -200,21 +130,7 @@ commons = Depends(CommonQueryParams) ..전체적인 코드는 아래와 같습니다: -//// tab | 파이썬 3.6 이상 - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial003.py!} -``` - -//// - -//// tab | 파이썬 3.10 이상 - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial003.py hl[19] *} 그러나 자료형을 선언하면 에디터가 매개변수 `commons`로 전달될 것이 무엇인지 알게 되고, 이를 통해 코드 완성, 자료형 확인 등에 도움이 될 수 있으므로 권장됩니다. @@ -248,25 +164,11 @@ commons: CommonQueryParams = Depends() 아래에 같은 예제가 있습니다: -//// tab | 파이썬 3.6 이상 - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial004.py!} -``` - -//// - -//// tab | 파이썬 3.10 이상 - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial004.py hl[19] *} ...이렇게 코드를 단축하여도 **FastAPI**는 무엇을 해야하는지 알고 있습니다. -/// tip | "팁" +/// tip | 팁 만약 이것이 도움이 되기보다 더 헷갈리게 만든다면, 잊어버리십시오. 이것이 반드시 필요한 것은 아닙니다. diff --git a/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index e71ba8546d8fd..4a3854cefad83 100644 --- a/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -14,39 +14,11 @@ `Depends()`로 된 `list`이어야합니다: -//// tab | Python 3.9+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18" -{!> ../../docs_src/dependencies/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8 Annotated가 없는 경우 - -/// tip | "팁" - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial006.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[19] *} 이러한 의존성들은 기존 의존성들과 같은 방식으로 실행/해결됩니다. 그러나 값은 (무엇이든 반환한다면) *경로 작동 함수*에 제공되지 않습니다. -/// tip | "팁" +/// tip | 팁 일부 편집기에서는 사용되지 않는 함수 매개변수를 검사하고 오류로 표시합니다. @@ -56,7 +28,7 @@ /// -/// info | "정보" +/// info | 정보 이 예시에서 `X-Key`와 `X-Token`이라는 커스텀 헤더를 만들어 사용했습니다. @@ -72,69 +44,13 @@ (헤더같은) 요청 요구사항이나 하위-의존성을 선언할 수 있습니다: -//// tab | Python 3.9+ - -```Python hl_lines="8 13" -{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="7 12" -{!> ../../docs_src/dependencies/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8 Annotated가 없는 경우 - -/// tip | "팁" - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="6 11" -{!> ../../docs_src/dependencies/tutorial006.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[8,13] *} ### 오류 발생시키기 다음 의존성은 기존 의존성과 동일하게 예외를 `raise`를 일으킬 수 있습니다: -//// tab | Python 3.9+ - -```Python hl_lines="10 15" -{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 14" -{!> ../../docs_src/dependencies/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8 Annotated가 없는 경우 - -/// tip | "팁" - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="8 13" -{!> ../../docs_src/dependencies/tutorial006.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[10,15] *} ### 값 반환하기 @@ -142,35 +58,7 @@ 그래서 이미 다른 곳에서 사용된 (값을 반환하는) 일반적인 의존성을 재사용할 수 있고, 비록 값은 사용되지 않지만 의존성은 실행될 것입니다: -//// tab | Python 3.9+ - -```Python hl_lines="11 16" -{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10 15" -{!> ../../docs_src/dependencies/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8 Annotated가 없는 경우 - -/// tip | "팁" - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="9 14" -{!> ../../docs_src/dependencies/tutorial006.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[11,16] *} ## *경로 작동* 모음에 대한 의존성 diff --git a/docs/ko/docs/tutorial/dependencies/global-dependencies.md b/docs/ko/docs/tutorial/dependencies/global-dependencies.md index dd6586c3edf76..0d0e7684dbd70 100644 --- a/docs/ko/docs/tutorial/dependencies/global-dependencies.md +++ b/docs/ko/docs/tutorial/dependencies/global-dependencies.md @@ -6,35 +6,7 @@ 그런 경우에, 애플리케이션의 모든 *경로 작동*에 적용될 것입니다: -//// tab | Python 3.9+ - -```Python hl_lines="16" -{!> ../../docs_src/dependencies/tutorial012_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="16" -{!> ../../docs_src/dependencies/tutorial012_an.py!} -``` - -//// - -//// tab | Python 3.8 Annotated가 없는 경우 - -/// tip | "팁" - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="15" -{!> ../../docs_src/dependencies/tutorial012.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial012_an_py39.py hl[16] *} 그리고 [*경로 작동 데코레이터*에 `dependencies` 추가하기](dependencies-in-path-operation-decorators.md){.internal-link target=_blank}에 대한 아이디어는 여전히 적용되지만 여기에서는 앱에 있는 모든 *경로 작동*에 적용됩니다. diff --git a/docs/ko/docs/tutorial/dependencies/index.md b/docs/ko/docs/tutorial/dependencies/index.md index f7b2f1788934d..b35a41e37af95 100644 --- a/docs/ko/docs/tutorial/dependencies/index.md +++ b/docs/ko/docs/tutorial/dependencies/index.md @@ -31,57 +31,7 @@ *경로 작동 함수*가 가질 수 있는 모든 매개변수를 갖는 단순한 함수입니다: -//// tab | Python 3.10+ - -```Python hl_lines="8-9" -{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="8-11" -{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9-12" -{!> ../../docs_src/dependencies/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ Annotated가 없는 경우 - -/// tip | "팁" - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="6-7" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ Annotated가 없는 경우 - -/// tip | "팁" - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="8-11" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8:9] *} 이게 다입니다. @@ -101,7 +51,7 @@ 그 후 위의 값을 포함한 `dict` 자료형으로 반환할 뿐입니다. -/// info | "정보" +/// info | 정보 FastAPI는 0.95.0 버전부터 `Annotated`에 대한 지원을 (그리고 이를 사용하기 권장합니다) 추가했습니다. @@ -113,113 +63,13 @@ FastAPI는 0.95.0 버전부터 `Annotated`에 대한 지원을 (그리고 이를 ### `Depends` 불러오기 -//// tab | Python 3.10+ - -```Python hl_lines="3" -{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3" -{!> ../../docs_src/dependencies/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ Annotated가 없는 경우 - -/// tip | "팁" - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ Annotated가 없는 경우 - -/// tip | "팁" - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="3" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[3] *} ### "의존자"에 의존성 명시하기 *경로 작동 함수*의 매개변수로 `Body`, `Query` 등을 사용하는 방식과 같이 새로운 매개변수로 `Depends`를 사용합니다: -//// tab | Python 3.10+ - -```Python hl_lines="13 18" -{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="15 20" -{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="16 21" -{!> ../../docs_src/dependencies/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ Annotated가 없는 경우 - -/// tip | "팁" - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="11 16" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ Annotated가 없는 경우 - -/// tip | "팁" - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="15 20" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[13,18] *} 비록 `Body`, `Query` 등을 사용하는 것과 같은 방식으로 여러분의 함수의 매개변수에 있는 `Depends`를 사용하지만, `Depends`는 약간 다르게 작동합니다. @@ -231,7 +81,7 @@ FastAPI는 0.95.0 버전부터 `Annotated`에 대한 지원을 (그리고 이를 그리고 그 함수는 *경로 작동 함수*가 작동하는 것과 같은 방식으로 매개변수를 받습니다. -/// tip | "팁" +/// tip | 팁 여러분은 다음 장에서 함수를 제외하고서, "다른 것들"이 어떻게 의존성으로 사용되는지 알게 될 것입니다. @@ -256,7 +106,7 @@ common_parameters --> read_users 이렇게 하면 공용 코드를 한번만 적어도 되며, **FastAPI**는 *경로 작동*을 위해 이에 대한 호출을 처리합니다. -/// check | "확인" +/// check | 확인 특별한 클래스를 만들지 않아도 되며, 이러한 것 혹은 비슷한 종류를 **FastAPI**에 "등록"하기 위해 어떤 곳에 넘겨주지 않아도 됩니다. @@ -276,31 +126,9 @@ commons: Annotated[dict, Depends(common_parameters)] 하지만 `Annotated`를 사용하고 있기에, `Annotated` 값을 변수에 저장하고 여러 장소에서 사용할 수 있습니다: -//// tab | Python 3.10+ - -```Python hl_lines="12 16 21" -{!> ../../docs_src/dependencies/tutorial001_02_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="14 18 23" -{!> ../../docs_src/dependencies/tutorial001_02_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="15 19 24" -{!> ../../docs_src/dependencies/tutorial001_02_an.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_02_an_py310.py hl[12,16,21] *} -/// tip | "팁" +/// tip | 팁 이는 그저 표준 파이썬이고 "type alias"라고 부르며 사실 **FastAPI**에 국한되는 것은 아닙니다. @@ -322,7 +150,7 @@ commons: Annotated[dict, Depends(common_parameters)] 아무 문제 없습니다. **FastAPI**는 무엇을 할지 알고 있습니다. -/// note | "참고" +/// note | 참고 잘 모르시겠다면, [Async: *"In a hurry?"*](../../async.md){.internal-link target=_blank} 문서에서 `async`와 `await`에 대해 확인할 수 있습니다. diff --git a/docs/ko/docs/tutorial/encoder.md b/docs/ko/docs/tutorial/encoder.md index 732566d6dc3db..4323957f41143 100644 --- a/docs/ko/docs/tutorial/encoder.md +++ b/docs/ko/docs/tutorial/encoder.md @@ -20,9 +20,7 @@ JSON 호환 가능 데이터만 수신하는 `fake_db` 데이터베이스가 존 Pydantic 모델과 같은 객체를 받고 JSON 호환 가능한 버전으로 반환합니다: -```Python hl_lines="5 22" -{!../../docs_src/encoder/tutorial001.py!} -``` +{* ../../docs_src/encoder/tutorial001.py hl[5,22] *} 이 예시는 Pydantic 모델을 `dict`로, `datetime` 형식을 `str`로 변환합니다. @@ -30,7 +28,7 @@ Pydantic 모델과 같은 객체를 받고 JSON 호환 가능한 버전으로 길이가 긴 문자열 형태의 JSON 형식(문자열)의 데이터가 들어있는 상황에서는 `str`로 반환하지 않습니다. JSON과 모두 호환되는 값과 하위 값이 있는 Python 표준 데이터 구조 (예: `dict`)를 반환합니다. -/// note | "참고" +/// note | 참고 실제로 `jsonable_encoder`는 **FastAPI** 에서 내부적으로 데이터를 변환하는 데 사용하지만, 다른 많은 곳에서도 이는 유용합니다. diff --git a/docs/ko/docs/tutorial/extra-data-types.md b/docs/ko/docs/tutorial/extra-data-types.md index 8baaa64fc3199..4a41ba0dc6391 100644 --- a/docs/ko/docs/tutorial/extra-data-types.md +++ b/docs/ko/docs/tutorial/extra-data-types.md @@ -55,108 +55,8 @@ 위의 몇몇 자료형을 매개변수로 사용하는 *경로 작동* 예시입니다. -//// tab | Python 3.10+ - -```Python hl_lines="1 3 12-16" -{!> ../../docs_src/extra_data_types/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="1 3 12-16" -{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 3 13-17" -{!> ../../docs_src/extra_data_types/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="1 2 11-15" -{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="1 2 12-16" -{!> ../../docs_src/extra_data_types/tutorial001.py!} -``` - -//// +{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[1,3,12:16] *} 함수 안의 매개변수가 그들만의 데이터 자료형을 가지고 있으며, 예를 들어, 다음과 같이 날짜를 조작할 수 있음을 참고하십시오: -//// tab | Python 3.10+ - -```Python hl_lines="18-19" -{!> ../../docs_src/extra_data_types/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="18-19" -{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="19-20" -{!> ../../docs_src/extra_data_types/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="17-18" -{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="18-19" -{!> ../../docs_src/extra_data_types/tutorial001.py!} -``` - -//// +{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[18:19] *} diff --git a/docs/ko/docs/tutorial/first-steps.md b/docs/ko/docs/tutorial/first-steps.md index c2c48fb3edc33..174f00d468979 100644 --- a/docs/ko/docs/tutorial/first-steps.md +++ b/docs/ko/docs/tutorial/first-steps.md @@ -2,9 +2,7 @@ 가장 단순한 FastAPI 파일은 다음과 같이 보일 것입니다: -```Python -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py *} 위 코드를 `main.py`에 복사합니다. @@ -24,7 +22,7 @@ $ uvicorn main:app --reload -/// note | "참고" +/// note | 참고 `uvicorn main:app` 명령은 다음을 의미합니다: @@ -133,13 +131,11 @@ API와 통신하는 클라이언트(프론트엔드, 모바일, IoT 애플리케 ### 1 단계: `FastAPI` 임포트 -```Python hl_lines="1" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[1] *} `FastAPI`는 당신의 API를 위한 모든 기능을 제공하는 파이썬 클래스입니다. -/// note | "기술 세부사항" +/// note | 기술 세부사항 `FastAPI`는 `Starlette`를 직접 상속하는 클래스입니다. @@ -149,9 +145,7 @@ API와 통신하는 클라이언트(프론트엔드, 모바일, IoT 애플리케 ### 2 단계: `FastAPI` "인스턴스" 생성 -```Python hl_lines="3" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[3] *} 여기에서 `app` 변수는 `FastAPI` 클래스의 "인스턴스"가 됩니다. @@ -171,9 +165,7 @@ $ uvicorn main:app --reload 아래처럼 앱을 만든다면: -```Python hl_lines="3" -{!../../docs_src/first_steps/tutorial002.py!} -``` +{* ../../docs_src/first_steps/tutorial002.py hl[3] *} 이를 `main.py` 파일에 넣고, `uvicorn`을 아래처럼 호출해야 합니다: @@ -205,7 +197,7 @@ https://example.com/items/foo /items/foo ``` -/// info | "정보" +/// info | 정보 "경로"는 일반적으로 "엔드포인트" 또는 "라우트"라고도 불립니다. @@ -250,16 +242,14 @@ API를 설계할 때 일반적으로 특정 행동을 수행하기 위해 특정 #### *경로 작동 데코레이터* 정의 -```Python hl_lines="6" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[6] *} `@app.get("/")`은 **FastAPI**에게 바로 아래에 있는 함수가 다음으로 이동하는 요청을 처리한다는 것을 알려줍니다. * 경로 `/` * get 작동 사용 -/// info | "`@decorator` 정보" +/// info | `@decorator` 정보 이 `@something` 문법은 파이썬에서 "데코레이터"라 부릅니다. @@ -286,7 +276,7 @@ API를 설계할 때 일반적으로 특정 행동을 수행하기 위해 특정 * `@app.patch()` * `@app.trace()` -/// tip | "팁" +/// tip | 팁 각 작동(HTTP 메소드)을 원하는 대로 사용해도 됩니다. @@ -306,9 +296,7 @@ API를 설계할 때 일반적으로 특정 행동을 수행하기 위해 특정 * **작동**: 은 `get`입니다. * **함수**: 는 "데코레이터" 아래에 있는 함수입니다 (`@app.get("/")` 아래). -```Python hl_lines="7" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[7] *} 이것은 파이썬 함수입니다. @@ -320,11 +308,9 @@ 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}을 확인하세요. @@ -332,9 +318,7 @@ URL "`/`"에 대한 `GET` 작동을 사용하는 요청을 받을 때마다 **Fa ### 5 단계: 콘텐츠 반환 -```Python hl_lines="8" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[8] *} `dict`, `list`, 단일값을 가진 `str`, `int` 등을 반환할 수 있습니다. diff --git a/docs/ko/docs/tutorial/header-params.md b/docs/ko/docs/tutorial/header-params.md index 26e1988693443..7379eb2a07a45 100644 --- a/docs/ko/docs/tutorial/header-params.md +++ b/docs/ko/docs/tutorial/header-params.md @@ -6,9 +6,7 @@ 먼저 `Header`를 임포트합니다: -```Python hl_lines="3" -{!../../docs_src/header_params/tutorial001.py!} -``` +{* ../../docs_src/header_params/tutorial001.py hl[3] *} ## `Header` 매개변수 선언 @@ -16,11 +14,9 @@ 첫 번째 값은 기본값이며, 추가 검증이나 어노테이션 매개변수 모두 전달할 수 있습니다: -```Python hl_lines="9" -{!../../docs_src/header_params/tutorial001.py!} -``` +{* ../../docs_src/header_params/tutorial001.py hl[9] *} -/// note | "기술 세부사항" +/// note | 기술 세부사항 `Header`는 `Path`, `Query` 및 `Cookie`의 "자매"클래스입니다. 이 역시 동일한 공통 `Param` 클래스를 상속합니다. @@ -28,7 +24,7 @@ /// -/// info | "정보" +/// info | 정보 헤더를 선언하기 위해서 `Header`를 사용해야 합니다. 그렇지 않으면 해당 매개변수를 쿼리 매개변수로 해석하기 때문입니다. @@ -50,11 +46,9 @@ 만약 언더스코어를 하이픈으로 자동 변환을 비활성화해야 할 어떤 이유가 있다면, `Header`의 `convert_underscores` 매개변수를 `False`로 설정하십시오: -```Python hl_lines="10" -{!../../docs_src/header_params/tutorial002.py!} -``` +{* ../../docs_src/header_params/tutorial002.py hl[10] *} -/// warning | "경고" +/// warning | 경고 `convert_underscore`를 `False`로 설정하기 전에, 어떤 HTTP 프록시들과 서버들은 언더스코어가 포함된 헤더 사용을 허락하지 않는다는 것을 명심하십시오. @@ -70,9 +64,7 @@ 예를 들어, 두 번 이상 나타날 수 있는 `X-Token`헤더를 선언하려면, 다음과 같이 작성합니다: -```Python hl_lines="9" -{!../../docs_src/header_params/tutorial003.py!} -``` +{* ../../docs_src/header_params/tutorial003.py hl[9] *} 다음과 같은 두 개의 HTTP 헤더를 전송하여 해당 *경로* 와 통신할 경우: diff --git a/docs/ko/docs/tutorial/index.md b/docs/ko/docs/tutorial/index.md index a148bc76e990e..9f5328992f0f9 100644 --- a/docs/ko/docs/tutorial/index.md +++ b/docs/ko/docs/tutorial/index.md @@ -53,7 +53,7 @@ $ pip install "fastapi[all]" ...이는 코드를 실행하는 서버로 사용할 수 있는 `uvicorn` 또한 포함하고 있습니다. -/// note | "참고" +/// note | 참고 부분적으로 설치할 수도 있습니다. diff --git a/docs/ko/docs/tutorial/metadata.md b/docs/ko/docs/tutorial/metadata.md new file mode 100644 index 0000000000000..a50dfa2e7756e --- /dev/null +++ b/docs/ko/docs/tutorial/metadata.md @@ -0,0 +1,118 @@ +# 메타데이터 및 문서화 URL + +**FastAPI** 응용 프로그램에서 다양한 메타데이터 구성을 사용자 맞춤 설정할 수 있습니다. + +## API에 대한 메타데이터 + +OpenAPI 명세 및 자동화된 API 문서 UI에 사용되는 다음 필드를 설정할 수 있습니다: + +| 매개변수 | 타입 | 설명 | +|----------|------|-------| +| `title` | `str` | API의 제목입니다. | +| `summary` | `str` | API에 대한 짧은 요약입니다. OpenAPI 3.1.0, FastAPI 0.99.0부터 사용 가능 | +| `description` | `str` | API에 대한 짧은 설명입니다. 마크다운을 사용할 수 있습니다. | +| `version` | `string` | API의 버전입니다. OpenAPI의 버전이 아닌, 여러분의 애플리케이션의 버전을 나타냅니다. 예: `2.5.0` | +| `terms_of_service` | `str` | API 이용 약관의 URL입니다. 제공하는 경우 URL 형식이어야 합니다. | +| `contact` | `dict` | 노출된 API에 대한 연락처 정보입니다. 여러 필드를 포함할 수 있습니다.
contact 필드
매개변수타입설명
namestr연락처 인물/조직의 식별명입니다.
urlstr연락처 정보가 담긴 URL입니다. URL 형식이어야 합니다.
emailstr연락처 인물/조직의 이메일 주소입니다. 이메일 주소 형식이어야 합니다.
| +| `license_info` | `dict` | 노출된 API의 라이선스 정보입니다. 여러 필드를 포함할 수 있습니다.
license_info 필드
매개변수타입설명
namestr필수 (license_info가 설정된 경우). API에 사용된 라이선스 이름입니다.
identifierstrAPI에 대한 SPDX 라이선스 표현입니다. identifier 필드는 url 필드와 상호 배타적입니다. OpenAPI 3.1.0, FastAPI 0.99.0부터 사용 가능
urlstrAPI에 사용된 라이선스의 URL입니다. URL 형식이어야 합니다.
| + +다음과 같이 설정할 수 있습니다: + +{* ../../docs_src/metadata/tutorial001.py hl[3:16,19:32] *} + +/// tip + +`description` 필드에 마크다운을 사용할 수 있으며, 출력에서 렌더링됩니다. + +/// + +이 구성을 사용하면 문서 자동화(로 생성된) API 문서는 다음과 같이 보입니다: + + + +## 라이선스 식별자 + +OpenAPI 3.1.0 및 FastAPI 0.99.0부터 `license_info`에 `identifier`를 URL 대신 설정할 수 있습니다. + +예: + +{* ../../docs_src/metadata/tutorial001_1.py hl[31] *} + +## 태그에 대한 메타데이터 + +`openapi_tags` 매개변수를 사용하여 경로 작동을 그룹화하는 데 사용되는 태그에 추가 메타데이터를 추가할 수 있습니다. + +리스트는 각 태그에 대해 하나의 딕셔너리를 포함해야 합니다. + +각 딕셔너리에는 다음이 포함될 수 있습니다: + +* `name` (**필수**): `tags` 매개변수에서 *경로 작동*과 `APIRouter`에 사용된 태그 이름과 동일한 `str`입니다. +* `description`: 태그에 대한 간단한 설명을 담은 `str`입니다. 마크다운을 사용할 수 있으며 문서 UI에 표시됩니다. +* `externalDocs`: 외부 문서를 설명하는 `dict`이며: + * `description`: 외부 문서에 대한 간단한 설명을 담은 `str`입니다. + * `url` (**필수**): 외부 문서의 URL을 담은 `str`입니다. + +### 태그에 대한 메타데이터 생성 + +`users` 및 `items`에 대한 태그 예시와 함께 메타데이터를 생성하고 이를 `openapi_tags` 매개변수로 전달해 보겠습니다: + +{* ../../docs_src/metadata/tutorial004.py hl[3:16,18] *} + +설명 안에 마크다운을 사용할 수 있습니다. 예를 들어 "login"은 굵게(**login**) 표시되고, "fancy"는 기울임꼴(_fancy_)로 표시됩니다. + +/// tip + +사용 중인 모든 태그에 메타데이터를 추가할 필요는 없습니다. + +/// + +### 태그 사용 + +`tags` 매개변수를 *경로 작동* 및 `APIRouter`와 함께 사용하여 태그에 할당할 수 있습니다: + +{* ../../docs_src/metadata/tutorial004.py hl[21,26] *} + +/// info + +태그에 대한 자세한 내용은 [경로 작동 구성](path-operation-configuration.md#tags){.internal-link target=_blank}에서 읽어보세요. + +/// + +### 문서 확인 + +이제 문서를 확인하면 모든 추가 메타데이터가 표시됩니다: + + + +### 태그 순서 + +각 태그 메타데이터 딕셔너리의 순서는 문서 UI에 표시되는 순서를 정의합니다. + +예를 들어, 알파벳 순서상 `users`는 `items` 뒤에 오지만, 우리는 `users` 메타데이터를 리스트의 첫 번째 딕셔너리로 추가했기 때문에 먼저 표시됩니다. + +## OpenAPI URL + +OpenAPI 구조는 기본적으로 `/openapi.json`에서 제공됩니다. + +`openapi_url` 매개변수를 통해 이를 설정할 수 있습니다. + +예를 들어, 이를 `/api/v1/openapi.json`에 제공하도록 설정하려면: + +{* ../../docs_src/metadata/tutorial002.py hl[3] *} + +OpenAPI 구조를 완전히 비활성화하려면 `openapi_url=None`으로 설정할 수 있으며, 이를 사용하여 문서화 사용자 인터페이스도 비활성화됩니다. + +## 문서화 URL + +포함된 두 가지 문서화 사용자 인터페이스를 설정할 수 있습니다: + +* **Swagger UI**: `/docs`에서 제공됩니다. + * `docs_url` 매개변수로 URL을 설정할 수 있습니다. + * `docs_url=None`으로 설정하여 비활성화할 수 있습니다. +* **ReDoc**: `/redoc`에서 제공됩니다. + * `redoc_url` 매개변수로 URL을 설정할 수 있습니다. + * `redoc_url=None`으로 설정하여 비활성화할 수 있습니다. + +예를 들어, Swagger UI를 `/documentation`에서 제공하고 ReDoc을 비활성화하려면: + +{* ../../docs_src/metadata/tutorial003.py hl[3] *} diff --git a/docs/ko/docs/tutorial/middleware.md b/docs/ko/docs/tutorial/middleware.md index f36f11a273605..3cd752a0ebad6 100644 --- a/docs/ko/docs/tutorial/middleware.md +++ b/docs/ko/docs/tutorial/middleware.md @@ -11,7 +11,7 @@ * **응답** 또는 다른 필요한 코드를 실행시키는 동작을 할 수 있습니다. * **응답**를 반환합니다. -/// note | "기술 세부사항" +/// note | 기술 세부사항 만약 `yield`를 사용한 의존성을 가지고 있다면, 미들웨어가 실행되고 난 후에 exit이 실행됩니다. @@ -31,11 +31,9 @@ * 그런 다음, *경로 작업*에 의해 생성된 `response` 를 반환합니다. * `response`를 반환하기 전에 추가로 `response`를 수정할 수 있습니다. -```Python hl_lines="8-9 11 14" -{!../../docs_src/middleware/tutorial001.py!} -``` +{* ../../docs_src/middleware/tutorial001.py hl[8:9,11,14] *} -/// tip | "팁" +/// tip | 팁 사용자 정의 헤더는 'X-' 접두사를 사용하여 추가할 수 있습니다. @@ -43,7 +41,7 @@ /// -/// note | "기술적 세부사항" +/// note | 기술적 세부사항 `from starlette.requests import request`를 사용할 수도 있습니다. @@ -59,9 +57,7 @@ 예를 들어, 요청을 수행하고 응답을 생성하는데 까지 걸린 시간 값을 가지고 있는 `X-Process-Time` 같은 사용자 정의 헤더를 추가할 수 있습니다. -```Python hl_lines="10 12-13" -{!../../docs_src/middleware/tutorial001.py!} -``` +{* ../../docs_src/middleware/tutorial001.py hl[10,12:13] *} ## 다른 미들웨어 diff --git a/docs/ko/docs/tutorial/path-operation-configuration.md b/docs/ko/docs/tutorial/path-operation-configuration.md index 6ebe613a80dbc..81914182af3fb 100644 --- a/docs/ko/docs/tutorial/path-operation-configuration.md +++ b/docs/ko/docs/tutorial/path-operation-configuration.md @@ -2,7 +2,7 @@ *경로 작동 데코레이터*를 설정하기 위해서 전달할수 있는 몇 가지 매개변수가 있습니다. -/// warning | "경고" +/// warning | 경고 아래 매개변수들은 *경로 작동 함수*가 아닌 *경로 작동 데코레이터*에 직접 전달된다는 사실을 기억하십시오. @@ -16,13 +16,11 @@ 하지만 각 코드의 의미를 모른다면, `status`에 있는 단축 상수들을 사용할수 있습니다: -```Python hl_lines="3 17" -{!../../docs_src/path_operation_configuration/tutorial001.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial001.py hl[3,17] *} 각 상태 코드들은 응답에 사용되며, OpenAPI 스키마에 추가됩니다. -/// note | "기술적 세부사항" +/// note | 기술적 세부사항 다음과 같이 임포트하셔도 좋습니다. `from starlette import status`. @@ -34,9 +32,7 @@ (보통 단일 `str`인) `str`로 구성된 `list`와 함께 매개변수 `tags`를 전달하여, `경로 작동`에 태그를 추가할 수 있습니다: -```Python hl_lines="17 22 27" -{!../../docs_src/path_operation_configuration/tutorial002.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial002.py hl[17,22,27] *} 전달된 태그들은 OpenAPI의 스키마에 추가되며, 자동 문서 인터페이스에서 사용됩니다: @@ -46,9 +42,7 @@ `summary`와 `description`을 추가할 수 있습니다: -```Python hl_lines="20-21" -{!../../docs_src/path_operation_configuration/tutorial003.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial003.py hl[20:21] *} ## 독스트링으로 만든 기술 @@ -56,9 +50,7 @@ 마크다운 문법으로 독스트링을 작성할 수 있습니다, 작성된 마크다운 형식의 독스트링은 (마크다운의 들여쓰기를 고려하여) 올바르게 화면에 출력됩니다. -```Python hl_lines="19-27" -{!../../docs_src/path_operation_configuration/tutorial004.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial004.py hl[19:27] *} 이는 대화형 문서에서 사용됩니다: @@ -68,17 +60,15 @@ `response_description` 매개변수로 응답에 관한 설명을 명시할 수 있습니다: -```Python hl_lines="21" -{!../../docs_src/path_operation_configuration/tutorial005.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial005.py hl[21] *} -/// info | "정보" +/// info | 정보 `response_description`은 구체적으로 응답을 지칭하며, `description`은 일반적인 *경로 작동*을 지칭합니다. /// -/// check | "확인" +/// check | 확인 OpenAPI는 각 *경로 작동*이 응답에 관한 설명을 요구할 것을 명시합니다. @@ -92,9 +82,7 @@ OpenAPI는 각 *경로 작동*이 응답에 관한 설명을 요구할 것을 단일 *경로 작동*을 없애지 않고 지원중단을 해야한다면, `deprecated` 매개변수를 전달하면 됩니다. -```Python hl_lines="16" -{!../../docs_src/path_operation_configuration/tutorial006.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial006.py hl[16] *} 대화형 문서에 지원중단이라고 표시됩니다. diff --git a/docs/ko/docs/tutorial/path-params-numeric-validations.md b/docs/ko/docs/tutorial/path-params-numeric-validations.md index caab2d453aa41..f21c9290edae4 100644 --- a/docs/ko/docs/tutorial/path-params-numeric-validations.md +++ b/docs/ko/docs/tutorial/path-params-numeric-validations.md @@ -6,9 +6,7 @@ 먼저 `fastapi`에서 `Path`를 임포트합니다: -```Python hl_lines="3" -{!../../docs_src/path_params_numeric_validations/tutorial001.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial001.py hl[3] *} ## 메타데이터 선언 @@ -16,11 +14,9 @@ 예를 들어, `title` 메타데이터 값을 경로 매개변수 `item_id`에 선언하려면 다음과 같이 입력할 수 있습니다: -```Python hl_lines="10" -{!../../docs_src/path_params_numeric_validations/tutorial001.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial001.py hl[10] *} -/// note | "참고" +/// note | 참고 경로 매개변수는 경로의 일부여야 하므로 언제나 필수적입니다. @@ -46,9 +42,7 @@ 따라서 함수를 다음과 같이 선언 할 수 있습니다: -```Python hl_lines="7" -{!../../docs_src/path_params_numeric_validations/tutorial002.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial002.py hl[7] *} ## 필요한 경우 매개변수 정렬하기, 트릭 @@ -58,9 +52,7 @@ 파이썬은 `*`으로 아무런 행동도 하지 않지만, 따르는 매개변수들은 kwargs로도 알려진 키워드 인자(키-값 쌍)여야 함을 인지합니다. 기본값을 가지고 있지 않더라도 그렇습니다. -```Python hl_lines="7" -{!../../docs_src/path_params_numeric_validations/tutorial003.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *} ## 숫자 검증: 크거나 같음 @@ -68,9 +60,7 @@ 여기서 `ge=1`인 경우, `item_id`는 `1`보다 "크거나(`g`reater) 같은(`e`qual)" 정수형 숫자여야 합니다. -```Python hl_lines="8" -{!../../docs_src/path_params_numeric_validations/tutorial004.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial004.py hl[8] *} ## 숫자 검증: 크거나 같음 및 작거나 같음 @@ -79,9 +69,7 @@ * `gt`: 크거나(`g`reater `t`han) * `le`: 작거나 같은(`l`ess than or `e`qual) -```Python hl_lines="9" -{!../../docs_src/path_params_numeric_validations/tutorial005.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial005.py hl[9] *} ## 숫자 검증: 부동소수, 크거나 및 작거나 @@ -93,9 +81,7 @@ lt 역시 마찬가지입니다. -```Python hl_lines="11" -{!../../docs_src/path_params_numeric_validations/tutorial006.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial006.py hl[11] *} ## 요약 @@ -108,7 +94,7 @@ * `lt`: 작거나(`l`ess `t`han) * `le`: 작거나 같은(`l`ess than or `e`qual) -/// info | "정보" +/// info | 정보 `Query`, `Path`, 그리고 나중에게 보게될 것들은 (여러분이 사용할 필요가 없는) 공통 `Param` 클래스의 서브 클래스입니다. @@ -116,7 +102,7 @@ /// -/// note | "기술 세부사항" +/// note | 기술 세부사항 `fastapi`에서 `Query`, `Path` 등을 임포트 할 때, 이것들은 실제로 함수입니다. diff --git a/docs/ko/docs/tutorial/path-params.md b/docs/ko/docs/tutorial/path-params.md index 09a27a7b3a422..b72787e0b286c 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,13 +16,11 @@ 파이썬 표준 타입 어노테이션을 사용하여 함수에 있는 경로 매개변수의 타입을 선언할 수 있습니다: -```Python hl_lines="7" -{!../../docs_src/path_params/tutorial002.py!} -``` +{* ../../docs_src/path_params/tutorial002.py hl[7] *} 위의 예시에서, `item_id`는 `int`로 선언되었습니다. -/// check | "확인" +/// check | 확인 이 기능은 함수 내에서 오류 검사, 자동완성 등의 편집기 기능을 활용할 수 있게 해줍니다. @@ -38,7 +34,7 @@ {"item_id":3} ``` -/// check | "확인" +/// check | 확인 함수가 받은(반환도 하는) 값은 문자열 `"3"`이 아니라 파이썬 `int` 형인 `3`입니다. @@ -69,7 +65,7 @@ `int`가 아닌 `float`을 전달하는 경우에도 동일한 오류가 나타납니다: http://127.0.0.1:8000/items/4.2 -/// check | "확인" +/// check | 확인 즉, 파이썬 타입 선언을 하면 **FastAPI**는 데이터 검증을 합니다. @@ -85,7 +81,7 @@ -/// check | "확인" +/// check | 확인 그저 파이썬 타입 선언을 하기만 하면 **FastAPI**는 자동 대화형 API 문서(Swagger UI)를 제공합니다. @@ -121,9 +117,7 @@ *경로 작동*은 순차적으로 실행되기 때문에 `/users/{user_id}` 이전에 `/users/me`를 먼저 선언해야 합니다: -```Python hl_lines="6 11" -{!../../docs_src/path_params/tutorial003.py!} -``` +{* ../../docs_src/path_params/tutorial003.py hl[6,11] *} 그렇지 않으면 `/users/{user_id}`는 `/users/me` 요청 또한 매개변수 `user_id`의 값이 `"me"`인 것으로 "생각하게" 됩니다. @@ -139,17 +133,15 @@ 가능한 값들에 해당하는 고정된 값의 클래스 어트리뷰트들을 만듭니다: -```Python hl_lines="1 6-9" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[1,6:9] *} -/// info | "정보" +/// info | 정보 열거형(또는 enums)은 파이썬 버전 3.4 이후로 사용 가능합니다. /// -/// tip | "팁" +/// tip | 팁 혹시 궁금하다면, "AlexNet", "ResNet", 그리고 "LeNet"은 그저 기계 학습 모델들의 이름입니다. @@ -159,9 +151,7 @@ 생성한 열거형 클래스(`ModelName`)를 사용하는 타입 어노테이션으로 *경로 매개변수*를 만듭니다: -```Python hl_lines="16" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[16] *} ### 문서 확인 @@ -177,19 +167,15 @@ 열거형 `ModelName`의 *열거형 멤버*를 비교할 수 있습니다: -```Python hl_lines="17" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[17] *} #### *열거형 값* 가져오기 `model_name.value` 또는 일반적으로 `your_enum_member.value`를 이용하여 실제 값(위 예시의 경우 `str`)을 가져올 수 있습니다: -```Python hl_lines="20" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[20] *} -/// tip | "팁" +/// tip | 팁 `ModelName.lenet.value`로도 값 `"lenet"`에 접근할 수 있습니다. @@ -201,9 +187,7 @@ 클라이언트에 반환하기 전에 해당 값(이 경우 문자열)으로 변환됩니다: -```Python hl_lines="18 21 23" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[18,21,23] *} 클라이언트는 아래의 JSON 응답을 얻습니다: @@ -242,11 +226,9 @@ Starlette의 옵션을 직접 이용하여 다음과 같은 URL을 사용함으 따라서 다음과 같이 사용할 수 있습니다: -```Python hl_lines="6" -{!../../docs_src/path_params/tutorial004.py!} -``` +{* ../../docs_src/path_params/tutorial004.py hl[6] *} -/// tip | "팁" +/// tip | 팁 매개변수가 가져야 하는 값이 `/home/johndoe/myfile.txt`와 같이 슬래시로 시작(`/`)해야 할 수 있습니다. diff --git a/docs/ko/docs/tutorial/query-param-models.md b/docs/ko/docs/tutorial/query-param-models.md new file mode 100644 index 0000000000000..2ca65a3319757 --- /dev/null +++ b/docs/ko/docs/tutorial/query-param-models.md @@ -0,0 +1,68 @@ +# 쿼리 매개변수 모델 + +연관된 쿼리 **매개변수** 그룹이 있다면 **Pydantic 모델** 을 사용해 선언할 수 있습니다. + +이렇게 하면 **여러 곳**에서 **모델을 재사용**할 수 있을 뿐만 아니라, 매개변수에 대한 검증 및 메타데이터도 한 번에 선언할 수 있습니다. 😎 + +/// note | 참고 + +이 기능은 FastAPI 버전 `0.115.0`부터 제공됩니다. 🤓 + +/// + +## 쿼리 매개변수와 Pydantic 모델 + +필요한 **쿼리 매개변수**를 **Pydantic 모델** 안에 선언한 다음, 모델을 `Query`로 선언합니다. + +{* ../../docs_src/query_param_models/tutorial001_an_py310.py hl[9:13,17] *} + +**FastAPI**는 요청의 **쿼리 매개변수**에서 **각 필드**의 데이터를 **추출**해 정의한 Pydantic 모델로 제공합니다. + +## 문서 확인하기 + +`/docs` 경로의 API 문서에서 매개변수를 확인할 수 있습니다. + +
+ +
+ +## 추가 쿼리 매개변수 금지 + +몇몇의 특이한 경우에 (흔치 않지만), 허용할 쿼리 매개변수를 **제한**해야할 수 있습니다. + +Pydantic 모델 설정에서 `extra` 필드를 `forbid` 로 설정할 수 있습니다. + +{* ../../docs_src/query_param_models/tutorial002_an_py310.py hl[10] *} + +만약 클라이언트가 쿼리 매개변수로 **추가적인** 데이터를 보내려고 하면, 클라이언트는 **에러** 응답을 받게 됩니다. + +예를 들어, 아래와 같이 만약 클라이언트가 `tool` 쿼리 매개변수에 `plumbus` 라는 값을 추가해서 보내려고 하면, + +```http +https://example.com/items/?limit=10&tool=plumbus +``` + +클라이언트는 쿼리 매개변수 `tool` 이 허용되지 않는다는 **에러** 응답을 받게 됩니다. + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["query", "tool"], + "msg": "Extra inputs are not permitted", + "input": "plumbus" + } + ] +} +``` + +## 요약 + +**FastAPI** 에서 **쿼리 매개변수** 를 선언할 때 **Pydantic 모델** 을 사용할 수 있습니다. 😎 + +/// tip | 팁 + +스포일러 경고: Pydantic 모델을 쿠키와 헤더에도 적용할 수 있습니다. 이에 대해서는 이후 튜토리얼에서 다룰 예정입니다. 🤫 + +/// diff --git a/docs/ko/docs/tutorial/query-params-str-validations.md b/docs/ko/docs/tutorial/query-params-str-validations.md index e44f6dd16c705..f2ca453ac5a37 100644 --- a/docs/ko/docs/tutorial/query-params-str-validations.md +++ b/docs/ko/docs/tutorial/query-params-str-validations.md @@ -4,13 +4,11 @@ 이 응용 프로그램을 예로 들어보겠습니다: -```Python hl_lines="9" -{!../../docs_src/query_params_str_validations/tutorial001.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial001.py hl[9] *} 쿼리 매개변수 `q`는 `Optional[str]` 자료형입니다. 즉, `str` 자료형이지만 `None` 역시 될 수 있음을 뜻하고, 실제로 기본값은 `None`이기 때문에 FastAPI는 이 매개변수가 필수가 아니라는 것을 압니다. -/// note | "참고" +/// note | 참고 FastAPI는 `q`의 기본값이 `= None`이기 때문에 필수가 아님을 압니다. @@ -26,17 +24,13 @@ FastAPI는 `q`의 기본값이 `= None`이기 때문에 필수가 아님을 압 이를 위해 먼저 `fastapi`에서 `Query`를 임포트합니다: -```Python hl_lines="3" -{!../../docs_src/query_params_str_validations/tutorial002.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial002.py hl[3] *} ## 기본값으로 `Query` 사용 이제 `Query`를 매개변수의 기본값으로 사용하여 `max_length` 매개변수를 50으로 설정합니다: -```Python hl_lines="9" -{!../../docs_src/query_params_str_validations/tutorial002.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial002.py hl[9] *} 기본값 `None`을 `Query(None)`으로 바꿔야 하므로, `Query`의 첫 번째 매개변수는 기본값을 정의하는 것과 같은 목적으로 사용됩니다. @@ -54,7 +48,7 @@ q: Optional[str] = None 하지만 명시적으로 쿼리 매개변수를 선언합니다. -/// info | "정보" +/// info | 정보 FastAPI는 다음 부분에 관심이 있습니다: @@ -86,17 +80,13 @@ q: str = Query(None, max_length=50) 매개변수 `min_length` 또한 추가할 수 있습니다: -```Python hl_lines="9" -{!../../docs_src/query_params_str_validations/tutorial003.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial003.py hl[9] *} ## 정규식 추가 매개변수와 일치해야 하는 정규표현식을 정의할 수 있습니다: -```Python hl_lines="10" -{!../../docs_src/query_params_str_validations/tutorial004.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial004.py hl[10] *} 이 특정 정규표현식은 전달 받은 매개변수 값을 검사합니다: @@ -114,11 +104,9 @@ q: str = Query(None, max_length=50) `min_length`가 `3`이고, 기본값이 `"fixedquery"`인 쿼리 매개변수 `q`를 선언해봅시다: -```Python hl_lines="7" -{!../../docs_src/query_params_str_validations/tutorial005.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial005.py hl[7] *} -/// note | "참고" +/// note | 참고 기본값을 갖는 것만으로 매개변수는 선택적이 됩니다. @@ -146,11 +134,9 @@ q: Optional[str] = Query(None, min_length=3) 그래서 `Query`를 필수값으로 만들어야 할 때면, 첫 번째 인자로 `...`를 사용할 수 있습니다: -```Python hl_lines="7" -{!../../docs_src/query_params_str_validations/tutorial006.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial006.py hl[7] *} -/// info | "정보" +/// info | 정보 이전에 `...`를 본적이 없다면: 특별한 단일값으로, 파이썬의 일부이며 "Ellipsis"라 부릅니다. @@ -164,9 +150,7 @@ q: Optional[str] = Query(None, min_length=3) 예를 들어, URL에서 여러번 나오는 `q` 쿼리 매개변수를 선언하려면 다음과 같이 작성할 수 있습니다: -```Python hl_lines="9" -{!../../docs_src/query_params_str_validations/tutorial011.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial011.py hl[9] *} 아래와 같은 URL을 사용합니다: @@ -187,7 +171,7 @@ http://localhost:8000/items/?q=foo&q=bar } ``` -/// tip | "팁" +/// tip | 팁 위의 예와 같이 `list` 자료형으로 쿼리 매개변수를 선언하려면 `Query`를 명시적으로 사용해야 합니다. 그렇지 않으면 요청 본문으로 해석됩니다. @@ -201,9 +185,7 @@ http://localhost:8000/items/?q=foo&q=bar 그리고 제공된 값이 없으면 기본 `list` 값을 정의할 수도 있습니다: -```Python hl_lines="9" -{!../../docs_src/query_params_str_validations/tutorial012.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial012.py hl[9] *} 아래로 이동한다면: @@ -226,11 +208,9 @@ http://localhost:8000/items/ `List[str]` 대신 `list`를 직접 사용할 수도 있습니다: -```Python hl_lines="7" -{!../../docs_src/query_params_str_validations/tutorial013.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial013.py hl[7] *} -/// note | "참고" +/// note | 참고 이 경우 FastAPI는 리스트의 내용을 검사하지 않음을 명심하기 바랍니다. @@ -244,7 +224,7 @@ http://localhost:8000/items/ 해당 정보는 생성된 OpenAPI에 포함되고 문서 사용자 인터페이스 및 외부 도구에서 사용됩니다. -/// note | "참고" +/// note | 참고 도구에 따라 OpenAPI 지원 수준이 다를 수 있음을 명심하기 바랍니다. @@ -254,15 +234,11 @@ http://localhost:8000/items/ `title`을 추가할 수 있습니다: -```Python hl_lines="10" -{!../../docs_src/query_params_str_validations/tutorial007.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial007.py hl[10] *} 그리고 `description`도 추가할 수 있습니다: -```Python hl_lines="13" -{!../../docs_src/query_params_str_validations/tutorial008.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial008.py hl[13] *} ## 별칭 매개변수 @@ -282,9 +258,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems 이럴 경우 `alias`를 선언할 수 있으며, 해당 별칭은 매개변수 값을 찾는 데 사용됩니다: -```Python hl_lines="9" -{!../../docs_src/query_params_str_validations/tutorial009.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial009.py hl[9] *} ## 매개변수 사용하지 않게 하기 @@ -294,9 +268,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems 그렇다면 `deprecated=True` 매개변수를 `Query`로 전달합니다: -```Python hl_lines="18" -{!../../docs_src/query_params_str_validations/tutorial010.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial010.py hl[18] *} 문서가 아래와 같이 보일겁니다: diff --git a/docs/ko/docs/tutorial/query-params.md b/docs/ko/docs/tutorial/query-params.md index b2a946c092514..d5b9837c4e9b1 100644 --- a/docs/ko/docs/tutorial/query-params.md +++ b/docs/ko/docs/tutorial/query-params.md @@ -2,9 +2,7 @@ 경로 매개변수의 일부가 아닌 다른 함수 매개변수를 선언하면 "쿼리" 매개변수로 자동 해석합니다. -```Python hl_lines="9" -{!../../docs_src/query_params/tutorial001.py!} -``` +{* ../../docs_src/query_params/tutorial001.py hl[9] *} 쿼리는 URL에서 `?` 후에 나오고 `&`으로 구분되는 키-값 쌍의 집합입니다. @@ -63,19 +61,17 @@ http://127.0.0.1:8000/items/?skip=20 같은 방법으로 기본값을 `None`으로 설정하여 선택적 매개변수를 선언할 수 있습니다: -```Python hl_lines="9" -{!../../docs_src/query_params/tutorial002.py!} -``` +{* ../../docs_src/query_params/tutorial002.py hl[9] *} 이 경우 함수 매개변수 `q`는 선택적이며 기본값으로 `None` 값이 됩니다. -/// check | "확인" +/// check | 확인 **FastAPI**는 `item_id`가 경로 매개변수이고 `q`는 경로 매개변수가 아닌 쿼리 매개변수라는 것을 알 정도로 충분히 똑똑합니다. /// -/// note | "참고" +/// note | 참고 FastAPI는 `q`가 `= None`이므로 선택적이라는 것을 인지합니다. @@ -87,9 +83,7 @@ FastAPI는 `q`가 `= None`이므로 선택적이라는 것을 인지합니다. `bool` 형으로 선언할 수도 있고, 아래처럼 변환됩니다: -```Python hl_lines="9" -{!../../docs_src/query_params/tutorial003.py!} -``` +{* ../../docs_src/query_params/tutorial003.py hl[9] *} 이 경우, 아래로 이동하면: @@ -132,9 +126,7 @@ http://127.0.0.1:8000/items/foo?short=yes 매개변수들은 이름으로 감지됩니다: -```Python hl_lines="8 10" -{!../../docs_src/query_params/tutorial004.py!} -``` +{* ../../docs_src/query_params/tutorial004.py hl[8,10] *} ## 필수 쿼리 매개변수 @@ -144,9 +136,7 @@ http://127.0.0.1:8000/items/foo?short=yes 그러나 쿼리 매개변수를 필수로 만들려면 단순히 기본값을 선언하지 않으면 됩니다: -```Python hl_lines="6-7" -{!../../docs_src/query_params/tutorial005.py!} -``` +{* ../../docs_src/query_params/tutorial005.py hl[6:7] *} 여기 쿼리 매개변수 `needy`는 `str`형인 필수 쿼리 매개변수입니다. @@ -190,9 +180,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy 그리고 물론, 일부 매개변수는 필수로, 다른 일부는 기본값을, 또 다른 일부는 선택적으로 선언할 수 있습니다: -```Python hl_lines="10" -{!../../docs_src/query_params/tutorial006.py!} -``` +{* ../../docs_src/query_params/tutorial006.py hl[10] *} 위 예시에서는 3가지 쿼리 매개변수가 있습니다: @@ -200,7 +188,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy * `skip`, 기본값이 `0`인 `int`. * `limit`, 선택적인 `int`. -/// tip | "팁" +/// tip | 팁 [경로 매개변수](path-params.md#_8){.internal-link target=_blank}와 마찬가지로 `Enum`을 사용할 수 있습니다. diff --git a/docs/ko/docs/tutorial/request-files.md b/docs/ko/docs/tutorial/request-files.md index 40579dd51a5bd..9162b353cd84a 100644 --- a/docs/ko/docs/tutorial/request-files.md +++ b/docs/ko/docs/tutorial/request-files.md @@ -2,7 +2,7 @@ `File`을 사용하여 클라이언트가 업로드할 파일들을 정의할 수 있습니다. -/// info | "정보" +/// info | 정보 업로드된 파일을 전달받기 위해 먼저 `python-multipart`를 설치해야합니다. @@ -16,19 +16,15 @@ `fastapi` 에서 `File` 과 `UploadFile` 을 임포트 합니다: -```Python hl_lines="1" -{!../../docs_src/request_files/tutorial001.py!} -``` +{* ../../docs_src/request_files/tutorial001.py hl[1] *} ## `File` 매개변수 정의 `Body` 및 `Form` 과 동일한 방식으로 파일의 매개변수를 생성합니다: -```Python hl_lines="7" -{!../../docs_src/request_files/tutorial001.py!} -``` +{* ../../docs_src/request_files/tutorial001.py hl[7] *} -/// info | "정보" +/// info | 정보 `File` 은 `Form` 으로부터 직접 상속된 클래스입니다. @@ -36,7 +32,7 @@ /// -/// tip | "팁" +/// tip | 팁 File의 본문을 선언할 때, 매개변수가 쿼리 매개변수 또는 본문(JSON) 매개변수로 해석되는 것을 방지하기 위해 `File` 을 사용해야합니다. @@ -54,9 +50,7 @@ File의 본문을 선언할 때, 매개변수가 쿼리 매개변수 또는 본 `File` 매개변수를 `UploadFile` 타입으로 정의합니다: -```Python hl_lines="12" -{!../../docs_src/request_files/tutorial001.py!} -``` +{* ../../docs_src/request_files/tutorial001.py hl[12] *} `UploadFile` 을 사용하는 것은 `bytes` 과 비교해 다음과 같은 장점이 있습니다: @@ -104,7 +98,7 @@ contents = myfile.file.read() /// -/// note | "Starlette 기술적 세부사항" +/// note | Starlette 기술적 세부사항 **FastAPI**의 `UploadFile` 은 **Starlette**의 `UploadFile` 을 직접적으로 상속받지만, **Pydantic** 및 FastAPI의 다른 부분들과의 호환성을 위해 필요한 부분들이 추가되었습니다. @@ -116,7 +110,7 @@ HTML의 폼들(`
`)이 서버에 데이터를 전송하는 방식은 **FastAPI**는 JSON 대신 올바른 위치에서 데이터를 읽을 수 있도록 합니다. -/// note | "기술적 세부사항" +/// note | 기술적 세부사항 폼의 데이터는 파일이 포함되지 않은 경우 일반적으로 "미디어 유형" `application/x-www-form-urlencoded` 을 사용해 인코딩 됩니다. @@ -126,7 +120,7 @@ HTML의 폼들(`
`)이 서버에 데이터를 전송하는 방식은 /// -/// warning | "경고" +/// warning | 경고 다수의 `File` 과 `Form` 매개변수를 한 *경로 작동*에 선언하는 것이 가능하지만, 요청의 본문이 `application/json` 가 아닌 `multipart/form-data` 로 인코딩 되기 때문에 JSON으로 받아야하는 `Body` 필드를 함께 선언할 수는 없습니다. @@ -142,13 +136,11 @@ 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 | "참고" +/// note | 참고 2019년 4월 14일부터 Swagger UI가 하나의 폼 필드로 다수의 파일을 업로드하는 것을 지원하지 않습니다. 더 많은 정보를 원하면, #4276#3641을 참고하세요. @@ -158,7 +150,7 @@ HTML의 폼들(`
`)이 서버에 데이터를 전송하는 방식은 /// -/// note | "기술적 세부사항" +/// note | 기술적 세부사항 `from starlette.responses import HTMLResponse` 역시 사용할 수 있습니다. diff --git a/docs/ko/docs/tutorial/request-forms-and-files.md b/docs/ko/docs/tutorial/request-forms-and-files.md index 24501fe34f06c..dc1bda21a8fcd 100644 --- a/docs/ko/docs/tutorial/request-forms-and-files.md +++ b/docs/ko/docs/tutorial/request-forms-and-files.md @@ -2,7 +2,7 @@ `File` 과 `Form` 을 사용하여 파일과 폼을 함께 정의할 수 있습니다. -/// info | "정보" +/// info | 정보 파일과 폼 데이터를 함께, 또는 각각 업로드하기 위해 먼저 `python-multipart`를 설치해야합니다. @@ -12,23 +12,19 @@ ## `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 | "경고" +/// warning | 경고 다수의 `File`과 `Form` 매개변수를 한 *경로 작동*에 선언하는 것이 가능하지만, 요청의 본문이 `application/json`가 아닌 `multipart/form-data`로 인코딩 되기 때문에 JSON으로 받아야하는 `Body` 필드를 함께 선언할 수는 없습니다. diff --git a/docs/ko/docs/tutorial/response-model.md b/docs/ko/docs/tutorial/response-model.md index 74034e34de2a7..a71d649f90c8e 100644 --- a/docs/ko/docs/tutorial/response-model.md +++ b/docs/ko/docs/tutorial/response-model.md @@ -8,11 +8,9 @@ * `@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)처럼 *경로 작동 함수*가 아닙니다. @@ -31,7 +29,7 @@ FastAPI는 이 `response_model`를 사용하여: * 해당 모델의 출력 데이터 제한. 이것이 얼마나 중요한지 아래에서 볼 것입니다. -/// note | "기술 세부사항" +/// note | 기술 세부사항 응답 모델은 함수의 타입 어노테이션 대신 이 매개변수로 선언하는데, 경로 함수가 실제 응답 모델을 반환하지 않고 `dict`, 데이터베이스 객체나 기타 다른 모델을 `response_model`을 사용하여 필드 제한과 직렬화를 수행하고 반환할 수 있기 때문입니다 @@ -41,15 +39,11 @@ FastAPI는 이 `response_model`를 사용하여: 여기서 우리는 평문 비밀번호를 포함하는 `UserIn` 모델을 선언합니다: -```Python hl_lines="9 11" -{!../../docs_src/response_model/tutorial002.py!} -``` +{* ../../docs_src/response_model/tutorial002.py hl[9,11] *} 그리고 이 모델을 사용하여 입력을 선언하고 같은 모델로 출력을 선언합니다: -```Python hl_lines="17-18" -{!../../docs_src/response_model/tutorial002.py!} -``` +{* ../../docs_src/response_model/tutorial002.py hl[17:18] *} 이제 브라우저가 비밀번호로 사용자를 만들 때마다 API는 응답으로 동일한 비밀번호를 반환합니다. @@ -57,7 +51,7 @@ FastAPI는 이 `response_model`를 사용하여: 그러나 동일한 모델을 다른 *경로 작동*에서 사용할 경우, 모든 클라이언트에게 사용자의 비밀번호를 발신할 수 있습니다. -/// danger | "위험" +/// danger | 위험 절대로 사용자의 평문 비밀번호를 저장하거나 응답으로 발신하지 마십시오. @@ -67,21 +61,15 @@ FastAPI는 이 `response_model`를 사용하여: 대신 평문 비밀번호로 입력 모델을 만들고 해당 비밀번호 없이 출력 모델을 만들 수 있습니다: -```Python hl_lines="9 11 16" -{!../../docs_src/response_model/tutorial003.py!} -``` +{* ../../docs_src/response_model/tutorial003.py hl[9,11,16] *} 여기서 *경로 작동 함수*가 비밀번호를 포함하는 동일한 입력 사용자를 반환할지라도: -```Python hl_lines="24" -{!../../docs_src/response_model/tutorial003.py!} -``` +{* ../../docs_src/response_model/tutorial003.py hl[24] *} ...`response_model`을 `UserOut` 모델로 선언했기 때문에 비밀번호를 포함하지 않습니다: -```Python hl_lines="22" -{!../../docs_src/response_model/tutorial003.py!} -``` +{* ../../docs_src/response_model/tutorial003.py hl[22] *} 따라서 **FastAPI**는 출력 모델에서 선언하지 않은 모든 데이터를 (Pydantic을 사용하여) 필터링합니다. @@ -99,9 +87,7 @@ FastAPI는 이 `response_model`를 사용하여: 응답 모델은 아래와 같이 기본값을 가질 수 있습니다: -```Python hl_lines="11 13-14" -{!../../docs_src/response_model/tutorial004.py!} -``` +{* ../../docs_src/response_model/tutorial004.py hl[11,13:14] *} * `description: Optional[str] = None`은 기본값으로 `None`을 갖습니다. * `tax: float = 10.5`는 기본값으로 `10.5`를 갖습니다. @@ -115,9 +101,7 @@ FastAPI는 이 `response_model`를 사용하여: *경로 작동 데코레이터* 매개변수를 `response_model_exclude_unset=True`로 설정 할 수 있습니다: -```Python hl_lines="24" -{!../../docs_src/response_model/tutorial004.py!} -``` +{* ../../docs_src/response_model/tutorial004.py hl[24] *} 이러한 기본값은 응답에 포함되지 않고 실제로 설정된 값만 포함됩니다. @@ -130,13 +114,13 @@ FastAPI는 이 `response_model`를 사용하여: } ``` -/// info | "정보" +/// info | 정보 FastAPI는 이를 위해 Pydantic 모델의 `.dict()`의 `exclude_unset` 매개변수를 사용합니다. /// -/// info | "정보" +/// info | 정보 아래 또한 사용할 수 있습니다: @@ -181,7 +165,7 @@ ID가 `baz`인 항목(items)처럼 기본값과 동일한 값을 갖는다면: 따라서 JSON 스키마에 포함됩니다. -/// tip | "팁" +/// tip | 팁 `None` 뿐만 아니라 다른 어떤 것도 기본값이 될 수 있습니다. @@ -197,7 +181,7 @@ ID가 `baz`인 항목(items)처럼 기본값과 동일한 값을 갖는다면: Pydantic 모델이 하나만 있고 출력에서 ​​일부 데이터를 제거하려는 경우 빠른 지름길로 사용할 수 있습니다. -/// tip | "팁" +/// tip | 팁 하지만 이러한 매개변수 대신 여러 클래스를 사용하여 위 아이디어를 사용하는 것을 추천합니다. @@ -207,11 +191,9 @@ Pydantic 모델이 하나만 있고 출력에서 ​​일부 데이터를 제 /// -```Python hl_lines="31 37" -{!../../docs_src/response_model/tutorial005.py!} -``` +{* ../../docs_src/response_model/tutorial005.py hl[31,37] *} -/// tip | "팁" +/// tip | 팁 문법 `{"name", "description"}`은 두 값을 갖는 `set`을 만듭니다. @@ -223,9 +205,7 @@ Pydantic 모델이 하나만 있고 출력에서 ​​일부 데이터를 제 `list` 또는 `tuple` 대신 `set`을 사용하는 법을 잊었더라도, FastAPI는 `set`으로 변환하고 정상적으로 작동합니다: -```Python hl_lines="31 37" -{!../../docs_src/response_model/tutorial006.py!} -``` +{* ../../docs_src/response_model/tutorial006.py hl[31,37] *} ## 요약 diff --git a/docs/ko/docs/tutorial/response-status-code.md b/docs/ko/docs/tutorial/response-status-code.md index 57eef6ba170b2..bcaf7843b9985 100644 --- a/docs/ko/docs/tutorial/response-status-code.md +++ b/docs/ko/docs/tutorial/response-status-code.md @@ -8,11 +8,9 @@ * `@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` 등)의 매개변수입니다. 모든 매개변수들과 본문처럼 *경로 작동 함수*가 아닙니다. @@ -20,7 +18,7 @@ `status_code` 매개변수는 HTTP 상태 코드를 숫자로 입력받습니다. -/// info | "정보" +/// info | 정보 `status_code` 는 파이썬의 `http.HTTPStatus` 와 같은 `IntEnum` 을 입력받을 수도 있습니다. @@ -33,7 +31,7 @@ -/// note | "참고" +/// note | 참고 어떤 응답 코드들은 해당 응답에 본문이 없다는 것을 의미하기도 합니다 (다음 항목 참고). @@ -43,7 +41,7 @@ ## HTTP 상태 코드에 대하여 -/// note | "참고" +/// note | 참고 만약 HTTP 상태 코드에 대하여 이미 알고있다면, 다음 항목으로 넘어가십시오. @@ -66,7 +64,7 @@ HTTP는 세자리의 숫자 상태 코드를 응답의 일부로 전송합니다 * 일반적인 클라이언트 오류의 경우 `400` 을 사용할 수 있습니다. * `5xx` 상태 코드는 서버 오류에 사용됩니다. 이것들을 직접 사용할 일은 거의 없습니다. 응용 프로그램 코드나 서버의 일부에서 문제가 발생하면 자동으로 이들 상태 코드 중 하나를 반환합니다. -/// tip | "팁" +/// tip | 팁 각각의 상태 코드와 이들이 의미하는 내용에 대해 더 알고싶다면 MDN HTTP 상태 코드에 관한 문서 를 확인하십시오. @@ -76,9 +74,7 @@ HTTP는 세자리의 숫자 상태 코드를 응답의 일부로 전송합니다 상기 예시 참고: -```Python hl_lines="6" -{!../../docs_src/response_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_status_code/tutorial001.py hl[6] *} `201` 은 "생성됨"를 의미하는 상태 코드입니다. @@ -86,15 +82,13 @@ HTTP는 세자리의 숫자 상태 코드를 응답의 일부로 전송합니다 `fastapi.status` 의 편의 변수를 사용할 수 있습니다. -```Python hl_lines="1 6" -{!../../docs_src/response_status_code/tutorial002.py!} -``` +{* ../../docs_src/response_status_code/tutorial002.py hl[1,6] *} 이것은 단순히 작업을 편리하게 하기 위한 것으로, HTTP 상태 코드와 동일한 번호를 갖고있지만, 이를 사용하면 편집기의 자동완성 기능을 사용할 수 있습니다: -/// note | "기술적 세부사항" +/// note | 기술적 세부사항 `from starlette import status` 역시 사용할 수 있습니다. diff --git a/docs/ko/docs/tutorial/schema-extra-example.md b/docs/ko/docs/tutorial/schema-extra-example.md index 71052b3348891..77e94db720620 100644 --- a/docs/ko/docs/tutorial/schema-extra-example.md +++ b/docs/ko/docs/tutorial/schema-extra-example.md @@ -8,35 +8,15 @@ 생성된 JSON 스키마에 추가될 Pydantic 모델을 위한 `examples`을 선언할 수 있습니다. -//// tab | Python 3.10+ Pydantic v2 - -```Python hl_lines="13-24" -{!> ../../docs_src/schema_extra_example/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.10+ Pydantic v1 - -```Python hl_lines="13-23" -{!> ../../docs_src/schema_extra_example/tutorial001_py310_pv1.py!} -``` - -//// - -//// tab | Python 3.8+ Pydantic v2 +//// tab | Pydantic v2 -```Python hl_lines="15-26" -{!> ../../docs_src/schema_extra_example/tutorial001.py!} -``` +{* ../../docs_src/schema_extra_example/tutorial001_py310.py hl[13:24] *} //// -//// tab | Python 3.8+ Pydantic v1 +//// tab | Pydantic v1 -```Python hl_lines="15-25" -{!> ../../docs_src/schema_extra_example/tutorial001_pv1.py!} -``` +{* ../../docs_src/schema_extra_example/tutorial001_pv1_py310.py hl[13:23] *} //// @@ -58,7 +38,7 @@ Pydantic v1에서 ../../docs_src/schema_extra_example/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4 10-13" -{!> ../../docs_src/schema_extra_example/tutorial002.py!} -``` - -//// +{* ../../docs_src/schema_extra_example/tutorial002_py310.py hl[2,8:11] *} ## JSON Schema에서의 `examples` - OpenAPI @@ -114,57 +80,7 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 여기, `Body()`에 예상되는 예제 데이터 하나를 포함한 `examples`를 넘겼습니다: -//// tab | Python 3.10+ - -```Python hl_lines="22-29" -{!> ../../docs_src/schema_extra_example/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="22-29" -{!> ../../docs_src/schema_extra_example/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="23-30" -{!> ../../docs_src/schema_extra_example/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ Annotated가 없는 경우 - -/// tip | "팁" - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="18-25" -{!> ../../docs_src/schema_extra_example/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ Annotated가 없는 경우 - -/// tip | "팁" - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="20-27" -{!> ../../docs_src/schema_extra_example/tutorial003.py!} -``` - -//// +{* ../../docs_src/schema_extra_example/tutorial003_an_py310.py hl[22:29] *} ### 문서 UI 예시 @@ -176,57 +92,7 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 물론 여러 `examples`를 넘길 수 있습니다: -//// tab | Python 3.10+ - -```Python hl_lines="23-38" -{!> ../../docs_src/schema_extra_example/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="23-38" -{!> ../../docs_src/schema_extra_example/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24-39" -{!> ../../docs_src/schema_extra_example/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ Annotated가 없는 경우 - -/// tip | "팁" - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="19-34" -{!> ../../docs_src/schema_extra_example/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ Annotated가 없는 경우 - -/// tip | "팁" - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="21-36" -{!> ../../docs_src/schema_extra_example/tutorial004.py!} -``` - -//// +{* ../../docs_src/schema_extra_example/tutorial004_an_py310.py hl[23:38] *} 이와 같이 하면 이 예제는 그 본문 데이터를 위한 내부 **JSON 스키마**의 일부가 될 것입니다. @@ -267,57 +133,7 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 이를 다음과 같이 사용할 수 있습니다: -//// tab | Python 3.10+ - -```Python hl_lines="23-49" -{!> ../../docs_src/schema_extra_example/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="23-49" -{!> ../../docs_src/schema_extra_example/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24-50" -{!> ../../docs_src/schema_extra_example/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ Annotated가 없는 경우 - -/// tip | "팁" - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="19-45" -{!> ../../docs_src/schema_extra_example/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.8+ Annotated가 없는 경우 - -/// tip | "팁" - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="21-47" -{!> ../../docs_src/schema_extra_example/tutorial005.py!} -``` - -//// +{* ../../docs_src/schema_extra_example/tutorial005_an_py310.py hl[23:49] *} ### 문서 UI에서의 OpenAPI 예시 @@ -327,7 +143,7 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 ## 기술적 세부 사항 -/// tip | "팁" +/// tip | 팁 이미 **FastAPI**의 **0.99.0 혹은 그 이상** 버전을 사용하고 있다면, 이 세부 사항을 **스킵**해도 상관 없을 것입니다. @@ -337,7 +153,7 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 /// -/// warning | "경고" +/// warning | 경고 표준 **JSON 스키마**와 **OpenAPI**에 대한 아주 기술적인 세부사항입니다. @@ -361,7 +177,7 @@ OpenAPI는 또한 `example`과 `examples` 필드를 명세서의 다른 부분 * `File()` * `Form()` -/// info | "정보" +/// info | 정보 이 예전 OpenAPI-특화 `examples` 매개변수는 이제 FastAPI `0.103.0`부터 `openapi_examples`입니다. @@ -377,7 +193,7 @@ OpenAPI는 또한 `example`과 `examples` 필드를 명세서의 다른 부분 JSON 스키마의 새로운 `examples` 필드는 예제 속 **단순한 `list`**이며, (위에서 상술한 것처럼) OpenAPI의 다른 곳에 존재하는 dict으로 된 추가적인 메타데이터가 아닙니다. -/// info | "정보" +/// info | 정보 더 쉽고 새로운 JSON 스키마와의 통합과 함께 OpenAPI 3.1.0가 배포되었지만, 잠시동안 자동 문서 생성을 제공하는 도구인 Swagger UI는 OpenAPI 3.1.0을 지원하지 않았습니다 (5.0.0 버전부터 지원합니다 🎉). diff --git a/docs/ko/docs/tutorial/security/get-current-user.md b/docs/ko/docs/tutorial/security/get-current-user.md index 56f5792a74d7b..98ef3885e4d8c 100644 --- a/docs/ko/docs/tutorial/security/get-current-user.md +++ b/docs/ko/docs/tutorial/security/get-current-user.md @@ -2,9 +2,7 @@ 이전 장에서 (의존성 주입 시스템을 기반으로 한)보안 시스템은 *경로 작동 함수*에서 `str`로 `token`을 제공했습니다: -```Python hl_lines="10" -{!../../docs_src/security/tutorial001.py!} -``` +{* ../../docs_src/security/tutorial001.py hl[10] *} 그러나 아직도 유용하지 않습니다. @@ -16,21 +14,7 @@ Pydantic을 사용하여 본문을 선언하는 것과 같은 방식으로 다른 곳에서 사용할 수 있습니다. -//// tab | 파이썬 3.7 이상 - -```Python hl_lines="5 12-16" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// - -//// tab | 파이썬 3.10 이상 - -```Python hl_lines="3 10-14" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial002.py hl[5,12:16] *} ## `get_current_user` 의존성 생성하기 @@ -42,67 +26,25 @@ Pydantic을 사용하여 본문을 선언하는 것과 같은 방식으로 다 이전에 *경로 작동*에서 직접 수행했던 것과 동일하게 새 종속성 `get_current_user`는 하위 종속성 `oauth2_scheme`에서 `str`로 `token`을 수신합니다. -//// tab | 파이썬 3.7 이상 - -```Python hl_lines="25" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// - -//// tab | 파이썬 3.10 이상 - -```Python hl_lines="23" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial002.py hl[25] *} ## 유저 가져오기 `get_current_user`는 토큰을 `str`로 취하고 Pydantic `User` 모델을 반환하는 우리가 만든 (가짜) 유틸리티 함수를 사용합니다. -//// tab | 파이썬 3.7 이상 - -```Python hl_lines="19-22 26-27" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// - -//// tab | 파이썬 3.10 이상 - -```Python hl_lines="17-20 24-25" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial002.py hl[19:22,26:27] *} ## 현재 유저 주입하기 이제 *경로 작동*에서 `get_current_user`와 동일한 `Depends`를 사용할 수 있습니다. -//// tab | 파이썬 3.7 이상 - -```Python hl_lines="31" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// - -//// tab | 파이썬 3.10 이상 - -```Python hl_lines="29" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial002.py hl[31] *} Pydantic 모델인 `User`로 `current_user`의 타입을 선언하는 것을 알아야 합니다. 이것은 모든 완료 및 타입 검사를 통해 함수 내부에서 우리를 도울 것입니다. -/// tip | "팁" +/// tip | 팁 요청 본문도 Pydantic 모델로 선언된다는 것을 기억할 것입니다. @@ -110,7 +52,7 @@ Pydantic 모델인 `User`로 `current_user`의 타입을 선언하는 것을 알 /// -/// check | "확인" +/// check | 확인 이 의존성 시스템이 설계된 방식은 모두 `User` 모델을 반환하는 다양한 의존성(다른 "의존적인")을 가질 수 있도록 합니다. @@ -150,21 +92,7 @@ Pydantic 모델인 `User`로 `current_user`의 타입을 선언하는 것을 알 그리고 이 수천 개의 *경로 작동*은 모두 3줄 정도로 줄일 수 있습니다. -//// tab | 파이썬 3.7 이상 - -```Python hl_lines="30-32" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// - -//// tab | 파이썬 3.10 이상 - -```Python hl_lines="28-30" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial002.py hl[30:32] *} ## 요약 diff --git a/docs/ko/docs/tutorial/security/simple-oauth2.md b/docs/ko/docs/tutorial/security/simple-oauth2.md index fd18c1d479bc1..ddc7430af80d7 100644 --- a/docs/ko/docs/tutorial/security/simple-oauth2.md +++ b/docs/ko/docs/tutorial/security/simple-oauth2.md @@ -52,21 +52,7 @@ OAuth2의 경우 문자열일 뿐입니다. 먼저 `OAuth2PasswordRequestForm`을 가져와 `/token`에 대한 *경로 작동*에서 `Depends`의 의존성으로 사용합니다. -//// tab | 파이썬 3.7 이상 - -```Python hl_lines="4 76" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// - -//// tab | 파이썬 3.10 이상 - -```Python hl_lines="2 74" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial003.py hl[4,76] *} `OAuth2PasswordRequestForm`은 다음을 사용하여 폼 본문을 선언하는 클래스 의존성입니다: @@ -114,21 +100,7 @@ OAuth2 사양은 실제로 `password`라는 고정 값이 있는 `grant_type` 오류의 경우 `HTTPException` 예외를 사용합니다: -//// tab | 파이썬 3.7 이상 - -```Python hl_lines="3 77-79" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// - -//// tab | 파이썬 3.10 이상 - -```Python hl_lines="1 75-77" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial003.py hl[3,77:79] *} ### 패스워드 확인하기 @@ -156,19 +128,11 @@ OAuth2 사양은 실제로 `password`라는 고정 값이 있는 `grant_type` //// tab | P파이썬 3.7 이상 -```Python hl_lines="80-83" -{!> ../../docs_src/security/tutorial003.py!} -``` +{* ../../docs_src/security/tutorial003.py hl[80:83] *} //// -//// tab | 파이썬 3.10 이상 - -```Python hl_lines="78-81" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial003_py310.py hl[78:81] *} #### `**user_dict`에 대해 @@ -210,21 +174,7 @@ UserInDB( /// -//// tab | 파이썬 3.7 이상 - -```Python hl_lines="85" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// - -//// tab | 파이썬 3.10 이상 - -```Python hl_lines="83" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial003.py hl[85] *} /// 팁 @@ -250,21 +200,7 @@ UserInDB( 따라서 엔드포인트에서는 사용자가 존재하고 올바르게 인증되었으며 활성 상태인 경우에만 사용자를 얻습니다: -//// tab | 파이썬 3.7 이상 - -```Python hl_lines="58-66 69-72 90" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// - -//// tab | 파이썬 3.10 이상 - -```Python hl_lines="55-64 67-70 88" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial003.py hl[58:66,69:72,90] *} /// 정보 diff --git a/docs/ko/docs/tutorial/static-files.md b/docs/ko/docs/tutorial/static-files.md index 90a60d1939d6b..9db5e1c67ec57 100644 --- a/docs/ko/docs/tutorial/static-files.md +++ b/docs/ko/docs/tutorial/static-files.md @@ -7,11 +7,9 @@ * `StaticFiles` 임포트합니다. * 특정 경로에 `StaticFiles()` 인스턴스를 "마운트" 합니다. -```Python hl_lines="2 6" -{!../../docs_src/static_files/tutorial001.py!} -``` +{* ../../docs_src/static_files/tutorial001.py hl[2,6] *} -/// note | "기술적 세부사항" +/// note | 기술적 세부사항 `from starlette.staticfiles import StaticFiles` 를 사용할 수도 있습니다. diff --git a/docs/nl/docs/python-types.md b/docs/nl/docs/python-types.md index 00052037cc6ae..fb8b1e5fd8b19 100644 --- a/docs/nl/docs/python-types.md +++ b/docs/nl/docs/python-types.md @@ -22,9 +22,8 @@ Als je een Python expert bent en alles al weet over type hints, sla dan dit hoof Laten we beginnen met een eenvoudig voorbeeld: -```Python -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py *} + Het aanroepen van dit programma leidt tot het volgende resultaat: @@ -39,9 +38,8 @@ De functie voert het volgende uit: `` * Voeg samen met een spatie in het midden. -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py hl[2] *} + ### Bewerk het @@ -83,9 +81,8 @@ Dat is alles. Dat zijn de "type hints": -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial002.py!} -``` +{* ../../docs_src/python_types/tutorial002.py hl[1] *} + Dit is niet hetzelfde als het declareren van standaardwaarden zoals bij: @@ -113,9 +110,8 @@ Nu kun je de opties bekijken en er doorheen scrollen totdat je de optie vindt di Bekijk deze functie, deze heeft al type hints: -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial003.py!} -``` +{* ../../docs_src/python_types/tutorial003.py hl[1] *} + Omdat de editor de types van de variabelen kent, krijgt u niet alleen aanvulling, maar ook controles op fouten: @@ -123,9 +119,8 @@ Omdat de editor de types van de variabelen kent, krijgt u niet alleen aanvulling Nu weet je hoe je het moet oplossen, converteer `age` naar een string met `str(age)`: -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial004.py!} -``` +{* ../../docs_src/python_types/tutorial004.py hl[2] *} + ## Types declareren @@ -144,9 +139,8 @@ Je kunt bijvoorbeeld het volgende gebruiken: * `bool` * `bytes` -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial005.py!} -``` +{* ../../docs_src/python_types/tutorial005.py hl[1] *} + ### Generieke types met typeparameters @@ -370,9 +364,8 @@ Het gaat alleen om de woorden en naamgeving. Maar die naamgeving kan invloed heb Laten we als voorbeeld deze functie nemen: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial009c.py!} -``` +{* ../../docs_src/python_types/tutorial009c.py hl[1,4] *} + De parameter `name` is gedefinieerd als `Optional[str]`, maar is **niet optioneel**, je kunt de functie niet aanroepen zonder de parameter: @@ -388,9 +381,8 @@ say_hi(name=None) # Dit werkt, None is geldig 🎉 Het goede nieuws is dat als je eenmaal Python 3.10 gebruikt, je je daar geen zorgen meer over hoeft te maken, omdat je dan gewoon `|` kunt gebruiken om unions van types te definiëren: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial009c_py310.py!} -``` +{* ../../docs_src/python_types/tutorial009c_py310.py hl[1,4] *} + Dan hoef je je geen zorgen te maken over namen als `Optional` en `Union`. 😎 @@ -452,15 +444,13 @@ Je kunt een klasse ook declareren als het type van een variabele. Stel dat je een klasse `Person` hebt, met een naam: -```Python hl_lines="1-3" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[1:3] *} + Vervolgens kun je een variabele van het type `Persoon` declareren: -```Python hl_lines="6" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[6] *} + Dan krijg je ook nog eens volledige editorondersteuning: diff --git a/docs/pl/docs/help-fastapi.md b/docs/pl/docs/help-fastapi.md index 4daad5e903c90..3ea328dc2cbbd 100644 --- a/docs/pl/docs/help-fastapi.md +++ b/docs/pl/docs/help-fastapi.md @@ -229,7 +229,7 @@ Jeśli możesz mi w tym pomóc, **pomożesz mi utrzymać FastAPI** i zapewnisz Dołącz do 👥 serwera czatu na Discordzie 👥 i spędzaj czas z innymi w społeczności FastAPI. -/// tip | "Wskazówka" +/// tip | Wskazówka Jeśli masz pytania, zadaj je w Dyskusjach na GitHubie, jest dużo większa szansa, że otrzymasz pomoc od [Ekspertów FastAPI](fastapi-people.md#fastapi-experts){.internal-link target=_blank}. diff --git a/docs/pl/docs/tutorial/first-steps.md b/docs/pl/docs/tutorial/first-steps.md index 9466ca84d1bed..8fa4c75ad91d7 100644 --- a/docs/pl/docs/tutorial/first-steps.md +++ b/docs/pl/docs/tutorial/first-steps.md @@ -135,7 +135,7 @@ Możesz go również użyć do automatycznego generowania kodu dla klientów, kt `FastAPI` jest klasą, która zapewnia wszystkie funkcjonalności Twojego API. -/// note | "Szczegóły techniczne" +/// note | Szczegóły techniczne `FastAPI` jest klasą, która dziedziczy bezpośrednio z `Starlette`. @@ -249,7 +249,7 @@ Będziemy je również nazywali "**operacjami**". * ścieżki `/` * używając operacji get -/// info | "`@decorator` Info" +/// info | `@decorator` Info Składnia `@something` jest w Pythonie nazywana "dekoratorem". diff --git a/docs/pt/docs/advanced/additional-responses.md b/docs/pt/docs/advanced/additional-responses.md index 46cf1efc3ecea..1060d18afc17b 100644 --- a/docs/pt/docs/advanced/additional-responses.md +++ b/docs/pt/docs/advanced/additional-responses.md @@ -1,6 +1,6 @@ # Retornos Adicionais no OpenAPI -/// warning | "Aviso" +/// warning | Aviso Este é um tema bem avançado. @@ -26,17 +26,15 @@ 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" +/// note | Nota Lembre-se que você deve retornar o `JSONResponse` diretamente. /// -/// info | "Informação" +/// info | Informação A chave `model` não é parte do OpenAPI. @@ -177,17 +175,15 @@ 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 | 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`). @@ -207,9 +203,7 @@ Por exemplo, você pode declarar um retorno com o código de status `404` que ut E um retorno com o código de status `200` que utiliza o seu `response_model`, porém inclui um `example` customizado: -```Python hl_lines="20-31" -{!../../docs_src/additional_responses/tutorial003.py!} -``` +{* ../../docs_src/additional_responses/tutorial003.py hl[20:31] *} Isso será combinado e incluído em seu OpenAPI, e disponibilizado na documentação da sua API: @@ -243,9 +237,7 @@ Você pode utilizar essa técnica para reutilizar alguns retornos predefinidos n Por exemplo: -```Python hl_lines="13-17 26" -{!../../docs_src/additional_responses/tutorial004.py!} -``` +{* ../../docs_src/additional_responses/tutorial004.py hl[13:17,26] *} ## Mais informações sobre retornos OpenAPI diff --git a/docs/pt/docs/advanced/additional-status-codes.md b/docs/pt/docs/advanced/additional-status-codes.md index 02bb4c0154071..06d6191519654 100644 --- a/docs/pt/docs/advanced/additional-status-codes.md +++ b/docs/pt/docs/advanced/additional-status-codes.md @@ -14,59 +14,9 @@ Mas você também deseja aceitar novos itens. E quando os itens não existiam, e Para conseguir isso, importe `JSONResponse` e retorne o seu conteúdo diretamente, definindo o `status_code` que você deseja: -//// tab | Python 3.10+ +{* ../../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!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="4 25" -{!> ../../docs_src/additional_status_codes/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4 26" -{!> ../../docs_src/additional_status_codes/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | "Dica" - -Faça uso da versão `Annotated` quando possível. - -/// - -```Python hl_lines="2 23" -{!> ../../docs_src/additional_status_codes/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | "Dica" - -Faça uso da versão `Annotated` quando possível. - -/// - -```Python hl_lines="4 25" -{!> ../../docs_src/additional_status_codes/tutorial001.py!} -``` - -//// - -/// warning | "Aviso" +/// warning | Aviso Quando você retorna um `Response` diretamente, como no exemplo acima, ele será retornado diretamente. @@ -76,7 +26,7 @@ Garanta que ele tenha toda informação que você deseja, e que os valores sejam /// -/// note | "Detalhes técnicos" +/// note | Detalhes técnicos Você também pode utilizar `from starlette.responses import JSONResponse`. diff --git a/docs/pt/docs/advanced/advanced-dependencies.md b/docs/pt/docs/advanced/advanced-dependencies.md index a656390a466f9..f57abba61859c 100644 --- a/docs/pt/docs/advanced/advanced-dependencies.md +++ b/docs/pt/docs/advanced/advanced-dependencies.md @@ -18,35 +18,7 @@ Não propriamente a classe (que já é um chamável), mas a instância desta cla Para fazer isso, nós declaramos o método `__call__`: -//// tab | Python 3.9+ - -```Python hl_lines="12" -{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/dependencies/tutorial011_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | "Dica" - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/dependencies/tutorial011.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[12] *} Neste caso, o `__call__` é o que o **FastAPI** utilizará para verificar parâmetros adicionais e sub dependências, e isso é o que será chamado para passar o valor ao parâmetro na sua *função de operação de rota* posteriormente. @@ -54,35 +26,7 @@ Neste caso, o `__call__` é o que o **FastAPI** utilizará para verificar parâm E agora, nós podemos utilizar o `__init__` para declarar os parâmetros da instância que podemos utilizar para "parametrizar" a dependência: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/dependencies/tutorial011_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | "Dica" - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/dependencies/tutorial011.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[9] *} Neste caso, o **FastAPI** nunca tocará ou se importará com o `__init__`, nós vamos utilizar diretamente em nosso código. @@ -90,35 +34,7 @@ Neste caso, o **FastAPI** nunca tocará ou se importará com o `__init__`, nós Nós poderíamos criar uma instância desta classe com: -//// tab | Python 3.9+ - -```Python hl_lines="18" -{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial011_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | "Dica" - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="16" -{!> ../../docs_src/dependencies/tutorial011.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[18] *} E deste modo nós podemos "parametrizar" a nossa dependência, que agora possui `"bar"` dentro dele, como o atributo `checker.fixed_content`. @@ -134,37 +50,9 @@ checker(q="somequery") ...e passar o que quer que isso retorne como valor da dependência em nossa *função de operação de rota* como o parâmetro `fixed_content_included`: -//// tab | Python 3.9+ - -```Python hl_lines="22" -{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="21" -{!> ../../docs_src/dependencies/tutorial011_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | "Dica" - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="20" -{!> ../../docs_src/dependencies/tutorial011.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[22] *} -/// tip | "Dica" +/// tip | Dica Tudo isso parece não ser natural. E pode não estar muito claro ou aparentar ser útil ainda. diff --git a/docs/pt/docs/advanced/async-tests.md b/docs/pt/docs/advanced/async-tests.md index c81d6124be85f..a2b79426c6057 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,11 +56,9 @@ $ 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" +/// 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. @@ -72,9 +66,7 @@ Note que a função de teste é `async def` agora, no lugar de apenas `def` como Então podemos criar um `AsyncClient` com a aplicação, e enviar requisições assíncronas para ela utilizando `await`. -```Python hl_lines="9-12" -{!../../docs_src/async_tests/test_main.py!} -``` +{* ../../docs_src/async_tests/test_main.py hl[9:12] *} Isso é equivalente a: @@ -84,13 +76,13 @@ response = client.get('/') ...que nós utilizamos para fazer as nossas requisições utilizando o `TestClient`. -/// tip | "Dica" +/// tip | Dica Note que nós estamos utilizando async/await com o novo `AsyncClient` - a requisição é assíncrona. /// -/// warning | "Aviso" +/// warning | Aviso Se a sua aplicação depende dos eventos de vida útil (*lifespan*), o `AsyncClient` não acionará estes eventos. Para garantir que eles são acionados, utilize o `LifespanManager` do florimondmanca/asgi-lifespan. @@ -100,7 +92,7 @@ Se a sua aplicação depende dos eventos de vida útil (*lifespan*), o `AsyncCli Como a função de teste agora é assíncrona, você pode chamar (e `esperar`) outras funções `async` além de enviar requisições para a sua aplicação FastAPI em seus testes, exatamente como você as chamaria em qualquer outro lugar do seu código. -/// tip | "Dica" +/// tip | Dica Se você se deparar com um `RuntimeError: Task attached to a different loop` ao integrar funções assíncronas em seus testes (e.g. ao utilizar o MotorClient do MongoDB) Lembre-se de instanciar objetos que precisam de um loop de eventos (*event loop*) apenas em funções assíncronas, e.g. um *"callback"* `'@app.on_event("startup")`. diff --git a/docs/pt/docs/advanced/behind-a-proxy.md b/docs/pt/docs/advanced/behind-a-proxy.md index 12fd83f3d9ecf..6837c95426e1c 100644 --- a/docs/pt/docs/advanced/behind-a-proxy.md +++ b/docs/pt/docs/advanced/behind-a-proxy.md @@ -41,7 +41,7 @@ browser --> proxy proxy --> server ``` -/// tip | "Dica" +/// tip | Dica O IP `0.0.0.0` é comumente usado para significar que o programa escuta em todos os IPs disponíveis naquela máquina/servidor. @@ -82,7 +82,7 @@ $ fastapi run main.py --root-path /api/v1 Se você usar Hypercorn, ele também tem a opção `--root-path`. -/// note | "Detalhes Técnicos" +/// note | Detalhes Técnicos A especificação ASGI define um `root_path` para esse caso de uso. @@ -172,7 +172,7 @@ Então, crie um arquivo `traefik.toml` com: Isso diz ao Traefik para escutar na porta 9999 e usar outro arquivo `routes.toml`. -/// tip | "Dica" +/// tip | Dica Estamos usando a porta 9999 em vez da porta padrão HTTP 80 para que você não precise executá-lo com privilégios de administrador (`sudo`). @@ -242,7 +242,7 @@ Agora, se você for ao URL com a porta para o Uvicorn: -/// tip | "Dica" +/// tip | Dica A interface de documentação interagirá com o servidor que você selecionar. diff --git a/docs/pt/docs/advanced/custom-response.md b/docs/pt/docs/advanced/custom-response.md new file mode 100644 index 0000000000000..a0bcc2b978428 --- /dev/null +++ b/docs/pt/docs/advanced/custom-response.md @@ -0,0 +1,314 @@ +# Resposta Personalizada - HTML, Stream, File e outras + +Por padrão, o **FastAPI** irá retornar respostas utilizando `JSONResponse`. + +Mas você pode sobrescrever esse comportamento utilizando `Response` diretamente, como visto em [Retornando uma Resposta Diretamente](response-directly.md){.internal-link target=_blank}. + +Mas se você retornar uma `Response` diretamente (ou qualquer subclasse, como `JSONResponse`), os dados não serão convertidos automaticamente (mesmo que você declare um `response_model`), e a documentação não será gerada automaticamente (por exemplo, incluindo o "media type", no cabeçalho HTTP `Content-Type` como parte do esquema OpenAPI gerado). + +Mas você também pode declarar a `Response` que você deseja utilizar (e.g. qualquer subclasse de `Response`), em um *decorador de operação de rota* utilizando o parâmetro `response_class`. + +Os conteúdos que você retorna em sua *função de operador de rota* serão colocados dentro dessa `Response`. + +E se a `Response` tiver um media type JSON (`application/json`), como é o caso com `JSONResponse` e `UJSONResponse`, os dados que você retornar serão automaticamente convertidos (e filtrados) com qualquer `response_model` do Pydantic que for declarado em sua *função de operador de rota*. + +/// note | Nota + +Se você utilizar uma classe de Resposta sem media type, o FastAPI esperará que sua resposta não tenha conteúdo, então ele não irá documentar o formato da resposta na documentação OpenAPI gerada. + +/// + +## Utilizando `ORJSONResponse` + +Por exemplo, se você precisa bastante de performance, você pode instalar e utilizar o `orjson` e definir a resposta para ser uma `ORJSONResponse`. + +Importe a classe, ou subclasse, de `Response` que você deseja utilizar e declare ela no *decorador de operação de rota*. + +Para respostas grandes, retornar uma `Response` diretamente é muito mais rápido que retornar um dicionário. + +Isso ocorre por que, por padrão, o FastAPI irá verificar cada item dentro do dicionário e garantir que ele seja serializável para JSON, utilizando o mesmo[Codificador Compatível com JSON](../tutorial/encoder.md){.internal-link target=_blank} explicado no tutorial. Isso permite que você retorne **objetos abstratos**, como modelos do banco de dados, por exemplo. + +Mas se você tem certeza que o conteúdo que você está retornando é **serializável com JSON**, você pode passá-lo diretamente para a classe de resposta e evitar o trabalho extra que o FastAPI teria ao passar o conteúdo pelo `jsonable_encoder` antes de passar para a classe de resposta. + +{* ../../docs_src/custom_response/tutorial001b.py hl[2,7] *} + +/// info | Informação + +O parâmetro `response_class` também será usado para definir o "media type" da resposta. + +Neste caso, o cabeçalho HTTP `Content-Type` irá ser definido como `application/json`. + +E será documentado como tal no OpenAPI. + +/// + +/// tip | Dica + +A `ORJSONResponse` está disponível apenas no FastAPI, e não no Starlette. + +/// + +## Resposta HTML + +Para retornar uma resposta com HTML diretamente do **FastAPI**, utilize `HTMLResponse`. + +* Importe `HTMLResponse` +* Passe `HTMLResponse` como o parâmetro de `response_class` do seu *decorador de operação de rota*. + +{* ../../docs_src/custom_response/tutorial002.py hl[2,7] *} + +/// info | Informação + +O parâmetro `response_class` também será usado para definir o "media type" da resposta. + +Neste caso, o cabeçalho HTTP `Content-Type` será definido como `text/html`. + +E será documentado como tal no OpenAPI. + +/// + +### Retornando uma `Response` + +Como visto em [Retornando uma Resposta Diretamente](response-directly.md){.internal-link target=_blank}, você também pode sobrescrever a resposta diretamente na sua *operação de rota*, ao retornar ela. + +O mesmo exemplo de antes, retornando uma `HTMLResponse`, poderia parecer com: + +{* ../../docs_src/custom_response/tutorial003.py hl[2,7,19] *} + +/// warning | Aviso + +Uma `Response` retornada diretamente em sua *função de operação de rota* não será documentada no OpenAPI (por exemplo, o `Content-Type` não será documentado) e não será visível na documentação interativa automática. + +/// + +/// info | Informação + +Obviamente, o cabeçalho `Content-Type`, o código de status, etc, virão do objeto `Response` que você retornou. + +/// + +### Documentar no OpenAPI e sobrescrever `Response` + +Se você deseja sobrescrever a resposta dentro de uma função, mas ao mesmo tempo documentar o "media type" no OpenAPI, você pode utilizar o parâmetro `response_class` E retornar um objeto `Response`. + +A `response_class` será usada apenas para documentar o OpenAPI da *operação de rota*, mas sua `Response` será usada como foi definida. + +##### Retornando uma `HTMLResponse` diretamente + +Por exemplo, poderia ser algo como: + +{* ../../docs_src/custom_response/tutorial004.py hl[7,21,23] *} + +Neste exemplo, a função `generate_html_response()` já cria e retorna uma `Response` em vez de retornar o HTML em uma `str`. + +Ao retornar o resultado chamando `generate_html_response()`, você já está retornando uma `Response` que irá sobrescrever o comportamento padrão do **FastAPI**. + +Mas se você passasse uma `HTMLResponse` em `response_class` também, o **FastAPI** saberia como documentar isso no OpenAPI e na documentação interativa como um HTML com `text/html`: + + + +## Respostas disponíveis + +Aqui estão algumas dos tipos de resposta disponíveis. + +Lembre-se que você pode utilizar `Response` para retornar qualquer outra coisa, ou até mesmo criar uma subclasse personalizada. + +/// note | Detalhes Técnicos + +Você também pode utilizar `from starlette.responses import HTMLResponse`. + +O **FastAPI** provê a mesma `starlette.responses` como `fastapi.responses` apenas como uma facilidade para você, desenvolvedor. Mas a maioria das respostas disponíveis vêm diretamente do Starlette. + +/// + +### `Response` + +A classe principal de respostas, todas as outras respostas herdam dela. + +Você pode retorná-la diretamente. + +Ela aceita os seguintes parâmetros: + +* `content` - Uma sequência de caracteres (`str`) ou `bytes`. +* `status_code` - Um código de status HTTP do tipo `int`. +* `headers` - Um dicionário `dict` de strings. +* `media_type` - Uma `str` informando o media type. E.g. `"text/html"`. + +O FastAPI (Starlette, na verdade) irá incluir o cabeçalho Content-Length automaticamente. Ele também irá incluir o cabeçalho Content-Type, baseado no `media_type` e acrescentando uma codificação para tipos textuais. + +{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *} + +### `HTMLResponse` + +Usa algum texto ou sequência de bytes e retorna uma resposta HTML. Como você leu acima. + +### `PlainTextResponse` + +Usa algum texto ou sequência de bytes para retornar uma resposta de texto não formatado. + +{* ../../docs_src/custom_response/tutorial005.py hl[2,7,9] *} + +### `JSONResponse` + +Pega alguns dados e retorna uma resposta com codificação `application/json`. + +É a resposta padrão utilizada no **FastAPI**, como você leu acima. + +### `ORJSONResponse` + +Uma alternativa mais rápida de resposta JSON utilizando o `orjson`, como você leu acima. + +/// info | Informação + +Essa resposta requer a instalação do pacote `orjson`, com o comando `pip install orjson`, por exemplo. + +/// + +### `UJSONResponse` + +Uma alternativa de resposta JSON utilizando a biblioteca `ujson`. + +/// info | Informação + +Essa resposta requer a instalação do pacote `ujson`, com o comando `pip install ujson`, por exemplo. + +/// + +/// warning | Aviso + +`ujson` é menos cauteloso que a implementação nativa do Python na forma que os casos especiais são tratados + +/// + +{* ../../docs_src/custom_response/tutorial001.py hl[2,7] *} + +/// tip | Dica + +É possível que `ORJSONResponse` seja uma alternativa mais rápida. + +/// + +### `RedirectResponse` + +Retorna um redirecionamento HTTP. Utiliza o código de status 307 (Redirecionamento Temporário) por padrão. + +Você pode retornar uma `RedirectResponse` diretamente: + +{* ../../docs_src/custom_response/tutorial006.py hl[2,9] *} + +--- + +Ou você pode utilizá-la no parâmetro `response_class`: + +{* ../../docs_src/custom_response/tutorial006b.py hl[2,7,9] *} + +Se você fizer isso, então você pode retornar a URL diretamente da sua *função de operação de rota* + +Neste caso, o `status_code` utilizada será o padrão de `RedirectResponse`, que é `307`. + +--- + +Você também pode utilizar o parâmetro `status_code` combinado com o parâmetro `response_class`: + +{* ../../docs_src/custom_response/tutorial006c.py hl[2,7,9] *} + +### `StreamingResponse` + +Recebe uma gerador assíncrono ou um gerador/iterador comum e retorna o corpo da requisição continuamente (stream). + +{* ../../docs_src/custom_response/tutorial007.py hl[2,14] *} + +#### Utilizando `StreamingResponse` com objetos semelhantes a arquivos + +Se você tiver um objeto semelhante a um arquivo (e.g. o objeto retornado por `open()`), você pode criar uma função geradora para iterar sobre esse objeto. + +Dessa forma, você não precisa ler todo o arquivo na memória primeiro, e você pode passar essa função geradora para `StreamingResponse` e retorná-la. + +Isso inclui muitas bibliotecas que interagem com armazenamento em nuvem, processamento de vídeos, entre outras. + +```{ .python .annotate hl_lines="2 10-12 14" } +{!../../docs_src/custom_response/tutorial008.py!} +``` + +1. Essa é a função geradora. É definida como "função geradora" porque contém declarações `yield` nela. +2. Ao utilizar o bloco `with`, nós garantimos que o objeto semelhante a um arquivo é fechado após a função geradora ser finalizada. Isto é, após a resposta terminar de ser enivada. +3. Essa declaração `yield from` informa a função para iterar sobre essa coisa nomeada de `file_like`. E então, para cada parte iterada, fornece essa parte como se viesse dessa função geradora (`iterfile`). + + Então, é uma função geradora que transfere o trabalho de "geração" para alguma outra coisa interna. + + Fazendo dessa forma, podemos colocá-la em um bloco `with`, e assim garantir que o objeto semelhante a um arquivo é fechado quando a função termina. + +/// tip | Dica + +Perceba que aqui estamos utilizando o `open()` da biblioteca padrão que não suporta `async` e `await`, e declaramos a operação de rota com o `def` básico. + +/// + +### `FileResponse` + +Envia um arquivo de forma assíncrona e contínua (stream). +* +Recebe um conjunto de argumentos do construtor diferente dos outros tipos de resposta: + +* `path` - O caminho do arquivo que será transmitido +* `headers` - quaisquer cabeçalhos que serão incluídos, como um dicionário. +* `media_type` - Uma string com o media type. Se não for definida, o media type é inferido a partir do nome ou caminho do arquivo. +* `filename` - Se for definido, é incluído no cabeçalho `Content-Disposition`. + +Respostas de Arquivos incluem o tamanho do arquivo, data da última modificação e ETags apropriados, nos cabeçalhos `Content-Length`, `Last-Modified` e `ETag`, respectivamente. + +{* ../../docs_src/custom_response/tutorial009.py hl[2,10] *} + +Você também pode usar o parâmetro `response_class`: + +{* ../../docs_src/custom_response/tutorial009b.py hl[2,8,10] *} + +Nesse caso, você pode retornar o caminho do arquivo diretamente da sua *função de operação de rota*. + +## Classe de resposta personalizada + +Você pode criar sua própria classe de resposta, herdando de `Response` e usando essa nova classe. + +Por exemplo, vamos supor que você queira utilizar o `orjson`, mas com algumas configurações personalizadas que não estão incluídas na classe `ORJSONResponse`. + +Vamos supor também que você queira retornar um JSON indentado e formatado, então você quer utilizar a opção `orjson.OPT_INDENT_2` do orjson. + +Você poderia criar uma classe `CustomORJSONResponse`. A principal coisa a ser feita é sobrecarregar o método render da classe Response, `Response.render(content)`, que retorna o conteúdo em bytes, para retornar o conteúdo que você deseja: + +{* ../../docs_src/custom_response/tutorial009c.py hl[9:14,17] *} + +Agora em vez de retornar: + +```json +{"message": "Hello World"} +``` + +...essa resposta retornará: + +```json +{ + "message": "Hello World" +} +``` + +Obviamente, você provavelmente vai encontrar maneiras muito melhores de se aproveitar disso do que a formatação de JSON. 😉 + +## Classe de resposta padrão + +Quando você criar uma instância da classe **FastAPI** ou um `APIRouter` você pode especificar qual classe de resposta utilizar por padrão. + +O padrão que define isso é o `default_response_class`. + +No exemplo abaixo, o **FastAPI** irá utilizar `ORJSONResponse` por padrão, em todas as *operações de rota*, em vez de `JSONResponse`. + +{* ../../docs_src/custom_response/tutorial010.py hl[2,4] *} + +/// tip | Dica + +Você ainda pode substituir `response_class` em *operações de rota* como antes. + +/// + +## Documentação adicional + +Você também pode declarar o media type e muitos outros detalhes no OpenAPI utilizando `responses`: [Retornos Adicionais no OpenAPI](additional-responses.md){.internal-link target=_blank}. diff --git a/docs/pt/docs/advanced/dataclasses.md b/docs/pt/docs/advanced/dataclasses.md index af603ada7dea9..600c8c2682128 100644 --- a/docs/pt/docs/advanced/dataclasses.md +++ b/docs/pt/docs/advanced/dataclasses.md @@ -4,9 +4,7 @@ FastAPI é construído em cima do **Pydantic**, e eu tenho mostrado como usar mo Mas o FastAPI também suporta o uso de `dataclasses` da mesma forma: -```Python hl_lines="1 7-12 19-20" -{!../../docs_src/dataclasses/tutorial001.py!} -``` +{* ../../docs_src/dataclasses/tutorial001.py hl[1,7:12,19:20] *} Isso ainda é suportado graças ao **Pydantic**, pois ele tem suporte interno para `dataclasses`. @@ -34,9 +32,7 @@ Mas se você tem um monte de dataclasses por aí, este é um truque legal para u Você também pode usar `dataclasses` no parâmetro `response_model`: -```Python hl_lines="1 7-13 19" -{!../../docs_src/dataclasses/tutorial002.py!} -``` +{* ../../docs_src/dataclasses/tutorial002.py hl[1,7:13,19] *} A dataclass será automaticamente convertida para uma dataclass Pydantic. diff --git a/docs/pt/docs/advanced/events.md b/docs/pt/docs/advanced/events.md index 02f5b6d2b7d86..504b6db57b301 100644 --- a/docs/pt/docs/advanced/events.md +++ b/docs/pt/docs/advanced/events.md @@ -31,15 +31,13 @@ Vamos iniciar com um exemplo e ver isso detalhadamente. Nós criamos uma função assíncrona chamada `lifespan()` com `yield` como este: -```Python hl_lines="16 19" -{!../../docs_src/events/tutorial003.py!} -``` +{* ../../docs_src/events/tutorial003.py hl[16,19] *} Aqui nós estamos simulando a *inicialização* custosa do carregamento do modelo colocando a (falsa) função de modelo no dicionário com modelos de _machine learning_ antes do `yield`. Este código será executado **antes** da aplicação **começar a receber requisições**, durante a *inicialização*. E então, logo após o `yield`, descarregaremos o modelo. Esse código será executado **após** a aplicação **terminar de lidar com as requisições**, pouco antes do *encerramento*. Isso poderia, por exemplo, liberar recursos como memória ou GPU. -/// tip | "Dica" +/// tip | Dica O `shutdown` aconteceria quando você estivesse **encerrando** a aplicação. @@ -51,9 +49,7 @@ Talvez você precise inicializar uma nova versão, ou apenas cansou de executá- A primeira coisa a notar, é que estamos definindo uma função assíncrona com `yield`. Isso é muito semelhante à Dependências com `yield`. -```Python hl_lines="14-19" -{!../../docs_src/events/tutorial003.py!} -``` +{* ../../docs_src/events/tutorial003.py hl[14:19] *} A primeira parte da função, antes do `yield`, será executada **antes** da aplicação inicializar. @@ -65,9 +61,7 @@ Se você verificar, a função está decorada com um `@asynccontextmanager`. Que converte a função em algo chamado de "**Gerenciador de Contexto Assíncrono**". -```Python hl_lines="1 13" -{!../../docs_src/events/tutorial003.py!} -``` +{* ../../docs_src/events/tutorial003.py hl[1,13] *} Um **gerenciador de contexto** em Python é algo que você pode usar em uma declaração `with`, por exemplo, `open()` pode ser usado como um gerenciador de contexto: @@ -89,13 +83,11 @@ No nosso exemplo de código acima, nós não usamos ele diretamente, mas nós pa O parâmetro `lifespan` da aplicação `FastAPI` usa um **Gerenciador de Contexto Assíncrono**, então nós podemos passar nosso novo gerenciador de contexto assíncrono do `lifespan` para ele. -```Python hl_lines="22" -{!../../docs_src/events/tutorial003.py!} -``` +{* ../../docs_src/events/tutorial003.py hl[22] *} ## Eventos alternativos (deprecados) -/// warning | "Aviso" +/// warning | Aviso A maneira recomendada para lidar com a *inicialização* e o *encerramento* é usando o parâmetro `lifespan` da aplicação `FastAPI` como descrito acima. @@ -113,9 +105,7 @@ Essas funções podem ser declaradas com `async def` ou `def` normal. Para adicionar uma função que deve rodar antes da aplicação iniciar, declare-a com o evento `"startup"`: -```Python hl_lines="8" -{!../../docs_src/events/tutorial001.py!} -``` +{* ../../docs_src/events/tutorial001.py hl[8] *} Nesse caso, a função de manipulação de evento `startup` irá inicializar os itens do "banco de dados" (só um `dict`) com alguns valores. @@ -127,19 +117,17 @@ E sua aplicação não irá começar a receber requisições até que todos os m Para adicionar uma função que deve ser executada quando a aplicação estiver encerrando, declare ela com o evento `"shutdown"`: -```Python hl_lines="6" -{!../../docs_src/events/tutorial002.py!} -``` +{* ../../docs_src/events/tutorial002.py hl[6] *} Aqui, a função de manipulação de evento `shutdown` irá escrever uma linha de texto `"Application shutdown"` no arquivo `log.txt`. -/// info | "Informação" +/// info | Informação Na função `open()`, o `mode="a"` significa "acrescentar", então, a linha irá ser adicionada depois de qualquer coisa que esteja naquele arquivo, sem sobrescrever o conteúdo anterior. /// -/// tip | "Dica" +/// tip | Dica Perceba que nesse caso nós estamos usando a função padrão do Python `open()` que interage com um arquivo. @@ -165,7 +153,7 @@ Só um detalhe técnico para nerds curiosos. 🤓 Por baixo, na especificação técnica ASGI, essa é a parte do Protocolo Lifespan, e define eventos chamados `startup` e `shutdown`. -/// info | "Informação" +/// info | Informação Você pode ler mais sobre o manipulador `lifespan` do Starlette na Documentação do Lifespan Starlette. diff --git a/docs/pt/docs/advanced/index.md b/docs/pt/docs/advanced/index.md index 2569fc914b7ee..22ba2bf4a4614 100644 --- a/docs/pt/docs/advanced/index.md +++ b/docs/pt/docs/advanced/index.md @@ -6,7 +6,7 @@ O [Tutorial - Guia de Usuário](../tutorial/index.md){.internal-link target=_bla Na próxima seção você verá outras opções, configurações, e recursos adicionais. -/// tip | "Dica" +/// tip | Dica As próximas seções **não são necessáriamente "avançadas"** diff --git a/docs/pt/docs/advanced/middleware.md b/docs/pt/docs/advanced/middleware.md new file mode 100644 index 0000000000000..8167f7d27c9c6 --- /dev/null +++ b/docs/pt/docs/advanced/middleware.md @@ -0,0 +1,96 @@ +# Middleware Avançado + +No tutorial principal você leu como adicionar [Middleware Personalizado](../tutorial/middleware.md){.internal-link target=_blank} à sua aplicação. + +E então você também leu como lidar com [CORS com o `CORSMiddleware`](../tutorial/cors.md){.internal-link target=_blank}. + +Nesta seção, veremos como usar outros middlewares. + +## Adicionando middlewares ASGI + +Como o **FastAPI** é baseado no Starlette e implementa a especificação ASGI, você pode usar qualquer middleware ASGI. + +O middleware não precisa ser feito para o FastAPI ou Starlette para funcionar, desde que siga a especificação ASGI. + +No geral, os middlewares ASGI são classes que esperam receber um aplicativo ASGI como o primeiro argumento. + +Então, na documentação de middlewares ASGI de terceiros, eles provavelmente dirão para você fazer algo como: + +```Python +from unicorn import UnicornMiddleware + +app = SomeASGIApp() + +new_app = UnicornMiddleware(app, some_config="rainbow") +``` + +Mas, o FastAPI (na verdade, o Starlette) fornece uma maneira mais simples de fazer isso que garante que os middlewares internos lidem com erros do servidor e que os manipuladores de exceções personalizados funcionem corretamente. + +Para isso, você usa `app.add_middleware()` (como no exemplo para CORS). + +```Python +from fastapi import FastAPI +from unicorn import UnicornMiddleware + +app = FastAPI() + +app.add_middleware(UnicornMiddleware, some_config="rainbow") +``` + +`app.add_middleware()` recebe uma classe de middleware como o primeiro argumento e quaisquer argumentos adicionais a serem passados para o middleware. + +## Middlewares Integrados + +**FastAPI** inclui vários middlewares para casos de uso comuns, veremos a seguir como usá-los. + +/// note | Detalhes Técnicos + +Para o próximo exemplo, você também poderia usar `from starlette.middleware.something import SomethingMiddleware`. + +**FastAPI** fornece vários middlewares em `fastapi.middleware` apenas como uma conveniência para você, o desenvolvedor. Mas a maioria dos middlewares disponíveis vem diretamente do Starlette. + +/// + +## `HTTPSRedirectMiddleware` + +Garante que todas as requisições devem ser `https` ou `wss`. + +Qualquer requisição para `http` ou `ws` será redirecionada para o esquema seguro. + +{* ../../docs_src/advanced_middleware/tutorial001.py hl[2,6] *} + +## `TrustedHostMiddleware` + +Garante que todas as requisições recebidas tenham um cabeçalho `Host` corretamente configurado, a fim de proteger contra ataques de cabeçalho de host HTTP. + +{* ../../docs_src/advanced_middleware/tutorial002.py hl[2,6:8] *} + +Os seguintes argumentos são suportados: + +* `allowed_hosts` - Uma lista de nomes de domínio que são permitidos como nomes de host. Domínios com coringa, como `*.example.com`, são suportados para corresponder a subdomínios. Para permitir qualquer nome de host, use `allowed_hosts=["*"]` ou omita o middleware. + +Se uma requisição recebida não for validada corretamente, uma resposta `400` será enviada. + +## `GZipMiddleware` + +Gerencia respostas GZip para qualquer requisição que inclua `"gzip"` no cabeçalho `Accept-Encoding`. + +O middleware lidará com respostas padrão e de streaming. + +{* ../../docs_src/advanced_middleware/tutorial003.py hl[2,6] *} + +Os seguintes argumentos são suportados: + +* `minimum_size` - Não comprima respostas menores que este tamanho mínimo em bytes. O padrão é `500`. +* `compresslevel` - Usado durante a compressão GZip. É um inteiro variando de 1 a 9. O padrão é `9`. Um valor menor resulta em uma compressão mais rápida, mas em arquivos maiores, enquanto um valor maior resulta em uma compressão mais lenta, mas em arquivos menores. + +## Outros middlewares + +Há muitos outros middlewares ASGI. + +Por exemplo: + +* Uvicorn's `ProxyHeadersMiddleware` +* MessagePack + +Para checar outros middlewares disponíveis, confira Documentação de Middlewares do Starlette e a Lista Incrível do ASGI. diff --git a/docs/pt/docs/advanced/openapi-callbacks.md b/docs/pt/docs/advanced/openapi-callbacks.md new file mode 100644 index 0000000000000..b0659d3d6a850 --- /dev/null +++ b/docs/pt/docs/advanced/openapi-callbacks.md @@ -0,0 +1,186 @@ +# Callbacks na OpenAPI + +Você poderia criar uma API com uma *operação de rota* que poderia acionar uma solicitação a uma *API externa* criada por outra pessoa (provavelmente o mesmo desenvolvedor que estaria *usando* sua API). + +O processo que acontece quando seu aplicativo de API chama a *API externa* é chamado de "callback". Porque o software que o desenvolvedor externo escreveu envia uma solicitação para sua API e então sua API *chama de volta*, enviando uma solicitação para uma *API externa* (que provavelmente foi criada pelo mesmo desenvolvedor). + +Nesse caso, você poderia querer documentar como essa API externa *deveria* ser. Que *operação de rota* ela deveria ter, que corpo ela deveria esperar, que resposta ela deveria retornar, etc. + +## Um aplicativo com callbacks + +Vamos ver tudo isso com um exemplo. + +Imagine que você tem um aplicativo que permite criar faturas. + +Essas faturas terão um `id`, `title` (opcional), `customer` e `total`. + +O usuário da sua API (um desenvolvedor externo) criará uma fatura em sua API com uma solicitação POST. + +Então sua API irá (vamos imaginar): + +* Enviar uma solicitação de pagamento para o desenvolvedor externo. +* Coletar o dinheiro. +* Enviar a notificação de volta para o usuário da API (o desenvolvedor externo). +* Isso será feito enviando uma solicitação POST (de *sua API*) para alguma *API externa* fornecida por esse desenvolvedor externo (este é o "callback"). + +## O aplicativo **FastAPI** normal + +Vamos primeiro ver como o aplicativo da API normal se pareceria antes de adicionar o callback. + +Ele terá uma *operação de rota* que receberá um corpo `Invoice`, e um parâmetro de consulta `callback_url` que conterá a URL para o callback. + +Essa parte é bastante normal, a maior parte do código provavelmente já é familiar para você: + +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[9:13,36:53] *} + +/// tip | Dica + +O parâmetro de consulta `callback_url` usa um tipo Pydantic Url. + +/// + +A única coisa nova é o argumento `callbacks=invoices_callback_router.routes` no decorador da *operação de rota*. Veremos o que é isso a seguir. + +## Documentando o callback + +O código real do callback dependerá muito do seu próprio aplicativo de API. + +E provavelmente variará muito de um aplicativo para o outro. + +Poderia ser apenas uma ou duas linhas de código, como: + +```Python +callback_url = "https://example.com/api/v1/invoices/events/" +httpx.post(callback_url, json={"description": "Invoice paid", "paid": True}) +``` + +Mas possivelmente a parte mais importante do callback é garantir que o usuário da sua API (o desenvolvedor externo) implemente a *API externa* corretamente, de acordo com os dados que *sua API* vai enviar no corpo da solicitação do callback, etc. + +Então, o que faremos a seguir é adicionar o código para documentar como essa *API externa* deve ser para receber o callback de *sua API*. + +A documentação aparecerá na interface do Swagger em `/docs` em sua API, e permitirá que os desenvolvedores externos saibam como construir a *API externa*. + +Esse exemplo não implementa o callback em si (que poderia ser apenas uma linha de código), apenas a parte da documentação. + +/// tip | Dica + +O callback real é apenas uma solicitação HTTP. + +Quando implementando o callback por você mesmo, você pode usar algo como HTTPX ou Requisições. + +/// + +## Escrevendo o código de documentação do callback + +Esse código não será executado em seu aplicativo, nós só precisamos dele para *documentar* como essa *API externa* deveria ser. + +Mas, você já sabe como criar facilmente documentação automática para uma API com o **FastAPI**. + +Então vamos usar esse mesmo conhecimento para documentar como a *API externa* deveria ser... criando as *operações de rota* que a *API externa* deveria implementar (as que sua API irá chamar). + +/// tip | Dica + +Quando escrever o código para documentar um callback, pode ser útil imaginar que você é aquele *desenvolvedor externo*. E que você está atualmente implementando a *API externa*, não *sua API*. + +Adotar temporariamente esse ponto de vista (do *desenvolvedor externo*) pode ajudar a sentir que é mais óbvio onde colocar os parâmetros, o modelo Pydantic para o corpo, para a resposta, etc. para essa *API externa*. + +/// + +### Criar um `APIRouter` para o callback + +Primeiramente crie um novo `APIRouter` que conterá um ou mais callbacks. + +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[3,25] *} + +### Crie a *operação de rota* do callback + +Para criar a *operação de rota* do callback, use o mesmo `APIRouter` que você criou acima. + +Ele deve parecer exatamente como uma *operação de rota* normal do FastAPI: + +* Ele provavelmente deveria ter uma declaração do corpo que deveria receber, por exemplo. `body: InvoiceEvent`. +* E também deveria ter uma declaração de um código de status de resposta, por exemplo. `response_model=InvoiceEventReceived`. + +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[16:18,21:22,28:32] *} + +Há 2 diferenças principais de uma *operação de rota* normal: + +* Ela não necessita ter nenhum código real, porque seu aplicativo nunca chamará esse código. Ele é usado apenas para documentar a *API externa*. Então, a função poderia ter apenas `pass`. +* A *rota* pode conter uma expressão OpenAPI 3 (veja mais abaixo) onde pode usar variáveis com parâmetros e partes da solicitação original enviada para *sua API*. + +### A expressão do caminho do callback + +A *rota* do callback pode ter uma expressão OpenAPI 3 que pode conter partes da solicitação original enviada para *sua API*. + +Nesse caso, é a `str`: + +```Python +"{$callback_url}/invoices/{$request.body.id}" +``` + +Então, se o usuário da sua API (o desenvolvedor externo) enviar uma solicitação para *sua API* para: + +``` +https://yourapi.com/invoices/?callback_url=https://www.external.org/events +``` + +com um corpo JSON de: + +```JSON +{ + "id": "2expen51ve", + "customer": "Mr. Richie Rich", + "total": "9999" +} +``` + +então *sua API* processará a fatura e, em algum momento posterior, enviará uma solicitação de callback para o `callback_url` (a *API externa*): + +``` +https://www.external.org/events/invoices/2expen51ve +``` + +com um corpo JSON contendo algo como: + +```JSON +{ + "description": "Payment celebration", + "paid": true +} +``` + +e esperaria uma resposta daquela *API externa* com um corpo JSON como: + +```JSON +{ + "ok": true +} +``` + +/// tip | Dica + +Perceba como a URL de callback usada contém a URL recebida como um parâmetro de consulta em `callback_url` (`https://www.external.org/events`) e também o `id` da fatura de dentro do corpo JSON (`2expen51ve`). + +/// + +### Adicionar o roteador de callback + +Nesse ponto você tem a(s) *operação de rota de callback* necessária(s) (a(s) que o *desenvolvedor externo* deveria implementar na *API externa*) no roteador de callback que você criou acima. + +Agora use o parâmetro `callbacks` no decorador da *operação de rota de sua API* para passar o atributo `.routes` (que é na verdade apenas uma `list` de rotas/*operações de rota*) do roteador de callback que você criou acima: + +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[35] *} + +/// tip | Dica + +Perceba que você não está passando o roteador em si (`invoices_callback_router`) para `callback=`, mas o atributo `.routes`, como em `invoices_callback_router.routes`. + +/// + +### Verifique a documentação + +Agora você pode iniciar seu aplicativo e ir para http://127.0.0.1:8000/docs. + +Você verá sua documentação incluindo uma seção "Callbacks" para sua *operação de rota* que mostra como a *API externa* deveria ser: + + diff --git a/docs/pt/docs/advanced/openapi-webhooks.md b/docs/pt/docs/advanced/openapi-webhooks.md index 5a0226c74214f..f35922234f586 100644 --- a/docs/pt/docs/advanced/openapi-webhooks.md +++ b/docs/pt/docs/advanced/openapi-webhooks.md @@ -22,7 +22,7 @@ Com o **FastAPI**, utilizando o OpenAPI, você pode definir os nomes destes webh Isto pode facilitar bastante para os seus usuários **implementarem as APIs deles** para receber as requisições dos seus **webhooks**, eles podem inclusive ser capazes de gerar parte do código da API deles. -/// info | "Informação" +/// info | Informação Webhooks estão disponíveis a partir do OpenAPI 3.1.0, e possui suporte do FastAPI a partir da versão `0.99.0`. @@ -32,13 +32,11 @@ Webhooks estão disponíveis a partir do OpenAPI 3.1.0, e possui suporte do Fast Quando você cria uma aplicação com o **FastAPI**, existe um atributo chamado `webhooks`, que você utilizar para defini-los da mesma maneira que você definiria as suas **operações de rotas**, utilizando por exemplo `@app.webhooks.post()`. -```Python hl_lines="9-13 36-53" -{!../../docs_src/openapi_webhooks/tutorial001.py!} -``` +{* ../../docs_src/openapi_webhooks/tutorial001.py hl[9:13,36:53] *} Os webhooks que você define aparecerão no esquema do **OpenAPI** e na **página de documentação** gerada automaticamente. -/// info | "Informação" +/// info | Informação O objeto `app.webhooks` é na verdade apenas um `APIRouter`, o mesmo tipo que você utilizaria ao estruturar a sua aplicação com diversos arquivos. diff --git a/docs/pt/docs/advanced/path-operation-advanced-configuration.md b/docs/pt/docs/advanced/path-operation-advanced-configuration.md new file mode 100644 index 0000000000000..411d0f9a7ae83 --- /dev/null +++ b/docs/pt/docs/advanced/path-operation-advanced-configuration.md @@ -0,0 +1,204 @@ +# Configuração Avançada da Operação de Rota + +## operationId do OpenAPI + +/// warning | Aviso + +Se você não é um "especialista" no OpenAPI, você provavelmente não precisa disso. + +/// + +Você pode definir o `operationId` do OpenAPI que será utilizado na sua *operação de rota* com o parâmetro `operation_id`. + +Você precisa ter certeza que ele é único para cada operação. + +{* ../../docs_src/path_operation_advanced_configuration/tutorial001.py hl[6] *} + +### Utilizando o nome da *função de operação de rota* como o operationId + +Se você quiser utilizar o nome das funções da sua API como `operationId`s, você pode iterar sobre todos esses nomes e sobrescrever o `operationId` em cada *operação de rota* utilizando o `APIRoute.name` dela. + +Você deve fazer isso depois de adicionar todas as suas *operações de rota*. + +{* ../../docs_src/path_operation_advanced_configuration/tutorial002.py hl[2,12:21,24] *} + +/// tip | Dica + +Se você chamar `app.openapi()` manualmente, os `operationId`s devem ser atualizados antes dessa chamada. + +/// + +/// warning | Aviso + +Se você fizer isso, você tem que ter certeza de que cada uma das suas *funções de operação de rota* tem um nome único. + +Mesmo que elas estejam em módulos (arquivos Python) diferentes. + +/// + +## Excluir do OpenAPI + +Para excluir uma *operação de rota* do esquema OpenAPI gerado (e por consequência, dos sistemas de documentação automáticos), utilize o parâmetro `include_in_schema` e defina ele como `False`: + +{* ../../docs_src/path_operation_advanced_configuration/tutorial003.py hl[6] *} + +## Descrição avançada a partir de docstring + +Você pode limitar as linhas utilizadas a partir de uma docstring de uma *função de operação de rota* para o OpenAPI. + +Adicionar um `\f` (um caractere de escape para alimentação de formulário) faz com que o **FastAPI** restrinja a saída utilizada pelo OpenAPI até esse ponto. + +Ele não será mostrado na documentação, mas outras ferramentas (como o Sphinx) serão capazes de utilizar o resto do texto. + +{* ../../docs_src/path_operation_advanced_configuration/tutorial004.py hl[19:29] *} + +## Respostas Adicionais + +Você provavelmente já viu como declarar o `response_model` e `status_code` para uma *operação de rota*. + +Isso define os metadados sobre a resposta principal da *operação de rota*. + +Você também pode declarar respostas adicionais, com seus modelos, códigos de status, etc. + +Existe um capítulo inteiro da nossa documentação sobre isso, você pode ler em [Retornos Adicionais no OpenAPI](additional-responses.md){.internal-link target=_blank}. + +## Extras do OpenAPI + +Quando você declara uma *operação de rota* na sua aplicação, o **FastAPI** irá gerar os metadados relevantes da *operação de rota* automaticamente para serem incluídos no esquema do OpenAPI. + +/// note | Nota + +Na especificação do OpenAPI, isso é chamado de um Objeto de Operação. + +/// + +Ele possui toda a informação sobre a *operação de rota* e é usado para gerar a documentação automaticamente. + +Ele inclui os atributos `tags`, `parameters`, `requestBody`, `responses`, etc. + +Esse esquema específico para uma *operação de rota* normalmente é gerado automaticamente pelo **FastAPI**, mas você também pode estender ele. + +/// tip | Dica + +Esse é um ponto de extensão de baixo nível. + +Caso você só precise declarar respostas adicionais, uma forma conveniente de fazer isso é com [Retornos Adicionais no OpenAPI](additional-responses.md){.internal-link target=_blank}. + +/// + +Você pode estender o esquema do OpenAPI para uma *operação de rota* utilizando o parâmetro `openapi_extra`. + +### Extensões do OpenAPI + +Esse parâmetro `openapi_extra` pode ser útil, por exemplo, para declarar [Extensões do OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions): + +{* ../../docs_src/path_operation_advanced_configuration/tutorial005.py hl[6] *} + +Se você abrir os documentos criados automaticamente para a API, sua extensão aparecerá no final da *operação de rota* específica. + + + +E se você olhar o esquema OpenAPI resultante (na rota `/openapi.json` da sua API), você verá que a sua extensão também faz parte da *operação de rota* específica: + +```JSON hl_lines="22" +{ + "openapi": "3.1.0", + "info": { + "title": "FastAPI", + "version": "0.1.0" + }, + "paths": { + "/items/": { + "get": { + "summary": "Read Items", + "operationId": "read_items_items__get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + } + }, + "x-aperture-labs-portal": "blue" + } + } + } +} +``` + +### Esquema de *operação de rota* do OpenAPI personalizado + +O dicionário em `openapi_extra` vai ter todos os seus níveis mesclados dentro do esquema OpenAPI gerado automaticamente para a *operação de rota*. + +Então, você pode adicionar dados extras para o esquema gerado automaticamente. + +Por exemplo, você poderia optar por ler e validar a requisição com seu próprio código, sem utilizar funcionalidades automatizadas do FastAPI com o Pydantic, mas você ainda pode quere definir a requisição no esquema OpenAPI. + +Você pode fazer isso com `openapi_extra`: + +{* ../../docs_src/path_operation_advanced_configuration/tutorial006.py hl[19:36,39:40] *} + +Nesse exemplo, nós não declaramos nenhum modelo do Pydantic. Na verdade, o corpo da requisição não está nem mesmo analisado como JSON, ele é lido diretamente como `bytes` e a função `magic_data_reader()` seria a responsável por analisar ele de alguma forma. + +De toda forma, nós podemos declarar o esquema esperado para o corpo da requisição. + +### Tipo de conteúdo do OpenAPI personalizado + +Utilizando esse mesmo truque, você pode utilizar um modelo Pydantic para definir o esquema JSON que é então incluído na seção do esquema personalizado do OpenAPI na *operação de rota*. + +E você pode fazer isso até mesmo quando os dados da requisição não seguem o formato JSON. + +Por exemplo, nesta aplicação nós não usamos a funcionalidade integrada ao FastAPI de extrair o esquema JSON dos modelos Pydantic nem a validação automática do JSON. Na verdade, estamos declarando o tipo do conteúdo da requisição como YAML, em vez de JSON: + +//// tab | Pydantic v2 + +{* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[17:22,24] *} + +//// + +//// tab | Pydantic v1 + +{* ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py hl[17:22,24] *} + +//// + +/// info | Informação + +Na versão 1 do Pydantic, o método para obter o esquema JSON de um modelo é `Item.schema()`, na versão 2 do Pydantic, o método é `Item.model_json_schema()` + +/// + +Entretanto, mesmo que não utilizemos a funcionalidade integrada por padrão, ainda estamos usando um modelo Pydantic para gerar um esquema JSON manualmente para os dados que queremos receber no formato YAML. + +Então utilizamos a requisição diretamente, e extraímos o corpo como `bytes`. Isso significa que o FastAPI não vai sequer tentar analisar o corpo da requisição como JSON. + +E então no nosso código, nós analisamos o conteúdo YAML diretamente, e estamos utilizando o mesmo modelo Pydantic para validar o conteúdo YAML: + +//// tab | Pydantic v2 + +{* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[26:33] *} + +//// + +//// tab | Pydantic v1 + +{* ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py hl[26:33] *} + +//// + +/// info | Informação + +Na versão 1 do Pydantic, o método para analisar e validar um objeto era `Item.parse_obj()`, na versão 2 do Pydantic, o método é chamado de `Item.model_validate()`. + +/// + +///tip | Dica + +Aqui reutilizamos o mesmo modelo do Pydantic. + +Mas da mesma forma, nós poderíamos ter validado de alguma outra forma. + +/// diff --git a/docs/pt/docs/advanced/response-change-status-code.md b/docs/pt/docs/advanced/response-change-status-code.md index 2ac5eca185616..358c12d549e5f 100644 --- a/docs/pt/docs/advanced/response-change-status-code.md +++ b/docs/pt/docs/advanced/response-change-status-code.md @@ -20,9 +20,7 @@ Você pode declarar um parâmetro do tipo `Response` em sua *função de operaç E então você pode definir o `status_code` neste objeto de retorno temporal. -```Python hl_lines="1 9 12" -{!../../docs_src/response_change_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_change_status_code/tutorial001.py hl[1,9,12] *} E então você pode retornar qualquer objeto que você precise, como você faria normalmente (um `dict`, um modelo de banco de dados, etc.). diff --git a/docs/pt/docs/advanced/response-cookies.md b/docs/pt/docs/advanced/response-cookies.md index d0821b5b2061e..eed69f2222351 100644 --- a/docs/pt/docs/advanced/response-cookies.md +++ b/docs/pt/docs/advanced/response-cookies.md @@ -6,9 +6,7 @@ Você pode declarar um parâmetro do tipo `Response` na sua *função de operaç E então você pode definir cookies nesse objeto de resposta *temporário*. -```Python hl_lines="1 8-9" -{!../../docs_src/response_cookies/tutorial002.py!} -``` +{* ../../docs_src/response_cookies/tutorial002.py hl[1,8:9] *} Em seguida, você pode retornar qualquer objeto que precise, como normalmente faria (um `dict`, um modelo de banco de dados, etc). @@ -26,9 +24,7 @@ Para fazer isso, você pode criar uma resposta como descrito em [Retornando uma Então, defina os cookies nela e a retorne: -```Python hl_lines="10-12" -{!../../docs_src/response_cookies/tutorial001.py!} -``` +{* ../../docs_src/response_cookies/tutorial001.py hl[10:12] *} /// tip | Dica @@ -42,7 +38,7 @@ E também que você não esteja enviando nenhum dado que deveria ter sido filtra ### Mais informações -/// note | "Detalhes Técnicos" +/// note | Detalhes Técnicos Você também poderia usar `from starlette.responses import Response` ou `from starlette.responses import JSONResponse`. diff --git a/docs/pt/docs/advanced/response-directly.md b/docs/pt/docs/advanced/response-directly.md index fd2a0eef11c48..ea717be008864 100644 --- a/docs/pt/docs/advanced/response-directly.md +++ b/docs/pt/docs/advanced/response-directly.md @@ -34,9 +34,7 @@ Por exemplo, você não pode colocar um modelo do Pydantic em uma `JSONResponse` Para esses casos, você pode usar o `jsonable_encoder` para converter seus dados antes de repassá-los para a resposta: -```Python hl_lines="6-7 21-22" -{!../../docs_src/response_directly/tutorial001.py!} -``` +{* ../../docs_src/response_directly/tutorial001.py hl[6:7,21:22] *} /// note | Detalhes Técnicos @@ -56,9 +54,7 @@ Vamos dizer quer retornar uma resposta ../../docs_src/security/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="2 7 11" -{!> ../../docs_src/security/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | "Dica" - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="2 6 10" -{!> ../../docs_src/security/tutorial006.py!} -``` - -//// +{* ../../docs_src/security/tutorial006_an_py39.py hl[4,8,12] *} Quando você tentar abrir a URL pela primeira vez (ou clicar no botão "Executar" nos documentos) o navegador vai pedir pelo seu usuário e senha: @@ -68,35 +40,7 @@ Para lidar com isso, primeiramente nós convertemos o `username` e o `password` Então nós podemos utilizar o `secrets.compare_digest()` para garantir que o `credentials.username` é `"stanleyjobson"`, e que o `credentials.password` é `"swordfish"`. -//// tab | Python 3.9+ - -```Python hl_lines="1 12-24" -{!> ../../docs_src/security/tutorial007_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 12-24" -{!> ../../docs_src/security/tutorial007_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | "Dica" - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="1 11-21" -{!> ../../docs_src/security/tutorial007.py!} -``` - -//// +{* ../../docs_src/security/tutorial007_an_py39.py hl[1,12:24] *} Isso seria parecido com: @@ -161,32 +105,4 @@ Deste modo, ao utilizar `secrets.compare_digest()` no código de sua aplicação Após detectar que as credenciais estão incorretas, retorne um `HTTPException` com o status 401 (o mesmo retornado quando nenhuma credencial foi informada) e adicione o cabeçalho `WWW-Authenticate` para fazer com que o navegador mostre o prompt de login novamente: -//// tab | Python 3.9+ - -```Python hl_lines="26-30" -{!> ../../docs_src/security/tutorial007_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="26-30" -{!> ../../docs_src/security/tutorial007_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | "Dica" - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="23-27" -{!> ../../docs_src/security/tutorial007.py!} -``` - -//// +{* ../../docs_src/security/tutorial007_an_py39.py hl[26:30] *} diff --git a/docs/pt/docs/advanced/security/index.md b/docs/pt/docs/advanced/security/index.md index ae63f1c96d12e..6c7becb67abce 100644 --- a/docs/pt/docs/advanced/security/index.md +++ b/docs/pt/docs/advanced/security/index.md @@ -4,7 +4,7 @@ Existem algumas funcionalidades adicionais para lidar com segurança além das cobertas em [Tutorial - Guia de Usuário: Segurança](../../tutorial/security/index.md){.internal-link target=_blank}. -/// tip | "Dica" +/// tip | Dica As próximas seções **não são necessariamente "avançadas"**. diff --git a/docs/pt/docs/advanced/security/oauth2-scopes.md b/docs/pt/docs/advanced/security/oauth2-scopes.md index fa4594c890887..1d53f42d8c3fa 100644 --- a/docs/pt/docs/advanced/security/oauth2-scopes.md +++ b/docs/pt/docs/advanced/security/oauth2-scopes.md @@ -10,7 +10,7 @@ Toda vez que você "se autentica com" Facebook, Google, GitHub, Microsoft, Twitt Nesta seção, você verá como gerenciar a autenticação e autorização com os mesmos escopos do OAuth2 em sua aplicação **FastAPI**. -/// warning | "Aviso" +/// warning | Aviso Isso é uma seção mais ou menos avançada. Se você está apenas começando, você pode pular. @@ -62,71 +62,7 @@ Para o OAuth2, eles são apenas strings. Primeiro, vamos olhar rapidamente as partes que mudam dos exemplos do **Tutorial - Guia de Usuário** para [OAuth2 com Senha (e hash), Bearer com tokens JWT](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. Agora utilizando escopos OAuth2: -//// tab | Python 3.10+ - -```Python hl_lines="5 9 13 47 65 106 108-116 122-125 129-135 140 156" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="2 5 9 13 48 66 107 109-117 123-126 130-136 141 157" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="4 8 12 46 64 105 107-115 121-124 128-134 139 155" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[5,9,13,47,65,106,108:116,122:125,129:135,140,156] *} Agora vamos revisar essas mudanças passo a passo. @@ -136,71 +72,7 @@ A primeira mudança é que agora nós estamos declarando o esquema de segurança O parâmetro `scopes` recebe um `dict` contendo cada escopo como chave e a descrição como valor: -//// tab | Python 3.10+ - -```Python hl_lines="63-66" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="63-66" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="64-67" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="62-65" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="63-66" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="63-66" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[63:66] *} Pelo motivo de estarmos declarando estes escopos, eles aparecerão nos documentos da API quando você se autenticar/autorizar. @@ -226,71 +98,7 @@ Porém em sua aplicação, por segurança, você deve garantir que você apenas /// -//// tab | Python 3.10+ - -```Python hl_lines="156" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="156" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="157" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="155" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="156" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="156" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[156] *} ## Declare escopos em *operações de rota* e dependências @@ -308,7 +116,7 @@ E a função de dependência `get_current_active_user` também pode declarar sub Neste caso, ele requer o escopo `me` (poderia requerer mais de um escopo). -/// note | "Nota" +/// note | Nota Você não necessariamente precisa adicionar diferentes escopos em diferentes lugares. @@ -316,71 +124,7 @@ Nós estamos fazendo isso aqui para demonstrar como o **FastAPI** lida com escop /// -//// tab | Python 3.10+ - -```Python hl_lines="5 140 171" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="5 140 171" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="5 141 172" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="4 139 168" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="5 140 169" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="5 140 169" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[5,140,171] *} /// info | Informações Técnicas @@ -406,71 +150,7 @@ Nós também declaramos um parâmetro especial do tipo `SecurityScopes`, importa A classe `SecurityScopes` é semelhante à classe `Request` (`Request` foi utilizada para obter o objeto da requisição diretamente). -//// tab | Python 3.10+ - -```Python hl_lines="9 106" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9 106" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 107" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="8 105" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="9 106" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="9 106" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[9,106] *} ## Utilize os `scopes` @@ -484,71 +164,7 @@ Nós criamos uma `HTTPException` que nós podemos reutilizar (`raise`) mais tard Nesta exceção, nós incluímos os escopos necessários (se houver algum) como uma string separada por espaços (utilizando `scope_str`). Nós colocamos esta string contendo os escopos no cabeçalho `WWW-Authenticate` (isso é parte da especificação). -//// tab | Python 3.10+ - -```Python hl_lines="106 108-116" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="106 108-116" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="107 109-117" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="105 107-115" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="106 108-116" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="106 108-116" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[106,108:116] *} ## Verifique o `username` e o formato dos dados @@ -564,71 +180,7 @@ No lugar de, por exemplo, um `dict`, ou alguma outra coisa, que poderia quebrar Nós também verificamos que nós temos um usuário com o "*username*", e caso contrário, nós levantamos a mesma exceção que criamos anteriormente. -//// tab | Python 3.10+ - -```Python hl_lines="47 117-128" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="47 117-128" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="48 118-129" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="46 116-127" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="47 117-128" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="47 117-128" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[47,117:128] *} ## Verifique os `scopes` @@ -636,71 +188,7 @@ Nós verificamos agora que todos os escopos necessários, por essa dependência Para isso, nós utilizamos `security_scopes.scopes`, que contém uma `list` com todos esses escopos como uma `str`. -//// tab | Python 3.10+ - -```Python hl_lines="129-135" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="129-135" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="130-136" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="128-134" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="129-135" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="129-135" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[129:135] *} ## Árvore de dependência e escopos @@ -771,7 +259,7 @@ O mais comum é o fluxo implícito. O mais seguro é o fluxo de código, mas ele é mais complexo para implementar, pois ele necessita mais passos. Como ele é mais complexo, muitos provedores terminam sugerindo o fluxo implícito. -/// note | "Nota" +/// note | Nota É comum que cada provedor de autenticação nomeie os seus fluxos de forma diferente, para torná-lo parte de sua marca. diff --git a/docs/pt/docs/advanced/settings.md b/docs/pt/docs/advanced/settings.md index d32b70ed429bc..00a39b0af494c 100644 --- a/docs/pt/docs/advanced/settings.md +++ b/docs/pt/docs/advanced/settings.md @@ -180,9 +180,7 @@ Você pode utilizar todas as ferramentas e funcionalidades de validação que s //// tab | Pydantic v2 -```Python hl_lines="2 5-8 11" -{!> ../../docs_src/settings/tutorial001.py!} -``` +{* ../../docs_src/settings/tutorial001.py hl[2,5:8,11] *} //// @@ -194,9 +192,7 @@ Na versão 1 do Pydantic você importaria `BaseSettings` diretamente do módulo /// -```Python hl_lines="2 5-8 11" -{!> ../../docs_src/settings/tutorial001_pv1.py!} -``` +{* ../../docs_src/settings/tutorial001_pv1.py hl[2,5:8,11] *} //// @@ -214,9 +210,7 @@ Depois ele irá converter e validar os dados. Assim, quando você utilizar aquel Depois, Você pode utilizar o novo objeto `settings` na sua aplicação: -```Python hl_lines="18-20" -{!../../docs_src/settings/tutorial001.py!} -``` +{* ../../docs_src/settings/tutorial001.py hl[18:20] *} ### Executando o servidor @@ -250,15 +244,11 @@ Você também pode incluir essas configurações em um arquivo de um módulo sep Por exemplo, você pode adicionar um arquivo `config.py` com: -```Python -{!../../docs_src/settings/app01/config.py!} -``` +{* ../../docs_src/settings/app01/config.py *} E utilizar essa configuração em `main.py`: -```Python hl_lines="3 11-13" -{!../../docs_src/settings/app01/main.py!} -``` +{* ../../docs_src/settings/app01/main.py hl[3,11:13] *} /// dica @@ -276,9 +266,7 @@ Isso é especialmente útil durante os testes, já que é bastante simples sobre Baseando-se no exemplo anterior, seu arquivo `config.py` seria parecido com isso: -```Python hl_lines="10" -{!../../docs_src/settings/app02/config.py!} -``` +{* ../../docs_src/settings/app02/config.py hl[10] *} Perceba que dessa vez não criamos uma instância padrão `settings = Settings()`. @@ -286,35 +274,7 @@ Perceba que dessa vez não criamos uma instância padrão `settings = Settings() Agora criamos a dependência que retorna um novo objeto `config.Settings()`. -//// tab | Python 3.9+ - -```Python hl_lines="6 12-13" -{!> ../../docs_src/settings/app02_an_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="6 12-13" -{!> ../../docs_src/settings/app02_an/main.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="5 11-12" -{!> ../../docs_src/settings/app02/main.py!} -``` - -//// +{* ../../docs_src/settings/app02_an_py39/main.py hl[6,12:13] *} /// dica @@ -326,43 +286,13 @@ Por enquanto, você pode considerar `get_settings()` como uma função normal. E então podemos declarar essas configurações como uma dependência na função de operação da rota e utilizar onde for necessário. -//// tab | Python 3.9+ - -```Python hl_lines="17 19-21" -{!> ../../docs_src/settings/app02_an_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17 19-21" -{!> ../../docs_src/settings/app02_an/main.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="16 18-20" -{!> ../../docs_src/settings/app02/main.py!} -``` - -//// +{* ../../docs_src/settings/app02_an_py39/main.py hl[17,19:21] *} ### Configurações e testes Então seria muito fácil fornecer uma configuração diferente durante a execução dos testes sobrescrevendo a dependência de `get_settings`: -```Python hl_lines="9-10 13 21" -{!../../docs_src/settings/app02/test_main.py!} -``` +{* ../../docs_src/settings/app02/test_main.py hl[9:10,13,21] *} Na sobrescrita da dependência, definimos um novo valor para `admin_email` quando instanciamos um novo objeto `Settings`, e então retornamos esse novo objeto. @@ -405,9 +335,7 @@ E então adicionar o seguinte código em `config.py`: //// tab | Pydantic v2 -```Python hl_lines="9" -{!> ../../docs_src/settings/app03_an/config.py!} -``` +{* ../../docs_src/settings/app03_an/config.py hl[9] *} /// dica @@ -419,9 +347,7 @@ O atributo `model_config` é usado apenas para configuração do Pydantic. Você //// tab | Pydantic v1 -```Python hl_lines="9-10" -{!> ../../docs_src/settings/app03_an/config_pv1.py!} -``` +{* ../../docs_src/settings/app03_an/config_pv1.py hl[9:10] *} /// dica @@ -462,35 +388,7 @@ Iriamos criar um novo objeto a cada requisição, e estaríamos lendo o arquivo Mas como estamos utilizando o decorador `@lru_cache` acima, o objeto `Settings` é criado apenas uma vez, na primeira vez que a função é chamada. ✔️ -//// tab | Python 3.9+ - -```Python hl_lines="1 11" -{!> ../../docs_src/settings/app03_an_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 11" -{!> ../../docs_src/settings/app03_an/main.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="1 10" -{!> ../../docs_src/settings/app03/main.py!} -``` - -//// +{* ../../docs_src/settings/app03_an_py39/main.py hl[1,11] *} Dessa forma, todas as chamadas da função `get_settings()` nas dependências das próximas requisições, em vez de executar o código interno de `get_settings()` e instanciar um novo objeto `Settings`, irão retornar o mesmo objeto que foi retornado na primeira chamada, de novo e de novo. diff --git a/docs/pt/docs/advanced/sub-applications.md b/docs/pt/docs/advanced/sub-applications.md index 7f0381cc2fe04..efc6bef6470a9 100644 --- a/docs/pt/docs/advanced/sub-applications.md +++ b/docs/pt/docs/advanced/sub-applications.md @@ -10,9 +10,7 @@ Se você precisar ter duas aplicações FastAPI independentes, cada uma com seu Primeiro, crie a aplicação principal, de nível superior, **FastAPI**, e suas *operações de rota*: -```Python hl_lines="3 6-8" -{!../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[3,6:8] *} ### Sub-aplicação @@ -20,9 +18,7 @@ Em seguida, crie sua sub-aplicação e suas *operações de rota*. Essa sub-aplicação é apenas outra aplicação FastAPI padrão, mas esta é a que será "montada": -```Python hl_lines="11 14-16" -{!../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[11,14:16] *} ### Monte a sub-aplicação @@ -30,9 +26,7 @@ Na sua aplicação de nível superior, `app`, monte a sub-aplicação, `subapi`. Neste caso, ela será montada no caminho `/subapi`: -```Python hl_lines="11 19" -{!../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[11,19] *} ### Verifique a documentação automática da API diff --git a/docs/pt/docs/advanced/templates.md b/docs/pt/docs/advanced/templates.md index 88a5b940e97e4..4d22bfbbf148c 100644 --- a/docs/pt/docs/advanced/templates.md +++ b/docs/pt/docs/advanced/templates.md @@ -25,9 +25,7 @@ $ pip install jinja2 * Declare um parâmetro `Request` no *path operation* que retornará um template. * Use o `template` que você criou para renderizar e retornar uma `TemplateResponse`, passe o nome do template, o request object, e um "context" dict com pares chave-valor a serem usados dentro do template do Jinja2. -```Python hl_lines="4 11 15-18" -{!../../docs_src/templates/tutorial001.py!} -``` +{* ../../docs_src/templates/tutorial001.py hl[4,11,15:18] *} /// note @@ -37,13 +35,13 @@ Além disso, em versões anteriores, o objeto `request` era passado como parte d /// -/// tip | "Dica" +/// tip | Dica Ao declarar `response_class=HTMLResponse`, a documentação entenderá que a resposta será HTML. /// -/// note | "Detalhes Técnicos" +/// note | Detalhes Técnicos Você também poderia usar `from starlette.templating import Jinja2Templates`. diff --git a/docs/pt/docs/advanced/testing-dependencies.md b/docs/pt/docs/advanced/testing-dependencies.md index f978350a528b9..3ede4741d9b67 100644 --- a/docs/pt/docs/advanced/testing-dependencies.md +++ b/docs/pt/docs/advanced/testing-dependencies.md @@ -28,59 +28,9 @@ Para sobrepor a dependência para os testes, você coloca como chave a dependên E então o **FastAPI** chamará a sobreposição no lugar da dependência original. -//// tab | Python 3.10+ +{* ../../docs_src/dependency_testing/tutorial001_an_py310.py hl[26:27,30] *} -```Python hl_lines="26-27 30" -{!> ../../docs_src/dependency_testing/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="28-29 32" -{!> ../../docs_src/dependency_testing/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="29-30 33" -{!> ../../docs_src/dependency_testing/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | "Dica" - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="24-25 28" -{!> ../../docs_src/dependency_testing/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | "Dica" - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="28-29 32" -{!> ../../docs_src/dependency_testing/tutorial001.py!} -``` - -//// - -/// tip | "Dica" +/// tip | Dica Você pode definir uma sobreposição de dependência para uma dependência que é utilizada em qualquer lugar da sua aplicação **FastAPI**. @@ -96,7 +46,7 @@ E então você pode redefinir as suas sobreposições (removê-las) definindo o app.dependency_overrides = {} ``` -/// tip | "Dica" +/// tip | Dica Se você quer sobrepor uma dependência apenas para alguns testes, você pode definir a sobreposição no início do testes (dentro da função de teste) e reiniciá-la ao final (no final da função de teste). diff --git a/docs/pt/docs/advanced/testing-events.md b/docs/pt/docs/advanced/testing-events.md index b6796e8351c32..6113c99136c95 100644 --- a/docs/pt/docs/advanced/testing-events.md +++ b/docs/pt/docs/advanced/testing-events.md @@ -2,6 +2,4 @@ Quando você precisa que os seus manipuladores de eventos (`startup` e `shutdown`) sejam executados em seus testes, você pode utilizar o `TestClient` usando a instrução `with`: -```Python hl_lines="9-12 20-24" -{!../../docs_src/app_testing/tutorial003.py!} -``` +{* ../../docs_src/app_testing/tutorial003.py hl[9:12,20:24] *} diff --git a/docs/pt/docs/advanced/testing-websockets.md b/docs/pt/docs/advanced/testing-websockets.md index daa610df63c74..942771bc980af 100644 --- a/docs/pt/docs/advanced/testing-websockets.md +++ b/docs/pt/docs/advanced/testing-websockets.md @@ -4,11 +4,9 @@ Você pode usar o mesmo `TestClient` para testar WebSockets. Para isso, você utiliza o `TestClient` dentro de uma instrução `with`, conectando com o WebSocket: -```Python hl_lines="27-31" -{!../../docs_src/app_testing/tutorial002.py!} -``` +{* ../../docs_src/app_testing/tutorial002.py hl[27:31] *} -/// note | "Nota" +/// note | Nota Para mais detalhes, confira a documentação do Starlette para testar WebSockets. diff --git a/docs/pt/docs/advanced/using-request-directly.md b/docs/pt/docs/advanced/using-request-directly.md index c2114c214d2f9..f31e2ed15251e 100644 --- a/docs/pt/docs/advanced/using-request-directly.md +++ b/docs/pt/docs/advanced/using-request-directly.md @@ -29,13 +29,11 @@ Vamos imaginar que você deseja obter o endereço de IP/host do cliente dentro d Para isso você precisa acessar a requisição diretamente. -```Python hl_lines="1 7-8" -{!../../docs_src/using_request_directly/tutorial001.py!} -``` +{* ../../docs_src/using_request_directly/tutorial001.py hl[1,7:8] *} Ao declarar o parâmetro com o tipo sendo um `Request` em sua *função de operação de rota*, o **FastAPI** saberá como passar o `Request` neste parâmetro. -/// tip | "Dica" +/// tip | Dica Note que neste caso, nós estamos declarando o parâmetro da rota ao lado do parâmetro da requisição. @@ -49,7 +47,7 @@ Do mesmo jeito, você pode declarar qualquer outro parâmetro normalmente, e al Você pode ler mais sobre os detalhes do objeto `Request` no site da documentação oficial do Starlette.. -/// note | "Detalhes Técnicos" +/// note | Detalhes Técnicos Você também pode utilizar `from starlette.requests import Request`. diff --git a/docs/pt/docs/advanced/websockets.md b/docs/pt/docs/advanced/websockets.md new file mode 100644 index 0000000000000..82e443886b9f7 --- /dev/null +++ b/docs/pt/docs/advanced/websockets.md @@ -0,0 +1,186 @@ +# WebSockets + +Você pode usar WebSockets com **FastAPI**. + +## Instalando `WebSockets` + +Garanta que você criou um [ambiente virtual](../virtual-environments.md){.internal-link target=_blank}, o ativou e instalou o `websockets`: + +
+ +```console +$ pip install websockets + +---> 100% +``` + +
+ +## Cliente WebSockets + +### Em produção + +Em seu sistema de produção, você provavelmente tem um frontend criado com um framework moderno como React, Vue.js ou Angular. + +E para comunicar usando WebSockets com seu backend, você provavelmente usaria as utilidades do seu frontend. + +Ou você pode ter um aplicativo móvel nativo que se comunica diretamente com seu backend WebSocket, em código nativo. + +Ou você pode ter qualquer outra forma de comunicar com o endpoint WebSocket. + +--- + +Mas para este exemplo, usaremos um documento HTML muito simples com algum JavaScript, tudo dentro de uma string longa. + +Esse, é claro, não é o ideal e você não o usaria para produção. + +Na produção, você teria uma das opções acima. + +Mas é a maneira mais simples de focar no lado do servidor de WebSockets e ter um exemplo funcional: + +{* ../../docs_src/websockets/tutorial001.py hl[2,6:38,41:43] *} + +## Criando um `websocket` + +Em sua aplicação **FastAPI**, crie um `websocket`: + +{*../../docs_src/websockets/tutorial001.py hl[46:47]*} + +/// note | Detalhes Técnicos + +Você também poderia usar `from starlette.websockets import WebSocket`. + +A **FastAPI** fornece o mesmo `WebSocket` diretamente apenas como uma conveniência para você, o desenvolvedor. Mas ele vem diretamente do Starlette. + +/// + +## Aguardar por mensagens e enviar mensagens + +Em sua rota WebSocket você pode esperar (`await`) por mensagens e enviar mensagens. + +{*../../docs_src/websockets/tutorial001.py hl[48:52]*} + +Você pode receber e enviar dados binários, de texto e JSON. + +## Tente você mesmo + +Se seu arquivo for nomeado `main.py`, execute sua aplicação com: + +
+ +```console +$ fastapi dev main.py + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Abra seu navegador em: http://127.0.0.1:8000. + +Você verá uma página simples como: + + + +Você pode digitar mensagens na caixa de entrada e enviá-las: + + + +E sua aplicação **FastAPI** com WebSockets responderá de volta: + + + +Você pode enviar (e receber) muitas mensagens: + + + +E todas elas usarão a mesma conexão WebSocket. + +## Usando `Depends` e outros + +Nos endpoints WebSocket você pode importar do `fastapi` e usar: + +* `Depends` +* `Security` +* `Cookie` +* `Header` +* `Path` +* `Query` + +Eles funcionam da mesma forma que para outros endpoints FastAPI/*operações de rota*: + +{*../../docs_src/websockets/tutorial002_an_py310.py hl[68:69,82]*} + +/// info | Informação + +Como isso é um WebSocket, não faz muito sentido levantar uma `HTTPException`, em vez disso levantamos uma `WebSocketException`. + +Você pode usar um código de fechamento dos códigos válidos definidos na especificação. + +/// + +### Tente os WebSockets com dependências + +Se seu arquivo for nomeado `main.py`, execute sua aplicação com: + +
+ +```console +$ fastapi dev main.py + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Abrar seu browser em: http://127.0.0.1:8000. + +Lá você pode definir: + +* O "Item ID", usado na rota. +* O "Token" usado como um parâmetro de consulta. + +/// tip | Dica + +Perceba que a consulta `token` será manipulada por uma dependência. + +/// + +Com isso você pode conectar o WebSocket e então enviar e receber mensagens: + + + +## Lidando com desconexões e múltiplos clientes + +Quando uma conexão WebSocket é fechada, o `await websocket.receive_text()` levantará uma exceção `WebSocketDisconnect`, que você pode então capturar e lidar como neste exemplo. + +{*../../docs_src/websockets/tutorial003_py39.py hl[79:81]*} + +Para testar: + +* Abrar o aplicativo com várias abas do navegador. +* Escreva mensagens a partir delas. +* Então feche uma das abas. + +Isso levantará a exceção `WebSocketDisconnect`, e todos os outros clientes receberão uma mensagem como: + +``` +Client #1596980209979 left the chat +``` + +/// tip | Dica + +O app acima é um exemplo mínimo e simples para demonstrar como lidar e transmitir mensagens para várias conexões WebSocket. + +Mas tenha em mente que, como tudo é manipulado na memória, em uma única lista, ele só funcionará enquanto o processo estiver em execução e só funcionará com um único processo. + +Se você precisa de algo fácil de integrar com o FastAPI, mas que seja mais robusto, suportado por Redis, PostgreSQL ou outros, verifique o encode/broadcaster. + +/// + +## Mais informações + +Para aprender mais sobre as opções, verifique a documentação do Starlette para: + +* A classe `WebSocket`. +* Manipulação de WebSockets baseada em classes. diff --git a/docs/pt/docs/advanced/wsgi.md b/docs/pt/docs/advanced/wsgi.md index e6d08c8dbb0fd..a36261e5ef1a2 100644 --- a/docs/pt/docs/advanced/wsgi.md +++ b/docs/pt/docs/advanced/wsgi.md @@ -12,9 +12,7 @@ Em seguinda, encapsular a aplicação WSGI (e.g. Flask) com o middleware. E então **"montar"** em um caminho de rota. -```Python hl_lines="2-3 23" -{!../../docs_src/wsgi/tutorial001.py!} -``` +{* ../../docs_src/wsgi/tutorial001.py hl[2:3,23] *} ## Conferindo diff --git a/docs/pt/docs/alternatives.md b/docs/pt/docs/alternatives.md index 2a2632bbc9fe7..29c9693bba7a8 100644 --- a/docs/pt/docs/alternatives.md +++ b/docs/pt/docs/alternatives.md @@ -30,13 +30,13 @@ Ele é utilizado por muitas companhias incluindo Mozilla, Red Hat e Eventbrite. Ele foi um dos primeiros exemplos de **documentação automática de API**, e essa foi especificamente uma das primeiras idéias que inspirou "a busca por" **FastAPI**. -/// note | "Nota" +/// note | Nota Django REST Framework foi criado por Tom Christie. O mesmo criador de Starlette e Uvicorn, nos quais **FastAPI** é baseado. /// -/// check | "**FastAPI** inspirado para" +/// check | **FastAPI** inspirado para Ter uma documentação automática da API em interface web. @@ -56,7 +56,7 @@ Esse desacoplamento de partes, e sendo um "microframework" que pode ser extendid Dada a simplicidade do Flask, parecia uma ótima opção para construção de APIs. A próxima coisa a procurar era um "Django REST Framework" para Flask. -/// check | "**FastAPI** inspirado para" +/// check | **FastAPI** inspirado para Ser um microframework. Fazer ele fácil para misturar e combinar com ferramentas e partes necessárias. @@ -98,7 +98,7 @@ def read_url(): Veja as similaridades em `requests.get(...)` e `@app.get(...)`. -/// check | "**FastAPI** inspirado para" +/// check | **FastAPI** inspirado para * Ter uma API simples e intuitiva. * Utilizar nomes de métodos HTTP (operações) diretamente, de um jeito direto e intuitivo. @@ -118,7 +118,7 @@ Em algum ponto, Swagger foi dado para a Fundação Linux, e foi renomeado OpenAP Isso acontece porquê quando alguém fala sobre a versão 2.0 é comum dizer "Swagger", e para a versão 3+, "OpenAPI". -/// check | "**FastAPI** inspirado para" +/// check | **FastAPI** inspirado para Adotar e usar um padrão aberto para especificações API, ao invés de algum esquema customizado. @@ -147,7 +147,7 @@ Esses recursos são o que Marshmallow foi construído para fornecer. Ele é uma Mas ele foi criado antes da existência do _type hints_ do Python. Então, para definir todo o _schema_ você precisa utilizar específicas ferramentas e classes fornecidas pelo Marshmallow. -/// check | "**FastAPI** inspirado para" +/// check | **FastAPI** inspirado para Usar código para definir "schemas" que forneçam, automaticamente, tipos de dados e validação. @@ -169,7 +169,7 @@ Webargs foi criado pelos mesmos desenvolvedores do Marshmallow. /// -/// check | "**FastAPI** inspirado para" +/// check | **FastAPI** inspirado para Ter validação automática de dados vindos de requisições. @@ -199,7 +199,7 @@ APISpec foi criado pelos mesmos desenvolvedores do Marshmallow. /// -/// check | "**FastAPI** inspirado para" +/// check | **FastAPI** inspirado para Dar suporte a padrões abertos para APIs, OpenAPI. @@ -231,7 +231,7 @@ Flask-apispec foi criado pelos mesmos desenvolvedores do Marshmallow. /// -/// check | "**FastAPI** inspirado para" +/// check | **FastAPI** inspirado para Gerar _schema_ OpenAPI automaticamente, a partir do mesmo código que define serialização e validação. @@ -251,7 +251,7 @@ Mas como os dados TypeScript não são preservados após a compilação para o J Ele também não controla modelos aninhados muito bem. Então, se o corpo JSON na requisição for um objeto JSON que contém campos internos que contém objetos JSON aninhados, ele não consegue ser validado e documentado apropriadamente. -/// check | "**FastAPI** inspirado para" +/// check | **FastAPI** inspirado para Usar tipos Python para ter um ótimo suporte do editor. @@ -263,7 +263,7 @@ Ter um sistema de injeção de dependência poderoso. Achar um jeito de minimiza Ele foi um dos primeiros frameworks Python extremamente rápido baseado em `asyncio`. Ele foi feito para ser muito similar ao Flask. -/// note | "Detalhes técnicos" +/// note | Detalhes técnicos Ele utiliza `uvloop` ao invés do '_loop_' `asyncio` padrão do Python. É isso que deixa ele tão rápido. @@ -271,7 +271,7 @@ Ele claramente inspirou Uvicorn e Starlette, que são atualmente mais rápidos q /// -/// check | "**FastAPI** inspirado para" +/// check | **FastAPI** inspirado para Achar um jeito de ter uma performance insana. @@ -289,7 +289,7 @@ Ele é projetado para ter funções que recebem dois parâmetros, uma "requisiç Então, validação de dados, serialização e documentação tem que ser feitos no código, não automaticamente. Ou eles terão que ser implementados como um framework acima do Falcon, como o Hug. Essa mesma distinção acontece em outros frameworks que são inspirados pelo design do Falcon, tendo um objeto de requisição e um objeto de resposta como parâmetros. -/// check | "**FastAPI** inspirado para" +/// check | **FastAPI** inspirado para Achar jeitos de conseguir melhor performance. @@ -315,7 +315,7 @@ O sistema de injeção de dependência exige pré-registro das dependências e a Rotas são declaradas em um único lugar, usando funções declaradas em outros lugares (ao invés de usar decoradores que possam ser colocados diretamente acima da função que controla o _endpoint_). Isso é mais perto de como o Django faz isso do que como Flask (e Starlette) faz. Ele separa no código coisas que são relativamente amarradas. -/// check | "**FastAPI** inspirado para" +/// check | **FastAPI** inspirado para Definir validações extras para tipos de dados usando valores "padrão" de atributos dos modelos. Isso melhora o suporte do editor, e não estava disponível no Pydantic antes. @@ -343,7 +343,7 @@ Hug foi criado por Timothy Crosley, o mesmo criador do - -```console -$ python -m venv env -``` - - - -Isso criará o diretório `./env/` com os binários Python e então você será capaz de instalar pacotes nesse ambiente isolado. - -### Ativar o ambiente - -Ative o novo ambiente com: - -//// tab | Linux, macOS - -
- -```console -$ source ./env/bin/activate -``` - -
- -//// - -//// tab | Windows PowerShell - -
- -```console -$ .\env\Scripts\Activate.ps1 -``` - -
- -//// - -//// tab | Windows Bash - -Ou se você usa Bash para Windows (por exemplo
Git Bash): - -
- -```console -$ source ./env/Scripts/activate -``` - -
- -//// - -Para verificar se funcionou, use: - -//// tab | Linux, macOS, Windows Bash - -
- -```console -$ which pip - -some/directory/fastapi/env/bin/pip -``` - -
- -//// - -//// tab | Windows PowerShell - -
- -```console -$ Get-Command pip - -some/directory/fastapi/env/bin/pip -``` - -
- -//// - -Se ele exibir o binário `pip` em `env/bin/pip` então funcionou. 🎉 - - - -/// tip - -Toda vez que você instalar um novo pacote com `pip` nesse ambiente, ative o ambiente novamente. - -Isso garante que se você usar um programa instalado por aquele pacote, você utilizará aquele de seu ambiente local e não outro que possa estar instalado globalmente. - -/// - -### pip - -Após ativar o ambiente como descrito acima: - -
- -```console -$ pip install -r requirements.txt - ----> 100% -``` - -
- -Isso irá instalar todas as dependências e seu FastAPI local em seu ambiente local. - -#### Usando seu FastAPI local - -Se você cria um arquivo Python que importa e usa FastAPI, e roda com Python de seu ambiente local, ele irá utilizar o código fonte de seu FastAPI local. - -E se você atualizar o código fonte do FastAPI local, como ele é instalado com `-e`, quando você rodar aquele arquivo Python novamente, ele irá utilizar a nova versão do FastAPI que você acabou de editar. - -Desse modo, você não tem que "instalar" sua versão local para ser capaz de testar cada mudança. - -### Formato - -Tem um arquivo que você pode rodar que irá formatar e limpar todo o seu código: - -
- -```console -$ bash scripts/format.sh -``` - -
- -Ele irá organizar também todos os seus imports. - -Para que ele organize os imports corretamente, você precisa ter o FastAPI instalado localmente em seu ambiente, com o comando na seção acima usando `-e`. - -### Formato dos imports - -Tem outro _script_ que formata todos os imports e garante que você não tenha imports não utilizados: - -
- -```console -$ bash scripts/format-imports.sh -``` - -
- -Como ele roda um comando após o outro, modificando e revertendo muitos arquivos, ele demora um pouco para concluir, então pode ser um pouco mais fácil utilizar `scripts/format.sh` frequentemente e `scripts/format-imports.sh` somente após "commitar uma branch". - -## Documentação - -Primeiro, tenha certeza de configurar seu ambiente como descrito acima, isso irá instalar todas as requisições. - -A documentação usa MkDocs. - -E existem ferramentas/_scripts_ extras para controlar as traduções em `./scripts/docs.py`. - -/// tip - -Você não precisa ver o código em `./scripts/docs.py`, você apenas o utiliza na linha de comando. - -/// - -Toda a documentação está no formato Markdown no diretório `./docs/pt/`. - -Muitos dos tutoriais tem blocos de código. - -Na maioria dos casos, esse blocos de código são aplicações completas que podem ser rodadas do jeito que estão apresentados. - -De fato, esses blocos de código não estão escritos dentro do Markdown, eles são arquivos Python dentro do diretório `./docs_src/`. - -E esses arquivos Python são incluídos/injetados na documentação quando se gera o site. - -### Testes para Documentação - -A maioria dos testes na verdade rodam encima dos arquivos fonte na documentação. - -Isso ajuda a garantir: - -* Que a documentação esteja atualizada. -* Que os exemplos da documentação possam ser rodadas do jeito que estão apresentadas. -* A maior parte dos recursos é coberta pela documentação, garantida por cobertura de testes. - -Durante o desenvolvimento local, existe um _script_ que constrói o site e procura por quaisquer mudanças, carregando na hora: - -
- -```console -$ python ./scripts/docs.py live - -[INFO] Serving on http://127.0.0.1:8008 -[INFO] Start watching changes -[INFO] Start detecting changes -``` - -
- -Isso irá servir a documentação em `http://127.0.0.1:8008`. - -Desse jeito, você poderá editar a documentação/arquivos fonte e ver as mudanças na hora. - -#### Typer CLI (opcional) - -As instruções aqui mostram como utilizar _scripts_ em `./scripts/docs.py` com o programa `python` diretamente. - -Mas você pode usar também Typer CLI, e você terá auto-completação para comandos no seu terminal após instalar o _completion_. - -Se você instalou Typer CLI, você pode instalar _completion_ com: - -
- -```console -$ typer --install-completion - -zsh completion installed in /home/user/.bashrc. -Completion will take effect once you restart the terminal. -``` - -
- -### Aplicações e documentação ao mesmo tempo - -Se você rodar os exemplos com, por exemplo: - -
- -```console -$ uvicorn tutorial001:app --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -
- -como Uvicorn utiliza por padrão a porta `8000`, a documentação na porta `8008` não dará conflito. - -### Traduções - -Ajuda com traduções É MUITO apreciada! E essa tarefa não pode ser concluída sem a ajuda da comunidade. 🌎 🚀 - -Aqui estão os passos para ajudar com as traduções. - -#### Dicas e orientações - -* Verifique sempre os _pull requests_ existentes para a sua linguagem e faça revisões das alterações e aprove elas. - -/// tip - -Você pode adicionar comentários com sugestões de alterações para _pull requests_ existentes. - -Verifique as documentações sobre adicionar revisão ao _pull request_ para aprovação ou solicitação de alterações. - -/// - -* Verifique em _issues_ para ver se existe alguém coordenando traduções para a sua linguagem. - -* Adicione um único _pull request_ por página traduzida. Isso tornará muito mais fácil a revisão para as outras pessoas. - -Para as linguagens que eu não falo, vou esperar por várias pessoas revisarem a tradução antes de _mergear_. - -* Você pode verificar também se há traduções para sua linguagem e adicionar revisão para elas, isso irá me ajudar a saber que a tradução está correta e eu possa _mergear_. - -* Utilize os mesmos exemplos Python e somente traduza o texto na documentação. Você não tem que alterar nada no código para que funcione. - -* Utilize as mesmas imagens, nomes de arquivo e links. Você não tem que alterar nada disso para que funcione. - -* Para verificar o código de duas letras para a linguagem que você quer traduzir, você pode usar a Lista de códigos ISO 639-1. - -#### Linguagem existente - -Vamos dizer que você queira traduzir uma página para uma linguagem que já tenha traduções para algumas páginas, como o Espanhol. - -No caso do Espanhol, o código de duas letras é `es`. Então, o diretório para traduções em Espanhol está localizada em `docs/es/`. - -/// tip - -A principal ("oficial") linguagem é o Inglês, localizado em `docs/en/`. - -/// - -Agora rode o _servidor ao vivo_ para as documentações em Espanhol: - -
- -```console -// Use o comando "live" e passe o código da linguagem como um argumento de linha de comando -$ python ./scripts/docs.py live es - -[INFO] Serving on http://127.0.0.1:8008 -[INFO] Start watching changes -[INFO] Start detecting changes -``` - -
- -Agora você pode ir em http://127.0.0.1:8008 e ver suas mudanças ao vivo. - -Se você procurar no site da documentação do FastAPI, você verá que toda linguagem tem todas as páginas. Mas algumas páginas não estão traduzidas e tem notificação sobre a falta da tradução. - -Mas quando você rodar localmente como descrito acima, você somente verá as páginas que já estão traduzidas. - -Agora vamos dizer que você queira adicionar uma tradução para a seção [Recursos](features.md){.internal-link target=_blank}. - -* Copie o arquivo em: - -``` -docs/en/docs/features.md -``` - -* Cole ele exatamente no mesmo local mas para a linguagem que você quer traduzir, por exemplo: - -``` -docs/es/docs/features.md -``` - -/// tip - -Observe que a única mudança na rota é o código da linguagem, de `en` para `es`. - -/// - -* Agora abra o arquivo de configuração MkDocs para Inglês em: - -``` -docs/en/docs/mkdocs.yml -``` - -* Procure o lugar onde `docs/features.md` está localizado no arquivo de configuração. Algum lugar como: - -```YAML hl_lines="8" -site_name: FastAPI -# Mais coisas -nav: -- FastAPI: index.md -- Languages: - - en: / - - es: /es/ -- features.md -``` - -* Abra o arquivo de configuração MkDocs para a linguagem que você está editando, por exemplo: - -``` -docs/es/docs/mkdocs.yml -``` - -* Adicione no mesmo local que está no arquivo em Inglês, por exemplo: - -```YAML hl_lines="8" -site_name: FastAPI -# Mais coisas -nav: -- FastAPI: index.md -- Languages: - - en: / - - es: /es/ -- features.md -``` - -Tenha certeza que se existem outras entradas, a nova entrada com sua tradução esteja exatamente na mesma ordem como na versão em Inglês. - -Se você for no seu navegador verá que agora a documentação mostra sua nova seção. 🎉 - -Agora você poderá traduzir tudo e ver como está toda vez que salva o arquivo. - -#### Nova linguagem - -Vamos dizer que você queira adicionar traduções para uma linguagem que ainda não foi traduzida, nem sequer uma página. - -Vamos dizer que você queira adicionar tradução para Haitiano, e ainda não tenha na documentação. - -Verificando o link acima, o código para "Haitiano" é `ht`. - -O próximo passo é rodar o _script_ para gerar um novo diretório de tradução: - -
- -```console -// Use o comando new-lang, passe o código da linguagem como um argumento de linha de comando -$ python ./scripts/docs.py new-lang ht - -Successfully initialized: docs/ht -Updating ht -Updating en -``` - -
- -Agora você pode verificar em seu editor de código o mais novo diretório criado `docs/ht/`. - -/// tip - -Crie um primeiro _pull request_ com apenas isso, para iniciar a configuração da nova linguagem, antes de adicionar traduções. - -Desse modo outros poderão ajudar com outras páginas enquanto você trabalha na primeira. 🚀 - -/// - -Inicie traduzindo a página principal, `docs/ht/index.md`. - -Então você pode continuar com as instruções anteriores, para uma "Linguagem Existente". - -##### Nova linguagem não suportada - -Se quando rodar o _script_ do _servidor ao vivo_ você pega um erro sobre linguagem não suportada, alguma coisa como: - -``` - raise TemplateNotFound(template) -jinja2.exceptions.TemplateNotFound: partials/language/xx.html -``` - -Isso significa que o tema não suporta essa linguagem (nesse caso, com um código falso de duas letras `xx`). - -Mas não se preocupe, você pode configurar o tema de linguagem para Inglês e então traduzir o conteúdo da documentação. - -Se você precisar fazer isso, edite o `mkdocs.yml` para sua nova linguagem, teremos algo como: - -```YAML hl_lines="5" -site_name: FastAPI -# Mais coisas -theme: - # Mais coisas - language: xx -``` - -Altere essa linguagem de `xx` (do seu código de linguagem) para `en`. - -Então você poderá iniciar novamente o _servidor ao vivo_. - -#### Pré-visualize o resultado - -Quando você usa o _script_ em `./scripts/docs.py` com o comando `live` ele somente exibe os arquivos e traduções disponíveis para a linguagem atual. - -Mas uma vez que você tenha concluído, você poderá testar tudo como se parecesse _online_. - -Para fazer isso, primeiro construa toda a documentação: - -
- -```console -// Use o comando "build-all", isso leverá um tempinho -$ python ./scripts/docs.py build-all - -Updating es -Updating en -Building docs for: en -Building docs for: es -Successfully built docs for: es -Copying en index.md to README.md -``` - -
- -Isso gera toda a documentação em `./docs_build/` para cada linguagem. Isso inclui a adição de quaisquer arquivos com tradução faltando, com uma nota dizendo que "esse arquivo ainda não tem tradução". Mas você não tem que fazer nada com esse diretório. - -Então ele constrói todos aqueles _sites_ independentes MkDocs para cada linguagem, combina eles, e gera a saída final em `./site/`. - -Então você poderá "servir" eles com o comando `serve`: - -
- -```console -// Use o comando "serve" após rodar "build-all" -$ python ./scripts/docs.py serve - -Warning: this is a very simple server. For development, use mkdocs serve instead. -This is here only to preview a site with translations already built. -Make sure you run the build-all command first. -Serving at: http://127.0.0.1:8008 -``` - -
- -## Testes - -Tem um _script_ que você pode rodar localmente para testar todo o código e gerar relatórios de cobertura em HTML: - -
- -```console -$ bash scripts/test-cov-html.sh -``` - -
- -Esse comando gera um diretório `./htmlcov/`, se você abrir o arquivo `./htmlcov/index.html` no seu navegador, poderá explorar interativamente as regiões de código que estão cobertas pelos testes, e observar se existe alguma região faltando. - -### Testes no seu editor - -Se você quer usar os testes integrados em seu editor adicione `./docs_src` na sua variável `PYTHONPATH`. - -Por exemplo, no VS Code você pode criar um arquivo `.env` com: - -```env -PYTHONPATH=./docs_src -``` diff --git a/docs/pt/docs/deployment/concepts.md b/docs/pt/docs/deployment/concepts.md index 20513c3663d17..8cf70d0b4729e 100644 --- a/docs/pt/docs/deployment/concepts.md +++ b/docs/pt/docs/deployment/concepts.md @@ -151,7 +151,7 @@ E ainda assim, você provavelmente não gostaria que o aplicativo permanecesse i Mas nos casos com erros realmente graves que travam o **processo** em execução, você vai querer um componente externo que seja responsável por **reiniciar** o processo, pelo menos algumas vezes... -/// tip | "Dica" +/// tip | Dica ...Embora se o aplicativo inteiro estiver **travando imediatamente**, provavelmente não faça sentido reiniciá-lo para sempre. Mas nesses casos, você provavelmente notará isso durante o desenvolvimento, ou pelo menos logo após a implantação. @@ -239,7 +239,7 @@ Aqui estão algumas combinações e estratégias possíveis: * **Serviços de nuvem** que cuidam disso para você * O serviço de nuvem provavelmente **cuidará da replicação para você**. Ele possivelmente deixaria você definir **um processo para executar**, ou uma **imagem de contêiner** para usar, em qualquer caso, provavelmente seria **um único processo Uvicorn**, e o serviço de nuvem seria responsável por replicá-lo. -/// tip | "Dica" +/// tip | Dica Não se preocupe se alguns desses itens sobre **contêineres**, Docker ou Kubernetes ainda não fizerem muito sentido. @@ -261,7 +261,7 @@ E você terá que se certificar de que é um único processo executando essas et Claro, há alguns casos em que não há problema em executar as etapas anteriores várias vezes; nesse caso, é muito mais fácil de lidar. -/// tip | "Dica" +/// tip | Dica Além disso, tenha em mente que, dependendo da sua configuração, em alguns casos você **pode nem precisar de nenhuma etapa anterior** antes de iniciar sua aplicação. @@ -279,7 +279,7 @@ Aqui estão algumas ideias possíveis: * Um script bash que roda os passos anteriores e então inicia seu aplicativo * Você ainda precisaria de uma maneira de iniciar/reiniciar *aquele* script bash, detectar erros, etc. -/// tip | "Dica" +/// tip | Dica Darei exemplos mais concretos de como fazer isso com contêineres em um capítulo futuro: [FastAPI em contêineres - Docker](docker.md){.internal-link target=_blank}. diff --git a/docs/pt/docs/deployment/docker.md b/docs/pt/docs/deployment/docker.md index df93bac2c4707..cf18bb15325a8 100644 --- a/docs/pt/docs/deployment/docker.md +++ b/docs/pt/docs/deployment/docker.md @@ -4,7 +4,7 @@ Ao fazer o deploy de aplicações FastAPI uma abordagem comum é construir uma * Usando contêineres Linux você tem diversas vantagens incluindo **segurança**, **replicabilidade**, **simplicidade**, entre outras. -/// tip | "Dica" +/// tip | Dica Está com pressa e já sabe dessas coisas? Pode ir direto para [`Dockerfile` abaixo 👇](#construindo-uma-imagem-docker-para-fastapi). diff --git a/docs/pt/docs/deployment/https.md b/docs/pt/docs/deployment/https.md index 6ccc875fd4180..9a13977ec4a31 100644 --- a/docs/pt/docs/deployment/https.md +++ b/docs/pt/docs/deployment/https.md @@ -4,7 +4,7 @@ Mas é bem mais complexo do que isso. -/// tip | "Dica" +/// tip | Dica Se você está com pressa ou não se importa, continue com as seções seguintes para instruções passo a passo para configurar tudo com diferentes técnicas. diff --git a/docs/pt/docs/deployment/manually.md b/docs/pt/docs/deployment/manually.md index 9eff3daaa5254..237f4f8b946ec 100644 --- a/docs/pt/docs/deployment/manually.md +++ b/docs/pt/docs/deployment/manually.md @@ -102,7 +102,7 @@ $ pip install "uvicorn[standard]" Um processo semelhante se aplicaria a qualquer outro programa de servidor ASGI. -/// tip | "Dica" +/// tip | Dica Adicionando o `standard`, o Uvicorn instalará e usará algumas dependências extras recomendadas. @@ -126,7 +126,7 @@ $ uvicorn main:app --host 0.0.0.0 --port 80 -/// note | "Nota" +/// note | Nota O comando `uvicorn main:app` refere-se a: @@ -143,7 +143,7 @@ from main import app Cada programa de servidor ASGI alternativo teria um comando semelhante, você pode ler mais na documentação respectiva. -/// warning | "Aviso" +/// warning | Aviso Uvicorn e outros servidores suportam a opção `--reload` que é útil durante o desenvolvimento. diff --git a/docs/pt/docs/deployment/server-workers.md b/docs/pt/docs/deployment/server-workers.md index 0d6cd5b3985b7..63eda56b4e47c 100644 --- a/docs/pt/docs/deployment/server-workers.md +++ b/docs/pt/docs/deployment/server-workers.md @@ -17,7 +17,7 @@ Como você viu no capítulo anterior sobre [Conceitos de implantação](concepts Aqui mostrarei como usar o **Uvicorn** com **processos de trabalho** usando o comando `fastapi` ou o comando `uvicorn` diretamente. -/// info | "Informação" +/// info | Informação Se você estiver usando contêineres, por exemplo com Docker ou Kubernetes, falarei mais sobre isso no próximo capítulo: [FastAPI em contêineres - Docker](docker.md){.internal-link target=_blank}. diff --git a/docs/pt/docs/deployment/versions.md b/docs/pt/docs/deployment/versions.md index 79243a0146e76..323ddbd450066 100644 --- a/docs/pt/docs/deployment/versions.md +++ b/docs/pt/docs/deployment/versions.md @@ -42,7 +42,7 @@ Seguindo as convenções de controle de versão semântica, qualquer versão aba FastAPI também segue a convenção de que qualquer alteração de versão "PATCH" é para correção de bugs e alterações não significativas. -/// tip | "Dica" +/// tip | Dica O "PATCH" é o último número, por exemplo, em `0.2.3`, a versão PATCH é `3`. @@ -56,7 +56,7 @@ fastapi>=0.45.0,<0.46.0 Mudanças significativas e novos recursos são adicionados em versões "MINOR". -/// tip | "Dica" +/// tip | Dica O "MINOR" é o número que está no meio, por exemplo, em `0.2.3`, a versão MINOR é `2`. diff --git a/docs/pt/docs/environment-variables.md b/docs/pt/docs/environment-variables.md index 360d1c496bd49..432f78af04b63 100644 --- a/docs/pt/docs/environment-variables.md +++ b/docs/pt/docs/environment-variables.md @@ -1,6 +1,6 @@ # Variáveis de Ambiente -/// tip | "Dica" +/// tip | Dica Se você já sabe o que são "variáveis de ambiente" e como usá-las, pode pular esta seção. @@ -63,7 +63,7 @@ name = os.getenv("MY_NAME", "World") print(f"Hello {name} from Python") ``` -/// tip | "Dica" +/// tip | Dica O segundo argumento para `os.getenv()` é o valor padrão a ser retornado. @@ -151,7 +151,7 @@ Hello World from Python -/// tip | "Dica" +/// tip | Dica Você pode ler mais sobre isso em The Twelve-Factor App: Config. diff --git a/docs/pt/docs/help-fastapi.md b/docs/pt/docs/help-fastapi.md index 61eeac0dcf023..3d6e1f9d2e51a 100644 --- a/docs/pt/docs/help-fastapi.md +++ b/docs/pt/docs/help-fastapi.md @@ -109,7 +109,7 @@ Assim podendo tentar ajudar a resolver essas questões. Entre no 👥 server de conversa do Discord 👥 e conheça novas pessoas da comunidade do FastAPI. -/// tip | "Dica" +/// tip | Dica Para perguntas, pergunte nas questões do GitHub, lá tem um chance maior de você ser ajudado sobre o FastAPI [FastAPI Experts](fastapi-people.md#especialistas){.internal-link target=_blank}. diff --git a/docs/pt/docs/how-to/conditional-openapi.md b/docs/pt/docs/how-to/conditional-openapi.md index 675b812e6609d..6b44e9c81311d 100644 --- a/docs/pt/docs/how-to/conditional-openapi.md +++ b/docs/pt/docs/how-to/conditional-openapi.md @@ -29,9 +29,7 @@ Você pode usar facilmente as mesmas configurações do Pydantic para configurar Por exemplo: -```Python hl_lines="6 11" -{!../../docs_src/conditional_openapi/tutorial001.py!} -``` +{* ../../docs_src/conditional_openapi/tutorial001.py hl[6,11] *} Aqui declaramos a configuração `openapi_url` com o mesmo padrão de `"/openapi.json"`. diff --git a/docs/pt/docs/how-to/configure-swagger-ui.md b/docs/pt/docs/how-to/configure-swagger-ui.md index 58bb1557ca06d..915b2b5c5733e 100644 --- a/docs/pt/docs/how-to/configure-swagger-ui.md +++ b/docs/pt/docs/how-to/configure-swagger-ui.md @@ -18,9 +18,7 @@ Sem alterar as configurações, o destaque de sintaxe é habilitado por padrão: Mas você pode desabilitá-lo definindo `syntaxHighlight` como `False`: -```Python hl_lines="3" -{!../../docs_src/configure_swagger_ui/tutorial001.py!} -``` +{* ../../docs_src/configure_swagger_ui/tutorial001.py hl[3] *} ...e então o Swagger UI não mostrará mais o destaque de sintaxe: @@ -30,9 +28,7 @@ Mas você pode desabilitá-lo definindo `syntaxHighlight` como `False`: Da mesma forma que você pode definir o tema de destaque de sintaxe com a chave `"syntaxHighlight.theme"` (observe que há um ponto no meio): -```Python hl_lines="3" -{!../../docs_src/configure_swagger_ui/tutorial002.py!} -``` +{* ../../docs_src/configure_swagger_ui/tutorial002.py hl[3] *} Essa configuração alteraria o tema de cores de destaque de sintaxe: @@ -44,17 +40,13 @@ O FastAPI inclui alguns parâmetros de configuração padrão apropriados para a Inclui estas configurações padrão: -```Python -{!../../fastapi/openapi/docs.py[ln:7-23]!} -``` +{* ../../fastapi/openapi/docs.py ln[7:23] *} Você pode substituir qualquer um deles definindo um valor diferente no argumento `swagger_ui_parameters`. Por exemplo, para desabilitar `deepLinking` você pode passar essas configurações para `swagger_ui_parameters`: -```Python hl_lines="3" -{!../../docs_src/configure_swagger_ui/tutorial003.py!} -``` +{* ../../docs_src/configure_swagger_ui/tutorial003.py hl[3] *} ## Outros parâmetros da UI do Swagger diff --git a/docs/pt/docs/how-to/custom-docs-ui-assets.md b/docs/pt/docs/how-to/custom-docs-ui-assets.md index 00dd144c93f39..3adc7529e161d 100644 --- a/docs/pt/docs/how-to/custom-docs-ui-assets.md +++ b/docs/pt/docs/how-to/custom-docs-ui-assets.md @@ -18,9 +18,7 @@ O primeiro passo é desativar a documentação automática, pois por padrão, el Para desativá-los, defina suas URLs como `None` ao criar seu aplicativo `FastAPI`: -```Python hl_lines="8" -{!../../docs_src/custom_docs_ui/tutorial001.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial001.py hl[8] *} ### Incluir a documentação personalizada @@ -36,9 +34,7 @@ Você pode reutilizar as funções internas do FastAPI para criar as páginas HT E de forma semelhante para o ReDoc... -```Python hl_lines="2-6 11-19 22-24 27-33" -{!../../docs_src/custom_docs_ui/tutorial001.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial001.py hl[2:6,11:19,22:24,27:33] *} /// tip | Dica @@ -54,9 +50,7 @@ Swagger UI lidará com isso nos bastidores para você, mas ele precisa desse aux Agora, para poder testar se tudo funciona, crie uma *operação de rota*: -```Python hl_lines="36-38" -{!../../docs_src/custom_docs_ui/tutorial001.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial001.py hl[36:38] *} ### Teste @@ -124,9 +118,7 @@ Depois disso, sua estrutura de arquivos deve se parecer com: * Importe `StaticFiles`. * "Monte" a instância `StaticFiles()` em um caminho específico. -```Python hl_lines="7 11" -{!../../docs_src/custom_docs_ui/tutorial002.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[7,11] *} ### Teste os arquivos estáticos @@ -158,9 +150,7 @@ Da mesma forma que ao usar um CDN personalizado, o primeiro passo é desativar a Para desativá-los, defina suas URLs como `None` ao criar seu aplicativo `FastAPI`: -```Python hl_lines="9" -{!../../docs_src/custom_docs_ui/tutorial002.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[9] *} ### Incluir a documentação personalizada para arquivos estáticos @@ -176,9 +166,7 @@ Novamente, você pode reutilizar as funções internas do FastAPI para criar as E de forma semelhante para o ReDoc... -```Python hl_lines="2-6 14-22 25-27 30-36" -{!../../docs_src/custom_docs_ui/tutorial002.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[2:6,14:22,25:27,30:36] *} /// tip | Dica @@ -194,9 +182,7 @@ Swagger UI lidará com isso nos bastidores para você, mas ele precisa desse aux Agora, para poder testar se tudo funciona, crie uma *operação de rota*: -```Python hl_lines="39-41" -{!../../docs_src/custom_docs_ui/tutorial002.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[39:41] *} ### Teste a UI de Arquivos Estáticos diff --git a/docs/pt/docs/how-to/custom-request-and-route.md b/docs/pt/docs/how-to/custom-request-and-route.md index 64325eed91b2b..8f432f6fe8eaa 100644 --- a/docs/pt/docs/how-to/custom-request-and-route.md +++ b/docs/pt/docs/how-to/custom-request-and-route.md @@ -42,9 +42,7 @@ Se não houver `gzip` no cabeçalho, ele não tentará descomprimir o corpo. Dessa forma, a mesma classe de rota pode lidar com requisições comprimidas ou não comprimidas. -```Python hl_lines="8-15" -{!../../docs_src/custom_request_and_route/tutorial001.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial001.py hl[8:15] *} ### Criar uma classe `GzipRoute` personalizada @@ -56,9 +54,7 @@ Esse método retorna uma função. E essa função é o que irá receber uma req Aqui nós usamos para criar um `GzipRequest` a partir da requisição original. -```Python hl_lines="18-26" -{!../../docs_src/custom_request_and_route/tutorial001.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial001.py hl[18:26] *} /// note | Detalhes Técnicos @@ -96,26 +92,18 @@ Também podemos usar essa mesma abordagem para acessar o corpo da requisição e Tudo que precisamos fazer é manipular a requisição dentro de um bloco `try`/`except`: -```Python hl_lines="13 15" -{!../../docs_src/custom_request_and_route/tutorial002.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial002.py hl[13,15] *} Se uma exceção ocorrer, a instância `Request` ainda estará em escopo, então podemos ler e fazer uso do corpo da requisição ao lidar com o erro: -```Python hl_lines="16-18" -{!../../docs_src/custom_request_and_route/tutorial002.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial002.py hl[16:18] *} ## Classe `APIRoute` personalizada em um router você também pode definir o parametro `route_class` de uma `APIRouter`; -```Python hl_lines="26" -{!../../docs_src/custom_request_and_route/tutorial003.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial003.py hl[26] *} Nesse exemplo, as *operações de rota* sob o `router` irão usar a classe `TimedRoute` personalizada, e terão um cabeçalho extra `X-Response-Time` na resposta com o tempo que levou para gerar a resposta: -```Python hl_lines="13-20" -{!../../docs_src/custom_request_and_route/tutorial003.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial003.py hl[13:20] *} diff --git a/docs/pt/docs/how-to/extending-openapi.md b/docs/pt/docs/how-to/extending-openapi.md index 40917325b6086..b4785edc15286 100644 --- a/docs/pt/docs/how-to/extending-openapi.md +++ b/docs/pt/docs/how-to/extending-openapi.md @@ -1,4 +1,3 @@ - # Extendendo o OpenAPI Existem alguns casos em que pode ser necessário modificar o esquema OpenAPI gerado. @@ -44,25 +43,19 @@ Por exemplo, vamos adicionar documentação do Strawberry. @@ -49,7 +47,7 @@ Versões anteriores do Starlette incluiam uma classe `GraphQLApp` para integrar Ela foi descontinuada do Starlette, mas se você tem código que a utilizava, você pode facilmente **migrar** para starlette-graphene3, que cobre o mesmo caso de uso e tem uma **interface quase idêntica**. -/// tip | "Dica" +/// tip | Dica Se você precisa de GraphQL, eu ainda recomendaria que você desse uma olhada no Strawberry, pois ele é baseado em type annotations em vez de classes e tipos personalizados. diff --git a/docs/pt/docs/how-to/separate-openapi-schemas.md b/docs/pt/docs/how-to/separate-openapi-schemas.md index 50d321d4caee9..291b0e163927a 100644 --- a/docs/pt/docs/how-to/separate-openapi-schemas.md +++ b/docs/pt/docs/how-to/separate-openapi-schemas.md @@ -10,123 +10,13 @@ Vamos ver como isso funciona e como alterar se for necessário. Digamos que você tenha um modelo Pydantic com valores padrão, como este: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-7]!} - -# Code below omitted 👇 -``` - -
-👀 Visualização completa do arquivo - -```Python -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} -``` - -
- -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-9]!} - -# Code below omitted 👇 -``` - -
-👀 Visualização completa do arquivo - -```Python -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} -``` - -
- -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-9]!} - -# Code below omitted 👇 -``` - -
-👀 Visualização completa do arquivo - -```Python -{!> ../../docs_src/separate_openapi_schemas/tutorial001.py!} -``` - -
- -//// +{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:7] hl[7] *} ### Modelo para Entrada Se você usar esse modelo como entrada, como aqui: -//// tab | Python 3.10+ - -```Python hl_lines="14" -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-15]!} - -# Code below omitted 👇 -``` - -
-👀 Visualização completa do arquivo - -```Python -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} -``` - -
- -//// - -//// tab | Python 3.9+ - -```Python hl_lines="16" -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-17]!} - -# Code below omitted 👇 -``` - -
-👀 Visualização completa do arquivo - -```Python -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} -``` - -
- -//// - -//// tab | Python 3.8+ - -```Python hl_lines="16" -{!> ../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-17]!} - -# Code below omitted 👇 -``` - -
-👀 Visualização completa do arquivo - -```Python -{!> ../../docs_src/separate_openapi_schemas/tutorial001.py!} -``` - -
- -//// +{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:15] hl[14] *} ... então o campo `description` não será obrigatório. Porque ele tem um valor padrão de `None`. @@ -142,29 +32,7 @@ Você pode confirmar que na documentação, o campo `description` não tem um ** Mas se você usar o mesmo modelo como saída, como aqui: -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="21" -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="21" -{!> ../../docs_src/separate_openapi_schemas/tutorial001.py!} -``` - -//// +{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py hl[19] *} ... então, como `description` tem um valor padrão, se você **não retornar nada** para esse campo, ele ainda terá o **valor padrão**. @@ -223,29 +91,7 @@ O suporte para `separate_input_output_schemas` foi adicionado no FastAPI `0.102. /// -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/separate_openapi_schemas/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="12" -{!> ../../docs_src/separate_openapi_schemas/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="12" -{!> ../../docs_src/separate_openapi_schemas/tutorial002.py!} -``` - -//// +{* ../../docs_src/separate_openapi_schemas/tutorial002_py310.py hl[10] *} ### Mesmo Esquema para Modelos de Entrada e Saída na Documentação diff --git a/docs/pt/docs/python-types.md b/docs/pt/docs/python-types.md index a0938259fd4d2..90a361f4039df 100644 --- a/docs/pt/docs/python-types.md +++ b/docs/pt/docs/python-types.md @@ -22,9 +22,7 @@ Se você é um especialista em Python e já sabe tudo sobre type hints, pule par Vamos começar com um exemplo simples: -```Python -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py *} A chamada deste programa gera: @@ -38,9 +36,7 @@ A função faz o seguinte: * Converte a primeira letra de cada uma em maiúsculas com `title()`. * Concatena com um espaço no meio. -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py hl[2] *} ### Edite-o @@ -82,9 +78,7 @@ para: Esses são os "type hints": -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial002.py!} -``` +{* ../../docs_src/python_types/tutorial002.py hl[1] *} Isso não é o mesmo que declarar valores padrão como seria com: @@ -112,9 +106,7 @@ Com isso, você pode rolar, vendo as opções, até encontrar o que "soa familia Verifique esta função, ela já possui type hints: -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial003.py!} -``` +{* ../../docs_src/python_types/tutorial003.py hl[1] *} Como o editor conhece os tipos de variáveis, você não obtém apenas o preenchimento automático, mas também as verificações de erro: @@ -122,9 +114,7 @@ Como o editor conhece os tipos de variáveis, você não obtém apenas o preench Agora você sabe que precisa corrigí-lo, converta `age` em uma string com `str(age)`: -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial004.py!} -``` +{* ../../docs_src/python_types/tutorial004.py hl[2] *} ## Declarando Tipos @@ -143,9 +133,7 @@ Você pode usar, por exemplo: * `bool` * `bytes` -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial005.py!} -``` +{* ../../docs_src/python_types/tutorial005.py hl[1] *} ### Tipos genéricos com parâmetros de tipo @@ -321,7 +309,7 @@ Você pode declarar que um valor pode ter um tipo, como `str`, mas que ele tamb No Python 3.6 e superior (incluindo o Python 3.10) você pode declará-lo importando e utilizando `Optional` do módulo `typing`. -```Python hl_lines="1 4" +```Python hl_lines="1 4" {!../../docs_src/python_types/tutorial009.py!} ``` @@ -370,9 +358,7 @@ Isso é apenas sobre palavras e nomes. Mas estas palavras podem afetar como os s Por exemplo, vamos pegar esta função: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial009c.py!} -``` +{* ../../docs_src/python_types/tutorial009c.py hl[1,4] *} O paâmetro `name` é definido como `Optional[str]`, mas ele **não é opcional**, você não pode chamar a função sem o parâmetro: @@ -388,9 +374,7 @@ say_hi(name=None) # This works, None is valid 🎉 A boa notícia é, quando você estiver no Python 3.10 você não precisará se preocupar mais com isso, pois você poderá simplesmente utilizar o `|` para definir uniões de tipos: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial009c_py310.py!} -``` +{* ../../docs_src/python_types/tutorial009c_py310.py hl[1,4] *} E então você não precisará mais se preocupar com nomes como `Optional` e `Union`. 😎 @@ -452,15 +436,11 @@ Você também pode declarar uma classe como o tipo de uma variável. Digamos que você tenha uma classe `Person`, com um nome: -```Python hl_lines="1-3" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[1:3] *} Então você pode declarar que uma variável é do tipo `Person`: -```Python hl_lines="6" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[6] *} E então, novamente, você recebe todo o suporte do editor: diff --git a/docs/pt/docs/tutorial/background-tasks.md b/docs/pt/docs/tutorial/background-tasks.md index 2b5f824648f63..0f3796371e0e6 100644 --- a/docs/pt/docs/tutorial/background-tasks.md +++ b/docs/pt/docs/tutorial/background-tasks.md @@ -15,9 +15,7 @@ Isso inclui, por exemplo: Primeiro, importe `BackgroundTasks` e defina um parâmetro em sua _função de operação de caminho_ com uma declaração de tipo de `BackgroundTasks`: -```Python hl_lines="1 13" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *} O **FastAPI** criará o objeto do tipo `BackgroundTasks` para você e o passará como esse parâmetro. @@ -33,17 +31,13 @@ Nesse caso, a função de tarefa gravará em um arquivo (simulando o envio de um E como a operação de gravação não usa `async` e `await`, definimos a função com `def` normal: -```Python hl_lines="6-9" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *} ## Adicionar a tarefa em segundo plano Dentro de sua _função de operação de caminho_, passe sua função de tarefa para o objeto _tarefas em segundo plano_ com o método `.add_task()`: -```Python hl_lines="14" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[14] *} `.add_task()` recebe como argumentos: @@ -57,9 +51,7 @@ Usar `BackgroundTasks` também funciona com o sistema de injeção de dependênc O **FastAPI** sabe o que fazer em cada caso e como reutilizar o mesmo objeto, de forma que todas as tarefas em segundo plano sejam mescladas e executadas em segundo plano posteriormente: -```Python hl_lines="13 15 22 25" -{!../../docs_src/background_tasks/tutorial002.py!} -``` +{* ../../docs_src/background_tasks/tutorial002.py hl[13,15,22,25] *} Neste exemplo, as mensagens serão gravadas no arquivo `log.txt` _após_ o envio da resposta. @@ -85,8 +77,6 @@ Se você precisa realizar cálculos pesados ​​em segundo plano e não necess Eles tendem a exigir configurações mais complexas, um gerenciador de fila de mensagens/tarefas, como RabbitMQ ou Redis, mas permitem que você execute tarefas em segundo plano em vários processos e, especialmente, em vários servidores. -Para ver um exemplo, verifique os [Geradores de projeto](../project-generation.md){.internal-link target=\_blank}, todos incluem celery já configurado. - Mas se você precisa acessar variáveis ​​e objetos do mesmo aplicativo **FastAPI**, ou precisa realizar pequenas tarefas em segundo plano (como enviar uma notificação por e-mail), você pode simplesmente usar `BackgroundTasks`. ## Recapitulando diff --git a/docs/pt/docs/tutorial/bigger-applications.md b/docs/pt/docs/tutorial/bigger-applications.md index fcc30961f86f2..a094005fd714c 100644 --- a/docs/pt/docs/tutorial/bigger-applications.md +++ b/docs/pt/docs/tutorial/bigger-applications.md @@ -4,7 +4,7 @@ Se você está construindo uma aplicação ou uma API web, é raro que você pos **FastAPI** oferece uma ferramenta conveniente para estruturar sua aplicação, mantendo toda a flexibilidade. -/// info | "Informação" +/// info | Informação Se você vem do Flask, isso seria o equivalente aos Blueprints do Flask. @@ -29,7 +29,7 @@ Digamos que você tenha uma estrutura de arquivos como esta: │   └── admin.py ``` -/// tip | "Dica" +/// tip | Dica Existem vários arquivos `__init__.py` presentes em cada diretório ou subdiretório. @@ -105,7 +105,7 @@ Todas as mesmas opções são suportadas. Todos os mesmos `parameters`, `responses`, `dependencies`, `tags`, etc. -/// tip | "Dica" +/// tip | Dica Neste exemplo, a variável é chamada de `router`, mas você pode nomeá-la como quiser. @@ -139,7 +139,7 @@ Agora usaremos uma dependência simples para ler um cabeçalho `X-Token` persona //// tab | Python 3.8+ non-Annotated -/// tip | "Dica" +/// tip | Dica Prefira usar a versão `Annotated` se possível. @@ -151,7 +151,7 @@ Prefira usar a versão `Annotated` se possível. //// -/// tip | "Dica" +/// tip | Dica Estamos usando um cabeçalho inventado para simplificar este exemplo. @@ -201,7 +201,7 @@ Também podemos adicionar uma lista de `tags` e `responses` extras que serão ap E podemos adicionar uma lista de `dependencies` que serão adicionadas a todas as *operações de rota* no roteador e serão executadas/resolvidas para cada solicitação feita a elas. -/// tip | "Dica" +/// tip | Dica Observe que, assim como [dependências em *decoradores de operação de rota*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, nenhum valor será passado para sua *função de operação de rota*. @@ -222,7 +222,7 @@ O resultado final é que os caminhos dos itens agora são: * As dependências do roteador são executadas primeiro, depois as [`dependencies` no decorador](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank} e, em seguida, as dependências de parâmetros normais. * Você também pode adicionar [dependências de `Segurança` com `scopes`](../advanced/security/oauth2-scopes.md){.internal-link target=_blank}. -/// tip | "Dica" +/// tip | Dica Ter `dependências` no `APIRouter` pode ser usado, por exemplo, para exigir autenticação para um grupo inteiro de *operações de rota*. Mesmo que as dependências não sejam adicionadas individualmente a cada uma delas. @@ -248,7 +248,7 @@ Então usamos uma importação relativa com `..` para as dependências: #### Como funcionam as importações relativas -/// tip | "Dica" +/// tip | Dica Se você sabe perfeitamente como funcionam as importações, continue para a próxima seção abaixo. @@ -319,7 +319,7 @@ Mas ainda podemos adicionar _mais_ `tags` que serão aplicadas a uma *operação {!../../docs_src/bigger_applications/app/routers/items.py!} ``` -/// tip | "Dica" +/// tip | Dica Esta última operação de caminho terá a combinação de tags: `["items", "custom"]`. @@ -381,7 +381,7 @@ Também poderíamos importá-los como: from app.routers import items, users ``` -/// info | "Informação" +/// info | Informação A primeira versão é uma "importação relativa": @@ -428,7 +428,7 @@ Agora, vamos incluir os `roteadores` dos submódulos `usuários` e `itens`: {!../../docs_src/bigger_applications/app/main.py!} ``` -/// info | "Informação" +/// info | Informação `users.router` contém o `APIRouter` dentro do arquivo `app/routers/users.py`. @@ -440,7 +440,7 @@ Com `app.include_router()` podemos adicionar cada `APIRouter` ao aplicativo prin Ele incluirá todas as rotas daquele roteador como parte dele. -/// note | "Detalhe Técnico" +/// note | Detalhe Técnico Na verdade, ele criará internamente uma *operação de rota* para cada *operação de rota* que foi declarada no `APIRouter`. @@ -503,7 +503,7 @@ Aqui fazemos isso... só para mostrar que podemos 🤷: e funcionará corretamente, junto com todas as outras *operações de rota* adicionadas com `app.include_router()`. -/// info | "Detalhes Técnicos" +/// info | Detalhes Técnicos **Observação**: este é um detalhe muito técnico que você provavelmente pode **simplesmente pular**. diff --git a/docs/pt/docs/tutorial/body-fields.md b/docs/pt/docs/tutorial/body-fields.md index ab9377fdb2698..e7dfb07f2abd5 100644 --- a/docs/pt/docs/tutorial/body-fields.md +++ b/docs/pt/docs/tutorial/body-fields.md @@ -6,11 +6,9 @@ Da mesma forma que você pode declarar validações adicionais e metadados nos p Primeiro, você tem que importá-lo: -```Python hl_lines="4" -{!../../docs_src/body_fields/tutorial001.py!} -``` +{* ../../docs_src/body_fields/tutorial001.py hl[4] *} -/// warning | "Aviso" +/// warning | Aviso Note que `Field` é importado diretamente do `pydantic`, não do `fastapi` como todo o resto (`Query`, `Path`, `Body`, etc). @@ -20,13 +18,11 @@ Note que `Field` é importado diretamente do `pydantic`, não do `fastapi` como Você pode então utilizar `Field` com atributos do modelo: -```Python hl_lines="11-14" -{!../../docs_src/body_fields/tutorial001.py!} -``` +{* ../../docs_src/body_fields/tutorial001.py hl[11:14] *} `Field` funciona da mesma forma que `Query`, `Path` e `Body`, ele possui todos os mesmos parâmetros, etc. -/// note | "Detalhes técnicos" +/// note | Detalhes técnicos Na realidade, `Query`, `Path` e outros que você verá em seguida, criam objetos de subclasses de uma classe `Param` comum, que é ela mesma uma subclasse da classe `FieldInfo` do Pydantic. @@ -38,7 +34,7 @@ Lembre-se que quando você importa `Query`, `Path`, e outros de `fastapi`, esse /// -/// tip | "Dica" +/// tip | Dica Note como cada atributo do modelo com um tipo, valor padrão e `Field` possuem a mesma estrutura que parâmetros de *funções de operações de rota*, com `Field` ao invés de `Path`, `Query` e `Body`. diff --git a/docs/pt/docs/tutorial/body-multiple-params.md b/docs/pt/docs/tutorial/body-multiple-params.md index 400813a7b94c8..eda9b4dfffa54 100644 --- a/docs/pt/docs/tutorial/body-multiple-params.md +++ b/docs/pt/docs/tutorial/body-multiple-params.md @@ -8,23 +8,9 @@ Primeiro, é claro, você pode misturar `Path`, `Query` e declarações de parâ E você também pode declarar parâmetros de corpo como opcionais, definindo o valor padrão com `None`: -//// tab | Python 3.10+ +{* ../../docs_src/body_multiple_params/tutorial001_py310.py hl[17:19] *} -```Python hl_lines="17-19" -{!> ../../docs_src/body_multiple_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="19-21" -{!> ../../docs_src/body_multiple_params/tutorial001.py!} -``` - -//// - -/// note | "Nota" +/// note | Nota Repare que, neste caso, o `item` que seria capturado a partir do corpo é opcional. Visto que ele possui `None` como valor padrão. @@ -45,21 +31,7 @@ No exemplo anterior, as *operações de rota* esperariam um JSON no corpo conten Mas você pode também declarar múltiplos parâmetros de corpo, por exemplo, `item` e `user`: -//// tab | Python 3.10+ - -```Python hl_lines="20" -{!> ../../docs_src/body_multiple_params/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="22" -{!> ../../docs_src/body_multiple_params/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial002_py310.py hl[20] *} Neste caso, o **FastAPI** perceberá que existe mais de um parâmetro de corpo na função (dois parâmetros que são modelos Pydantic). @@ -80,7 +52,7 @@ Então, ele usará o nome dos parâmetros como chaves (nome dos campos) no corpo } ``` -/// note | "Nota" +/// note | Nota Repare que mesmo que o `item` esteja declarado da mesma maneira que antes, agora é esperado que ele esteja dentro do corpo com uma chave `item`. @@ -100,21 +72,7 @@ Se você declará-lo como é, porque é um valor singular, o **FastAPI** assumir Mas você pode instruir o **FastAPI** para tratá-lo como outra chave do corpo usando `Body`: -//// tab | Python 3.8+ - -```Python hl_lines="22" -{!> ../../docs_src/body_multiple_params/tutorial003.py!} -``` - -//// - -//// tab | Python 3.10+ - -```Python hl_lines="20" -{!> ../../docs_src/body_multiple_params/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial003.py hl[22] *} Neste caso, o **FastAPI** esperará um corpo como: @@ -154,23 +112,9 @@ q: str | None = None Por exemplo: -//// tab | Python 3.10+ - -```Python hl_lines="26" -{!> ../../docs_src/body_multiple_params/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="27" -{!> ../../docs_src/body_multiple_params/tutorial004.py!} -``` +{* ../../docs_src/body_multiple_params/tutorial004_py310.py hl[26] *} -//// - -/// info | "Informação" +/// info | Informação `Body` também possui todas as validações adicionais e metadados de parâmetros como em `Query`,`Path` e outras que você verá depois. @@ -190,21 +134,7 @@ item: Item = Body(embed=True) como em: -//// tab | Python 3.10+ - -```Python hl_lines="15" -{!> ../../docs_src/body_multiple_params/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17" -{!> ../../docs_src/body_multiple_params/tutorial005.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial005_py310.py hl[15] *} Neste caso o **FastAPI** esperará um corpo como: diff --git a/docs/pt/docs/tutorial/body-nested-models.md b/docs/pt/docs/tutorial/body-nested-models.md index 3aa79d563f5a3..2954ae3db39f4 100644 --- a/docs/pt/docs/tutorial/body-nested-models.md +++ b/docs/pt/docs/tutorial/body-nested-models.md @@ -6,9 +6,7 @@ Com o **FastAPI**, você pode definir, validar, documentar e usar modelos profun Você pode definir um atributo como um subtipo. Por exemplo, uma `list` do Python: -```Python hl_lines="14" -{!../../docs_src/body_nested_models/tutorial001.py!} -``` +{* ../../docs_src/body_nested_models/tutorial001.py hl[14] *} Isso fará com que tags seja uma lista de itens mesmo sem declarar o tipo dos elementos desta lista. @@ -20,9 +18,7 @@ Mas o Python tem uma maneira específica de declarar listas com tipos internos o Primeiramente, importe `List` do módulo `typing` que já vem por padrão no Python: -```Python hl_lines="1" -{!../../docs_src/body_nested_models/tutorial002.py!} -``` +{* ../../docs_src/body_nested_models/tutorial002.py hl[1] *} ### Declare a `List` com um parâmetro de tipo @@ -44,9 +40,7 @@ Use a mesma sintaxe padrão para atributos de modelo com tipos internos. Portanto, em nosso exemplo, podemos fazer com que `tags` sejam especificamente uma "lista de strings": -```Python hl_lines="14" -{!../../docs_src/body_nested_models/tutorial002.py!} -``` +{* ../../docs_src/body_nested_models/tutorial002.py hl[14] *} ## Tipo "set" @@ -58,9 +52,7 @@ E que o Python tem um tipo de dados especial para conjuntos de itens únicos, o Então podemos importar `Set` e declarar `tags` como um `set` de `str`s: -```Python hl_lines="1 14" -{!../../docs_src/body_nested_models/tutorial003.py!} -``` +{* ../../docs_src/body_nested_models/tutorial003.py hl[1,14] *} Com isso, mesmo que você receba uma requisição contendo dados duplicados, ela será convertida em um conjunto de itens exclusivos. @@ -82,17 +74,13 @@ Tudo isso, aninhado arbitrariamente. Por exemplo, nós podemos definir um modelo `Image`: -```Python hl_lines="9-11" -{!../../docs_src/body_nested_models/tutorial004.py!} -``` +{* ../../docs_src/body_nested_models/tutorial004.py hl[9:11] *} ### Use o sub-modelo como um tipo E então podemos usa-lo como o tipo de um atributo: -```Python hl_lines="20" -{!../../docs_src/body_nested_models/tutorial004.py!} -``` +{* ../../docs_src/body_nested_models/tutorial004.py hl[20] *} Isso significa que o **FastAPI** vai esperar um corpo similar à: @@ -125,9 +113,7 @@ Para ver todas as opções possíveis, cheque a documentação para os ../../../docs_src/body_updates/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="30-35" -{!> ../../../docs_src/body_updates/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="30-35" -{!> ../../../docs_src/body_updates/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial001_py310.py hl[28:33] *} `PUT` é usado para receber dados que devem substituir os dados existentes. @@ -84,29 +62,7 @@ Isso gera um `dict` com apenas os dados definidos ao criar o modelo `item`, excl Então, você pode usar isso para gerar um `dict` com apenas os dados definidos (enviados na solicitação), omitindo valores padrão: -//// tab | Python 3.10+ - -```Python hl_lines="32" -{!> ../../../docs_src/body_updates/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="34" -{!> ../../../docs_src/body_updates/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="34" -{!> ../../../docs_src/body_updates/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial002_py310.py hl[32] *} ### Usando o parâmetro `update` do Pydantic @@ -122,29 +78,7 @@ Os exemplos aqui usam `.copy()` para compatibilidade com o Pydantic v1, mas voc Como `stored_item_model.model_copy(update=update_data)`: -//// tab | Python 3.10+ - -```Python hl_lines="33" -{!> ../../../docs_src/body_updates/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="35" -{!> ../../../docs_src/body_updates/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="35" -{!> ../../../docs_src/body_updates/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial002_py310.py hl[33] *} ### Recapitulando as atualizações parciais @@ -161,29 +95,7 @@ Resumindo, para aplicar atualizações parciais você pode: * Salvar os dados no seu banco de dados. * Retornar o modelo atualizado. -//// tab | Python 3.10+ - -```Python hl_lines="28-35" -{!> ../../../docs_src/body_updates/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="30-37" -{!> ../../../docs_src/body_updates/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="30-37" -{!> ../../../docs_src/body_updates/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial002_py310.py hl[28:35] *} /// tip | Dica diff --git a/docs/pt/docs/tutorial/body.md b/docs/pt/docs/tutorial/body.md index 429e4fd5ac6ea..2508d7981b73b 100644 --- a/docs/pt/docs/tutorial/body.md +++ b/docs/pt/docs/tutorial/body.md @@ -8,7 +8,7 @@ Sua API quase sempre irá enviar um corpo na **resposta**. Mas os clientes não Para declarar um corpo da **requisição**, você utiliza os modelos do Pydantic com todos os seus poderes e benefícios. -/// info | "Informação" +/// info | Informação Para enviar dados, você deve usar utilizar um dos métodos: `POST` (Mais comum), `PUT`, `DELETE` ou `PATCH`. @@ -22,9 +22,7 @@ Como é desencorajado, a documentação interativa com Swagger UI não irá most Primeiro, você precisa importar `BaseModel` do `pydantic`: -```Python hl_lines="4" -{!../../docs_src/body/tutorial001.py!} -``` +{* ../../docs_src/body/tutorial001.py hl[4] *} ## Crie seu modelo de dados @@ -32,9 +30,7 @@ Então você declara seu modelo de dados como uma classe que herda `BaseModel`. Utilize os tipos Python padrão para todos os atributos: -```Python hl_lines="7-11" -{!../../docs_src/body/tutorial001.py!} -``` +{* ../../docs_src/body/tutorial001.py hl[7:11] *} Assim como quando declaramos parâmetros de consulta, quando um atributo do modelo possui um valor padrão, ele se torna opcional. Caso contrário, se torna obrigatório. Use `None` para torná-lo opcional. @@ -62,9 +58,7 @@ Por exemplo, o modelo acima declara um JSON "`object`" (ou `dict` no Python) com Para adicionar o corpo na *função de operação de rota*, declare-o da mesma maneira que você declarou parâmetros de rota e consulta: -```Python hl_lines="18" -{!../../docs_src/body/tutorial001.py!} -``` +{* ../../docs_src/body/tutorial001.py hl[18] *} ...E declare o tipo como o modelo que você criou, `Item`. @@ -113,7 +107,7 @@ Mas você terá o mesmo suporte do editor no -/// tip | "Dica" +/// tip | Dica Se você utiliza o PyCharm como editor, você pode utilizar o Plugin do Pydantic para o PyCharm . @@ -131,9 +125,7 @@ Melhora o suporte do editor para seus modelos Pydantic com:: Dentro da função, você pode acessar todos os atributos do objeto do modelo diretamente: -```Python hl_lines="21" -{!../../docs_src/body/tutorial002.py!} -``` +{* ../../docs_src/body/tutorial002.py hl[21] *} ## Corpo da requisição + parâmetros de rota @@ -141,9 +133,7 @@ Você pode declarar parâmetros de rota e corpo da requisição ao mesmo tempo. O **FastAPI** irá reconhecer que os parâmetros da função que combinam com parâmetros de rota devem ser **retirados da rota**, e parâmetros da função que são declarados como modelos Pydantic sejam **retirados do corpo da requisição**. -```Python hl_lines="17-18" -{!../../docs_src/body/tutorial003.py!} -``` +{* ../../docs_src/body/tutorial003.py hl[17:18] *} ## Corpo da requisição + parâmetros de rota + parâmetros de consulta @@ -151,9 +141,7 @@ Você também pode declarar parâmetros de **corpo**, **rota** e **consulta**, a O **FastAPI** irá reconhecer cada um deles e retirar a informação do local correto. -```Python hl_lines="18" -{!../../docs_src/body/tutorial004.py!} -``` +{* ../../docs_src/body/tutorial004.py hl[18] *} Os parâmetros da função serão reconhecidos conforme abaixo: @@ -161,7 +149,7 @@ Os parâmetros da função serão reconhecidos conforme abaixo: * Se o parâmetro é de um **tipo único** (como `int`, `float`, `str`, `bool`, etc) será interpretado como um parâmetro de **consulta**. * Se o parâmetro é declarado como um **modelo Pydantic**, será interpretado como o **corpo** da requisição. -/// note | "Observação" +/// note | Observação O FastAPI saberá que o valor de `q` não é obrigatório por causa do valor padrão `= None`. diff --git a/docs/pt/docs/tutorial/cookie-param-models.md b/docs/pt/docs/tutorial/cookie-param-models.md index 671e0d74f24e8..3d46ba44cb899 100644 --- a/docs/pt/docs/tutorial/cookie-param-models.md +++ b/docs/pt/docs/tutorial/cookie-param-models.md @@ -20,57 +20,7 @@ Essa mesma técnica se aplica para `Query`, `Cookie`, e `Header`. 😎 Declare o parâmetro de **cookie** que você precisa em um **modelo Pydantic**, e depois declare o parâmetro como um `Cookie`: -//// tab | Python 3.10+ - -```Python hl_lines="9-12 16" -{!> ../../docs_src/cookie_param_models/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9-12 16" -{!> ../../docs_src/cookie_param_models/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10-13 17" -{!> ../../docs_src/cookie_param_models/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="7-10 14" -{!> ../../docs_src/cookie_param_models/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="9-12 16" -{!> ../../docs_src/cookie_param_models/tutorial001.py!} -``` - -//// +{* ../../docs_src/cookie_param_models/tutorial001_an_py310.py hl[9:12,16] *} O **FastAPI** irá **extrair** os dados para **cada campo** dos **cookies** recebidos na requisição e lhe fornecer o modelo Pydantic que você definiu. @@ -102,35 +52,7 @@ Agora a sua API possui o poder de contrar o seu próprio ../../docs_src/cookie_param_models/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/cookie_param_models/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/cookie_param_models/tutorial002.py!} -``` - -//// +{* ../../docs_src/cookie_param_models/tutorial002_an_py39.py hl[10] *} Se o cliente tentar enviar alguns **cookies extras**, eles receberão um retorno de **erro**. diff --git a/docs/pt/docs/tutorial/cookie-params.md b/docs/pt/docs/tutorial/cookie-params.md index 50bec8cf7f3ec..da85d796ea3bf 100644 --- a/docs/pt/docs/tutorial/cookie-params.md +++ b/docs/pt/docs/tutorial/cookie-params.md @@ -6,57 +6,7 @@ Você pode definir parâmetros de Cookie da mesma maneira que define paramêtros Primeiro importe `Cookie`: -//// tab | Python 3.10+ - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/cookie_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[3] *} ## Declare parâmetros de `Cookie` @@ -65,57 +15,7 @@ Então declare os paramêtros de cookie usando a mesma estrutura que em `Path` e Você pode definir o valor padrão, assim como todas as validações extras ou parâmetros de anotação: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/cookie_params/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/cookie_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[9] *} /// note | Detalhes Técnicos diff --git a/docs/pt/docs/tutorial/cors.md b/docs/pt/docs/tutorial/cors.md index 16c4e9bf5dca1..0ab07a3c210b0 100644 --- a/docs/pt/docs/tutorial/cors.md +++ b/docs/pt/docs/tutorial/cors.md @@ -46,9 +46,7 @@ Você também pode especificar se o seu backend permite: * Métodos HTTP específicos (`POST`, `PUT`) ou todos eles com o curinga `"*"`. * Cabeçalhos HTTP específicos ou todos eles com o curinga `"*"`. -```Python hl_lines="2 6-11 13-19" -{!../../docs_src/cors/tutorial001.py!} -``` +{* ../../docs_src/cors/tutorial001.py hl[2,6:11,13:19] *} Os parâmetros padrão usados ​​pela implementação `CORSMiddleware` são restritivos por padrão, então você precisará habilitar explicitamente as origens, métodos ou cabeçalhos específicos para que os navegadores tenham permissão para usá-los em um contexto de domínios diferentes. @@ -78,7 +76,7 @@ Qualquer solicitação com um cabeçalho `Origin`. Neste caso, o middleware pass Para mais informações CORS, acesse Mozilla CORS documentation. -/// note | "Detalhes técnicos" +/// note | Detalhes técnicos Você também pode usar `from starlette.middleware.cors import CORSMiddleware`. diff --git a/docs/pt/docs/tutorial/debugging.md b/docs/pt/docs/tutorial/debugging.md index 6bac7eb85e451..67b7644577e92 100644 --- a/docs/pt/docs/tutorial/debugging.md +++ b/docs/pt/docs/tutorial/debugging.md @@ -6,9 +6,7 @@ Você pode conectar o depurador no seu editor, por exemplo, com o Visual Studio Em seu aplicativo FastAPI, importe e execute `uvicorn` diretamente: -```Python hl_lines="1 15" -{!../../docs_src/debugging/tutorial001.py!} -``` +{* ../../docs_src/debugging/tutorial001.py hl[1,15] *} ### Sobre `__name__ == "__main__"` @@ -74,7 +72,7 @@ Então, a linha: não será executada. -/// info | "Informação" +/// info | Informação Para mais informações, consulte a documentação oficial do Python. diff --git a/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md index 179bfefb52209..ef67aa979e944 100644 --- a/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md @@ -6,57 +6,7 @@ Antes de nos aprofundarmos no sistema de **Injeção de Dependência**, vamos me No exemplo anterior, nós retornávamos um `dict` da nossa dependência ("injetável"): -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="11" -{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="12" -{!> ../../docs_src/dependencies/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | "Dica" - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | "Dica" - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="11" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[9] *} Mas assim obtemos um `dict` como valor do parâmetro `commons` na *função de operação de rota*. @@ -119,165 +69,15 @@ Isso também se aplica a objetos chamáveis que não recebem nenhum parâmetro. Então, podemos mudar o "injetável" na dependência `common_parameters` acima para a classe `CommonQueryParams`: -//// tab | Python 3.10+ - -```Python hl_lines="11-15" -{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="11-15" -{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="12-16" -{!> ../../docs_src/dependencies/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | "Dica" - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="9-13" -{!> ../../docs_src/dependencies/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | "Dica" - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="11-15" -{!> ../../docs_src/dependencies/tutorial002.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[11:15] *} Observe o método `__init__` usado para criar uma instância da classe: -//// tab | Python 3.10+ - -```Python hl_lines="12" -{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="12" -{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="13" -{!> ../../docs_src/dependencies/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | "Dica" - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/dependencies/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | "Dica" - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="12" -{!> ../../docs_src/dependencies/tutorial002.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[12] *} ...ele possui os mesmos parâmetros que nosso `common_parameters` anterior: -//// tab | Python 3.10+ - -```Python hl_lines="8" -{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/dependencies/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | "Dica" - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="6" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | "Dica" - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8] *} Esses parâmetros são utilizados pelo **FastAPI** para "definir" a dependência. @@ -293,57 +93,7 @@ Os dados serão convertidos, validados, documentados no esquema da OpenAPI e etc Agora você pode declarar sua dependência utilizando essa classe. -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20" -{!> ../../docs_src/dependencies/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | "Dica" - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | "Dica" - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial002.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[19] *} O **FastAPI** chama a classe `CommonQueryParams`. Isso cria uma "instância" dessa classe e é a instância que será passada para o parâmetro `commons` na sua função. @@ -361,7 +111,7 @@ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] //// tab | Python 3.8+ non-Annotated -/// tip | "Dica" +/// tip | Dica Utilize a versão com `Annotated` se possível. @@ -397,7 +147,7 @@ commons: Annotated[CommonQueryParams, ... //// tab | Python 3.8+ non-Annotated -/// tip | "Dica" +/// tip | Dica Utilize a versão com `Annotated` se possível. @@ -423,7 +173,7 @@ commons: Annotated[Any, Depends(CommonQueryParams)] //// tab | Python 3.8+ non-Annotated -/// tip | "Dica" +/// tip | Dica Utilize a versão com `Annotated` se possível. @@ -437,57 +187,7 @@ commons = Depends(CommonQueryParams) ...como em: -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20" -{!> ../../docs_src/dependencies/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | "Dica" - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | "Dica" - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial003.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial003_an_py310.py hl[19] *} Mas declarar o tipo é encorajado por que é a forma que o seu editor de texto sabe o que será passado como valor do parâmetro `commons`. @@ -507,7 +207,7 @@ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] //// tab | Python 3.8+ non-Annotated -/// tip | "Dica" +/// tip | Dica Utilize a versão com `Annotated` se possível. @@ -535,7 +235,7 @@ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] //// tab | Python 3.8+ non-Annotated -/// tip | "Dica" +/// tip | Dica Utilize a versão com `Annotated` se possível. @@ -559,7 +259,7 @@ commons: Annotated[CommonQueryParams, Depends()] //// tab | Python 3.8 non-Annotated -/// tip | "Dica" +/// tip | Dica Utilize a versão com `Annotated` se possível. @@ -575,61 +275,11 @@ Você declara a dependência como o tipo do parâmetro, e utiliza `Depends()` se O mesmo exemplo ficaria então dessa forma: -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20" -{!> ../../docs_src/dependencies/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | "Dica" - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | "Dica" - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial004.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial004_an_py310.py hl[19] *} ...e o **FastAPI** saberá o que fazer. -/// tip | "Dica" +/// tip | Dica Se isso parece mais confuso do que útil, não utilize, você não *precisa* disso. diff --git a/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index 7d70869456fb4..d7d31bb45e9cb 100644 --- a/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -14,39 +14,11 @@ O *decorador da operação de rota* recebe um argumento opcional `dependencies`. Ele deve ser uma lista de `Depends()`: -//// tab | Python 3.9+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18" -{!> ../../docs_src/dependencies/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8 non-Annotated - -/// tip | "Dica" - -Utilize a versão com `Annotated` se possível - -/// - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial006.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[19] *} Essas dependências serão executadas/resolvidas da mesma forma que dependências comuns. Mas o valor delas (se existir algum) não será passado para a sua *função de operação de rota*. -/// tip | "Dica" +/// tip | Dica Alguns editores de texto checam parâmetros de funções não utilizados, e os mostram como erros. @@ -56,7 +28,7 @@ Isso também pode ser útil para evitar confundir novos desenvolvedores que ao v /// -/// info | "Informação" +/// info | Informação Neste exemplo utilizamos cabeçalhos personalizados inventados `X-Keys` e `X-Token`. @@ -72,69 +44,13 @@ Você pode utilizar as mesmas *funções* de dependências que você usaria norm Dependências podem declarar requisitos de requisições (como cabeçalhos) ou outras subdependências: -//// tab | Python 3.9+ - -```Python hl_lines="8 13" -{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="7 12" -{!> ../../docs_src/dependencies/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8 non-Annotated - -/// tip | "Dica" - -Utilize a versão com `Annotated` se possível - -/// - -```Python hl_lines="6 11" -{!> ../../docs_src/dependencies/tutorial006.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[8,13] *} ### Levantando exceções Essas dependências podem levantar exceções, da mesma forma que dependências comuns: -//// tab | Python 3.9+ - -```Python hl_lines="10 15" -{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 14" -{!> ../../docs_src/dependencies/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8 non-Annotated - -/// tip | "Dica" - -Utilize a versão com `Annotated` se possível - -/// - -```Python hl_lines="8 13" -{!> ../../docs_src/dependencies/tutorial006.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[10,15] *} ### Valores de retorno @@ -142,37 +58,7 @@ E elas também podem ou não retornar valores, eles não serão utilizados. Então, você pode reutilizar uma dependência comum (que retorna um valor) que já seja utilizada em outro lugar, e mesmo que o valor não seja utilizado, a dependência será executada: -//// tab | Python 3.9+ - -```Python hl_lines="11 16" -{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10 15" -{!> ../../docs_src/dependencies/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8 non-Annotated - -/// tip | "Dica" - - - -/// - - Utilize a versão com `Annotated` se possível - -```Python hl_lines="9 14" -{!> ../../docs_src/dependencies/tutorial006.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[11,16] *} ## Dependências para um grupo de *operações de rota* diff --git a/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md index d90bebe397bb6..eaf711197f3ad 100644 --- a/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md @@ -4,13 +4,13 @@ O FastAPI possui suporte para dependências que realizam . @@ -43,7 +41,7 @@ Mas se você tiver cabeçalhos personalizados desejando que um cliente em um nav /// -/// note | "Detalhes técnicos" +/// note | Detalhes técnicos Você também pode usar `from starlette.requests import Request`. @@ -59,9 +57,7 @@ E também depois que a `response` é gerada, antes de retorná-la. Por exemplo, você pode adicionar um cabeçalho personalizado `X-Process-Time` contendo o tempo em segundos que levou para processar a solicitação e gerar uma resposta: -```Python hl_lines="10 12-13" -{!../../docs_src/middleware/tutorial001.py!} -``` +{* ../../docs_src/middleware/tutorial001.py hl[10,12:13] *} ## Outros middlewares diff --git a/docs/pt/docs/tutorial/path-operation-configuration.md b/docs/pt/docs/tutorial/path-operation-configuration.md index 48753d7259b4f..f183c9d23b75c 100644 --- a/docs/pt/docs/tutorial/path-operation-configuration.md +++ b/docs/pt/docs/tutorial/path-operation-configuration.md @@ -2,7 +2,7 @@ Existem vários parâmetros que você pode passar para o seu *decorador de operação de rota* para configurá-lo. -/// warning | "Aviso" +/// warning | Aviso Observe que esses parâmetros são passados diretamente para o *decorador de operação de rota*, não para a sua *função de operação de rota*. @@ -16,33 +16,11 @@ Você pode passar diretamente o código `int`, como `404`. Mas se você não se lembrar o que cada código numérico significa, pode usar as constantes de atalho em `status`: -//// tab | Python 3.8 and above - -```Python hl_lines="3 17" -{!> ../../docs_src/path_operation_configuration/tutorial001.py!} -``` - -//// - -//// tab | Python 3.9 and above - -```Python hl_lines="3 17" -{!> ../../docs_src/path_operation_configuration/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.10 and above - -```Python hl_lines="1 15" -{!> ../../docs_src/path_operation_configuration/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial001.py hl[3,17] *} Esse código de status será usado na resposta e será adicionado ao esquema OpenAPI. -/// note | "Detalhes Técnicos" +/// note | Detalhes Técnicos Você também poderia usar `from starlette import status`. @@ -54,29 +32,7 @@ Você também poderia usar `from starlette import status`. Você pode adicionar tags para sua *operação de rota*, passe o parâmetro `tags` com uma `list` de `str` (comumente apenas um `str`): -//// tab | Python 3.8 and above - -```Python hl_lines="17 22 27" -{!> ../../docs_src/path_operation_configuration/tutorial002.py!} -``` - -//// - -//// tab | Python 3.9 and above - -```Python hl_lines="17 22 27" -{!> ../../docs_src/path_operation_configuration/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.10 and above - -```Python hl_lines="15 20 25" -{!> ../../docs_src/path_operation_configuration/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial002.py hl[17,22,27] *} Eles serão adicionados ao esquema OpenAPI e usados pelas interfaces de documentação automática: @@ -90,37 +46,13 @@ Nestes casos, pode fazer sentido armazenar as tags em um `Enum`. **FastAPI** suporta isso da mesma maneira que com strings simples: -```Python hl_lines="1 8-10 13 18" -{!../../docs_src/path_operation_configuration/tutorial002b.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial002b.py hl[1,8:10,13,18] *} ## Resumo e descrição Você pode adicionar um `summary` e uma `description`: -//// tab | Python 3.8 and above - -```Python hl_lines="20-21" -{!> ../../docs_src/path_operation_configuration/tutorial003.py!} -``` - -//// - -//// tab | Python 3.9 and above - -```Python hl_lines="20-21" -{!> ../../docs_src/path_operation_configuration/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.10 and above - -```Python hl_lines="18-19" -{!> ../../docs_src/path_operation_configuration/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial003.py hl[20:21] *} ## Descrição do docstring @@ -128,29 +60,7 @@ Como as descrições tendem a ser longas e cobrir várias linhas, você pode dec Você pode escrever Markdown na docstring, ele será interpretado e exibido corretamente (levando em conta a indentação da docstring). -//// tab | Python 3.8 and above - -```Python hl_lines="19-27" -{!> ../../docs_src/path_operation_configuration/tutorial004.py!} -``` - -//// - -//// tab | Python 3.9 and above - -```Python hl_lines="19-27" -{!> ../../docs_src/path_operation_configuration/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.10 and above - -```Python hl_lines="17-25" -{!> ../../docs_src/path_operation_configuration/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial004.py hl[19:27] *} Ela será usada nas documentações interativas: @@ -161,31 +71,9 @@ Ela será usada nas documentações interativas: Você pode especificar a descrição da resposta com o parâmetro `response_description`: -//// tab | Python 3.8 and above - -```Python hl_lines="21" -{!> ../../docs_src/path_operation_configuration/tutorial005.py!} -``` - -//// - -//// tab | Python 3.9 and above - -```Python hl_lines="21" -{!> ../../docs_src/path_operation_configuration/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.10 and above - -```Python hl_lines="19" -{!> ../../docs_src/path_operation_configuration/tutorial005_py310.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial005.py hl[21] *} -/// info | "Informação" +/// info | Informação Note que `response_description` se refere especificamente à resposta, a `description` se refere à *operação de rota* em geral. @@ -205,9 +93,7 @@ Então, se você não fornecer uma, o **FastAPI** irá gerar automaticamente uma Se você precisar marcar uma *operação de rota* como descontinuada, mas sem removê-la, passe o parâmetro `deprecated`: -```Python hl_lines="16" -{!../../docs_src/path_operation_configuration/tutorial006.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial006.py hl[16] *} Ela será claramente marcada como descontinuada nas documentações interativas: diff --git a/docs/pt/docs/tutorial/path-params-numeric-validations.md b/docs/pt/docs/tutorial/path-params-numeric-validations.md index 28c55482f7ff6..3aea1188ddba8 100644 --- a/docs/pt/docs/tutorial/path-params-numeric-validations.md +++ b/docs/pt/docs/tutorial/path-params-numeric-validations.md @@ -6,21 +6,7 @@ Do mesmo modo que você pode declarar mais validações e metadados para parâme Primeiro, importe `Path` de `fastapi`: -//// tab | Python 3.10+ - -```Python hl_lines="1" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3" -{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial001_py310.py hl[1] *} ## Declare metadados @@ -28,23 +14,9 @@ Você pode declarar todos os parâmetros da mesma maneira que na `Query`. Por exemplo para declarar um valor de metadado `title` para o parâmetro de rota `item_id` você pode digitar: -//// tab | Python 3.10+ - -```Python hl_lines="8" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial001_py310.py hl[8] *} -/// note | "Nota" +/// note | Nota Um parâmetro de rota é sempre obrigatório, como se fizesse parte da rota. @@ -70,9 +42,7 @@ Isso não faz diferença para o **FastAPI**. Ele vai detectar os parâmetros pel Então, você pode declarar sua função assim: -```Python hl_lines="7" -{!../../docs_src/path_params_numeric_validations/tutorial002.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial002.py hl[7] *} ## Ordene os parâmetros de a acordo com sua necessidade, truques @@ -82,9 +52,7 @@ Passe `*`, como o primeiro parâmetro da função. O Python não vai fazer nada com esse `*`, mas ele vai saber que a partir dali os parâmetros seguintes deverão ser chamados argumentos nomeados (pares chave-valor), também conhecidos como kwargs. Mesmo que eles não possuam um valor padrão. -```Python hl_lines="7" -{!../../docs_src/path_params_numeric_validations/tutorial003.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *} ## Validações numéricas: maior que ou igual @@ -92,9 +60,7 @@ Com `Query` e `Path` (e outras que você verá mais tarde) você pode declarar r Aqui, com `ge=1`, `item_id` precisará ser um número inteiro maior que ("`g`reater than") ou igual ("`e`qual") a 1. -```Python hl_lines="8" -{!../../docs_src/path_params_numeric_validations/tutorial004.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial004.py hl[8] *} ## Validações numéricas: maior que e menor que ou igual @@ -103,9 +69,7 @@ O mesmo se aplica para: * `gt`: maior que (`g`reater `t`han) * `le`: menor que ou igual (`l`ess than or `e`qual) -```Python hl_lines="9" -{!../../docs_src/path_params_numeric_validations/tutorial005.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial005.py hl[9] *} ## Validações numéricas: valores do tipo float, maior que e menor que @@ -117,9 +81,7 @@ Assim, `0.5` seria um valor válido. Mas `0.0` ou `0` não seria. E o mesmo para lt. -```Python hl_lines="11" -{!../../docs_src/path_params_numeric_validations/tutorial006.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial006.py hl[11] *} ## Recapitulando @@ -132,7 +94,7 @@ E você também pode declarar validações numéricas: * `lt`: menor que (`l`ess `t`han) * `le`: menor que ou igual (`l`ess than or `e`qual) -/// info | "Informação" +/// info | Informação `Query`, `Path` e outras classes que você verá a frente são subclasses de uma classe comum `Param`. @@ -140,7 +102,7 @@ Todas elas compartilham os mesmos parâmetros para validação adicional e metad /// -/// note | "Detalhes Técnicos" +/// note | Detalhes Técnicos Quando você importa `Query`, `Path` e outras de `fastapi`, elas são na verdade funções. diff --git a/docs/pt/docs/tutorial/path-params.md b/docs/pt/docs/tutorial/path-params.md index a68354a1bc52e..ecf77d676d7ce 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,11 @@ Então, se você rodar este exemplo e for até http://127.0.0.1:8000/items/4.2 -/// check | "Verifique" +/// check | Verifique @@ -91,7 +87,7 @@ Quando você abrir o seu navegador em -/// check | "Verifique" +/// check | Verifique @@ -129,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"`. @@ -147,17 +141,15 @@ 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" +/// info | informação Enumerations (ou enums) estão disponíveis no Python desde a versão 3.4. /// -/// tip | "Dica" +/// tip | Dica @@ -169,9 +161,7 @@ Assim, crie atributos de classe com valores fixos, que serão os valores válido 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 @@ -187,19 +177,15 @@ 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 @@ -213,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: @@ -254,11 +238,9 @@ 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 diff --git a/docs/pt/docs/tutorial/query-param-models.md b/docs/pt/docs/tutorial/query-param-models.md index 854183fb4065d..01a6e462f1b7c 100644 --- a/docs/pt/docs/tutorial/query-param-models.md +++ b/docs/pt/docs/tutorial/query-param-models.md @@ -14,71 +14,7 @@ Isso é suportado desde o FastAPI versão `0.115.0`. 🤓 Declare os **parâmetros de consulta** que você precisa em um **modelo Pydantic**, e então declare o parâmetro como `Query`: -//// tab | Python 3.10+ - -```Python hl_lines="9-13 17" -{!> ../../docs_src/query_param_models/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="8-12 16" -{!> ../../docs_src/query_param_models/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10-14 18" -{!> ../../docs_src/query_param_models/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="9-13 17" -{!> ../../docs_src/query_param_models/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="8-12 16" -{!> ../../docs_src/query_param_models/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="9-13 17" -{!> ../../docs_src/query_param_models/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/query_param_models/tutorial001_an_py310.py hl[9:13,17] *} O **FastAPI** **extrairá** os dados para **cada campo** dos **parâmetros de consulta** presentes na requisição, e fornecerá o modelo Pydantic que você definiu. @@ -97,71 +33,7 @@ Em alguns casos especiais (provavelmente não muito comuns), você queira **rest Você pode usar a configuração do modelo Pydantic para `forbid` (proibir) qualquer campo `extra`: -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/query_param_models/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_param_models/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/query_param_models/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/query_param_models/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_param_models/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="11" -{!> ../../docs_src/query_param_models/tutorial002.py!} -``` - -//// +{* ../../docs_src/query_param_models/tutorial002_an_py310.py hl[10] *} Caso um cliente tente enviar alguns dados **extras** nos **parâmetros de consulta**, eles receberão um retorno de **erro**. diff --git a/docs/pt/docs/tutorial/query-params-str-validations.md b/docs/pt/docs/tutorial/query-params-str-validations.md index e6dcf748e85e0..8c4f2e655eae7 100644 --- a/docs/pt/docs/tutorial/query-params-str-validations.md +++ b/docs/pt/docs/tutorial/query-params-str-validations.md @@ -4,13 +4,11 @@ O **FastAPI** permite que você declare informações adicionais e validações Vamos utilizar essa aplicação como exemplo: -```Python hl_lines="9" -{!../../docs_src/query_params_str_validations/tutorial001.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial001.py hl[9] *} O parâmetro de consulta `q` é do tipo `Union[str, None]`, o que significa que é do tipo `str` mas que também pode ser `None`, e de fato, o valor padrão é `None`, então o FastAPI saberá que não é obrigatório. -/// note | "Observação" +/// note | Observação O FastAPI saberá que o valor de `q` não é obrigatório por causa do valor padrão `= None`. @@ -26,17 +24,13 @@ Nós iremos forçar que mesmo o parâmetro `q` seja opcional, sempre que informa Para isso, primeiro importe `Query` de `fastapi`: -```Python hl_lines="3" -{!../../docs_src/query_params_str_validations/tutorial002.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial002.py hl[3] *} ## Use `Query` como o valor padrão Agora utilize-o como valor padrão do seu parâmetro, definindo o parâmetro `max_length` para 50: -```Python hl_lines="9" -{!../../docs_src/query_params_str_validations/tutorial002.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial002.py hl[9] *} Note que substituímos o valor padrão de `None` para `Query(default=None)`, o primeiro parâmetro de `Query` serve para o mesmo propósito: definir o valor padrão do parâmetro. @@ -54,7 +48,7 @@ q: Union[str, None] = None Mas o declara explicitamente como um parâmetro de consulta. -/// info | "Informação" +/// info | Informação Tenha em mente que o FastAPI se preocupa com a parte: @@ -86,17 +80,13 @@ Isso irá validar os dados, mostrar um erro claro quando os dados forem inválid Você também pode incluir um parâmetro `min_length`: -```Python hl_lines="10" -{!../../docs_src/query_params_str_validations/tutorial003.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial003.py hl[10] *} ## Adicionando expressões regulares Você pode definir uma expressão regular que combine com um padrão esperado pelo parâmetro: -```Python hl_lines="11" -{!../../docs_src/query_params_str_validations/tutorial004.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial004.py hl[11] *} Essa expressão regular específica verifica se o valor recebido no parâmetro: @@ -114,11 +104,9 @@ Da mesma maneira que você utiliza `None` como o primeiro argumento para ser uti Vamos dizer que você queira que o parâmetro de consulta `q` tenha um `min_length` de `3`, e um valor padrão de `"fixedquery"`, então declararíamos assim: -```Python hl_lines="7" -{!../../docs_src/query_params_str_validations/tutorial005.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial005.py hl[7] *} -/// note | "Observação" +/// note | Observação O parâmetro torna-se opcional quando possui um valor padrão. @@ -146,11 +134,9 @@ q: Union[str, None] = Query(default=None, min_length=3) Então, quando você precisa declarar um parâmetro obrigatório utilizando o `Query`, você pode utilizar `...` como o primeiro argumento: -```Python hl_lines="7" -{!../../docs_src/query_params_str_validations/tutorial006.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial006.py hl[7] *} -/// info | "Informação" +/// info | Informação Se você nunca viu os `...` antes: é um valor único especial, faz parte do Python e é chamado "Ellipsis". @@ -164,9 +150,7 @@ Quando você declara explicitamente um parâmetro com `Query` você pode declar Por exemplo, para declarar que o parâmetro `q` pode aparecer diversas vezes na URL, você escreveria: -```Python hl_lines="9" -{!../../docs_src/query_params_str_validations/tutorial011.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial011.py hl[9] *} Então, com uma URL assim: @@ -187,7 +171,7 @@ Assim, a resposta para essa URL seria: } ``` -/// tip | "Dica" +/// tip | Dica Para declarar um parâmetro de consulta com o tipo `list`, como no exemplo acima, você precisa usar explicitamente o `Query`, caso contrário será interpretado como um corpo da requisição. @@ -201,9 +185,7 @@ A documentação interativa da API irá atualizar de acordo, permitindo múltipl E você também pode definir uma lista (`list`) de valores padrão caso nenhum seja informado: -```Python hl_lines="9" -{!../../docs_src/query_params_str_validations/tutorial012.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial012.py hl[9] *} Se você for até: @@ -226,11 +208,9 @@ O valor padrão de `q` será: `["foo", "bar"]` e sua resposta será: Você também pode utilizar o tipo `list` diretamente em vez de `List[str]`: -```Python hl_lines="7" -{!../../docs_src/query_params_str_validations/tutorial013.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial013.py hl[7] *} -/// note | "Observação" +/// note | Observação Tenha em mente que neste caso, o FastAPI não irá validar os conteúdos da lista. @@ -244,7 +224,7 @@ Você pode adicionar mais informações sobre o parâmetro. Essa informações serão inclusas no esquema do OpenAPI e utilizado pela documentação interativa e ferramentas externas. -/// note | "Observação" +/// note | Observação Tenha em mente que cada ferramenta oferece diferentes níveis de suporte ao OpenAPI. @@ -254,15 +234,11 @@ Algumas delas não exibem todas as informações extras que declaramos, ainda qu Você pode adicionar um `title`: -```Python hl_lines="10" -{!../../docs_src/query_params_str_validations/tutorial007.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial007.py hl[10] *} E uma `description`: -```Python hl_lines="13" -{!../../docs_src/query_params_str_validations/tutorial008.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial008.py hl[13] *} ## Apelidos (alias) de parâmetros @@ -282,9 +258,7 @@ Mas ainda você precisa que o nome seja exatamente `item-query`... Então você pode declarar um `alias`, e esse apelido (alias) que será utilizado para encontrar o valor do parâmetro: -```Python hl_lines="9" -{!../../docs_src/query_params_str_validations/tutorial009.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial009.py hl[9] *} ## Parâmetros descontinuados @@ -294,9 +268,7 @@ Você tem que deixá-lo ativo por um tempo, já que existem clientes o utilizand Então você passa o parâmetro `deprecated=True` para `Query`: -```Python hl_lines="18" -{!../../docs_src/query_params_str_validations/tutorial010.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial010.py hl[18] *} Na documentação aparecerá assim: diff --git a/docs/pt/docs/tutorial/query-params.md b/docs/pt/docs/tutorial/query-params.md index 6e6699cd53609..8199de5af920c 100644 --- a/docs/pt/docs/tutorial/query-params.md +++ b/docs/pt/docs/tutorial/query-params.md @@ -2,9 +2,7 @@ Quando você declara outros parâmetros na função que não fazem parte dos parâmetros da rota, esses parâmetros são automaticamente interpretados como parâmetros de "consulta". -```Python hl_lines="9" -{!../../docs_src/query_params/tutorial001.py!} -``` +{* ../../docs_src/query_params/tutorial001.py hl[9] *} A consulta é o conjunto de pares chave-valor que vai depois de `?` na URL, separado pelo caractere `&`. @@ -63,25 +61,11 @@ Os valores dos parâmetros na sua função serão: Da mesma forma, você pode declarar parâmetros de consulta opcionais, definindo o valor padrão para `None`: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/query_params/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params/tutorial002.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial002_py310.py hl[7] *} Nesse caso, o parâmetro da função `q` será opcional, e `None` será o padrão. -/// check | "Verificar" +/// check | Verificar Você também pode notar que o **FastAPI** é esperto o suficiente para perceber que o parâmetro da rota `item_id` é um parâmetro da rota, e `q` não é, portanto, `q` é o parâmetro de consulta. @@ -91,21 +75,7 @@ Você também pode notar que o **FastAPI** é esperto o suficiente para perceber Você também pode declarar tipos `bool`, e eles serão convertidos: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/query_params/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params/tutorial003.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial003_py310.py hl[7] *} Nesse caso, se você for para: @@ -147,21 +117,7 @@ E você não precisa declarar eles em nenhuma ordem específica. Eles serão detectados pelo nome: -//// tab | Python 3.10+ - -```Python hl_lines="6 8" -{!> ../../docs_src/query_params/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8 10" -{!> ../../docs_src/query_params/tutorial004.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial004_py310.py hl[6,8] *} ## Parâmetros de consulta obrigatórios @@ -171,9 +127,7 @@ Caso você não queira adicionar um valor específico mas queira apenas torná-l Porém, quando você quiser fazer com que o parâmetro de consulta seja obrigatório, você pode simplesmente não declarar nenhum valor como padrão. -```Python hl_lines="6-7" -{!../../docs_src/query_params/tutorial005.py!} -``` +{* ../../docs_src/query_params/tutorial005.py hl[6:7] *} Aqui o parâmetro de consulta `needy` é um valor obrigatório, do tipo `str`. @@ -217,21 +171,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy E claro, você pode definir alguns parâmetros como obrigatórios, alguns possuindo um valor padrão, e outros sendo totalmente opcionais: -//// tab | Python 3.10+ - -```Python hl_lines="8" -{!> ../../docs_src/query_params/tutorial006_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params/tutorial006.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial006_py310.py hl[8] *} Nesse caso, existem 3 parâmetros de consulta: @@ -239,7 +179,7 @@ Nesse caso, existem 3 parâmetros de consulta: * `skip`, um `int` com o valor padrão `0`. * `limit`, um `int` opcional. -/// tip | "Dica" +/// tip | Dica Você também poderia usar `Enum` da mesma forma que com [Path Parameters](path-params.md#valores-predefinidos){.internal-link target=_blank}. diff --git a/docs/pt/docs/tutorial/request-files.md b/docs/pt/docs/tutorial/request-files.md new file mode 100644 index 0000000000000..c22c1c5133edb --- /dev/null +++ b/docs/pt/docs/tutorial/request-files.md @@ -0,0 +1,176 @@ +# Arquivos de Requisição + +Você pode definir arquivos para serem enviados pelo cliente usando `File`. + +/// info | Informação + +Para receber arquivos enviados, primeiro instale o `python-multipart`. + +Garanta que você criou um [ambiente virtual](../virtual-environments.md){.internal-link target=_blank}, o ativou e então o instalou, por exemplo: + +```console +$ pip install python-multipart +``` + +Isso é necessário, visto que os arquivos enviados são enviados como "dados de formulário". + +/// + +## Importe `File` + +Importe `File` e `UploadFile` de `fastapi`: + +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[3] *} + +## Definir Parâmetros `File` + +Crie parâmetros de arquivo da mesma forma que você faria para `Body` ou `Form`: + +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[9] *} + +/// info | Informação + +`File` é uma classe que herda diretamente de `Form`. + +Mas lembre-se que quando você importa `Query`, `Path`, `File` e outros de `fastapi`, eles são, na verdade, funções que retornam classes especiais. + +/// + +/// tip | Dica + +Para declarar corpos de arquivos, você precisa usar `File`, caso contrário, os parâmetros seriam interpretados como parâmetros de consulta ou parâmetros de corpo (JSON). + +/// + +Os arquivos serão enviados como "dados de formulário". + +Se você declarar o tipo do parâmetro da função da sua *operação de rota* como `bytes`, o **FastAPI** lerá o arquivo para você e você receberá o conteúdo como `bytes`. + +Mantenha em mente que isso significa que todo o conteúdo será armazenado na memória. Isso funcionará bem para arquivos pequenos. + +Mas há muitos casos em que você pode se beneficiar do uso de `UploadFile`. + +## Parâmetros de Arquivo com `UploadFile` + +Defina um parâmetro de arquivo com um tipo de `UploadFile`: + +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[14] *} + +Utilizar `UploadFile` tem várias vantagens sobre `bytes`: + +* Você não precisa utilizar o `File()` no valor padrão do parâmetro. +* Ele utiliza um arquivo "spooled": + * Um arquivo armazenado na memória até um limite máximo de tamanho, e após passar esse limite, ele será armazenado no disco. +* Isso significa que funcionará bem para arquivos grandes como imagens, vídeos, binários grandes, etc., sem consumir toda a memória. +* Você pode receber metadados do arquivo enviado. +* Ele tem uma file-like interface `assíncrona`. +* Ele expõe um objeto python `SpooledTemporaryFile` que você pode passar diretamente para outras bibliotecas que esperam um objeto semelhante a um arquivo("file-like"). + +### `UploadFile` + +`UploadFile` tem os seguintes atributos: + +* `filename`: Uma `str` com o nome do arquivo original que foi enviado (por exemplo, `myimage.jpg`). +* `content_type`: Uma `str` com o tipo de conteúdo (tipo MIME / tipo de mídia) (por exemplo, `image/jpeg`). +* `file`: Um `SpooledTemporaryFile` (um file-like objeto). Este é o objeto de arquivo Python que você pode passar diretamente para outras funções ou bibliotecas que esperam um objeto semelhante a um arquivo("file-like"). + +`UploadFile` tem os seguintes métodos `assíncronos`. Todos eles chamam os métodos de arquivo correspondentes por baixo dos panos (usando o `SpooledTemporaryFile` interno). + +* `write(data)`: Escreve `data` (`str` ou `bytes`) no arquivo. +* `read(size)`: Lê `size` (`int`) bytes/caracteres do arquivo. +* `seek(offset)`: Vai para o byte na posição `offset` (`int`) no arquivo. + * Por exemplo, `await myfile.seek(0)` irá para o início do arquivo. + * Isso é especialmente útil se você executar `await myfile.read()` uma vez e precisar ler o conteúdo novamente. +* `close()`: Fecha o arquivo. + +Como todos esses métodos são métodos `assíncronos`, você precisa "aguardar" por eles. + +Por exemplo, dentro de uma função de *operação de rota* `assíncrona`, você pode obter o conteúdo com: + +```Python +contents = await myfile.read() +``` + +Se você estiver dentro de uma função de *operação de rota* normal `def`, você pode acessar o `UploadFile.file` diretamente, por exemplo: + +```Python +contents = myfile.file.read() +``` + +/// note | Detalhes Técnicos do `async` + +Quando você usa os métodos `async`, o **FastAPI** executa os métodos de arquivo em um threadpool e aguarda por eles. + +/// + +/// note | Detalhes Técnicos do Starlette + +O `UploadFile` do ***FastAPI** herda diretamente do `UploadFile` do **Starlette** , mas adiciona algumas partes necessárias para torná-lo compatível com o **Pydantic** e as outras partes do FastAPI. + +/// + +## O que é "Form Data" + +O jeito que os formulários HTML (`
`) enviam os dados para o servidor normalmente usa uma codificação "especial" para esses dados, a qual é diferente do JSON. + +**FastAPI** se certificará de ler esses dados do lugar certo, ao invés de JSON. + +/// note | Detalhes Técnicos + +Dados de formulários normalmente são codificados usando o "media type" (tipo de mídia) `application/x-www-form-urlencoded` quando não incluem arquivos. + +Mas quando o formulário inclui arquivos, ele é codificado como `multipart/form-data`. Se você usar `File`, o **FastAPI** saberá que tem que pegar os arquivos da parte correta do corpo da requisição. + +Se você quiser ler mais sobre essas codificações e campos de formulário, vá para a MDN web docs para POST. + +/// + +/// warning | Aviso + +Você pode declarar múltiplos parâmetros `File` e `Form` em uma *operação de rota*, mas você não pode declarar campos `Body` que você espera receber como JSON, pois a requisição terá o corpo codificado usando `multipart/form-data` ao invés de `application/json`. + +Isso não é uma limitação do **FastAPI**, é parte do protocolo HTTP. + +/// + +## Upload de Arquivo Opcional + +Você pode tornar um arquivo opcional usando anotações de tipo padrão e definindo um valor padrão de `None`: + +{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *} + +## `UploadFile` com Metadados Adicionais + +Você também pode usar `File()` com `UploadFile`, por exemplo, para definir metadados adicionais: + +{* ../../docs_src/request_files/tutorial001_03_an_py39.py hl[9,15] *} + +## Uploads de Múltiplos Arquivos + +É possível realizar o upload de vários arquivos ao mesmo tempo. + +Eles serão associados ao mesmo "campo de formulário" enviado usando "dados de formulário". + +Para usar isso, declare uma lista de `bytes` ou `UploadFile`: + +{* ../../docs_src/request_files/tutorial002_an_py39.py hl[10,15] *} + +Você receberá, tal como declarado, uma `list` de `bytes` ou `UploadFile`. + +/// note | Detalhes Técnicos + +Você pode também pode usar `from starlette.responses import HTMLResponse`. + +**FastAPI** providencia o mesmo `starlette.responses` que `fastapi.responses` apenas como uma conveniência para você, o desenvolvedor. Mas a maioria das respostas disponíveis vem diretamente do Starlette. + +/// + +### Uploads de Múltiplos Arquivos com Metadados Adicionais + +Da mesma forma de antes, você pode usar `File()` para definir parâmetros adicionais, mesmo para `UploadFile`: + +{* ../../docs_src/request_files/tutorial003_an_py39.py hl[11,18:20] *} + +## Recapitulando + +Utilize `File`, `bytes` e `UploadFile` para declarar arquivos a serem enviados na requisição, enviados como dados de formulário. diff --git a/docs/pt/docs/tutorial/request-form-models.md b/docs/pt/docs/tutorial/request-form-models.md index 837e24c3420b7..ea0e63d381b31 100644 --- a/docs/pt/docs/tutorial/request-form-models.md +++ b/docs/pt/docs/tutorial/request-form-models.md @@ -2,7 +2,7 @@ Você pode utilizar **Modelos Pydantic** para declarar **campos de formulários** no FastAPI. -/// info | "Informação" +/// info | Informação Para utilizar formulários, instale primeiramente o `python-multipart`. @@ -14,7 +14,7 @@ $ pip install python-multipart /// -/// note | "Nota" +/// note | Nota Isto é suportado desde a versão `0.113.0` do FastAPI. 🤓 @@ -24,35 +24,7 @@ Isto é suportado desde a versão `0.113.0` do FastAPI. 🤓 Você precisa apenas declarar um **modelo Pydantic** com os campos que deseja receber como **campos de formulários**, e então declarar o parâmetro como um `Form`: -//// tab | Python 3.9+ - -```Python hl_lines="9-11 15" -{!> ../../docs_src/request_form_models/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8-10 14" -{!> ../../docs_src/request_form_models/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | "Dica" - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="7-9 13" -{!> ../../docs_src/request_form_models/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_form_models/tutorial001_an_py39.py hl[9:11,15] *} O **FastAPI** irá **extrair** as informações para **cada campo** dos **dados do formulário** na requisição e dar para você o modelo Pydantic que você definiu. @@ -68,7 +40,7 @@ Você pode verificar na UI de documentação em `/docs`: Em alguns casos de uso especiais (provavelmente não muito comum), você pode desejar **restringir** os campos do formulário para aceitar apenas os declarados no modelo Pydantic. E **proibir** qualquer campo **extra**. -/// note | "Nota" +/// note | Nota Isso é suportado deste a versão `0.114.0` do FastAPI. 🤓 @@ -76,35 +48,7 @@ Isso é suportado deste a versão `0.114.0` do FastAPI. 🤓 Você pode utilizar a configuração de modelo do Pydantic para `proibir` qualquer campo `extra`: -//// tab | Python 3.9+ - -```Python hl_lines="12" -{!> ../../docs_src/request_form_models/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/request_form_models/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/request_form_models/tutorial002.py!} -``` - -//// +{* ../../docs_src/request_form_models/tutorial002_an_py39.py hl[12] *} Caso um cliente tente enviar informações adicionais, ele receberá um retorno de **erro**. diff --git a/docs/pt/docs/tutorial/request-forms-and-files.md b/docs/pt/docs/tutorial/request-forms-and-files.md index 29488b4f26ef7..b08d8701324d8 100644 --- a/docs/pt/docs/tutorial/request-forms-and-files.md +++ b/docs/pt/docs/tutorial/request-forms-and-files.md @@ -2,7 +2,7 @@ Você pode definir arquivos e campos de formulário ao mesmo tempo usando `File` e `Form`. -/// info | "Informação" +/// info | Informação Para receber arquivos carregados e/ou dados de formulário, primeiro instale `python-multipart`. @@ -12,23 +12,19 @@ Por exemplo: `pip install python-multipart`. ## Importe `File` e `Form` -```Python hl_lines="1" -{!../../docs_src/request_forms_and_files/tutorial001.py!} -``` +{* ../../docs_src/request_forms_and_files/tutorial001.py hl[1] *} ## Defina parâmetros de `File` e `Form` Crie parâmetros de arquivo e formulário da mesma forma que você faria para `Body` ou `Query`: -```Python hl_lines="8" -{!../../docs_src/request_forms_and_files/tutorial001.py!} -``` +{* ../../docs_src/request_forms_and_files/tutorial001.py hl[8] *} Os arquivos e campos de formulário serão carregados como dados de formulário e você receberá os arquivos e campos de formulário. E você pode declarar alguns dos arquivos como `bytes` e alguns como `UploadFile`. -/// warning | "Aviso" +/// warning | Aviso Você pode declarar vários parâmetros `File` e `Form` em uma *operação de caminho*, mas não é possível declarar campos `Body` para receber como JSON, pois a requisição terá o corpo codificado usando `multipart/form-data` ao invés de `application/json`. diff --git a/docs/pt/docs/tutorial/request-forms.md b/docs/pt/docs/tutorial/request-forms.md index 1e2faf269b8d2..756ceb5816f2a 100644 --- a/docs/pt/docs/tutorial/request-forms.md +++ b/docs/pt/docs/tutorial/request-forms.md @@ -2,7 +2,7 @@ Quando você precisar receber campos de formulário ao invés de JSON, você pode usar `Form`. -/// info | "Informação" +/// info | Informação Para usar formulários, primeiro instale `python-multipart`. @@ -14,17 +14,13 @@ Ex: `pip install python-multipart`. Importe `Form` de `fastapi`: -```Python hl_lines="1" -{!../../docs_src/request_forms/tutorial001.py!} -``` +{* ../../docs_src/request_forms/tutorial001.py hl[1] *} ## Declare parâmetros de `Form` Crie parâmetros de formulário da mesma forma que você faria para `Body` ou `Query`: -```Python hl_lines="7" -{!../../docs_src/request_forms/tutorial001.py!} -``` +{* ../../docs_src/request_forms/tutorial001.py hl[7] *} Por exemplo, em uma das maneiras que a especificação OAuth2 pode ser usada (chamada "fluxo de senha"), é necessário enviar um `username` e uma `password` como campos do formulário. @@ -32,13 +28,13 @@ A spec exige que os campos sejam exatamente Com `Form` você pode declarar os mesmos metadados e validação que com `Body` (e `Query`, `Path`, `Cookie`). -/// info | "Informação" +/// info | Informação `Form` é uma classe que herda diretamente de `Body`. /// -/// tip | "Dica" +/// tip | Dica Para declarar corpos de formulário, você precisa usar `Form` explicitamente, porque sem ele os parâmetros seriam interpretados como parâmetros de consulta ou parâmetros de corpo (JSON). @@ -50,7 +46,7 @@ A forma como os formulários HTML (`
`) enviam os dados para o servi O **FastAPI** fará a leitura desses dados no lugar certo em vez de JSON. -/// note | "Detalhes técnicos" +/// note | Detalhes técnicos Os dados dos formulários são normalmente codificados usando o "tipo de mídia" `application/x-www-form-urlencoded`. @@ -60,7 +56,7 @@ Se você quiser ler mais sobre essas codificações e campos de formulário, vá /// -/// warning | "Aviso" +/// warning | Aviso Você pode declarar vários parâmetros `Form` em uma *operação de caminho*, mas não pode declarar campos `Body` que espera receber como JSON, pois a solicitação terá o corpo codificado usando `application/x-www- form-urlencoded` em vez de `application/json`. diff --git a/docs/pt/docs/tutorial/request_files.md b/docs/pt/docs/tutorial/request_files.md index 39bfe284a7809..15c1ad825a565 100644 --- a/docs/pt/docs/tutorial/request_files.md +++ b/docs/pt/docs/tutorial/request_files.md @@ -16,69 +16,13 @@ Isso se deve por que arquivos enviados são enviados como "dados de formulário" Importe `File` e `UploadFile` do `fastapi`: -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/request_files/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1" -{!> ../../docs_src/request_files/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/request_files/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[3] *} ## Defina os parâmetros de `File` Cria os parâmetros do arquivo da mesma forma que você faria para `Body` ou `Form`: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/request_files/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/request_files/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/request_files/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[9] *} /// info | Informação @@ -106,35 +50,7 @@ Mas existem vários casos em que você pode se beneficiar ao usar `UploadFile`. Defina um parâmetro de arquivo com o tipo `UploadFile` -//// tab | Python 3.9+ - -```Python hl_lines="14" -{!> ../../docs_src/request_files/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="13" -{!> ../../docs_src/request_files/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="12" -{!> ../../docs_src/request_files/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[14] *} Utilizando `UploadFile` tem várias vantagens sobre `bytes`: @@ -217,91 +133,13 @@ Isso não é uma limitação do **FastAPI**, é uma parte do protocolo HTTP. Você pode definir um arquivo como opcional utilizando as anotações de tipo padrão e definindo o valor padrão como `None`: -//// tab | Python 3.10+ - -```Python hl_lines="9 17" -{!> ../../docs_src/request_files/tutorial001_02_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9 17" -{!> ../../docs_src/request_files/tutorial001_02_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10 18" -{!> ../../docs_src/request_files/tutorial001_02_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated`, se possível - -/// - -```Python hl_lines="7 15" -{!> ../../docs_src/request_files/tutorial001_02_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated`, se possível - -/// - -```Python hl_lines="9 17" -{!> ../../docs_src/request_files/tutorial001_02.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *} ## `UploadFile` com Metadados Adicionais Você também pode utilizar `File()` com `UploadFile`, por exemplo, para definir metadados adicionais: -//// tab | Python 3.9+ - -```Python hl_lines="9 15" -{!> ../../docs_src/request_files/tutorial001_03_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8 14" -{!> ../../docs_src/request_files/tutorial001_03_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível - -/// - -```Python hl_lines="7 13" -{!> ../../docs_src/request_files/tutorial001_03.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_03_an_py39.py hl[9,15] *} ## Envio de Múltiplos Arquivos @@ -311,49 +149,7 @@ Ele ficam associados ao mesmo "campo do formulário" enviado com "form data". Para usar isso, declare uma lista de `bytes` ou `UploadFile`: -//// tab | Python 3.9+ - -```Python hl_lines="10 15" -{!> ../../docs_src/request_files/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11 16" -{!> ../../docs_src/request_files/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível - -/// - -```Python hl_lines="8 13" -{!> ../../docs_src/request_files/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível - -/// - -```Python hl_lines="10 15" -{!> ../../docs_src/request_files/tutorial002.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial002_an_py39.py hl[10,15] *} Você irá receber, como delcarado uma lista (`list`) de `bytes` ou `UploadFile`s, @@ -369,49 +165,7 @@ O **FastAPI** fornece as mesmas `starlette.responses` como `fastapi.responses` a E da mesma forma que antes, você pode utilizar `File()` para definir parâmetros adicionais, até mesmo para `UploadFile`: -//// tab | Python 3.9+ - -```Python hl_lines="11 18-20" -{!> ../../docs_src/request_files/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="12 19-21" -{!> ../../docs_src/request_files/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="9 16" -{!> ../../docs_src/request_files/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="11 18" -{!> ../../docs_src/request_files/tutorial003.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial003_an_py39.py hl[11,18:20] *} ## Recapitulando diff --git a/docs/pt/docs/tutorial/response-model.md b/docs/pt/docs/tutorial/response-model.md new file mode 100644 index 0000000000000..6726a20a72ef5 --- /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: + + + +E ambos os modelos serão usados ​​para a documentação interativa da API: + + + +## Outras anotações de tipo de retorno + +Pode haver casos em que você retorna algo que não é um campo Pydantic válido e anota na função, apenas para obter o suporte fornecido pelas ferramentas (o editor, mypy, etc). + +### Retornar uma resposta diretamente + +O caso mais comum seria [retornar uma resposta diretamente, conforme explicado posteriormente na documentação avançada](../advanced/response-directly.md){.internal-link target=_blank}. + +{* ../../docs_src/response_model/tutorial003_02.py hl[8,10:11] *} + +Este caso simples é tratado automaticamente pelo FastAPI porque a anotação do tipo de retorno é a classe (ou uma subclasse de) `Response`. + +E as ferramentas também ficarão felizes porque `RedirectResponse` e ​​`JSONResponse` são subclasses de `Response`, então a anotação de tipo está correta. + +### Anotar uma subclasse de resposta + +Você também pode usar uma subclasse de `Response` na anotação de tipo: + +{* ../../docs_src/response_model/tutorial003_03.py hl[8:9] *} + +Isso também funcionará porque `RedirectResponse` é uma subclasse de `Response`, e o FastAPI tratará automaticamente este caso simples. + +### Anotações de Tipo de Retorno Inválido + +Mas quando você retorna algum outro objeto arbitrário que não é um tipo Pydantic válido (por exemplo, um objeto de banco de dados) e você o anota dessa forma na função, o FastAPI tentará criar um modelo de resposta Pydantic a partir dessa anotação de tipo e falhará. + +O mesmo aconteceria se você tivesse algo como uma união entre tipos diferentes onde um ou mais deles não são tipos Pydantic válidos, por exemplo, isso falharia 💥: + +{* ../../docs_src/response_model/tutorial003_04_py310.py hl[8] *} + +... isso falha porque a anotação de tipo não é um tipo Pydantic e não é apenas uma única classe ou subclasse `Response`, é uma união (qualquer uma das duas) entre um `Response` e ​​um `dict`. + +### Desabilitar modelo de resposta + +Continuando com o exemplo acima, você pode não querer ter a validação de dados padrão, documentação, filtragem, etc. que é realizada pelo FastAPI. + +Mas você pode querer manter a anotação do tipo de retorno na função para obter o suporte de ferramentas como editores e verificadores de tipo (por exemplo, mypy). + +Neste caso, você pode desabilitar a geração do modelo de resposta definindo `response_model=None`: + +{* ../../docs_src/response_model/tutorial003_05_py310.py hl[7] *} + +Isso fará com que o FastAPI pule a geração do modelo de resposta e, dessa forma, você pode ter quaisquer anotações de tipo de retorno que precisar sem afetar seu aplicativo FastAPI. 🤓 + +## Parâmetros de codificação do modelo de resposta + +Seu modelo de resposta pode ter valores padrão, como: + +{* ../../docs_src/response_model/tutorial004_py310.py hl[9,11:12] *} + +* `description: Union[str, None] = None` (ou `str | None = None` no Python 3.10) tem um padrão de `None`. +* `tax: float = 10.5` tem um padrão de `10.5`. +* `tags: List[str] = []` tem um padrão de uma lista vazia: `[]`. + +mas você pode querer omiti-los do resultado se eles não foram realmente armazenados. + +Por exemplo, se você tem modelos com muitos atributos opcionais em um banco de dados NoSQL, mas não quer enviar respostas JSON muito longas cheias de valores padrão. + +### Usar o parâmetro `response_model_exclude_unset` + +Você pode definir o parâmetro `response_model_exclude_unset=True` do *decorador de operação de rota* : + +{* ../../docs_src/response_model/tutorial004_py310.py hl[22] *} + +e esses valores padrão não serão incluídos na resposta, apenas os valores realmente definidos. + +Então, se você enviar uma solicitação para essa *operação de rota* para o item com ID `foo`, a resposta (sem incluir valores padrão) será: + +```JSON +{ +"name": "Foo", +"price": 50.2 +} +``` + +/// info | Informação + +No Pydantic v1, o método era chamado `.dict()`, ele foi descontinuado (mas ainda suportado) no Pydantic v2 e renomeado para `.model_dump()`. + +Os exemplos aqui usam `.dict()` para compatibilidade com Pydantic v1, mas você deve usar `.model_dump()` em vez disso se puder usar Pydantic v2. + +/// + +/// info | Informação + +O FastAPI usa `.dict()` do modelo Pydantic com seu parâmetro `exclude_unset` para chegar a isso. + +/// + +/// info | Informação + +Você também pode usar: + +* `response_model_exclude_defaults=True` +* `response_model_exclude_none=True` + +conforme descrito na documentação do Pydantic para `exclude_defaults` e `exclude_none`. + +/// + +#### Dados com valores para campos com padrões + +Mas se seus dados tiverem valores para os campos do modelo com valores padrões, como o item com ID `bar`: + +```Python hl_lines="3 5" +{ +"name": "Bar", +"description": "The bartenders", +"price": 62, +"tax": 20.2 +} +``` + +eles serão incluídos na resposta. + +#### Dados com os mesmos valores que os padrões + +Se os dados tiverem os mesmos valores que os padrões, como o item com ID `baz`: + +```Python hl_lines="3 5-6" +{ +"name": "Baz", +"description": None, +"price": 50.2, +"tax": 10.5, +"tags": [] +} +``` + +O FastAPI é inteligente o suficiente (na verdade, o Pydantic é inteligente o suficiente) para perceber que, embora `description`, `tax` e `tags` tenham os mesmos valores que os padrões, eles foram definidos explicitamente (em vez de retirados dos padrões). + +Portanto, eles serão incluídos na resposta JSON. + +/// tip | Dica + +Observe que os valores padrão podem ser qualquer coisa, não apenas `None`. + +Eles podem ser uma lista (`[]`), um `float` de `10.5`, etc. + +/// + +### `response_model_include` e `response_model_exclude` + +Você também pode usar os parâmetros `response_model_include` e `response_model_exclude` do *decorador de operação de rota*. + +Eles pegam um `set` de `str` com o nome dos atributos para incluir (omitindo o resto) ou para excluir (incluindo o resto). + +Isso pode ser usado como um atalho rápido se você tiver apenas um modelo Pydantic e quiser remover alguns dados da saída. + +/// tip | Dica + +Mas ainda é recomendado usar as ideias acima, usando várias classes, em vez desses parâmetros. + +Isso ocorre porque o Schema JSON gerado no OpenAPI do seu aplicativo (e a documentação) ainda será o único para o modelo completo, mesmo que você use `response_model_include` ou `response_model_exclude` para omitir alguns atributos. + +Isso também se aplica ao `response_model_by_alias` que funciona de forma semelhante. + +/// + +{* ../../docs_src/response_model/tutorial005_py310.py hl[29,35] *} + +/// tip | Dica + +A sintaxe `{"nome", "descrição"}` cria um `conjunto` com esses dois valores. + +É equivalente a `set(["nome", "descrição"])`. + +/// + +#### Usando `list`s em vez de `set`s + +Se você esquecer de usar um `set` e usar uma `lista` ou `tupla` em vez disso, o FastAPI ainda o converterá em um `set` e funcionará corretamente: + +{* ../../docs_src/response_model/tutorial006_py310.py hl[29,35] *} + +## Recapitulação + +Use o parâmetro `response_model` do *decorador de operação de rota* para definir modelos de resposta e, especialmente, para garantir que dados privados sejam filtrados. + +Use `response_model_exclude_unset` para retornar apenas os valores definidos explicitamente. diff --git a/docs/pt/docs/tutorial/response-status-code.md b/docs/pt/docs/tutorial/response-status-code.md index bc4a2cd348634..48957f67ac9ee 100644 --- a/docs/pt/docs/tutorial/response-status-code.md +++ b/docs/pt/docs/tutorial/response-status-code.md @@ -8,11 +8,9 @@ Da mesma forma que você pode especificar um modelo de resposta, você também p * `@app.delete()` * etc. -```Python hl_lines="6" -{!../../docs_src/response_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_status_code/tutorial001.py hl[6] *} -/// note | "Nota" +/// note | Nota Observe que `status_code` é um parâmetro do método "decorador" (get, post, etc). Não da sua função de *operação de caminho*, como todos os parâmetros e corpo. @@ -20,7 +18,7 @@ Observe que `status_code` é um parâmetro do método "decorador" (get, post, et O parâmetro `status_code` recebe um número com o código de status HTTP. -/// info | "Informação" +/// info | Informação `status_code` também pode receber um `IntEnum`, como o do Python `http.HTTPStatus`. @@ -33,7 +31,7 @@ Dessa forma: -/// note | "Nota" +/// note | Nota Alguns códigos de resposta (consulte a próxima seção) indicam que a resposta não possui um corpo. @@ -43,7 +41,7 @@ O FastAPI sabe disso e produzirá documentos OpenAPI informando que não há cor ## Sobre os códigos de status HTTP -/// note | "Nota" +/// note | Nota Se você já sabe o que são códigos de status HTTP, pule para a próxima seção. @@ -67,7 +65,7 @@ Resumidamente: * Para erros genéricos do cliente, você pode usar apenas `400`. * `500` e acima são para erros do servidor. Você quase nunca os usa diretamente. Quando algo der errado em alguma parte do código do seu aplicativo ou servidor, ele retornará automaticamente um desses códigos de status. -/// tip | "Dica" +/// tip | Dica Para saber mais sobre cada código de status e qual código serve para quê, verifique o MDN documentação sobre códigos de status HTTP. @@ -77,9 +75,7 @@ Para saber mais sobre cada código de status e qual código serve para quê, ver Vamos ver o exemplo anterior novamente: -```Python hl_lines="6" -{!../../docs_src/response_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_status_code/tutorial001.py hl[6] *} `201` é o código de status para "Criado". @@ -87,15 +83,13 @@ Mas você não precisa memorizar o que cada um desses códigos significa. Você pode usar as variáveis de conveniência de `fastapi.status`. -```Python hl_lines="1 6" -{!../../docs_src/response_status_code/tutorial002.py!} -``` +{* ../../docs_src/response_status_code/tutorial002.py hl[1,6] *} Eles são apenas uma conveniência, eles possuem o mesmo número, mas dessa forma você pode usar o autocomplete do editor para encontrá-los: -/// note | "Detalhes técnicos" +/// note | Detalhes técnicos Você também pode usar `from starlette import status`. diff --git a/docs/pt/docs/tutorial/schema-extra-example.md b/docs/pt/docs/tutorial/schema-extra-example.md index 2d78e4ef1f222..5d3498d7dec0d 100644 --- a/docs/pt/docs/tutorial/schema-extra-example.md +++ b/docs/pt/docs/tutorial/schema-extra-example.md @@ -8,13 +8,11 @@ Aqui estão várias formas de se fazer isso. Você pode declarar um `example` para um modelo Pydantic usando `Config` e `schema_extra`, conforme descrito em Documentação do Pydantic: Schema customization: -```Python hl_lines="15-23" -{!../../docs_src/schema_extra_example/tutorial001.py!} -``` +{* ../../docs_src/schema_extra_example/tutorial001.py hl[15:23] *} Essas informações extras serão adicionadas como se encontram no **JSON Schema** de resposta desse modelo e serão usadas na documentação da API. -/// tip | "Dica" +/// tip | Dica Você pode usar a mesma técnica para estender o JSON Schema e adicionar suas próprias informações extras de forma personalizada. @@ -28,11 +26,9 @@ Ao usar `Field ()` com modelos Pydantic, você também pode declarar informaçõ Você pode usar isso para adicionar um `example` para cada campo: -```Python hl_lines="4 10-13" -{!../../docs_src/schema_extra_example/tutorial002.py!} -``` +{* ../../docs_src/schema_extra_example/tutorial002.py hl[4,10:13] *} -/// warning | "Atenção" +/// warning | Atenção Lembre-se de que esses argumentos extras passados ​​não adicionarão nenhuma validação, apenas informações extras, para fins de documentação. @@ -56,9 +52,7 @@ você também pode declarar um dado `example` ou um grupo de `examples` com info Aqui nós passamos um `example` dos dados esperados por `Body()`: -```Python hl_lines="21-26" -{!../../docs_src/schema_extra_example/tutorial003.py!} -``` +{* ../../docs_src/schema_extra_example/tutorial003.py hl[21:26] *} ### Exemplo na UI da documentação @@ -79,9 +73,7 @@ Cada `dict` de exemplo específico em `examples` pode conter: * `value`: O próprio exemplo mostrado, ex: um `dict`. * `externalValue`: alternativa ao `value`, uma URL apontando para o exemplo. Embora isso possa não ser suportado por tantas ferramentas quanto `value`. -```Python hl_lines="22-48" -{!../../docs_src/schema_extra_example/tutorial004.py!} -``` +{* ../../docs_src/schema_extra_example/tutorial004.py hl[22:48] *} ### Exemplos na UI da documentação @@ -91,7 +83,7 @@ Com `examples` adicionado a `Body()`, os `/docs` vão ficar assim: ## Detalhes técnicos -/// warning | "Atenção" +/// warning | Atenção Esses são detalhes muito técnicos sobre os padrões **JSON Schema** e **OpenAPI**. diff --git a/docs/pt/docs/tutorial/security/first-steps.md b/docs/pt/docs/tutorial/security/first-steps.md index 9fb94fe674b1e..f4dea8e14bc75 100644 --- a/docs/pt/docs/tutorial/security/first-steps.md +++ b/docs/pt/docs/tutorial/security/first-steps.md @@ -19,13 +19,11 @@ Vamos primeiro usar o código e ver como funciona, e depois voltaremos para ente ## Crie um `main.py` Copie o exemplo em um arquivo `main.py`: -```Python -{!../../docs_src/security/tutorial001.py!} -``` +{* ../../docs_src/security/tutorial001.py *} ## Execute-o -/// info | "informação" +/// info | informação @@ -57,7 +55,7 @@ Você verá algo deste tipo: -/// check | "Botão de Autorizar!" +/// check | Botão de Autorizar! @@ -71,7 +69,7 @@ E se você clicar, você terá um pequeno formulário de autorização para digi -/// note | "Nota" +/// note | Nota @@ -119,7 +117,7 @@ Então, vamos rever de um ponto de vista simplificado: Neste exemplo, nós vamos usar o **OAuth2** com o fluxo de **Senha**, usando um token **Bearer**. Fazemos isso usando a classe `OAuth2PasswordBearer`. -/// info | "informação" +/// info | informação @@ -135,11 +133,9 @@ Neste exemplo, nós vamos usar o **OAuth2** com o fluxo de **Senha**, usando um Quando nós criamos uma instância da classe `OAuth2PasswordBearer`, nós passamos pelo parâmetro `tokenUrl` Esse parâmetro contém a URL que o client (o frontend rodando no browser do usuário) vai usar para mandar o `username` e `senha` para obter um token. -```Python hl_lines="6" -{!../../docs_src/security/tutorial001.py!} -``` +{* ../../docs_src/security/tutorial001.py hl[6] *} -/// tip | "Dica" +/// tip | Dica @@ -155,7 +151,7 @@ Esse parâmetro não cria um endpoint / *path operation*, mas declara que a URL Em breve também criaremos o atual path operation. -/// info | "informação" +/// info | informação @@ -179,15 +175,13 @@ Então, pode ser usado com `Depends`. Agora você pode passar aquele `oauth2_scheme` em uma dependência com `Depends`. -```Python hl_lines="10" -{!../../docs_src/security/tutorial001.py!} -``` +{* ../../docs_src/security/tutorial001.py hl[10] *} Esse dependência vai fornecer uma `str` que é atribuído ao parâmetro `token da *função do path operation* A **FastAPI** saberá que pode usar essa dependência para definir um "esquema de segurança" no esquema da OpenAPI (e na documentação da API automática). -/// info | "Detalhes técnicos" +/// info | Detalhes técnicos diff --git a/docs/pt/docs/tutorial/security/index.md b/docs/pt/docs/tutorial/security/index.md index 2f23aa47ee082..b4440ec0413e7 100644 --- a/docs/pt/docs/tutorial/security/index.md +++ b/docs/pt/docs/tutorial/security/index.md @@ -32,7 +32,7 @@ Não é muito popular ou usado nos dias atuais. OAuth2 não especifica como criptografar a comunicação, ele espera que você tenha sua aplicação em um servidor HTTPS. -/// tip | "Dica" +/// tip | Dica Na seção sobre **deployment** você irá ver como configurar HTTPS de modo gratuito, usando Traefik e Let’s Encrypt. @@ -89,7 +89,7 @@ OpenAPI define os seguintes esquemas de segurança: * Essa descoberta automática é o que é definido na especificação OpenID Connect. -/// tip | "Dica" +/// tip | Dica Integração com outros provedores de autenticação/autorização como Google, Facebook, Twitter, GitHub, etc. é bem possível e relativamente fácil. diff --git a/docs/pt/docs/tutorial/security/simple-oauth2.md b/docs/pt/docs/tutorial/security/simple-oauth2.md new file mode 100644 index 0000000000000..1cf05785eecf4 --- /dev/null +++ b/docs/pt/docs/tutorial/security/simple-oauth2.md @@ -0,0 +1,289 @@ +# Simples OAuth2 com senha e Bearer + +Agora vamos construir a partir do capítulo anterior e adicionar as partes que faltam para ter um fluxo de segurança completo. + +## Pegue o `username` (nome de usuário) e `password` (senha) + +É utilizado o utils de segurança da **FastAPI** para obter o `username` e a `password`. + +OAuth2 especifica que ao usar o "password flow" (fluxo de senha), que estamos usando, o cliente/usuário deve enviar os campos `username` e `password` como dados do formulário. + +E a especificação diz que os campos devem ser nomeados assim. Portanto, `user-name` ou `email` não funcionariam. + +Mas não se preocupe, você pode mostrá-lo como quiser aos usuários finais no frontend. + +E seus modelos de banco de dados podem usar qualquer outro nome que você desejar. + +Mas para a *operação de rota* de login, precisamos usar esses nomes para serem compatíveis com a especificação (e poder, por exemplo, usar o sistema integrado de documentação da API). + +A especificação também afirma que o `username` e a `password` devem ser enviados como dados de formulário (portanto, não há JSON aqui). + +### `scope` + +A especificação também diz que o cliente pode enviar outro campo de formulário "`scope`" (Escopo). + +O nome do campo do formulário é `scope` (no singular), mas na verdade é uma longa string com "escopos" separados por espaços. + +Cada “scope” é apenas uma string (sem espaços). + +Normalmente são usados para declarar permissões de segurança específicas, por exemplo: + +* `users:read` ou `users:write` são exemplos comuns. +* `instagram_basic` é usado pelo Facebook e Instagram. +* `https://www.googleapis.com/auth/drive` é usado pelo Google. + +/// info | Informação + +No OAuth2, um "scope" é apenas uma string que declara uma permissão específica necessária. + +Não importa se tem outros caracteres como `:` ou se é uma URL. + +Esses detalhes são específicos da implementação. + +Para OAuth2 são apenas strings. + +/// + +## Código para conseguir o `username` e a `password` + +Agora vamos usar os utilitários fornecidos pelo **FastAPI** para lidar com isso. + +### `OAuth2PasswordRequestForm` + +Primeiro, importe `OAuth2PasswordRequestForm` e use-o como uma dependência com `Depends` na *operação de rota* para `/token`: + +{* ../../docs_src/security/tutorial003_an_py310.py hl[4,78] *} + +`OAuth2PasswordRequestForm` é uma dependência de classe que declara um corpo de formulário com: + +* O `username`. +* A `password`. +* Um campo `scope` opcional como uma string grande, composta de strings separadas por espaços. +* Um `grant_type` (tipo de concessão) opcional. + +/// tip | Dica + +A especificação OAuth2 na verdade *requer* um campo `grant_type` com um valor fixo de `password`, mas `OAuth2PasswordRequestForm` não o impõe. + +Se você precisar aplicá-lo, use `OAuth2PasswordRequestFormStrict` em vez de `OAuth2PasswordRequestForm`. + +/// + +* Um `client_id` opcional (não precisamos dele em nosso exemplo). +* Um `client_secret` opcional (não precisamos dele em nosso exemplo). + +/// info | Informação + +O `OAuth2PasswordRequestForm` não é uma classe especial para **FastAPI** como é `OAuth2PasswordBearer`. + +`OAuth2PasswordBearer` faz com que **FastAPI** saiba que é um esquema de segurança. Portanto, é adicionado dessa forma ao OpenAPI. + +Mas `OAuth2PasswordRequestForm` é apenas uma dependência de classe que você mesmo poderia ter escrito ou poderia ter declarado os parâmetros do `Form` (formulário) diretamente. + +Mas como é um caso de uso comum, ele é fornecido diretamente pelo **FastAPI**, apenas para facilitar. + +/// + +### Use os dados do formulário + +/// tip | Dica + +A instância da classe de dependência `OAuth2PasswordRequestForm` não terá um atributo `scope` com a string longa separada por espaços, em vez disso, terá um atributo `scopes` com a lista real de strings para cada escopo enviado. + +Não estamos usando `scopes` neste exemplo, mas a funcionalidade está disponível se você precisar. + +/// + +Agora, obtenha os dados do usuário do banco de dados (falso), usando o `username` do campo do formulário. + +Se não existir tal usuário, retornaremos um erro dizendo "Incorrect username or password" (Nome de usuário ou senha incorretos). + +Para o erro, usamos a exceção `HTTPException`: + +{* ../../docs_src/security/tutorial003_an_py310.py hl[3,79:81] *} + +### Confira a password (senha) + +Neste ponto temos os dados do usuário do nosso banco de dados, mas não verificamos a senha. + +Vamos colocar esses dados primeiro no modelo `UserInDB` do Pydantic. + +Você nunca deve salvar senhas em texto simples, portanto, usaremos o sistema de hashing de senhas (falsas). + +Se as senhas não corresponderem, retornaremos o mesmo erro. + +#### Hashing de senha + +"Hashing" significa: converter algum conteúdo (uma senha neste caso) em uma sequência de bytes (apenas uma string) que parece algo sem sentido. + +Sempre que você passa exatamente o mesmo conteúdo (exatamente a mesma senha), você obtém exatamente a mesma sequência aleatória de caracteres. + +Mas você não pode converter a sequência aleatória de caracteres de volta para a senha. + +##### Porque usar hashing de senha + +Se o seu banco de dados for roubado, o ladrão não terá as senhas em texto simples dos seus usuários, apenas os hashes. + +Assim, o ladrão não poderá tentar usar essas mesmas senhas em outro sistema (como muitos usuários usam a mesma senha em todos os lugares, isso seria perigoso). + +{* ../../docs_src/security/tutorial003_an_py310.py hl[82:85] *} + +#### Sobre `**user_dict` + +`UserInDB(**user_dict)` significa: + +*Passe as keys (chaves) e values (valores) de `user_dict` diretamente como argumentos de valor-chave, equivalente a:* + +```Python +UserInDB( + username = user_dict["username"], + email = user_dict["email"], + full_name = user_dict["full_name"], + disabled = user_dict["disabled"], + hashed_password = user_dict["hashed_password"], +) +``` + +/// info | Informação + +Para uma explicação mais completa de `**user_dict`, verifique [a documentação para **Extra Models**](../extra-models.md#about-user_indict){.internal-link target=_blank}. + +/// + +## Retorne o token + +A resposta do endpoint `token` deve ser um objeto JSON. + +Deve ter um `token_type`. No nosso caso, como estamos usando tokens "Bearer", o tipo de token deve ser "`bearer`". + +E deve ter um `access_token`, com uma string contendo nosso token de acesso. + +Para este exemplo simples, seremos completamente inseguros e retornaremos o mesmo `username` do token. + +/// tip | Dica + +No próximo capítulo, você verá uma implementação realmente segura, com hash de senha e tokens JWT. + +Mas, por enquanto, vamos nos concentrar nos detalhes específicos de que precisamos. + +/// + +{* ../../docs_src/security/tutorial003_an_py310.py hl[87] *} + +/// tip | Dica + +Pela especificação, você deve retornar um JSON com um `access_token` e um `token_type`, o mesmo que neste exemplo. + +Isso é algo que você mesmo deve fazer em seu código e certifique-se de usar essas chaves JSON. + +É quase a única coisa que você deve se lembrar de fazer corretamente, para estar em conformidade com as especificações. + +De resto, **FastAPI** cuida disso para você. + +/// + +## Atualize as dependências + +Agora vamos atualizar nossas dependências. + +Queremos obter o `user_user` *somente* se este usuário estiver ativo. + +Portanto, criamos uma dependência adicional `get_current_active_user` que por sua vez usa `get_current_user` como dependência. + +Ambas as dependências retornarão apenas um erro HTTP se o usuário não existir ou se estiver inativo. + +Portanto, em nosso endpoint, só obteremos um usuário se o usuário existir, tiver sido autenticado corretamente e estiver ativo: + +{* ../../docs_src/security/tutorial003_an_py310.py hl[58:66,69:74,94] *} + +/// info | Informação + +O cabeçalho adicional `WWW-Authenticate` com valor `Bearer` que estamos retornando aqui também faz parte da especificação. + +Qualquer código de status HTTP (erro) 401 "UNAUTHORIZED" também deve retornar um cabeçalho `WWW-Authenticate`. + +No caso de tokens ao portador (nosso caso), o valor desse cabeçalho deve ser `Bearer`. + +Na verdade, você pode pular esse cabeçalho extra e ainda funcionaria. + +Mas é fornecido aqui para estar em conformidade com as especificações. + +Além disso, pode haver ferramentas que esperam e usam isso (agora ou no futuro) e que podem ser úteis para você ou seus usuários, agora ou no futuro. + +Esse é o benefício dos padrões... + +/// + +## Veja em ação + +Abra o docs interativo: http://127.0.0.1:8000/docs. + +### Autenticação + +Clique no botão "Authorize". + +Use as credenciais: + +User: `johndoe` + +Password: `secret` + + + +Após autenticar no sistema, você verá assim: + + + +### Obtenha seus próprios dados de usuário + +Agora use a operação `GET` com o caminho `/users/me`. + +Você obterá os dados do seu usuário, como: + +```JSON +{ + "username": "johndoe", + "email": "johndoe@example.com", + "full_name": "John Doe", + "disabled": false, + "hashed_password": "fakehashedsecret" +} +``` + + + +Se você clicar no ícone de cadeado, sair e tentar a mesma operação novamente, receberá um erro HTTP 401 de: + +```JSON +{ + "detail": "Not authenticated" +} +``` + +### Usuário inativo + +Agora tente com um usuário inativo, autentique-se com: + +User: `alice` + +Password: `secret2` + +E tente usar a operação `GET` com o caminho `/users/me`. + +Você receberá um erro "Usuário inativo", como: + +```JSON +{ + "detail": "Inactive user" +} +``` + +## Recaptulando + +Agora você tem as ferramentas para implementar um sistema de segurança completo baseado em `username` e `password` para sua API. + +Usando essas ferramentas, você pode tornar o sistema de segurança compatível com qualquer banco de dados e com qualquer usuário ou modelo de dados. + +O único detalhe que falta é que ainda não é realmente "seguro". + +No próximo capítulo você verá como usar uma biblioteca de hashing de senha segura e tokens JWT. diff --git a/docs/pt/docs/tutorial/static-files.md b/docs/pt/docs/tutorial/static-files.md index 901fca1d21aab..0660078f4021c 100644 --- a/docs/pt/docs/tutorial/static-files.md +++ b/docs/pt/docs/tutorial/static-files.md @@ -7,11 +7,9 @@ Você pode servir arquivos estáticos automaticamente de um diretório usando `S * Importe `StaticFiles`. * "Monte" uma instância de `StaticFiles()` em um caminho específico. -```Python hl_lines="2 6" -{!../../docs_src/static_files/tutorial001.py!} -``` +{* ../../docs_src/static_files/tutorial001.py hl[2,6] *} -/// note | "Detalhes técnicos" +/// note | Detalhes técnicos Você também pode usar `from starlette.staticfiles import StaticFiles`. diff --git a/docs/pt/docs/tutorial/testing.md b/docs/pt/docs/tutorial/testing.md index 4e28a43c09b66..8eb2f29b7646f 100644 --- a/docs/pt/docs/tutorial/testing.md +++ b/docs/pt/docs/tutorial/testing.md @@ -8,7 +8,7 @@ Com ele, você pode usar o `httpx`. @@ -30,11 +30,9 @@ Use o objeto `TestClient` da mesma forma que você faz com `httpx`. Escreva instruções `assert` simples com as expressões Python padrão que você precisa verificar (novamente, `pytest` padrão). -```Python hl_lines="2 12 15-18" -{!../../docs_src/app_testing/tutorial001.py!} -``` +{* ../../docs_src/app_testing/tutorial001.py hl[2,12,15:18] *} -/// tip | "Dica" +/// tip | Dica Observe que as funções de teste são `def` normais, não `async def`. @@ -44,7 +42,7 @@ Isso permite que você use `pytest` diretamente sem complicações. /// -/// note | "Detalhes técnicos" +/// note | Detalhes técnicos Você também pode usar `from starlette.testclient import TestClient`. @@ -52,7 +50,7 @@ Você também pode usar `from starlette.testclient import TestClient`. /// -/// tip | "Dica" +/// tip | Dica Se você quiser chamar funções `async` em seus testes além de enviar solicitações ao seu aplicativo FastAPI (por exemplo, funções de banco de dados assíncronas), dê uma olhada em [Testes assíncronos](../advanced/async-tests.md){.internal-link target=_blank} no tutorial avançado. @@ -78,9 +76,7 @@ Digamos que você tenha uma estrutura de arquivo conforme descrito em [Aplicativ No arquivo `main.py` você tem seu aplicativo **FastAPI**: -```Python -{!../../docs_src/app_testing/main.py!} -``` +{* ../../docs_src/app_testing/main.py *} ### Arquivo de teste @@ -96,9 +92,7 @@ Então você poderia ter um arquivo `test_main.py` com seus testes. Ele poderia Como esse arquivo está no mesmo pacote, você pode usar importações relativas para importar o objeto `app` do módulo `main` (`main.py`): -```Python hl_lines="3" -{!../../docs_src/app_testing/test_main.py!} -``` +{* ../../docs_src/app_testing/test_main.py hl[3] *} ...e ter o código para os testes como antes. @@ -152,7 +146,7 @@ Ambas as *operações de rotas* requerem um cabeçalho `X-Token`. //// tab | Python 3.10+ non-Annotated -/// tip | "Dica" +/// tip | Dica Prefira usar a versão `Annotated` se possível. @@ -166,7 +160,7 @@ Prefira usar a versão `Annotated` se possível. //// tab | Python 3.8+ non-Annotated -/// tip | "Dica" +/// tip | Dica Prefira usar a versão `Annotated` se possível. @@ -182,9 +176,7 @@ Prefira usar a versão `Annotated` se possível. Você pode então atualizar `test_main.py` com os testes estendidos: -```Python -{!> ../../docs_src/app_testing/app_b/test_main.py!} -``` +{* ../../docs_src/app_testing/app_b/test_main.py *} Sempre que você precisar que o cliente passe informações na requisição e não souber como, você pode pesquisar (no Google) como fazer isso no `httpx`, ou até mesmo como fazer isso com `requests`, já que o design do HTTPX é baseado no design do Requests. @@ -200,7 +192,7 @@ Por exemplo: Para mais informações sobre como passar dados para o backend (usando `httpx` ou `TestClient`), consulte a documentação do HTTPX. -/// info | "Informação" +/// info | Informação Observe que o `TestClient` recebe dados que podem ser convertidos para JSON, não para modelos Pydantic. diff --git a/docs/pt/docs/virtual-environments.md b/docs/pt/docs/virtual-environments.md index 863c8d65e6714..5fc1a88666250 100644 --- a/docs/pt/docs/virtual-environments.md +++ b/docs/pt/docs/virtual-environments.md @@ -2,13 +2,13 @@ Ao trabalhar em projetos Python, você provavelmente deve usar um **ambiente virtual** (ou um mecanismo similar) para isolar os pacotes que você instala para cada projeto. -/// info | "Informação" +/// info | Informação Se você já sabe sobre ambientes virtuais, como criá-los e usá-los, talvez seja melhor pular esta seção. 🤓 /// -/// tip | "Dica" +/// tip | Dica Um **ambiente virtual** é diferente de uma **variável de ambiente**. @@ -18,7 +18,7 @@ Um **ambiente virtual** é um diretório com alguns arquivos. /// -/// info | "Informação" +/// info | Informação Esta página lhe ensinará como usar **ambientes virtuais** e como eles funcionam. @@ -55,7 +55,7 @@ $ cd awesome-project Ao começar a trabalhar em um projeto Python **pela primeira vez**, crie um ambiente virtual **dentro do seu projeto**. -/// tip | "Dica" +/// tip | Dica Você só precisa fazer isso **uma vez por projeto**, não toda vez que trabalhar. @@ -96,7 +96,7 @@ $ uv venv -/// tip | "Dica" +/// tip | Dica Por padrão, `uv` criará um ambiente virtual em um diretório chamado `.venv`. @@ -118,7 +118,7 @@ Você pode criar o ambiente virtual em um diretório diferente, mas há uma conv Ative o novo ambiente virtual para que qualquer comando Python que você executar ou pacote que você instalar o utilize. -/// tip | "Dica" +/// tip | Dica Faça isso **toda vez** que iniciar uma **nova sessão de terminal** para trabalhar no projeto. @@ -162,7 +162,7 @@ $ source .venv/Scripts/activate //// -/// tip | "Dica" +/// tip | Dica Toda vez que você instalar um **novo pacote** naquele ambiente, **ative** o ambiente novamente. @@ -174,7 +174,7 @@ Isso garante que, se você usar um **programa de terminal (`uv`, você o usará para instalar coisas em vez do `pip`, então não precisará atualizar o `pip`. 😎 @@ -224,7 +224,7 @@ Se você estiver usando `pip` para instalar pacotes (ele vem por padrão com o P Muitos erros exóticos durante a instalação de um pacote são resolvidos apenas atualizando o `pip` primeiro. -/// tip | "Dica" +/// tip | Dica Normalmente, você faria isso **uma vez**, logo após criar o ambiente virtual. @@ -246,13 +246,13 @@ $ python -m pip install --upgrade pip Se você estiver usando **Git** (você deveria), adicione um arquivo `.gitignore` para excluir tudo em seu `.venv` do Git. -/// tip | "Dica" +/// tip | Dica Se você usou `uv` para criar o ambiente virtual, ele já fez isso para você, você pode pular esta etapa. 😎 /// -/// tip | "Dica" +/// tip | Dica Faça isso **uma vez**, logo após criar o ambiente virtual. @@ -286,7 +286,7 @@ Esse comando criará um arquivo `.gitignore` com o conteúdo: Após ativar o ambiente, você pode instalar pacotes nele. -/// tip | "Dica" +/// tip | Dica Faça isso **uma vez** ao instalar ou atualizar os pacotes que seu projeto precisa. @@ -298,7 +298,7 @@ Se precisar atualizar uma versão ou adicionar um novo pacote, você **fará iss Se estiver com pressa e não quiser usar um arquivo para declarar os requisitos de pacote do seu projeto, você pode instalá-los diretamente. -/// tip | "Dica" +/// tip | Dica É uma (muito) boa ideia colocar os pacotes e versões que seu programa precisa em um arquivo (por exemplo `requirements.txt` ou `pyproject.toml`). @@ -399,7 +399,7 @@ Por exemplo: * VS Code * PyCharm -/// tip | "Dica" +/// tip | Dica Normalmente, você só precisa fazer isso **uma vez**, ao criar o ambiente virtual. @@ -425,7 +425,7 @@ Agora você está pronto para começar a trabalhar no seu projeto. -/// tip | "Dica" +/// tip | Dica Você quer entender o que é tudo isso acima? @@ -516,7 +516,7 @@ flowchart LR end ``` -/// tip | "Dica" +/// tip | Dica É muito comum em pacotes Python tentar ao máximo **evitar alterações drásticas** em **novas versões**, mas é melhor prevenir do que remediar e instalar versões mais recentes intencionalmente e, quando possível, executar os testes para verificar se tudo está funcionando corretamente. @@ -623,7 +623,7 @@ Esse comando criará ou modificará algumas [variáveis ​​de ambiente](envir Uma dessas variáveis ​​é a variável `PATH`. -/// tip | "Dica" +/// tip | Dica Você pode aprender mais sobre a variável de ambiente `PATH` na seção [Variáveis ​​de ambiente](environment-variables.md#path-environment-variable){.internal-link target=_blank}. @@ -756,7 +756,7 @@ A parte mais importante é que quando você chama ``python`, esse é exatamente Assim, você pode confirmar se está no ambiente virtual correto. -/// tip | "Dica" +/// tip | Dica É fácil ativar um ambiente virtual, obter um Python e então **ir para outro projeto**. diff --git a/docs/ru/docs/alternatives.md b/docs/ru/docs/alternatives.md index f83024ad94607..3c5147e7939f7 100644 --- a/docs/ru/docs/alternatives.md +++ b/docs/ru/docs/alternatives.md @@ -33,14 +33,14 @@ DRF использовался многими компаниями, включа Это был один из первых примеров **автоматического документирования API** и это была одна из первых идей, вдохновивших на создание **FastAPI**. -/// note | "Заметка" +/// note | Заметка Django REST Framework был создан Tom Christie. Он же создал Starlette и Uvicorn, на которых основан **FastAPI**. /// -/// check | "Идея для **FastAPI**" +/// check | Идея для **FastAPI** Должно быть автоматическое создание документации API с пользовательским веб-интерфейсом. @@ -62,7 +62,7 @@ Flask часто используется и для приложений, кот Простота Flask, показалась мне подходящей для создания API. Но ещё нужно было найти "Django REST Framework" для Flask. -/// check | "Идеи для **FastAPI**" +/// check | Идеи для **FastAPI** Это будет микрофреймворк. К нему легко будет добавить необходимые инструменты и части. @@ -108,7 +108,7 @@ def read_url(): Глядите, как похоже `requests.get(...)` и `@app.get(...)`. -/// check | "Идеи для **FastAPI**" +/// check | Идеи для **FastAPI** * Должен быть простой и понятный API. * Нужно использовать названия HTTP-методов (операций) для упрощения понимания происходящего. @@ -129,7 +129,7 @@ def read_url(): Вот почему, когда говорят о версии 2.0, обычно говорят "Swagger", а для версии 3+ "OpenAPI". -/// check | "Идеи для **FastAPI**" +/// check | Идеи для **FastAPI** Использовать открытые стандарты для спецификаций API вместо самодельных схем. @@ -165,7 +165,7 @@ def read_url(): Итак, чтобы определить каждую схему, Вам нужно использовать определенные утилиты и классы, предоставляемые Marshmallow. -/// check | "Идея для **FastAPI**" +/// check | Идея для **FastAPI** Использовать код программы для автоматического создания "схем", определяющих типы данных и их проверку. @@ -181,13 +181,13 @@ Webargs - это инструмент, который был создан для Это превосходный инструмент и я тоже часто пользовался им до **FastAPI**. -/// info | "Информация" +/// info | Информация Webargs бы создан разработчиками Marshmallow. /// -/// check | "Идея для **FastAPI**" +/// check | Идея для **FastAPI** Должна быть автоматическая проверка входных данных. @@ -212,13 +212,13 @@ Marshmallow и Webargs осуществляют проверку, анализ Редактор кода не особо может помочь в такой парадигме. А изменив какие-то параметры или схемы для Marshmallow можно забыть отредактировать докстринг с YAML и сгенерированная схема становится недействительной. -/// info | "Информация" +/// info | Информация APISpec тоже был создан авторами Marshmallow. /// -/// check | "Идея для **FastAPI**" +/// check | Идея для **FastAPI** Необходима поддержка открытого стандарта для API - OpenAPI. @@ -246,13 +246,13 @@ APISpec тоже был создан авторами Marshmallow. Эти генераторы проектов также стали основой для [Генераторов проектов с **FastAPI**](project-generation.md){.internal-link target=_blank}. -/// info | "Информация" +/// info | Информация Как ни странно, но Flask-apispec тоже создан авторами Marshmallow. /// -/// check | "Идея для **FastAPI**" +/// check | Идея для **FastAPI** Схема OpenAPI должна создаваться автоматически и использовать тот же код, который осуществляет сериализацию и проверку данных. @@ -276,7 +276,7 @@ APISpec тоже был создан авторами Marshmallow. Кроме того, он не очень хорошо справляется с вложенными моделями. Если в запросе имеется объект JSON, внутренние поля которого, в свою очередь, являются вложенными объектами JSON, это не может быть должным образом задокументировано и проверено. -/// check | "Идеи для **FastAPI** " +/// check | Идеи для **FastAPI** Нужно использовать подсказки типов, чтоб воспользоваться поддержкой редактора кода. @@ -289,7 +289,7 @@ APISpec тоже был создан авторами Marshmallow. Sanic был одним из первых чрезвычайно быстрых Python-фреймворков основанных на `asyncio`. Он был сделан очень похожим на Flask. -/// note | "Технические детали" +/// note | Технические детали В нём использован `uvloop` вместо стандартного цикла событий `asyncio`, что и сделало его таким быстрым. @@ -297,7 +297,7 @@ Sanic был одним из первых чрезвычайно быстрых /// -/// check | "Идеи для **FastAPI**" +/// check | Идеи для **FastAPI** Должна быть сумасшедшая производительность. @@ -318,7 +318,7 @@ Falcon - ещё один высокопроизводительный Python-ф Либо эти функции должны быть встроены во фреймворк, сконструированный поверх Falcon, как в Hug. Такая же особенность присутствует и в других фреймворках, вдохновлённых идеей Falcon, использовать только один объект запроса и один объект ответа. -/// check | "Идея для **FastAPI**" +/// check | Идея для **FastAPI** Найдите способы добиться отличной производительности. @@ -348,7 +348,7 @@ Molten мне попался на начальной стадии написан Это больше похоже на Django, чем на Flask и Starlette. Он разделяет в коде вещи, которые довольно тесно связаны. -/// check | "Идея для **FastAPI**" +/// check | Идея для **FastAPI** Определить дополнительные проверки типов данных, используя значения атрибутов модели "по умолчанию". Это улучшает помощь редактора и раньше это не было доступно в Pydantic. @@ -374,13 +374,13 @@ Hug был одним из первых фреймворков, реализов Поскольку он основан на WSGI, старом стандарте для синхронных веб-фреймворков, он не может работать с веб-сокетами и другими модными штуками, но всё равно обладает высокой производительностью. -/// info | "Информация" +/// info | Информация Hug создан Timothy Crosley, автором `isort`, отличного инструмента для автоматической сортировки импортов в Python-файлах. /// -/// check | "Идеи для **FastAPI**" +/// check | Идеи для **FastAPI** Hug повлиял на создание некоторых частей APIStar и был одним из инструментов, которые я счел наиболее многообещающими, наряду с APIStar. @@ -418,7 +418,7 @@ Hug вдохновил **FastAPI** объявить параметр `ответ Ныне APIStar - это набор инструментов для проверки спецификаций OpenAPI. -/// info | "Информация" +/// info | Информация APIStar был создан Tom Christie. Тот самый парень, который создал: @@ -428,7 +428,7 @@ APIStar был создан Tom Christie. Тот самый парень, кот /// -/// check | "Идеи для **FastAPI**" +/// check | Идеи для **FastAPI** Воплощение. @@ -452,7 +452,7 @@ Pydantic - это библиотека для валидации данных, Его можно сравнить с Marshmallow, хотя в бенчмарках Pydantic быстрее, чем Marshmallow. И он основан на тех же подсказках типов, которые отлично поддерживаются редакторами кода. -/// check | "**FastAPI** использует Pydantic" +/// check | **FastAPI** использует Pydantic Для проверки данных, сериализации данных и автоматической документации моделей (на основе JSON Schema). @@ -488,7 +488,7 @@ Starlette обеспечивает весь функционал микрофр **FastAPI** добавляет эти функции используя подсказки типов Python и Pydantic. Ещё **FastAPI** добавляет систему внедрения зависимостей, утилиты безопасности, генерацию схемы OpenAPI и т.д. -/// note | "Технические детали" +/// note | Технические детали ASGI - это новый "стандарт" разработанный участниками команды Django. Он пока что не является "стандартом в Python" (то есть принятым PEP), но процесс принятия запущен. @@ -498,7 +498,7 @@ ASGI - это новый "стандарт" разработанный учас /// -/// check | "**FastAPI** использует Starlette" +/// check | **FastAPI** использует Starlette В качестве ядра веб-сервиса для обработки запросов, добавив некоторые функции сверху. @@ -518,7 +518,7 @@ Uvicorn является сервером, а не фреймворком. Он рекомендуется в качестве сервера для Starlette и **FastAPI**. -/// check | "**FastAPI** рекомендует его" +/// check | **FastAPI** рекомендует его Как основной сервер для запуска приложения **FastAPI**. diff --git a/docs/ru/docs/contributing.md b/docs/ru/docs/contributing.md deleted file mode 100644 index c4370f9bbfa7c..0000000000000 --- a/docs/ru/docs/contributing.md +++ /dev/null @@ -1,496 +0,0 @@ -# Участие в разработке фреймворка - -Возможно, для начала Вам стоит ознакомиться с основными способами [помочь FastAPI или получить помощь](help-fastapi.md){.internal-link target=_blank}. - -## Разработка - -Если Вы уже склонировали репозиторий и знаете, что Вам нужно более глубокое погружение в код фреймворка, то здесь представлены некоторые инструкции по настройке виртуального окружения. - -### Виртуальное окружение с помощью `venv` - -Находясь в нужной директории, Вы можете создать виртуальное окружение при помощи Python модуля `venv`. - -
- -```console -$ python -m venv env -``` - -
- -Эта команда создаст директорию `./env/` с бинарными (двоичными) файлами Python, а затем Вы сможете скачивать и устанавливать необходимые библиотеки в изолированное виртуальное окружение. - -### Активация виртуального окружения - -Активируйте виртуально окружение командой: - -//// tab | Linux, macOS - -
- -```console -$ source ./env/bin/activate -``` - -
- -//// - -//// tab | Windows PowerShell - -
- -```console -$ .\env\Scripts\Activate.ps1 -``` - -
- -//// - -//// tab | Windows Bash - -Если Вы пользуетесь Bash для Windows (например: Git Bash): - -
- -```console -$ source ./env/Scripts/activate -``` - -
- -//// - -Проверьте, что всё сработало: - -//// tab | Linux, macOS, Windows Bash - -
- -```console -$ which pip - -some/directory/fastapi/env/bin/pip -``` - -
- -//// - -//// tab | Windows PowerShell - -
- -```console -$ Get-Command pip - -some/directory/fastapi/env/bin/pip -``` - -
- -//// - -Если в терминале появится ответ, что бинарник `pip` расположен по пути `.../env/bin/pip`, значит всё в порядке. 🎉 - -Во избежание ошибок в дальнейших шагах, удостоверьтесь, что в Вашем виртуальном окружении установлена последняя версия `pip`: - -
- -```console -$ python -m pip install --upgrade pip - ----> 100% -``` - -
- -/// tip | "Подсказка" - -Каждый раз, перед установкой новой библиотеки в виртуальное окружение при помощи `pip`, не забудьте активировать это виртуальное окружение. - -Это гарантирует, что если Вы используете библиотеку, установленную этим пакетом, то Вы используете библиотеку из Вашего локального окружения, а не любую другую, которая может быть установлена глобально. - -/// - -### pip - -После активации виртуального окружения, как было указано ранее, введите следующую команду: - -
- -```console -$ pip install -r requirements.txt - ----> 100% -``` - -
- -Это установит все необходимые зависимости в локальное окружение для Вашего локального FastAPI. - -#### Использование локального FastAPI - -Если Вы создаёте Python файл, который импортирует и использует FastAPI,а затем запускаете его интерпретатором Python из Вашего локального окружения, то он будет использовать код из локального FastAPI. - -И, так как при вводе вышеупомянутой команды был указан флаг `-e`, если Вы измените код локального FastAPI, то при следующем запуске этого файла, он будет использовать свежую версию локального FastAPI, который Вы только что изменили. - -Таким образом, Вам не нужно "переустанавливать" Вашу локальную версию, чтобы протестировать каждое изменение. - -### Форматировние - -Скачанный репозиторий содержит скрипт, который может отформатировать и подчистить Ваш код: - -
- -```console -$ bash scripts/format.sh -``` - -
- -Заодно он упорядочит Ваши импорты. - -Чтобы он сортировал их правильно, необходимо, чтобы FastAPI был установлен локально в Вашей среде, с помощью команды из раздела выше, использующей флаг `-e`. - -## Документация - -Прежде всего, убедитесь, что Вы настроили своё окружение, как описано выше, для установки всех зависимостей. - -Документация использует MkDocs. - -Также существуют дополнительные инструменты/скрипты для работы с переводами в `./scripts/docs.py`. - -/// tip | "Подсказка" - -Нет необходимости заглядывать в `./scripts/docs.py`, просто используйте это в командной строке. - -/// - -Вся документация имеет формат Markdown и расположена в директории `./docs/en/`. - -Многие руководства содержат блоки кода. - -В большинстве случаев эти блоки кода представляют собой вполне законченные приложения, которые можно запускать как есть. - -На самом деле, эти блоки кода не написаны внутри Markdown, это Python файлы в директории `./docs_src/`. - -И эти Python файлы включаются/вводятся в документацию при создании сайта. - -### Тестирование документации - - -Фактически, большинство тестов запускаются с примерами исходных файлов в документации. - -Это помогает убедиться, что: - -* Документация находится в актуальном состоянии. -* Примеры из документации могут быть запущены как есть. -* Большинство функций описаны в документации и покрыты тестами. - -Существует скрипт, который во время локальной разработки создаёт сайт и проверяет наличие любых изменений, перезагружая его в реальном времени: - -
- -```console -$ python ./scripts/docs.py live - -[INFO] Serving on http://127.0.0.1:8008 -[INFO] Start watching changes -[INFO] Start detecting changes -``` - -
- -Он запустит сайт документации по адресу: `http://127.0.0.1:8008`. - - -Таким образом, Вы сможете редактировать файлы с документацией или кодом и наблюдать изменения вживую. - -#### Typer CLI (опционально) - - -Приведенная ранее инструкция показала Вам, как запускать скрипт `./scripts/docs.py` непосредственно через интерпретатор `python` . - -Но также можно использовать Typer CLI, что позволит Вам воспользоваться автозаполнением команд в Вашем терминале. - -Если Вы установили Typer CLI, то для включения функции автозаполнения, введите эту команду: - -
- -```console -$ typer --install-completion - -zsh completion installed in /home/user/.bashrc. -Completion will take effect once you restart the terminal. -``` - -
- -### Приложения и документация одновременно - -Если Вы запускаете приложение, например так: - -
- -```console -$ uvicorn tutorial001:app --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -
- -По умолчанию Uvicorn будет использовать порт `8000` и не будет конфликтовать с сайтом документации, использующим порт `8008`. - -### Переводы на другие языки - -Помощь с переводами ценится КРАЙНЕ ВЫСОКО! И переводы не могут быть сделаны без помощи сообщества. 🌎 🚀 - -Ниже приведены шаги, как помочь с переводами. - -#### Подсказки и инструкции - -* Проверьте существующие пул-реквесты для Вашего языка. Добавьте отзывы с просьбой внести изменения, если они необходимы, или одобрите их. - -/// tip | "Подсказка" - -Вы можете добавлять комментарии с предложениями по изменению в существующие пул-реквесты. - -Ознакомьтесь с документацией о добавлении отзыва к пул-реквесту, чтобы утвердить его или запросить изменения. - -/// - -* Проверьте проблемы и вопросы, чтобы узнать, есть ли кто-то, координирующий переводы для Вашего языка. - -* Добавляйте один пул-реквест для каждой отдельной переведённой страницы. Это значительно облегчит другим его просмотр. - -Для языков, которые я не знаю, прежде чем добавить перевод в основную ветку, я подожду пока несколько других участников сообщества проверят его. - -* Вы также можете проверить, есть ли переводы для Вашего языка и добавить к ним отзыв, который поможет мне убедиться в правильности перевода. Тогда я смогу объединить его с основной веткой. - -* Используйте те же самые примеры кода Python. Переводите только текст документации. Вам не нужно ничего менять, чтобы эти примеры работали. - -* Используйте те же самые изображения, имена файлов и ссылки. Вы не должны менять ничего для сохранения работоспособности. - -* Чтобы узнать 2-буквенный код языка, на который Вы хотите сделать перевод, Вы можете воспользоваться таблицей Список кодов языков ISO 639-1. - -#### Существующий язык - -Допустим, Вы хотите перевести страницу на язык, на котором уже есть какие-то переводы, например, на испанский. - -Кодом испанского языка является `es`. А значит директория для переводов на испанский язык: `docs/es/`. - -/// tip | "Подсказка" - -Главный ("официальный") язык - английский, директория для него `docs/en/`. - -/// - -Вы можете запустить сервер документации на испанском: - -
- -```console -// Используйте команду "live" и передайте код языка в качестве аргумента командной строки -$ python ./scripts/docs.py live es - -[INFO] Serving on http://127.0.0.1:8008 -[INFO] Start watching changes -[INFO] Start detecting changes -``` - -
- -Теперь Вы можете перейти по адресу: http://127.0.0.1:8008 и наблюдать вносимые Вами изменения вживую. - - -Если Вы посмотрите на сайт документации FastAPI, то увидите, что все страницы есть на каждом языке. Но некоторые страницы не переведены и имеют уведомление об отсутствующем переводе. - -Но когда Вы запускаете сайт локально, Вы видите только те страницы, которые уже переведены. - - -Предположим, что Вы хотите добавить перевод страницы [Основные свойства](features.md){.internal-link target=_blank}. - -* Скопируйте файл: - -``` -docs/en/docs/features.md -``` - -* Вставьте его точно в то же место, но в директорию языка, на который Вы хотите сделать перевод, например: - -``` -docs/es/docs/features.md -``` - -/// tip | "Подсказка" - -Заметьте, что в пути файла мы изменили только код языка с `en` на `es`. - -/// - -* Теперь откройте файл конфигурации MkDocs для английского языка, расположенный тут: - -``` -docs/en/mkdocs.yml -``` - -* Найдите в файле конфигурации место, где расположена строка `docs/features.md`. Похожее на это: - -```YAML hl_lines="8" -site_name: FastAPI -# More stuff -nav: -- FastAPI: index.md -- Languages: - - en: / - - es: /es/ -- features.md -``` - -* Откройте файл конфигурации MkDocs для языка, на который Вы переводите, например: - -``` -docs/es/mkdocs.yml -``` - -* Добавьте строку `docs/features.md` точно в то же место, как и в случае для английского, как-то так: - -```YAML hl_lines="8" -site_name: FastAPI -# More stuff -nav: -- FastAPI: index.md -- Languages: - - en: / - - es: /es/ -- features.md -``` - -Убедитесь, что при наличии других записей, новая запись с Вашим переводом находится точно в том же порядке, что и в английской версии. - -Если Вы зайдёте в свой браузер, то увидите, что в документации стал отображаться Ваш новый раздел.🎉 - -Теперь Вы можете переводить эту страницу и смотреть, как она выглядит при сохранении файла. - -#### Новый язык - -Допустим, Вы хотите добавить перевод для языка, на который пока что не переведена ни одна страница. - -Скажем, Вы решили сделать перевод для креольского языка, но его еще нет в документации. - -Перейдите в таблицу кодов языков по ссылке указанной выше, где найдёте, что кодом креольского языка является `ht`. - -Затем запустите скрипт, генерирующий директорию для переводов на новые языки: - -
- -```console -// Используйте команду new-lang и передайте код языка в качестве аргумента командной строки -$ python ./scripts/docs.py new-lang ht - -Successfully initialized: docs/ht -Updating ht -Updating en -``` - -
- -После чего Вы можете проверить в своем редакторе кода, что появился новый каталог `docs/ht/`. - -/// tip | "Подсказка" - -Создайте первый пул-реквест, который будет содержать только пустую директорию для нового языка, прежде чем добавлять переводы. - -Таким образом, другие участники могут переводить другие страницы, пока Вы работаете над одной. 🚀 - -/// - -Начните перевод с главной страницы `docs/ht/index.md`. - -В дальнейшем можно действовать, как указано в предыдущих инструкциях для "существующего языка". - -##### Новый язык не поддерживается - -Если при запуске скрипта `./scripts/docs.py live` Вы получаете сообщение об ошибке, что язык не поддерживается, что-то вроде: - -``` - raise TemplateNotFound(template) -jinja2.exceptions.TemplateNotFound: partials/language/xx.html -``` - -Сие означает, что тема не поддерживает этот язык (в данном случае с поддельным 2-буквенным кодом `xx`). - -Но не стоит переживать. Вы можете установить языком темы английский, а затем перевести текст документации. - -Если возникла такая необходимость, отредактируйте `mkdocs.yml` для Вашего нового языка. Это будет выглядеть как-то так: - -```YAML hl_lines="5" -site_name: FastAPI -# More stuff -theme: - # More stuff - language: xx -``` - -Измените `xx` (код Вашего языка) на `en` и перезапустите сервер. - -#### Предпросмотр результата - -Когда Вы запускаете скрипт `./scripts/docs.py` с командой `live`, то будут показаны файлы и переводы для указанного языка. - -Но когда Вы закончите, то можете посмотреть, как это будет выглядеть по-настоящему. - -Для этого сначала создайте всю документацию: - -
- -```console -// Используйте команду "build-all", это займёт немного времени -$ python ./scripts/docs.py build-all - -Updating es -Updating en -Building docs for: en -Building docs for: es -Successfully built docs for: es -Copying en index.md to README.md -``` - -
- -Скрипт сгенерирует `./docs_build/` для каждого языка. Он добавит все файлы с отсутствующими переводами с пометкой о том, что "у этого файла еще нет перевода". Но Вам не нужно ничего делать с этим каталогом. - -Затем он создаст независимые сайты MkDocs для каждого языка, объединит их и сгенерирует конечный результат на `./site/`. - -После чего Вы сможете запустить сервер со всеми языками командой `serve`: - -
- -```console -// Используйте команду "serve" после того, как отработает команда "build-all" -$ python ./scripts/docs.py serve - -Warning: this is a very simple server. For development, use mkdocs serve instead. -This is here only to preview a site with translations already built. -Make sure you run the build-all command first. -Serving at: http://127.0.0.1:8008 -``` - -
- -## Тесты - -Также в репозитории есть скрипт, который Вы можете запустить локально, чтобы протестировать весь код и сгенерировать отчеты о покрытии тестами в HTML: - -
- -```console -$ bash scripts/test-cov-html.sh -``` - -
- -Эта команда создаст директорию `./htmlcov/`, в которой будет файл `./htmlcov/index.html`. Открыв его в Вашем браузере, Вы можете в интерактивном режиме изучить, все ли части кода охвачены тестами. diff --git a/docs/ru/docs/deployment/concepts.md b/docs/ru/docs/deployment/concepts.md index c410257909905..7cdc295265459 100644 --- a/docs/ru/docs/deployment/concepts.md +++ b/docs/ru/docs/deployment/concepts.md @@ -151,7 +151,7 @@ Для случаев, когда ошибки приводят к сбою в запущенном **процессе**, Вам понадобится добавить компонент, который **перезапустит** процесс хотя бы пару раз... -/// tip | "Заметка" +/// tip | Заметка ... Если приложение падает сразу же после запуска, вероятно бесполезно его бесконечно перезапускать. Но полагаю, вы заметите такое поведение во время разработки или, по крайней мере, сразу после развёртывания. @@ -241,7 +241,7 @@ * **Облачные сервисы**, которые позаботятся обо всём за Вас * Возможно, что облачный сервис умеет **управлять запуском дополнительных экземпляров приложения**. Вероятно, он потребует, чтоб вы указали - какой **процесс** или **образ** следует клонировать. Скорее всего, вы укажете **один процесс Uvicorn** и облачный сервис будет запускать его копии при необходимости. -/// tip | "Заметка" +/// tip | Заметка Если вы не знаете, что такое **контейнеры**, Docker или Kubernetes, не переживайте. @@ -263,7 +263,7 @@ Безусловно, возможны случаи, когда нет проблем при выполнении предварительной подготовки параллельно или несколько раз. Тогда Вам повезло, работать с ними намного проще. -/// tip | "Заметка" +/// tip | Заметка Имейте в виду, что в некоторых случаях запуск вашего приложения **может не требовать каких-либо предварительных шагов вовсе**. @@ -281,7 +281,7 @@ * Bash-скрипт, выполняющий предварительные шаги, а затем запускающий приложение. * При этом Вам всё ещё нужно найти способ - как запускать/перезапускать *такой* bash-скрипт, обнаруживать ошибки и т.п. -/// tip | "Заметка" +/// tip | Заметка Я приведу Вам больше конкретных примеров работы с контейнерами в главе: [FastAPI внутри контейнеров - Docker](docker.md){.internal-link target=_blank}. diff --git a/docs/ru/docs/deployment/docker.md b/docs/ru/docs/deployment/docker.md index 9eef5c4d2a6a9..31da01b788820 100644 --- a/docs/ru/docs/deployment/docker.md +++ b/docs/ru/docs/deployment/docker.md @@ -4,7 +4,7 @@ Использование контейнеров на основе Linux имеет ряд преимуществ, включая **безопасность**, **воспроизводимость**, **простоту** и прочие. -/// tip | "Подсказка" +/// tip | Подсказка Торопитесь или уже знакомы с этой технологией? Перепрыгните на раздел [Создать Docker-образ для FastAPI 👇](#docker-fastapi) @@ -135,7 +135,7 @@ Successfully installed fastapi pydantic uvicorn -/// info | "Информация" +/// info | Информация Существуют и другие инструменты управления зависимостями. @@ -231,7 +231,7 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] Так как команда выполняется внутри директории `/code`, в которую мы поместили папку `./app` с приложением, то **Uvicorn** сможет найти и **импортировать** объект `app` из файла `app.main`. -/// tip | "Подсказка" +/// tip | Подсказка Если ткнёте на кружок с плюсом, то увидите пояснения. 👆 @@ -306,7 +306,7 @@ $ docker build -t myimage . -/// tip | "Подсказка" +/// tip | Подсказка Обратите внимание, что в конце написана точка - `.`, это то же самое что и `./`, тем самым мы указываем Docker директорию, из которой нужно выполнять сборку образа контейнера. @@ -410,7 +410,7 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] Это может быть другой контейнер, в котором есть, например, Traefik, работающий с **HTTPS** и **самостоятельно** обновляющий **сертификаты**. -/// tip | "Подсказка" +/// tip | Подсказка Traefik совместим с Docker, Kubernetes и им подобными инструментами. Он очень прост в установке и настройке использования HTTPS для Ваших контейнеров. @@ -442,7 +442,7 @@ Traefik совместим с Docker, Kubernetes и им подобными ин Поскольку этот компонент **принимает запросы** и равномерно **распределяет** их между компонентами, его также называют **балансировщиком нагрузки**. -/// tip | "Подсказка" +/// tip | Подсказка **Прокси-сервер завершения работы TLS** одновременно может быть **балансировщиком нагрузки**. @@ -525,7 +525,7 @@ Traefik совместим с Docker, Kubernetes и им подобными ин Когда вы запускаете **множество контейнеров**, в каждом из которых работает **только один процесс** (например, в кластере **Kubernetes**), может возникнуть необходимость иметь **отдельный контейнер**, который осуществит **предварительные шаги перед запуском** остальных контейнеров (например, применяет миграции к базе данных). -/// info | "Информация" +/// info | Информация При использовании Kubernetes, это может быть Инициализирующий контейнер. @@ -545,7 +545,7 @@ Traefik совместим с Docker, Kubernetes и им подобными ин * tiangolo/uvicorn-gunicorn-fastapi. -/// warning | "Предупреждение" +/// warning | Предупреждение Скорее всего у вас **нет необходимости** в использовании этого образа или подобного ему и лучше создать свой образ с нуля как описано тут: [Создать Docker-образ для FastAPI](#docker-fastapi). @@ -557,7 +557,7 @@ Traefik совместим с Docker, Kubernetes и им подобными ин Он также поддерживает прохождение **Подготовительных шагов при запуске контейнеров** при помощи скрипта. -/// tip | "Подсказка" +/// tip | Подсказка Для просмотра всех возможных настроек перейдите на страницу этого Docker-образа: tiangolo/uvicorn-gunicorn-fastapi. @@ -689,7 +689,7 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 11. Запустите `uvicorn`, указав ему использовать объект `app`, расположенный в `app.main`. -/// tip | "Подсказка" +/// tip | Подсказка Если ткнёте на кружок с плюсом, то увидите объяснения, что происходит в этой строке. diff --git a/docs/ru/docs/deployment/https.md b/docs/ru/docs/deployment/https.md index 3d487c465f453..85c4cce604e99 100644 --- a/docs/ru/docs/deployment/https.md +++ b/docs/ru/docs/deployment/https.md @@ -4,7 +4,7 @@ Но всё несколько сложнее. -/// tip | "Заметка" +/// tip | Заметка Если вы торопитесь или вам не интересно, можете перейти на следующую страницу этого пошагового руководства по размещению приложений на серверах с использованием различных технологий. @@ -78,7 +78,7 @@ Обычно эту запись достаточно указать один раз, при первоначальной настройке всего сервера. -/// tip | "Заметка" +/// tip | Заметка Уровни протоколов, работающих с именами доменов, намного ниже HTTPS, но об этом следует упомянуть здесь, так как всё зависит от доменов и IP-адресов. @@ -128,7 +128,7 @@ DNS-сервера присылают браузеру определённый Таким образом, **HTTPS** это тот же **HTTP**, но внутри **безопасного TLS-соединения** вместо чистого (незашифрованного) TCP-соединения. -/// tip | "Заметка" +/// tip | Заметка Обратите внимание, что шифрование происходит на **уровне TCP**, а не на более высоком уровне HTTP. diff --git a/docs/ru/docs/deployment/manually.md b/docs/ru/docs/deployment/manually.md index 78363cef88d7b..9b1d32be80290 100644 --- a/docs/ru/docs/deployment/manually.md +++ b/docs/ru/docs/deployment/manually.md @@ -39,7 +39,7 @@ $ pip install "uvicorn[standard]" -/// tip | "Подсказка" +/// tip | Подсказка С опцией `standard`, Uvicorn будет устанавливаться и использоваться с некоторыми дополнительными рекомендованными зависимостями. @@ -99,7 +99,7 @@ Running on 0.0.0.0:8080 over http (CTRL + C to quit) //// -/// warning | "Предупреждение" +/// warning | Предупреждение Не забудьте удалить опцию `--reload`, если ранее пользовались ею. diff --git a/docs/ru/docs/deployment/versions.md b/docs/ru/docs/deployment/versions.md index 17b6446d945ed..e8db30ce8965b 100644 --- a/docs/ru/docs/deployment/versions.md +++ b/docs/ru/docs/deployment/versions.md @@ -42,7 +42,7 @@ fastapi>=0.45.0,<0.46.0 FastAPI следует соглашению в том, что любые изменения "ПАТЧ"-версии предназначены для исправления багов и внесения обратно совместимых изменений. -/// tip | "Подсказка" +/// tip | Подсказка "ПАТЧ" - это последнее число. Например, в `0.2.3`, ПАТЧ-версия - это `3`. @@ -56,7 +56,7 @@ fastapi>=0.45.0,<0.46.0 Обратно несовместимые изменения и новые функции добавляются в "МИНОРНЫЕ" версии. -/// tip | "Подсказка" +/// tip | Подсказка "МИНОРНАЯ" версия - это число в середине. Например, в `0.2.3` МИНОРНАЯ версия - это `2`. diff --git a/docs/ru/docs/features.md b/docs/ru/docs/features.md index 31f245e7a312d..77d6b936a8996 100644 --- a/docs/ru/docs/features.md +++ b/docs/ru/docs/features.md @@ -66,7 +66,7 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -/// info | "Информация" +/// info | Информация `**second_user_data` означает: diff --git a/docs/ru/docs/help-fastapi.md b/docs/ru/docs/help-fastapi.md index fa82008171a3a..474b3d689b143 100644 --- a/docs/ru/docs/help-fastapi.md +++ b/docs/ru/docs/help-fastapi.md @@ -162,7 +162,7 @@ * Затем, используя **комментарий**, сообщите, что Вы сделали проверку, тогда я буду знать, что Вы действительно проверили код. -/// info | "Информация" +/// info | Информация К сожалению, я не могу так просто доверять пул-реквестам, у которых уже есть несколько одобрений. @@ -221,7 +221,7 @@ Подключайтесь к 👥 чату в Discord 👥 и общайтесь с другими участниками сообщества FastAPI. -/// tip | "Подсказка" +/// tip | Подсказка Вопросы по проблемам с фреймворком лучше задавать в GitHub issues, так больше шансов, что Вы получите помощь от [Экспертов FastAPI](fastapi-people.md#_3){.internal-link target=_blank}. diff --git a/docs/ru/docs/python-types.md b/docs/ru/docs/python-types.md index e5905304a359e..b1d4715fd3f66 100644 --- a/docs/ru/docs/python-types.md +++ b/docs/ru/docs/python-types.md @@ -22,9 +22,8 @@ Python имеет поддержку необязательных аннотац Давайте начнем с простого примера: -```Python -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py *} + Вызов этой программы выводит: @@ -38,9 +37,8 @@ John Doe * Преобразует первую букву содержимого каждой переменной в верхний регистр с `title()`. * Соединяет их через пробел. -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py hl[2] *} + ### Отредактируем пример @@ -82,9 +80,8 @@ John Doe Это аннотации типов: -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial002.py!} -``` +{* ../../docs_src/python_types/tutorial002.py hl[1] *} + Это не то же самое, что объявление значений по умолчанию, например: @@ -112,9 +109,8 @@ John Doe Проверьте эту функцию, она уже имеет аннотации типов: -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial003.py!} -``` +{* ../../docs_src/python_types/tutorial003.py hl[1] *} + Поскольку редактор знает типы переменных, вы получаете не только дополнение, но и проверки ошибок: @@ -122,9 +118,8 @@ John Doe Теперь вы знаете, что вам нужно исправить, преобразовав `age` в строку с `str(age)`: -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial004.py!} -``` +{* ../../docs_src/python_types/tutorial004.py hl[2] *} + ## Объявление типов @@ -143,9 +138,8 @@ John Doe * `bool` * `bytes` -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial005.py!} -``` +{* ../../docs_src/python_types/tutorial005.py hl[1] *} + ### Generic-типы с параметрами типов @@ -161,9 +155,8 @@ John Doe Импортируйте `List` из `typing` (с заглавной `L`): -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial006.py!} -``` +{* ../../docs_src/python_types/tutorial006.py hl[1] *} + Объявите переменную с тем же синтаксисом двоеточия (`:`). @@ -171,9 +164,8 @@ John Doe Поскольку список является типом, содержащим некоторые внутренние типы, вы помещаете их в квадратные скобки: -```Python hl_lines="4" -{!../../docs_src/python_types/tutorial006.py!} -``` +{* ../../docs_src/python_types/tutorial006.py hl[4] *} + /// tip @@ -199,9 +191,8 @@ John Doe Вы бы сделали то же самое, чтобы объявить `tuple` и `set`: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial007.py!} -``` +{* ../../docs_src/python_types/tutorial007.py hl[1,4] *} + Это означает: @@ -216,9 +207,8 @@ John Doe Второй параметр типа предназначен для значений `dict`: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial008.py!} -``` +{* ../../docs_src/python_types/tutorial008.py hl[1,4] *} + Это означает: @@ -255,15 +245,13 @@ John Doe Допустим, у вас есть класс `Person` с полем `name`: -```Python hl_lines="1-3" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[1:3] *} + Тогда вы можете объявить переменную типа `Person`: -```Python hl_lines="6" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[6] *} + И снова вы получаете полную поддержку редактора: @@ -283,9 +271,8 @@ John Doe Взято из официальной документации Pydantic: -```Python -{!../../docs_src/python_types/tutorial011.py!} -``` +{* ../../docs_src/python_types/tutorial011.py *} + /// info diff --git a/docs/ru/docs/tutorial/background-tasks.md b/docs/ru/docs/tutorial/background-tasks.md index 0f6ce0eb32097..bf2e9dec3fb7c 100644 --- a/docs/ru/docs/tutorial/background-tasks.md +++ b/docs/ru/docs/tutorial/background-tasks.md @@ -15,9 +15,7 @@ Сначала импортируйте `BackgroundTasks`, потом добавьте в функцию параметр с типом `BackgroundTasks`: -```Python hl_lines="1 13" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *} **FastAPI** создаст объект класса `BackgroundTasks` для вас и запишет его в параметр. @@ -33,17 +31,13 @@ Так как операция записи не использует `async` и `await`, мы определим ее как обычную `def`: -```Python hl_lines="6-9" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *} ## Добавление фоновой задачи Внутри функции вызовите метод `.add_task()` у объекта *background tasks* и передайте ему функцию, которую хотите выполнить в фоне: -```Python hl_lines="14" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[14] *} `.add_task()` принимает следующие аргументы: @@ -57,21 +51,7 @@ **FastAPI** знает, что нужно сделать в каждом случае и как переиспользовать тот же объект `BackgroundTasks`, так чтобы все фоновые задачи собрались и запустились вместе в фоне: -//// tab | Python 3.10+ - -```Python hl_lines="11 13 20 23" -{!> ../../docs_src/background_tasks/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="13 15 22 25" -{!> ../../docs_src/background_tasks/tutorial002.py!} -``` - -//// +{* ../../docs_src/background_tasks/tutorial002_py310.py hl[11,13,20,23] *} В этом примере сообщения будут записаны в `log.txt` *после* того, как ответ сервера был отправлен. @@ -97,8 +77,6 @@ Их тяжелее настраивать, также им нужен брокер сообщений наподобие RabbitMQ или Redis, но зато они позволяют вам запускать фоновые задачи в нескольких процессах и даже на нескольких серверах. -Для примера, посмотрите [Project Generators](../project-generation.md){.internal-link target=_blank}, там есть проект с уже настроенным Celery. - Но если вам нужен доступ к общим переменным и объектам вашего **FastAPI** приложения или вам нужно выполнять простые фоновые задачи (наподобие отправки письма из примера) вы можете просто использовать `BackgroundTasks`. ## Резюме diff --git a/docs/ru/docs/tutorial/body-fields.md b/docs/ru/docs/tutorial/body-fields.md index f3b2c61138379..5ed5f59fc53c5 100644 --- a/docs/ru/docs/tutorial/body-fields.md +++ b/docs/ru/docs/tutorial/body-fields.md @@ -6,23 +6,9 @@ Сначала вы должны импортировать его: -//// tab | Python 3.10+ +{* ../../docs_src/body_fields/tutorial001_py310.py hl[2] *} -```Python hl_lines="2" -{!> ../../docs_src/body_fields/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4" -{!> ../../docs_src/body_fields/tutorial001.py!} -``` - -//// - -/// warning | "Внимание" +/// warning | Внимание Обратите внимание, что функция `Field` импортируется непосредственно из `pydantic`, а не из `fastapi`, как все остальные функции (`Query`, `Path`, `Body` и т.д.). @@ -32,25 +18,11 @@ Вы можете использовать функцию `Field` с атрибутами модели: -//// tab | Python 3.10+ - -```Python hl_lines="9-12" -{!> ../../docs_src/body_fields/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11-14" -{!> ../../docs_src/body_fields/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_fields/tutorial001_py310.py hl[9:12] *} Функция `Field` работает так же, как `Query`, `Path` и `Body`, у неё такие же параметры и т.д. -/// note | "Технические детали" +/// note | Технические детали На самом деле, `Query`, `Path` и другие функции, которые вы увидите в дальнейшем, создают объекты подклассов общего класса `Param`, который сам по себе является подклассом `FieldInfo` из Pydantic. @@ -62,7 +34,7 @@ /// -/// tip | "Подсказка" +/// tip | Подсказка Обратите внимание, что каждый атрибут модели с типом, значением по умолчанию и `Field` имеет ту же структуру, что и параметр *функции обработки пути* с `Field` вместо `Path`, `Query` и `Body`. @@ -75,7 +47,7 @@ Вы узнаете больше о добавлении дополнительной информации позже в документации, когда будете изучать, как задавать примеры принимаемых данных. -/// warning | "Внимание" +/// warning | Внимание Дополнительные ключи, переданные в функцию `Field`, также будут присутствовать в сгенерированной OpenAPI схеме вашего приложения. Поскольку эти ключи не являются обязательной частью спецификации OpenAPI, некоторые инструменты OpenAPI, например, [валидатор OpenAPI](https://validator.swagger.io/), могут не работать с вашей сгенерированной схемой. diff --git a/docs/ru/docs/tutorial/body-multiple-params.md b/docs/ru/docs/tutorial/body-multiple-params.md index 53965f0ec09a1..9300aa1bdf4bb 100644 --- a/docs/ru/docs/tutorial/body-multiple-params.md +++ b/docs/ru/docs/tutorial/body-multiple-params.md @@ -8,59 +8,9 @@ Вы также можете объявить параметры тела запроса как необязательные, установив значение по умолчанию, равное `None`: -//// tab | Python 3.10+ +{* ../../docs_src/body_multiple_params/tutorial001_an_py310.py hl[18:20] *} -```Python hl_lines="18-20" -{!> ../../docs_src/body_multiple_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="18-20" -{!> ../../docs_src/body_multiple_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="19-21" -{!> ../../docs_src/body_multiple_params/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | "Заметка" - -Рекомендуется использовать `Annotated` версию, если это возможно. - -/// - -```Python hl_lines="17-19" -{!> ../../docs_src/body_multiple_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | "Заметка" - -Рекомендуется использовать версию с `Annotated`, если это возможно. - -/// - -```Python hl_lines="19-21" -{!> ../../docs_src/body_multiple_params/tutorial001.py!} -``` - -//// - -/// note | "Заметка" +/// note | Заметка Заметьте, что в данном случае параметр `item`, который будет взят из тела запроса, необязателен. Так как было установлено значение `None` по умолчанию. @@ -81,21 +31,7 @@ Но вы также можете объявить множество параметров тела запроса, например `item` и `user`: -//// tab | Python 3.10+ - -```Python hl_lines="20" -{!> ../../docs_src/body_multiple_params/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="22" -{!> ../../docs_src/body_multiple_params/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial002_py310.py hl[20] *} В этом случае **FastAPI** заметит, что в функции есть более одного параметра тела (два параметра, которые являются моделями Pydantic). @@ -116,7 +52,7 @@ } ``` -/// note | "Внимание" +/// note | Внимание Обратите внимание, что хотя параметр `item` был объявлен таким же способом, как и раньше, теперь предпологается, что он находится внутри тела с ключом `item`. @@ -136,57 +72,7 @@ Но вы можете указать **FastAPI** обрабатывать его, как ещё один ключ тела запроса, используя `Body`: -//// tab | Python 3.10+ - -```Python hl_lines="23" -{!> ../../docs_src/body_multiple_params/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="23" -{!> ../../docs_src/body_multiple_params/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24" -{!> ../../docs_src/body_multiple_params/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | "Заметка" - -Рекомендуется использовать `Annotated` версию, если это возможно. - -/// - -```Python hl_lines="20" -{!> ../../docs_src/body_multiple_params/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | "Заметка" - -Рекомендуется использовать `Annotated` версию, если это возможно. - -/// - -```Python hl_lines="22" -{!> ../../docs_src/body_multiple_params/tutorial003.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial003_an_py310.py hl[23] *} В этом случае, **FastAPI** будет ожидать тело запроса в формате: @@ -226,59 +112,9 @@ q: str | None = None Например: -//// tab | Python 3.10+ - -```Python hl_lines="27" -{!> ../../docs_src/body_multiple_params/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="27" -{!> ../../docs_src/body_multiple_params/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="28" -{!> ../../docs_src/body_multiple_params/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | "Заметка" - -Рекомендуется использовать `Annotated` версию, если это возможно. - -/// - -```Python hl_lines="25" -{!> ../../docs_src/body_multiple_params/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | "Заметка" - -Рекомендуется использовать `Annotated` версию, если это возможно. - -/// - -```Python hl_lines="27" -{!> ../../docs_src/body_multiple_params/tutorial004.py!} -``` +{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[27] *} -//// - -/// info | "Информация" +/// info | Информация `Body` также имеет все те же дополнительные параметры валидации и метаданных, как у `Query`,`Path` и других, которые вы увидите позже. @@ -298,57 +134,7 @@ item: Item = Body(embed=True) так же, как в этом примере: -//// tab | Python 3.10+ - -```Python hl_lines="17" -{!> ../../docs_src/body_multiple_params/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="17" -{!> ../../docs_src/body_multiple_params/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18" -{!> ../../docs_src/body_multiple_params/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | "Заметка" - -Рекомендуется использовать `Annotated` версию, если это возможно. - -/// - -```Python hl_lines="15" -{!> ../../docs_src/body_multiple_params/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | "Заметка" - -Рекомендуется использовать `Annotated` версию, если это возможно. - -/// - -```Python hl_lines="17" -{!> ../../docs_src/body_multiple_params/tutorial005.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial005_an_py310.py hl[17] *} В этом случае **FastAPI** будет ожидать тело запроса в формате: diff --git a/docs/ru/docs/tutorial/body-nested-models.md b/docs/ru/docs/tutorial/body-nested-models.md index 780946725a745..4300928928a57 100644 --- a/docs/ru/docs/tutorial/body-nested-models.md +++ b/docs/ru/docs/tutorial/body-nested-models.md @@ -6,21 +6,7 @@ Вы можете определять атрибут как подтип. Например, тип `list` в Python: -//// tab | Python 3.10+ - -```Python hl_lines="12" -{!> ../../docs_src/body_nested_models/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial001_py310.py hl[12] *} Это приведёт к тому, что обьект `tags` преобразуется в список, несмотря на то что тип его элементов не объявлен. @@ -34,9 +20,7 @@ Но в версиях Python до 3.9 (начиная с 3.6) сначала вам необходимо импортировать `List` из стандартного модуля `typing` в Python: -```Python hl_lines="1" -{!> ../../docs_src/body_nested_models/tutorial002.py!} -``` +{* ../../docs_src/body_nested_models/tutorial002.py hl[1] *} ### Объявление `list` с указанием типов для вложенных элементов @@ -65,29 +49,7 @@ my_list: List[str] Таким образом, в нашем примере мы можем явно указать тип данных для поля `tags` как "список строк": -//// tab | Python 3.10+ - -```Python hl_lines="12" -{!> ../../docs_src/body_nested_models/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial002_py310.py hl[12] *} ## Типы множеств @@ -97,29 +59,7 @@ my_list: List[str] Тогда мы можем обьявить поле `tags` как множество строк: -//// tab | Python 3.10+ - -```Python hl_lines="12" -{!> ../../docs_src/body_nested_models/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 14" -{!> ../../docs_src/body_nested_models/tutorial003.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial003_py310.py hl[12] *} С помощью этого, даже если вы получите запрос с повторяющимися данными, они будут преобразованы в множество уникальных элементов. @@ -141,57 +81,13 @@ my_list: List[str] Например, мы можем определить модель `Image`: -//// tab | Python 3.10+ - -```Python hl_lines="7-9" -{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9-11" -{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9-11" -{!> ../../docs_src/body_nested_models/tutorial004.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[7:9] *} ### Использование вложенной модели в качестве типа Также мы можем использовать эту модель как тип атрибута: -//// tab | Python 3.10+ - -```Python hl_lines="18" -{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial004.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[18] *} Это означает, что **FastAPI** будет ожидать тело запроса, аналогичное этому: @@ -224,29 +120,7 @@ my_list: List[str] Например, так как в модели `Image` у нас есть поле `url`, то мы можем объявить его как тип `HttpUrl` из модуля Pydantic вместо типа `str`: -//// tab | Python 3.10+ - -```Python hl_lines="2 8" -{!> ../../docs_src/body_nested_models/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="4 10" -{!> ../../docs_src/body_nested_models/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4 10" -{!> ../../docs_src/body_nested_models/tutorial005.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial005_py310.py hl[2,8] *} Строка будет проверена на соответствие допустимому URL-адресу и задокументирована в JSON схему / OpenAPI. @@ -254,29 +128,7 @@ my_list: List[str] Вы также можете использовать модели Pydantic в качестве типов вложенных в `list`, `set` и т.д: -//// tab | Python 3.10+ - -```Python hl_lines="18" -{!> ../../docs_src/body_nested_models/tutorial006_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial006_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial006.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial006_py310.py hl[18] *} Такая реализация будет ожидать (конвертировать, валидировать, документировать и т.д) JSON-содержимое в следующем формате: @@ -304,7 +156,7 @@ my_list: List[str] } ``` -/// info | "Информация" +/// info | Информация Заметьте, что теперь у ключа `images` есть список объектов изображений. @@ -314,31 +166,9 @@ my_list: List[str] Вы можете определять модели с произвольным уровнем вложенности: -//// tab | Python 3.10+ +{* ../../docs_src/body_nested_models/tutorial007_py310.py hl[7,12,18,21,25] *} -```Python hl_lines="7 12 18 21 25" -{!> ../../docs_src/body_nested_models/tutorial007_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9 14 20 23 27" -{!> ../../docs_src/body_nested_models/tutorial007_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 14 20 23 27" -{!> ../../docs_src/body_nested_models/tutorial007.py!} -``` - -//// - -/// info | "Информация" +/// info | Информация Заметьте, что у объекта `Offer` есть список объектов `Item`, которые, в свою очередь, могут содержать необязательный список объектов `Image` @@ -360,21 +190,7 @@ images: list[Image] например так: -//// tab | Python 3.9+ - -```Python hl_lines="13" -{!> ../../docs_src/body_nested_models/tutorial008_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="15" -{!> ../../docs_src/body_nested_models/tutorial008.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial008_py39.py hl[13] *} ## Универсальная поддержка редактора @@ -404,23 +220,9 @@ images: list[Image] В этом случае вы принимаете `dict`, пока у него есть ключи типа `int` со значениями типа `float`: -//// tab | Python 3.9+ - -```Python hl_lines="7" -{!> ../../docs_src/body_nested_models/tutorial009_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/body_nested_models/tutorial009.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial009_py39.py hl[7] *} -/// tip | "Совет" +/// tip | Совет Имейте в виду, что JSON поддерживает только ключи типа `str`. diff --git a/docs/ru/docs/tutorial/body-updates.md b/docs/ru/docs/tutorial/body-updates.md index 3ecfe52f4f145..99f475a41a436 100644 --- a/docs/ru/docs/tutorial/body-updates.md +++ b/docs/ru/docs/tutorial/body-updates.md @@ -6,29 +6,7 @@ Вы можете использовать функцию `jsonable_encoder` для преобразования входных данных в JSON, так как нередки случаи, когда работать можно только с простыми типами данных (например, для хранения в NoSQL-базе данных). -//// tab | Python 3.10+ - -```Python hl_lines="28-33" -{!> ../../docs_src/body_updates/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="30-35" -{!> ../../docs_src/body_updates/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="30-35" -{!> ../../docs_src/body_updates/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial001_py310.py hl[28:33] *} `PUT` используется для получения данных, которые должны полностью заменить существующие данные. @@ -54,7 +32,7 @@ Это означает, что можно передавать только те данные, которые необходимо обновить, оставляя остальные нетронутыми. -/// note | "Технические детали" +/// note | Технические детали `PATCH` менее распространен и известен, чем `PUT`. @@ -74,29 +52,7 @@ В результате будет сгенерирован словарь, содержащий только те данные, которые были заданы при создании модели `item`, без учета значений по умолчанию. Затем вы можете использовать это для создания словаря только с теми данными, которые были установлены (отправлены в запросе), опуская значения по умолчанию: -//// tab | Python 3.10+ - -```Python hl_lines="32" -{!> ../../docs_src/body_updates/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="34" -{!> ../../docs_src/body_updates/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="34" -{!> ../../docs_src/body_updates/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial002_py310.py hl[32] *} ### Использование параметра `update` в Pydantic @@ -104,29 +60,7 @@ Например, `stored_item_model.copy(update=update_data)`: -//// tab | Python 3.10+ - -```Python hl_lines="33" -{!> ../../docs_src/body_updates/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="35" -{!> ../../docs_src/body_updates/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="35" -{!> ../../docs_src/body_updates/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial002_py310.py hl[33] *} ### Кратко о частичном обновлении @@ -143,31 +77,9 @@ * Сохранить данные в своей БД. * Вернуть обновленную модель. -//// tab | Python 3.10+ - -```Python hl_lines="28-35" -{!> ../../docs_src/body_updates/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="30-37" -{!> ../../docs_src/body_updates/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="30-37" -{!> ../../docs_src/body_updates/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial002_py310.py hl[28:35] *} -/// tip | "Подсказка" +/// tip | Подсказка Эту же технику можно использовать и для операции HTTP `PUT`. @@ -175,7 +87,7 @@ /// -/// note | "Технические детали" +/// note | Технические детали Обратите внимание, что входная модель по-прежнему валидируется. diff --git a/docs/ru/docs/tutorial/body.md b/docs/ru/docs/tutorial/body.md index 91b169d07b589..2c91102261aa6 100644 --- a/docs/ru/docs/tutorial/body.md +++ b/docs/ru/docs/tutorial/body.md @@ -8,7 +8,7 @@ Чтобы объявить тело **запроса**, необходимо использовать модели Pydantic, со всей их мощью и преимуществами. -/// info | "Информация" +/// info | Информация Чтобы отправить данные, необходимо использовать один из методов: `POST` (обычно), `PUT`, `DELETE` или `PATCH`. @@ -22,9 +22,7 @@ Первое, что вам необходимо сделать, это импортировать `BaseModel` из пакета `pydantic`: -```Python hl_lines="4" -{!../../docs_src/body/tutorial001.py!} -``` +{* ../../docs_src/body/tutorial001.py hl[4] *} ## Создание вашей собственной модели @@ -32,9 +30,7 @@ Используйте аннотации типов Python для всех атрибутов: -```Python hl_lines="7-11" -{!../../docs_src/body/tutorial001.py!} -``` +{* ../../docs_src/body/tutorial001.py hl[7:11] *} Также как и при описании параметров запроса, когда атрибут модели имеет значение по умолчанию, он является необязательным. Иначе он обязателен. Используйте `None`, чтобы сделать его необязательным без использования конкретных значений по умолчанию. @@ -62,9 +58,7 @@ Чтобы добавить параметр к вашему *обработчику*, объявите его также, как вы объявляли параметры пути или параметры запроса: -```Python hl_lines="18" -{!../../docs_src/body/tutorial001.py!} -``` +{* ../../docs_src/body/tutorial001.py hl[18] *} ...и укажите созданную модель в качестве типа параметра, `Item`. @@ -113,7 +107,7 @@ -/// tip | "Подсказка" +/// tip | Подсказка Если вы используете PyCharm в качестве редактора, то вам стоит попробовать плагин Pydantic PyCharm Plugin. @@ -131,9 +125,7 @@ Внутри функции вам доступны все атрибуты объекта модели напрямую: -```Python hl_lines="21" -{!../../docs_src/body/tutorial002.py!} -``` +{* ../../docs_src/body/tutorial002.py hl[21] *} ## Тело запроса + параметры пути @@ -141,9 +133,7 @@ **FastAPI** распознает, какие параметры функции соответствуют параметрам пути и должны быть **получены из пути**, а какие параметры функции, объявленные как модели Pydantic, должны быть **получены из тела запроса**. -```Python hl_lines="17-18" -{!../../docs_src/body/tutorial003.py!} -``` +{* ../../docs_src/body/tutorial003.py hl[17:18] *} ## Тело запроса + параметры пути + параметры запроса @@ -151,9 +141,7 @@ **FastAPI** распознает каждый из них и возьмет данные из правильного источника. -```Python hl_lines="18" -{!../../docs_src/body/tutorial004.py!} -``` +{* ../../docs_src/body/tutorial004.py hl[18] *} Параметры функции распознаются следующим образом: @@ -161,7 +149,7 @@ * Если аннотация типа параметра содержит **примитивный тип** (`int`, `float`, `str`, `bool` и т.п.), он будет интерпретирован как параметр **запроса**. * Если аннотация типа параметра представляет собой **модель Pydantic**, он будет интерпретирован как параметр **тела запроса**. -/// note | "Заметка" +/// note | Заметка FastAPI понимает, что значение параметра `q` не является обязательным, потому что имеет значение по умолчанию `= None`. diff --git a/docs/ru/docs/tutorial/cookie-params.md b/docs/ru/docs/tutorial/cookie-params.md index 2a73a591832ec..d1ed943d780e5 100644 --- a/docs/ru/docs/tutorial/cookie-params.md +++ b/docs/ru/docs/tutorial/cookie-params.md @@ -6,21 +6,7 @@ Сначала импортируйте `Cookie`: -//// tab | Python 3.10+ - -```Python hl_lines="1" -{!> ../../docs_src/cookie_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/cookie_params/tutorial001_py310.py hl[1] *} ## Объявление параметров `Cookie` @@ -28,23 +14,9 @@ Первое значение - это значение по умолчанию, вы можете передать все дополнительные параметры проверки или аннотации: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/cookie_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/cookie_params/tutorial001_py310.py hl[7] *} -/// note | "Технические детали" +/// note | Технические детали `Cookie` - это класс, родственный `Path` и `Query`. Он также наследуется от общего класса `Param`. @@ -52,7 +24,7 @@ /// -/// info | "Дополнительная информация" +/// info | Дополнительная информация Для объявления cookies, вам нужно использовать `Cookie`, иначе параметры будут интерпретированы как параметры запроса. diff --git a/docs/ru/docs/tutorial/cors.md b/docs/ru/docs/tutorial/cors.md index 8d415a2c14366..e8bf04576d50e 100644 --- a/docs/ru/docs/tutorial/cors.md +++ b/docs/ru/docs/tutorial/cors.md @@ -46,9 +46,7 @@ * Отдельных HTTP-методов (`POST`, `PUT`) или всех вместе, используя `"*"`. * Отдельных HTTP-заголовков или всех вместе, используя `"*"`. -```Python hl_lines="2 6-11 13-19" -{!../../docs_src/cors/tutorial001.py!} -``` +{* ../../docs_src/cors/tutorial001.py hl[2,6:11,13:19] *} `CORSMiddleware` использует для параметров "запрещающие" значения по умолчанию, поэтому вам нужно явным образом разрешить использование отдельных источников, методов или заголовков, чтобы браузеры могли использовать их в кросс-доменном контексте. @@ -78,7 +76,7 @@ Для получения более подробной информации о CORS, обратитесь к Документации CORS от Mozilla. -/// note | "Технические детали" +/// note | Технические детали Вы также можете использовать `from starlette.middleware.cors import CORSMiddleware`. diff --git a/docs/ru/docs/tutorial/debugging.md b/docs/ru/docs/tutorial/debugging.md index 606a32bfced7c..05806f0879bd0 100644 --- a/docs/ru/docs/tutorial/debugging.md +++ b/docs/ru/docs/tutorial/debugging.md @@ -6,9 +6,7 @@ В вашем FastAPI приложении, импортируйте и вызовите `uvicorn` напрямую: -```Python hl_lines="1 15" -{!../../docs_src/debugging/tutorial001.py!} -``` +{* ../../docs_src/debugging/tutorial001.py hl[1,15] *} ### Описание `__name__ == "__main__"` @@ -74,7 +72,7 @@ from myapp import app не будет выполнена. -/// info | "Информация" +/// info | Информация Для получения дополнительной информации, ознакомьтесь с официальной документацией Python. diff --git a/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md index 161101bb30633..8037872b9ca4d 100644 --- a/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md @@ -6,57 +6,7 @@ В предыдущем примере мы возвращали `словарь` из нашей зависимости: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="11" -{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="12" -{!> ../../docs_src/dependencies/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | "Подсказка" - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | "Подсказка" - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="11" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[9] *} Но затем мы получаем `словарь` в параметре `commons` *функции операции пути*. И мы знаем, что редакторы не могут обеспечить достаточную поддержку для `словаря`, поскольку они не могут знать их ключи и типы значений. @@ -117,165 +67,15 @@ fluffy = Cat(name="Mr Fluffy") Теперь мы можем изменить зависимость `common_parameters`, указанную выше, на класс `CommonQueryParams`: -//// tab | Python 3.10+ - -```Python hl_lines="11-15" -{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="11-15" -{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="12-16" -{!> ../../docs_src/dependencies/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | "Подсказка" - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="9-13" -{!> ../../docs_src/dependencies/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | "Подсказка" - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="11-15" -{!> ../../docs_src/dependencies/tutorial002.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[11:15] *} Обратите внимание на метод `__init__`, используемый для создания экземпляра класса: -//// tab | Python 3.10+ - -```Python hl_lines="12" -{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="12" -{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="13" -{!> ../../docs_src/dependencies/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | "Подсказка" - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/dependencies/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | "Подсказка" - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="12" -{!> ../../docs_src/dependencies/tutorial002.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[12] *} ...имеет те же параметры, что и ранее используемая функция `common_parameters`: -//// tab | Python 3.10+ - -```Python hl_lines="8" -{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="10" -{!> ../../docs_src/dependencies/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | "Подсказка" - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="6" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | "Подсказка" - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8] *} Эти параметры и будут использоваться **FastAPI** для "решения" зависимости. @@ -291,57 +91,7 @@ fluffy = Cat(name="Mr Fluffy") Теперь вы можете объявить свою зависимость, используя этот класс. -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="20" -{!> ../../docs_src/dependencies/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | "Подсказка" - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | "Подсказка" - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial002.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[19] *} **FastAPI** вызывает класс `CommonQueryParams`. При этом создается "экземпляр" этого класса, который будет передан в качестве параметра `commons` в вашу функцию. @@ -351,7 +101,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | Python 3.6+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -395,7 +145,7 @@ commons: Annotated[CommonQueryParams, ... //// tab | Python 3.6+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -421,7 +171,7 @@ commons: Annotated[Any, Depends(CommonQueryParams)] //// tab | Python 3.6+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -435,57 +185,7 @@ commons = Depends(CommonQueryParams) ...как тут: -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="20" -{!> ../../docs_src/dependencies/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | "Подсказка" - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | "Подсказка" - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial003.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial003_an_py310.py hl[19] *} Но объявление типа приветствуется, так как в этом случае ваш редактор будет знать, что будет передано в качестве параметра `commons`, и тогда он сможет помочь вам с автодополнением, проверкой типов и т.д: @@ -497,7 +197,7 @@ commons = Depends(CommonQueryParams) //// tab | Python 3.6+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -532,7 +232,7 @@ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] //// tab | Python 3.6+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -556,7 +256,7 @@ commons: Annotated[CommonQueryParams, Depends()] //// tab | Python 3.6 без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -572,61 +272,11 @@ commons: CommonQueryParams = Depends() Аналогичный пример будет выглядеть следующим образом: -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="20" -{!> ../../docs_src/dependencies/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | "Подсказка" - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | "Подсказка" - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial004.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial004_an_py310.py hl[19] *} ...и **FastAPI** будет знать, что делать. -/// tip | "Подсказка" +/// tip | Подсказка Если это покажется вам более запутанным, чем полезным, не обращайте внимания, это вам не *нужно*. diff --git a/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index 305ce46cb5196..f9b9dec2557ce 100644 --- a/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -14,35 +14,7 @@ Это должен быть `list` состоящий из `Depends()`: -//// tab | Python 3.9+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18" -{!> ../../docs_src/dependencies/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8 без Annotated - -/// подсказка - -Рекомендуется использовать версию с Annotated, если возможно. - -/// - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial006.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[19] *} Зависимости из dependencies выполнятся так же, как и обычные зависимости. Но их значения (если они были) не будут переданы в *функцию операции пути*. @@ -72,69 +44,13 @@ Они могут объявлять требования к запросу (например заголовки) или другие подзависимости: -//// tab | Python 3.9+ - -```Python hl_lines="8 13" -{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="7 12" -{!> ../../docs_src/dependencies/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8 без Annotated - -/// подсказка - -Рекомендуется использовать версию с Annotated, если возможно. - -/// - -```Python hl_lines="6 11" -{!> ../../docs_src/dependencies/tutorial006.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[8,13] *} ### Вызов исключений Зависимости из dependencies могут вызывать исключения с помощью `raise`, как и обычные зависимости: -//// tab | Python 3.9+ - -```Python hl_lines="10 15" -{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 14" -{!> ../../docs_src/dependencies/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8 без Annotated - -/// подсказка - -Рекомендуется использовать версию с Annotated, если возможно. - -/// - -```Python hl_lines="8 13" -{!> ../../docs_src/dependencies/tutorial006.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[10,15] *} ### Возвращаемые значения @@ -142,35 +58,7 @@ Таким образом, вы можете переиспользовать обычную зависимость (возвращающую значение), которую вы уже используете где-то в другом месте, и хотя значение не будет использоваться, зависимость будет выполнена: -//// tab | Python 3.9+ - -```Python hl_lines="11 16" -{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10 15" -{!> ../../docs_src/dependencies/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8 без Annotated - -/// подсказка - -Рекомендуется использовать версию с Annotated, если возможно. - -/// - -```Python hl_lines="9 14" -{!> ../../docs_src/dependencies/tutorial006.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[11,16] *} ## Dependencies для группы *операций путей* diff --git a/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md index 99a86e999ea9c..e64f6777c27ca 100644 --- a/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md @@ -4,13 +4,13 @@ FastAPI поддерживает зависимости, которые выпо Для этого используйте `yield` вместо `return`, а дополнительный код напишите после него. -/// tip | "Подсказка" +/// tip | Подсказка Обязательно используйте `yield` один-единственный раз. /// -/// note | "Технические детали" +/// note | Технические детали Любая функция, с которой может работать: @@ -29,23 +29,17 @@ FastAPI поддерживает зависимости, которые выпо Перед созданием ответа будет выполнен только код до и включая `yield`. -```Python hl_lines="2-4" -{!../../docs_src/dependencies/tutorial007.py!} -``` +{* ../../docs_src/dependencies/tutorial007.py hl[2:4] *} Полученное значение и есть то, что будет внедрено в функцию операции пути и другие зависимости: -```Python hl_lines="4" -{!../../docs_src/dependencies/tutorial007.py!} -``` +{* ../../docs_src/dependencies/tutorial007.py hl[4] *} Код, следующий за оператором `yield`, выполняется после доставки ответа: -```Python hl_lines="5-6" -{!../../docs_src/dependencies/tutorial007.py!} -``` +{* ../../docs_src/dependencies/tutorial007.py hl[5:6] *} -/// tip | "Подсказка" +/// tip | Подсказка Можно использовать как `async` так и обычные функции. @@ -63,9 +57,7 @@ FastAPI поддерживает зависимости, которые выпо Таким же образом можно использовать `finally`, чтобы убедиться, что обязательные шаги при выходе выполнены, независимо от того, было ли исключение или нет. -```Python hl_lines="3 5" -{!../../docs_src/dependencies/tutorial007.py!} -``` +{* ../../docs_src/dependencies/tutorial007.py hl[3,5] *} ## Подзависимости с `yield` @@ -75,35 +67,7 @@ FastAPI поддерживает зависимости, которые выпо Например, `dependency_c` может иметь зависимость от `dependency_b`, а `dependency_b` от `dependency_a`: -//// tab | Python 3.9+ - -```Python hl_lines="6 14 22" -{!> ../../docs_src/dependencies/tutorial008_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="5 13 21" -{!> ../../docs_src/dependencies/tutorial008_an.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | "Подсказка" - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="4 12 20" -{!> ../../docs_src/dependencies/tutorial008.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial008_an_py39.py hl[6,14,22] *} И все они могут использовать `yield`. @@ -111,35 +75,7 @@ FastAPI поддерживает зависимости, которые выпо И, в свою очередь, `dependency_b` нуждается в том, чтобы значение из `dependency_a` (здесь `dep_a`) было доступно для ее завершающего кода. -//// tab | Python 3.9+ - -```Python hl_lines="18-19 26-27" -{!> ../../docs_src/dependencies/tutorial008_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="17-18 25-26" -{!> ../../docs_src/dependencies/tutorial008_an.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | "Подсказка" - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="16-17 24-25" -{!> ../../docs_src/dependencies/tutorial008.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial008_an_py39.py hl[18:19,26:27] *} Точно так же можно иметь часть зависимостей с `yield`, часть с `return`, и какие-то из них могут зависеть друг от друга. @@ -149,7 +85,7 @@ FastAPI поддерживает зависимости, которые выпо **FastAPI** проследит за тем, чтобы все выполнялось в правильном порядке. -/// note | "Технические детали" +/// note | Технические детали Это работает благодаря Контекстным менеджерам в Python. @@ -177,7 +113,7 @@ FastAPI поддерживает зависимости, которые выпо Если у вас есть пользовательские исключения, которые вы хотите обрабатывать *до* возврата ответа и, возможно, модифицировать ответ, даже вызывая `HTTPException`, создайте [Cобственный обработчик исключений](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}. -/// tip | "Подсказка" +/// tip | Подсказка Вы все еще можете вызывать исключения, включая `HTTPException`, *до* `yield`. Но не после. @@ -225,7 +161,7 @@ participant tasks as Background tasks end ``` -/// info | "Дополнительная информация" +/// info | Дополнительная информация Клиенту будет отправлен только **один ответ**. Это может быть один из ответов об ошибке или это будет ответ от *операции пути*. @@ -233,7 +169,7 @@ participant tasks as Background tasks /// -/// tip | "Подсказка" +/// tip | Подсказка На этой диаграмме показано "HttpException", но вы также можете вызвать любое другое исключение, для которого вы создаете [Пользовательский обработчик исключений](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}. @@ -243,7 +179,7 @@ participant tasks as Background tasks ## Зависимости с `yield`, `HTTPException` и фоновыми задачами -/// warning | "Внимание" +/// warning | Внимание Скорее всего, вам не нужны эти технические подробности, вы можете пропустить этот раздел и продолжить ниже. @@ -257,7 +193,7 @@ participant tasks as Background tasks Тем не менее, поскольку это означало бы ожидание ответа в сети, а также ненужное удержание ресурса в зависимости от доходности (например, соединение с базой данных), это было изменено в FastAPI 0.106.0. -/// tip | "Подсказка" +/// tip | Подсказка Кроме того, фоновая задача обычно представляет собой независимый набор логики, который должен обрабатываться отдельно, со своими собственными ресурсами (например, собственным подключением к базе данных). Таким образом, вы, вероятно, получите более чистый код. @@ -290,7 +226,7 @@ with open("./somefile.txt") as f: ### Использование менеджеров контекста в зависимостях с помощью `yield` -/// warning | "Внимание" +/// warning | Внимание Это более или менее "продвинутая" идея. @@ -303,11 +239,9 @@ with open("./somefile.txt") as f: Вы также можете использовать их внутри зависимостей **FastAPI** с `yield`, используя операторы `with` или `async with` внутри функции зависимости: -```Python hl_lines="1-9 13" -{!../../docs_src/dependencies/tutorial010.py!} -``` +{* ../../docs_src/dependencies/tutorial010.py hl[1:9,13] *} -/// tip | "Подсказка" +/// tip | Подсказка Другой способ создания контекстного менеджера - с помощью: diff --git a/docs/ru/docs/tutorial/dependencies/global-dependencies.md b/docs/ru/docs/tutorial/dependencies/global-dependencies.md index 7dbd50ae12618..5d2e70f6e620f 100644 --- a/docs/ru/docs/tutorial/dependencies/global-dependencies.md +++ b/docs/ru/docs/tutorial/dependencies/global-dependencies.md @@ -6,35 +6,7 @@ В этом случае они будут применяться ко всем *операциям пути* в приложении: -//// tab | Python 3.9+ - -```Python hl_lines="16" -{!> ../../docs_src/dependencies/tutorial012_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="16" -{!> ../../docs_src/dependencies/tutorial012_an.py!} -``` - -//// - -//// tab | Python 3.8 non-Annotated - -/// tip | "Подсказка" - -Рекомендуется использовать 'Annotated' версию, если это возможно. - -/// - -```Python hl_lines="15" -{!> ../../docs_src/dependencies/tutorial012.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial012_an_py39.py hl[16] *} Все способы [добавления зависимостей в *декораторах операций пути*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} по-прежнему применимы, но в данном случае зависимости применяются ко всем *операциям пути* приложения. diff --git a/docs/ru/docs/tutorial/dependencies/index.md b/docs/ru/docs/tutorial/dependencies/index.md index fcd9f46dc2c2a..28790bd5ac1a1 100644 --- a/docs/ru/docs/tutorial/dependencies/index.md +++ b/docs/ru/docs/tutorial/dependencies/index.md @@ -29,57 +29,7 @@ Давайте для начала сфокусируемся на зависимостях. Это просто функция, которая может принимать все те же параметры, что и *функции обработки пути*: -//// tab | Python 3.10+ - -```Python hl_lines="8-9" -{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="8-11" -{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9-12" -{!> ../../docs_src/dependencies/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | "Подсказка" - -Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. - -/// - -```Python hl_lines="6-7" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | "Подсказка" - -Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. - -/// - -```Python hl_lines="8-11" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8:9] *} **И всё.** @@ -99,7 +49,7 @@ И в конце она возвращает `dict`, содержащий эти значения. -/// info | "Информация" +/// info | Информация **FastAPI** добавил поддержку для `Annotated` (и начал её рекомендовать) в версии 0.95.0. @@ -111,113 +61,13 @@ ### Import `Depends` -//// tab | Python 3.10+ - -```Python hl_lines="3" -{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3" -{!> ../../docs_src/dependencies/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | "Подсказка" - -Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | "Подсказка" - -Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. - -/// - -```Python hl_lines="3" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[3] *} ### Объявите зависимость в "зависимом" Точно так же, как вы использовали `Body`, `Query` и т.д. с вашей *функцией обработки пути* для параметров, используйте `Depends` с новым параметром: -//// tab | Python 3.10+ - -```Python hl_lines="13 18" -{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="15 20" -{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="16 21" -{!> ../../docs_src/dependencies/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | "Подсказка" - -Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. - -/// - -```Python hl_lines="11 16" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | "Подсказка" - -Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. - -/// - -```Python hl_lines="15 20" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[13,18] *} `Depends` работает немного иначе. Вы передаёте в `Depends` одиночный параметр, который будет похож на функцию. @@ -225,7 +75,7 @@ И потом функция берёт параметры так же, как *функция обработки пути*. -/// tip | "Подсказка" +/// tip | Подсказка В следующей главе вы увидите, какие другие вещи, помимо функций, можно использовать в качестве зависимостей. @@ -250,7 +100,7 @@ common_parameters --> read_users Таким образом, вы пишете общий код один раз, и **FastAPI** позаботится о его вызове для ваших *операций с путями*. -/// check | "Проверка" +/// check | Проверка Обратите внимание, что вы не создаёте специальный класс и не передаёте его куда-то в **FastAPI** для регистрации, или что-то в этом роде. @@ -270,31 +120,9 @@ commons: Annotated[dict, Depends(common_parameters)] Но потому что мы используем `Annotated`, мы можем хранить `Annotated` значение в переменной и использовать его в нескольких местах: -//// tab | Python 3.10+ - -```Python hl_lines="12 16 21" -{!> ../../docs_src/dependencies/tutorial001_02_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="14 18 23" -{!> ../../docs_src/dependencies/tutorial001_02_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="15 19 24" -{!> ../../docs_src/dependencies/tutorial001_02_an.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_02_an_py310.py hl[12,16,21] *} -/// tip | "Подсказка" +/// tip | Подсказка Это стандартный синтаксис python и называется "type alias", это не особенность **FastAPI**. @@ -316,7 +144,7 @@ commons: Annotated[dict, Depends(common_parameters)] Это всё не важно. **FastAPI** знает, что нужно сделать. 😎 -/// note | "Информация" +/// note | Информация Если вам эта тема не знакома, прочтите [Async: *"In a hurry?"*](../../async.md){.internal-link target=_blank} раздел о `async` и `await` в документации. diff --git a/docs/ru/docs/tutorial/dependencies/sub-dependencies.md b/docs/ru/docs/tutorial/dependencies/sub-dependencies.md index ae0fd0824d342..5e8de0c4aa669 100644 --- a/docs/ru/docs/tutorial/dependencies/sub-dependencies.md +++ b/docs/ru/docs/tutorial/dependencies/sub-dependencies.md @@ -10,57 +10,7 @@ Можно создать первую зависимость следующим образом: -//// tab | Python 3.10+ - -```Python hl_lines="8-9" -{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="8-9" -{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="9-10" -{!> ../../docs_src/dependencies/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10 без Annotated - -/// tip | "Подсказка" - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="6-7" -{!> ../../docs_src/dependencies/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.6 без Annotated - -/// tip | "Подсказка" - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="8-9" -{!> ../../docs_src/dependencies/tutorial005.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[8:9] *} Она объявляет необязательный параметр запроса `q` как строку, а затем возвращает его. @@ -70,57 +20,7 @@ Затем можно создать еще одну функцию зависимости, которая в то же время содержит внутри себя первую зависимость (таким образом, она тоже является "зависимой"): -//// tab | Python 3.10+ - -```Python hl_lines="13" -{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="13" -{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="14" -{!> ../../docs_src/dependencies/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10 без Annotated - -/// tip | "Подсказка" - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="11" -{!> ../../docs_src/dependencies/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.6 без Annotated - -/// tip | "Подсказка" - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="13" -{!> ../../docs_src/dependencies/tutorial005.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[13] *} Остановимся на объявленных параметрах: @@ -133,59 +33,9 @@ Затем мы можем использовать зависимость вместе с: -//// tab | Python 3.10+ - -```Python hl_lines="23" -{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="23" -{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="24" -{!> ../../docs_src/dependencies/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10 без Annotated - -/// tip | "Подсказка" - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.6 без Annotated - -/// tip | "Подсказка" - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="22" -{!> ../../docs_src/dependencies/tutorial005.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[23] *} -/// info | "Дополнительная информация" +/// info | Дополнительная информация Обратите внимание, что мы объявляем только одну зависимость в *функции операции пути* - `query_or_cookie_extractor`. @@ -223,7 +73,7 @@ async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_ca //// tab | Python 3.6+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Предпочтительнее использовать версию с аннотацией, если это возможно. @@ -244,7 +94,7 @@ async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False Но, тем не менее, эта система очень мощная и позволяет вам объявлять вложенные графы (деревья) зависимостей сколь угодно глубоко. -/// tip | "Подсказка" +/// tip | Подсказка Все это может показаться не столь полезным на этих простых примерах. diff --git a/docs/ru/docs/tutorial/encoder.md b/docs/ru/docs/tutorial/encoder.md index c9900cb2c15db..4ed5039b3fb45 100644 --- a/docs/ru/docs/tutorial/encoder.md +++ b/docs/ru/docs/tutorial/encoder.md @@ -20,21 +20,7 @@ Она принимает объект, например, модель Pydantic, и возвращает его версию, совместимую с JSON: -//// tab | Python 3.10+ - -```Python hl_lines="4 21" -{!> ../../docs_src/encoder/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="5 22" -{!> ../../docs_src/encoder/tutorial001.py!} -``` - -//// +{* ../../docs_src/encoder/tutorial001_py310.py hl[4,21] *} В данном примере она преобразует Pydantic модель в `dict`, а `datetime` - в `str`. @@ -42,7 +28,7 @@ Функция не возвращает большой `str`, содержащий данные в формате JSON (в виде строки). Она возвращает стандартную структуру данных Python (например, `dict`) со значениями и подзначениями, которые совместимы с JSON. -/// note | "Технические детали" +/// note | Технические детали `jsonable_encoder` фактически используется **FastAPI** внутри системы для преобразования данных. Однако он полезен и во многих других сценариях. diff --git a/docs/ru/docs/tutorial/extra-data-types.md b/docs/ru/docs/tutorial/extra-data-types.md index 82cb0ff7a0f25..6d6d4aa9f6266 100644 --- a/docs/ru/docs/tutorial/extra-data-types.md +++ b/docs/ru/docs/tutorial/extra-data-types.md @@ -55,36 +55,8 @@ Вот пример *операции пути* с параметрами, который демонстрирует некоторые из вышеперечисленных типов. -//// tab | Python 3.8 и выше - -```Python hl_lines="1 3 12-16" -{!> ../../docs_src/extra_data_types/tutorial001.py!} -``` - -//// - -//// tab | Python 3.10 и выше - -```Python hl_lines="1 2 11-15" -{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/extra_data_types/tutorial001.py hl[1,3,12:16] *} Обратите внимание, что параметры внутри функции имеют свой естественный тип данных, и вы, например, можете выполнять обычные манипуляции с датами, такие как: -//// tab | Python 3.8 и выше - -```Python hl_lines="18-19" -{!> ../../docs_src/extra_data_types/tutorial001.py!} -``` - -//// - -//// tab | Python 3.10 и выше - -```Python hl_lines="17-18" -{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/extra_data_types/tutorial001.py hl[18:19] *} diff --git a/docs/ru/docs/tutorial/extra-models.md b/docs/ru/docs/tutorial/extra-models.md index e7ff3f40f21d7..5b51aa4023742 100644 --- a/docs/ru/docs/tutorial/extra-models.md +++ b/docs/ru/docs/tutorial/extra-models.md @@ -8,7 +8,7 @@ * **Модель для вывода** не должна содержать пароль. * **Модель для базы данных**, возможно, должна содержать хэшированный пароль. -/// danger | "Внимание" +/// danger | Внимание Никогда не храните пароли пользователей в чистом виде. Всегда храните "безопасный хэш", который вы затем сможете проверить. @@ -20,21 +20,7 @@ Ниже изложена основная идея того, как могут выглядеть эти модели с полями для паролей, а также описаны места, где они используются: -//// tab | Python 3.10+ - -```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" -{!> ../../docs_src/extra_models/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" -{!> ../../docs_src/extra_models/tutorial001.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial001_py310.py hl[7,9,14,20,22,27:28,31:33,38:39] *} ### Про `**user_in.dict()` @@ -146,7 +132,7 @@ UserInDB( ) ``` -/// warning | "Предупреждение" +/// warning | Предупреждение Цель использованных в примере вспомогательных функций - не более чем демонстрация возможных операций с данными, но, конечно, они не обеспечивают настоящую безопасность. @@ -168,21 +154,7 @@ UserInDB( В этом случае мы можем определить только различия между моделями (с `password` в чистом виде, с `hashed_password` и без пароля): -//// tab | Python 3.10+ - -```Python hl_lines="7 13-14 17-18 21-22" -{!> ../../docs_src/extra_models/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 15-16 19-20 23-24" -{!> ../../docs_src/extra_models/tutorial002.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial002_py310.py hl[7,13:14,17:18,21:22] *} ## `Union` или `anyOf` @@ -192,27 +164,13 @@ UserInDB( Для этого используйте стандартные аннотации типов в Python `typing.Union`: -/// note | "Примечание" +/// note | Примечание При объявлении `Union`, сначала указывайте наиболее детальные типы, затем менее детальные. В примере ниже более детальный `PlaneItem` стоит перед `CarItem` в `Union[PlaneItem, CarItem]`. /// -//// tab | Python 3.10+ - -```Python hl_lines="1 14-15 18-20 33" -{!> ../../docs_src/extra_models/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 14-15 18-20 33" -{!> ../../docs_src/extra_models/tutorial003.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial003_py310.py hl[1,14:15,18:20,33] *} ### `Union` в Python 3.10 @@ -234,21 +192,7 @@ some_variable: PlaneItem | CarItem Для этого используйте `typing.List` из стандартной библиотеки Python (или просто `list` в Python 3.9 и выше): -//// tab | Python 3.9+ - -```Python hl_lines="18" -{!> ../../docs_src/extra_models/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 20" -{!> ../../docs_src/extra_models/tutorial004.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial004_py39.py hl[18] *} ## Ответ с произвольным `dict` @@ -258,21 +202,7 @@ some_variable: PlaneItem | CarItem В этом случае вы можете использовать `typing.Dict` (или просто `dict` в Python 3.9 и выше): -//// tab | Python 3.9+ - -```Python hl_lines="6" -{!> ../../docs_src/extra_models/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 8" -{!> ../../docs_src/extra_models/tutorial005.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial005_py39.py hl[6] *} ## Резюме diff --git a/docs/ru/docs/tutorial/first-steps.md b/docs/ru/docs/tutorial/first-steps.md index b1de217cd48b8..cb3d19a711927 100644 --- a/docs/ru/docs/tutorial/first-steps.md +++ b/docs/ru/docs/tutorial/first-steps.md @@ -2,9 +2,7 @@ Самый простой FastAPI файл может выглядеть так: -```Python -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py *} Скопируйте в файл `main.py`. @@ -24,7 +22,7 @@ $ uvicorn main:app --reload -/// note | "Технические детали" +/// note | Технические детали Команда `uvicorn main:app` обращается к: @@ -133,13 +131,11 @@ OpenAPI описывает схему API. Эта схема содержит о ### Шаг 1: импортируйте `FastAPI` -```Python hl_lines="1" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[1] *} `FastAPI` это класс в Python, который предоставляет всю функциональность для API. -/// note | "Технические детали" +/// note | Технические детали `FastAPI` это класс, который наследуется непосредственно от `Starlette`. @@ -149,9 +145,7 @@ OpenAPI описывает схему API. Эта схема содержит о ### Шаг 2: создайте экземпляр `FastAPI` -```Python hl_lines="3" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[3] *} Переменная `app` является экземпляром класса `FastAPI`. @@ -171,9 +165,7 @@ $ uvicorn main:app --reload Если создать такое приложение: -```Python hl_lines="3" -{!../../docs_src/first_steps/tutorial002.py!} -``` +{* ../../docs_src/first_steps/tutorial002.py hl[3] *} И поместить его в `main.py`, тогда вызов `uvicorn` будет таким: @@ -205,7 +197,7 @@ https://example.com/items/foo /items/foo ``` -/// info | "Дополнительная иформация" +/// info | Дополнительная иформация Термин "path" также часто называется "endpoint" или "route". @@ -250,16 +242,14 @@ https://example.com/items/foo #### Определите *декоратор операции пути (path operation decorator)* -```Python hl_lines="6" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[6] *} Декоратор `@app.get("/")` указывает **FastAPI**, что функция, прямо под ним, отвечает за обработку запросов, поступающих по адресу: * путь `/` * использующих get операцию -/// info | "`@decorator` Дополнительная информация" +/// info | `@decorator` Дополнительная информация Синтаксис `@something` в Python называется "декоратор". @@ -286,7 +276,7 @@ https://example.com/items/foo * `@app.patch()` * `@app.trace()` -/// tip | "Подсказка" +/// tip | Подсказка Вы можете использовать каждую операцию (HTTP-метод) по своему усмотрению. @@ -306,9 +296,7 @@ https://example.com/items/foo * **операция**: `get`. * **функция**: функция ниже "декоратора" (ниже `@app.get("/")`). -```Python hl_lines="7" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[7] *} Это обычная Python функция. @@ -320,11 +308,9 @@ 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}. @@ -332,9 +318,7 @@ https://example.com/items/foo ### Шаг 5: верните результат -```Python hl_lines="8" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[8] *} Вы можете вернуть `dict`, `list`, отдельные значения `str`, `int` и т.д. diff --git a/docs/ru/docs/tutorial/handling-errors.md b/docs/ru/docs/tutorial/handling-errors.md index e7bfb85aa3434..c596abe1f1939 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,7 +59,7 @@ } ``` -/// tip | "Подсказка" +/// tip | Подсказка При вызове `HTTPException` в качестве параметра `detail` можно передавать любое значение, которое может быть преобразовано в JSON, а не только `str`. @@ -81,9 +77,7 @@ Но в случае, если это необходимо для продвинутого сценария, можно добавить пользовательские заголовки: -```Python hl_lines="14" -{!../../docs_src/handling_errors/tutorial002.py!} -``` +{* ../../docs_src/handling_errors/tutorial002.py hl[14] *} ## Установка пользовательских обработчиков исключений @@ -95,9 +89,7 @@ Можно добавить собственный обработчик исключений с помощью `@app.exception_handler()`: -```Python hl_lines="5-7 13-18 24" -{!../../docs_src/handling_errors/tutorial003.py!} -``` +{* ../../docs_src/handling_errors/tutorial003.py hl[5:7,13:18,24] *} Здесь, если запросить `/unicorns/yolo`, то *операция пути* вызовет `UnicornException`. @@ -109,7 +101,7 @@ {"message": "Oops! yolo did something. There goes a rainbow..."} ``` -/// note | "Технические детали" +/// note | Технические детали Также можно использовать `from starlette.requests import Request` и `from starlette.responses import JSONResponse`. @@ -135,9 +127,7 @@ Обработчик исключения получит объект `Request` и исключение. -```Python hl_lines="2 14-16" -{!../../docs_src/handling_errors/tutorial004.py!} -``` +{* ../../docs_src/handling_errors/tutorial004.py hl[2,14:16] *} Теперь, если перейти к `/items/foo`, то вместо стандартной JSON-ошибки с: @@ -166,7 +156,7 @@ path -> item_id #### `RequestValidationError` или `ValidationError` -/// warning | "Внимание" +/// warning | Внимание Это технические детали, которые можно пропустить, если они не важны для вас сейчас. @@ -188,11 +178,9 @@ 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`. @@ -206,9 +194,7 @@ path -> item_id Вы можете использовать его при разработке приложения для регистрации тела и его отладки, возврата пользователю и т.д. -```Python hl_lines="14" -{!../../docs_src/handling_errors/tutorial005.py!} -``` +{* ../../docs_src/handling_errors/tutorial005.py hl[14] *} Теперь попробуйте отправить недействительный элемент, например: @@ -266,8 +252,6 @@ from starlette.exceptions import HTTPException as StarletteHTTPException Если вы хотите использовать исключение вместе с теми же обработчиками исключений по умолчанию из **FastAPI**, вы можете импортировать и повторно использовать обработчики исключений по умолчанию из `fastapi.exception_handlers`: -```Python hl_lines="2-5 15 21" -{!../../docs_src/handling_errors/tutorial006.py!} -``` +{* ../../docs_src/handling_errors/tutorial006.py hl[2:5,15,21] *} В этом примере вы просто `выводите в терминал` ошибку с очень выразительным сообщением, но идея вам понятна. Вы можете использовать исключение, а затем просто повторно использовать стандартные обработчики исключений. diff --git a/docs/ru/docs/tutorial/header-params.md b/docs/ru/docs/tutorial/header-params.md index 18e1e60d07330..e892cfc071f20 100644 --- a/docs/ru/docs/tutorial/header-params.md +++ b/docs/ru/docs/tutorial/header-params.md @@ -6,57 +6,7 @@ Сперва импортируйте `Header`: -//// tab | Python 3.10+ - -```Python hl_lines="3" -{!> ../../docs_src/header_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/header_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3" -{!> ../../docs_src/header_params/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | "Подсказка" - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/header_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | "Подсказка" - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="3" -{!> ../../docs_src/header_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/header_params/tutorial001_an_py310.py hl[3] *} ## Объявление параметров `Header` @@ -64,59 +14,9 @@ Первое значение является значением по умолчанию, вы можете передать все дополнительные параметры валидации или аннотации: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/header_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/header_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/header_params/tutorial001_an.py!} -``` +{* ../../docs_src/header_params/tutorial001_an_py310.py hl[9] *} -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | "Подсказка" - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/header_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | "Подсказка" - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/header_params/tutorial001.py!} -``` - -//// - -/// note | "Технические детали" +/// note | Технические детали `Header` - это "родственный" класс `Path`, `Query` и `Cookie`. Он также наследуется от того же общего класса `Param`. @@ -124,7 +24,7 @@ /// -/// info | "Дополнительная информация" +/// info | Дополнительная информация Чтобы объявить заголовки, важно использовать `Header`, иначе параметры интерпретируются как query-параметры. @@ -146,59 +46,9 @@ Если по какой-либо причине вам необходимо отключить автоматическое преобразование подчеркиваний в дефисы, установите для параметра `convert_underscores` в `Header` значение `False`: -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/header_params/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ +{* ../../docs_src/header_params/tutorial002_an_py310.py hl[10] *} -```Python hl_lines="11" -{!> ../../docs_src/header_params/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="12" -{!> ../../docs_src/header_params/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | "Подсказка" - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="8" -{!> ../../docs_src/header_params/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | "Подсказка" - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/header_params/tutorial002.py!} -``` - -//// - -/// warning | "Внимание" +/// warning | Внимание Прежде чем установить для `convert_underscores` значение `False`, имейте в виду, что некоторые HTTP-прокси и серверы запрещают использование заголовков с подчеркиванием. @@ -214,71 +64,7 @@ Например, чтобы объявить заголовок `X-Token`, который может появляться более одного раза, вы можете написать: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/header_params/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/header_params/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/header_params/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | "Подсказка" - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/header_params/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.9+ без Annotated - -/// tip | "Подсказка" - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/header_params/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | "Подсказка" - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/header_params/tutorial003.py!} -``` - -//// +{* ../../docs_src/header_params/tutorial003_an_py310.py hl[9] *} Если вы взаимодействуете с этой *операцией пути*, отправляя два HTTP-заголовка, таких как: diff --git a/docs/ru/docs/tutorial/index.md b/docs/ru/docs/tutorial/index.md index 4cf45c0ed3578..ddca2fbb10d99 100644 --- a/docs/ru/docs/tutorial/index.md +++ b/docs/ru/docs/tutorial/index.md @@ -52,7 +52,7 @@ $ pip install "fastapi[all]" ...это также включает `uvicorn`, который вы можете использовать в качестве сервера, который запускает ваш код. -/// note | "Технические детали" +/// note | Технические детали Вы также можете установить его по частям. diff --git a/docs/ru/docs/tutorial/metadata.md b/docs/ru/docs/tutorial/metadata.md index 246458f420cd0..f070735085130 100644 --- a/docs/ru/docs/tutorial/metadata.md +++ b/docs/ru/docs/tutorial/metadata.md @@ -17,11 +17,9 @@ Вы можете задать их следующим образом: -```Python hl_lines="3-16 19-31" -{!../../docs_src/metadata/tutorial001.py!} -``` +{* ../../docs_src/metadata/tutorial001.py hl[3:16,19:31] *} -/// tip | "Подсказка" +/// tip | Подсказка Вы можете использовать Markdown в поле `description`, и оно будет отображено в выводе. @@ -51,13 +49,11 @@ Создайте метаданные для ваших тегов и передайте их в параметре `openapi_tags`: -```Python hl_lines="3-16 18" -{!../../docs_src/metadata/tutorial004.py!} -``` +{* ../../docs_src/metadata/tutorial004.py hl[3:16,18] *} Помните, что вы можете использовать Markdown внутри описания, к примеру "login" будет отображен жирным шрифтом (**login**) и "fancy" будет отображаться курсивом (_fancy_). -/// tip | "Подсказка" +/// tip | Подсказка Вам необязательно добавлять метаданные для всех используемых тегов @@ -66,11 +62,9 @@ ### Используйте собственные теги Используйте параметр `tags` с вашими *операциями пути* (и `APIRouter`ами), чтобы присвоить им различные теги: -```Python hl_lines="21 26" -{!../../docs_src/metadata/tutorial004.py!} -``` +{* ../../docs_src/metadata/tutorial004.py hl[21,26] *} -/// info | "Дополнительная информация" +/// info | Дополнительная информация Узнайте больше о тегах в [Конфигурации операции пути](path-operation-configuration.md#_3){.internal-link target=_blank}. @@ -96,9 +90,7 @@ К примеру, чтобы задать её отображение по адресу `/api/v1/openapi.json`: -```Python hl_lines="3" -{!../../docs_src/metadata/tutorial002.py!} -``` +{* ../../docs_src/metadata/tutorial002.py hl[3] *} Если вы хотите отключить схему OpenAPI полностью, вы можете задать `openapi_url=None`, это также отключит пользовательские интерфейсы документации, которые его использует. @@ -115,6 +107,4 @@ К примеру, чтобы задать отображение Swagger UI по адресу `/documentation` и отключить ReDoc: -```Python hl_lines="3" -{!../../docs_src/metadata/tutorial003.py!} -``` +{* ../../docs_src/metadata/tutorial003.py hl[3] *} diff --git a/docs/ru/docs/tutorial/path-operation-configuration.md b/docs/ru/docs/tutorial/path-operation-configuration.md index 5f3855af291e4..af471ca69e8a8 100644 --- a/docs/ru/docs/tutorial/path-operation-configuration.md +++ b/docs/ru/docs/tutorial/path-operation-configuration.md @@ -2,7 +2,7 @@ Существует несколько параметров, которые вы можете передать вашему *декоратору операций пути* для его настройки. -/// warning | "Внимание" +/// warning | Внимание Помните, что эти параметры передаются непосредственно *декоратору операций пути*, а не вашей *функции-обработчику операций пути*. @@ -16,33 +16,11 @@ Но если вы не помните, для чего нужен каждый числовой код, вы можете использовать сокращенные константы в параметре `status`: -//// tab | Python 3.10+ - -```Python hl_lines="1 15" -{!> ../../docs_src/path_operation_configuration/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="3 17" -{!> ../../docs_src/path_operation_configuration/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3 17" -{!> ../../docs_src/path_operation_configuration/tutorial001.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial001_py310.py hl[1,15] *} Этот код состояния будет использован в ответе и будет добавлен в схему OpenAPI. -/// note | "Технические детали" +/// note | Технические детали Вы также можете использовать `from starlette import status`. @@ -54,29 +32,7 @@ Вы можете добавлять теги к вашим *операциям пути*, добавив параметр `tags` с `list` заполненным `str`-значениями (обычно в нём только одна строка): -//// tab | Python 3.10+ - -```Python hl_lines="15 20 25" -{!> ../../docs_src/path_operation_configuration/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="17 22 27" -{!> ../../docs_src/path_operation_configuration/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17 22 27" -{!> ../../docs_src/path_operation_configuration/tutorial002.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial002_py310.py hl[15,20,25] *} Они будут добавлены в схему OpenAPI и будут использованы в автоматической документации интерфейса: @@ -90,37 +46,13 @@ **FastAPI** поддерживает это так же, как и в случае с обычными строками: -```Python hl_lines="1 8-10 13 18" -{!../../docs_src/path_operation_configuration/tutorial002b.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial002b.py hl[1,8:10,13,18] *} ## Краткое и развёрнутое содержание Вы можете добавить параметры `summary` и `description`: -//// tab | Python 3.10+ - -```Python hl_lines="18-19" -{!> ../../docs_src/path_operation_configuration/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="20-21" -{!> ../../docs_src/path_operation_configuration/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20-21" -{!> ../../docs_src/path_operation_configuration/tutorial003.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial003_py310.py hl[18:19] *} ## Описание из строк документации @@ -128,29 +60,7 @@ Вы можете использовать Markdown в строке документации, и он будет интерпретирован и отображён корректно (с учетом отступа в строке документации). -//// tab | Python 3.10+ - -```Python hl_lines="17-25" -{!> ../../docs_src/path_operation_configuration/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="19-27" -{!> ../../docs_src/path_operation_configuration/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="19-27" -{!> ../../docs_src/path_operation_configuration/tutorial004.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial004_py310.py hl[17:25] *} Он будет использован в интерактивной документации: @@ -160,37 +70,15 @@ Вы можете указать описание ответа с помощью параметра `response_description`: -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/path_operation_configuration/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="21" -{!> ../../docs_src/path_operation_configuration/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="21" -{!> ../../docs_src/path_operation_configuration/tutorial005.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial005_py310.py hl[19] *} -/// info | "Дополнительная информация" +/// info | Дополнительная информация Помните, что `response_description` относится конкретно к ответу, а `description` относится к *операции пути* в целом. /// -/// check | "Технические детали" +/// check | Технические детали OpenAPI указывает, что каждой *операции пути* необходимо описание ответа. @@ -204,9 +92,7 @@ OpenAPI указывает, что каждой *операции пути* не Если вам необходимо пометить *операцию пути* как устаревшую, при этом не удаляя её, передайте параметр `deprecated`: -```Python hl_lines="16" -{!../../docs_src/path_operation_configuration/tutorial006.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial006.py hl[16] *} Он будет четко помечен как устаревший в интерактивной документации: diff --git a/docs/ru/docs/tutorial/path-params-numeric-validations.md b/docs/ru/docs/tutorial/path-params-numeric-validations.md index bf42ec7253056..dca267f780035 100644 --- a/docs/ru/docs/tutorial/path-params-numeric-validations.md +++ b/docs/ru/docs/tutorial/path-params-numeric-validations.md @@ -6,59 +6,9 @@ Сначала импортируйте `Path` из `fastapi`, а также импортируйте `Annotated`: -//// tab | 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!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="1 3" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3-4" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | "Подсказка" - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | "Подсказка" - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="3" -{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} -``` - -//// - -/// info | "Информация" +/// info | Информация Поддержка `Annotated` была добавлена в FastAPI начиная с версии 0.95.0 (и с этой версии рекомендуется использовать этот подход). @@ -74,59 +24,9 @@ Например, чтобы указать значение метаданных `title` для path-параметра `item_id`, вы можете написать: -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[10] *} -//// - -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | "Подсказка" - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="8" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | "Подсказка" - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} -``` - -//// - -/// note | "Примечание" +/// note | Примечание Path-параметр всегда является обязательным, поскольку он составляет часть пути. @@ -138,7 +38,7 @@ Path-параметр всегда является обязательным, п ## Задайте нужный вам порядок параметров -/// tip | "Подсказка" +/// tip | Подсказка Это не имеет большого значения, если вы используете `Annotated`. @@ -160,7 +60,7 @@ Path-параметр всегда является обязательным, п //// tab | Python 3.8 без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -174,25 +74,11 @@ Path-параметр всегда является обязательным, п Но имейте в виду, что если вы используете `Annotated`, вы не столкнётесь с этой проблемой, так как вы не используете `Query()` или `Path()` в качестве значения по умолчанию для параметра функции. -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/path_params_numeric_validations/tutorial002_an.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py hl[10] *} ## Задайте нужный вам порядок параметров, полезные приёмы -/// tip | "Подсказка" +/// tip | Подсказка Это не имеет большого значения, если вы используете `Annotated`. @@ -213,29 +99,13 @@ Path-параметр всегда является обязательным, п Python не будет ничего делать с `*`, но он будет знать, что все следующие параметры являются именованными аргументами (парами ключ-значение), также известными как kwargs, даже если у них нет значений по умолчанию. -```Python hl_lines="7" -{!../../docs_src/path_params_numeric_validations/tutorial003.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *} ### Лучше с `Annotated` Имейте в виду, что если вы используете `Annotated`, то, поскольку вы не используете значений по умолчанию для параметров функции, то у вас не возникнет подобной проблемы и вам не придётся использовать `*`. -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/path_params_numeric_validations/tutorial003_an.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py hl[10] *} ## Валидация числовых данных: больше или равно @@ -243,35 +113,7 @@ Python не будет ничего делать с `*`, но он будет з В этом примере при указании `ge=1`, параметр `item_id` должен быть больше или равен `1` ("`g`reater than or `e`qual"). -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/path_params_numeric_validations/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | "Подсказка" - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="8" -{!> ../../docs_src/path_params_numeric_validations/tutorial004.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py hl[10] *} ## Валидация числовых данных: больше и меньше или равно @@ -280,35 +122,7 @@ Python не будет ничего делать с `*`, но он будет з * `gt`: больше (`g`reater `t`han) * `le`: меньше или равно (`l`ess than or `e`qual) -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/path_params_numeric_validations/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | "Подсказка" - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/path_params_numeric_validations/tutorial005.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py hl[10] *} ## Валидация числовых данных: числа с плавающей точкой, больше и меньше @@ -320,35 +134,7 @@ Python не будет ничего делать с `*`, но он будет з То же самое справедливо и для lt. -//// tab | Python 3.9+ - -```Python hl_lines="13" -{!> ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="12" -{!> ../../docs_src/path_params_numeric_validations/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | "Подсказка" - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="11" -{!> ../../docs_src/path_params_numeric_validations/tutorial006.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py hl[13] *} ## Резюме @@ -361,7 +147,7 @@ Python не будет ничего делать с `*`, но он будет з * `lt`: меньше (`l`ess `t`han) * `le`: меньше или равно (`l`ess than or `e`qual) -/// info | "Информация" +/// info | Информация `Query`, `Path` и другие классы, которые мы разберём позже, являются наследниками общего класса `Param`. @@ -369,7 +155,7 @@ Python не будет ничего делать с `*`, но он будет з /// -/// note | "Технические детали" +/// note | Технические детали `Query`, `Path` и другие "классы", которые вы импортируете из `fastapi`, на самом деле являются функциями, которые при вызове возвращают экземпляры одноимённых классов. diff --git a/docs/ru/docs/tutorial/path-params.md b/docs/ru/docs/tutorial/path-params.md index d1d76cf7b0617..5c2d82a650206 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,13 +16,11 @@ Вы можете объявить тип параметра пути в функции, используя стандартные аннотации типов Python. -```Python hl_lines="7" -{!../../docs_src/path_params/tutorial002.py!} -``` +{* ../../docs_src/path_params/tutorial002.py hl[7] *} Здесь, `item_id` объявлен типом `int`. -/// check | "Заметка" +/// check | Заметка Это обеспечит поддержку редактора внутри функции (проверка ошибок, автодополнение и т.п.). @@ -38,7 +34,7 @@ {"item_id":3} ``` -/// check | "Заметка" +/// check | Заметка Обратите внимание на значение `3`, которое получила (и вернула) функция. Это целочисленный Python `int`, а не строка `"3"`. @@ -69,7 +65,7 @@ Та же ошибка возникнет, если вместо `int` передать `float` , например: http://127.0.0.1:8000/items/4.2 -/// check | "Заметка" +/// check | Заметка **FastAPI** обеспечивает проверку типов, используя всё те же определения типов. @@ -85,7 +81,7 @@ -/// check | "Заметка" +/// check | Заметка Ещё раз, просто используя определения типов, **FastAPI** обеспечивает автоматическую интерактивную документацию (с интеграцией Swagger UI). @@ -122,17 +118,13 @@ Поскольку *операции пути* выполняются в порядке их объявления, необходимо, чтобы путь для `/users/me` был объявлен раньше, чем путь для `/users/{user_id}`: -```Python hl_lines="6 11" -{!../../docs_src/path_params/tutorial003.py!} -``` +{* ../../docs_src/path_params/tutorial003.py hl[6,11] *} Иначе путь для `/users/{user_id}` также будет соответствовать `/users/me`, "подразумевая", что он получает параметр `user_id` со значением `"me"`. Аналогично, вы не можете переопределить операцию с путем: -```Python hl_lines="6 11" -{!../../docs_src/path_params/tutorial003b.py!} -``` +{* ../../docs_src/path_params/tutorial003b.py hl[6,11] *} Первый будет выполняться всегда, так как путь совпадает первым. @@ -148,17 +140,15 @@ Затем создайте атрибуты класса с фиксированными допустимыми значениями: -```Python hl_lines="1 6-9" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[1,6:9] *} -/// info | "Дополнительная информация" +/// info | Дополнительная информация Перечисления (enum) доступны в Python начиная с версии 3.4. /// -/// tip | "Подсказка" +/// tip | Подсказка Если интересно, то "AlexNet", "ResNet" и "LeNet" - это названия моделей машинного обучения. @@ -168,9 +158,7 @@ Определите *параметр пути*, используя в аннотации типа класс перечисления (`ModelName`), созданный ранее: -```Python hl_lines="16" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[16] *} ### Проверьте документацию @@ -186,19 +174,15 @@ Вы можете сравнить это значение с *элементом перечисления* класса `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 | "Подсказка" +/// tip | Подсказка Значение `"lenet"` также можно получить с помощью `ModelName.lenet.value`. @@ -210,9 +194,7 @@ Они будут преобразованы в соответствующие значения (в данном случае - строки) перед их возвратом клиенту: -```Python hl_lines="18 21 23" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[18,21,23] *} Вы отправите клиенту такой JSON-ответ: ```JSON @@ -250,11 +232,9 @@ OpenAPI не поддерживает способов объявления *п Можете использовать так: -```Python hl_lines="6" -{!../../docs_src/path_params/tutorial004.py!} -``` +{* ../../docs_src/path_params/tutorial004.py hl[6] *} -/// tip | "Подсказка" +/// tip | Подсказка Возможно, вам понадобится, чтобы параметр содержал `/home/johndoe/myfile.txt` с ведущим слэшем (`/`). diff --git a/docs/ru/docs/tutorial/query-param-models.md b/docs/ru/docs/tutorial/query-param-models.md new file mode 100644 index 0000000000000..45de1cc76a7dd --- /dev/null +++ b/docs/ru/docs/tutorial/query-param-models.md @@ -0,0 +1,196 @@ +# Модели Query-Параметров + +Если у вас есть группа связанных **query-параметров**, то вы можете объединить их в одну **Pydantic-модель**. + +Это позволит вам **переиспользовать модель** в **разных местах**, устанавливать валидаторы и метаданные, в том числе для сразу всех параметров, в одном месте. 😎 + +/// note | Заметка + +Этот функционал доступен с версии `0.115.0`. 🤓 + +/// + +## Pydantic-Модель для Query-Параметров + +Объявите нужные **query-параметры** в **Pydantic-модели**, а после аннотируйте параметр как `Query`: + +//// tab | Python 3.10+ + +```Python hl_lines="9-13 17" +{!> ../../docs_src/query_param_models/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="8-12 16" +{!> ../../docs_src/query_param_models/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10-14 18" +{!> ../../docs_src/query_param_models/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ без Annotated + +/// tip | Совет + +При возможности используйте версию с `Annotated`. + +/// + +```Python hl_lines="9-13 17" +{!> ../../docs_src/query_param_models/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.9+ без Annotated + +/// tip | Совет + +При возможности используйте версию с `Annotated`. + +/// + +```Python hl_lines="8-12 16" +{!> ../../docs_src/query_param_models/tutorial001_py39.py!} +``` + +//// + +//// tab | Python 3.8+ без Annotated + +/// tip | Совет + +При возможности используйте версию с `Annotated`. + +/// + +```Python hl_lines="9-13 17" +{!> ../../docs_src/query_param_models/tutorial001_py310.py!} +``` + +//// + +**FastAPI извлечёт** данные соответствующие **каждому полю модели** из **query-параметров** запроса и выдаст вам объявленную Pydantic-модель заполненную ими. + +## Проверьте Сгенерированную Документацию + +Вы можете посмотреть query-параметры в графическом интерфейсе сгенерированной документации по пути `/docs`: + +
+ +
+ +## Запретить Дополнительные Query-Параметры + +В некоторых случаях (не особо часто встречающихся) вам может понадобиться **ограничить** query-параметры, которые вы хотите получить. + +Вы можете сконфигурировать Pydantic-модель так, чтобы запретить (`forbid`) все дополнительные (`extra`) поля. + +//// tab | Python 3.10+ + +```Python hl_lines="10" +{!> ../../docs_src/query_param_models/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../docs_src/query_param_models/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="11" +{!> ../../docs_src/query_param_models/tutorial002_an.py!} +``` + +//// + +//// tab | Python 3.10+ без Annotated + +/// tip | Совет + +При возможности используйте версию с `Annotated`. + +/// + +```Python hl_lines="10" +{!> ../../docs_src/query_param_models/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.9+ без Annotated + +/// tip | Совет + +При возможности используйте версию с `Annotated`. + +/// + +```Python hl_lines="9" +{!> ../../docs_src/query_param_models/tutorial002_py39.py!} +``` + +//// + +//// tab | Python 3.8+ без Annotated + +/// tip | Совет + +При возможности используйте версию с `Annotated`. + +/// + +```Python hl_lines="11" +{!> ../../docs_src/query_param_models/tutorial002.py!} +``` + +//// + +Если клиент попробует отправить **дополнительные** данные в **query-параметрах**, то в ответ он получит **ошибку**. + +Например, если клиент попытается отправить query-параметр `tool` с значением `plumbus`, в виде: + +```http +https://example.com/items/?limit=10&tool=plumbus +``` + +То в ответ он получит **ошибку**, сообщающую ему, что query-параметр `tool` не разрешен: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["query", "tool"], + "msg": "Extra inputs are not permitted", + "input": "plumbus" + } + ] +} +``` + +## Заключение + +Вы можете использовать **Pydantic-модели** для объявления **query-параметров** в **FastAPI**. 😎 + +/// tip | Совет + +Спойлер: вы также можете использовать Pydantic-модели для группировки кук (cookies) и заголовков (headers), но об этом вы прочитаете позже. 🤫 + +/// diff --git a/docs/ru/docs/tutorial/query-params-str-validations.md b/docs/ru/docs/tutorial/query-params-str-validations.md index 0054af6ed4057..32a98ff220b16 100644 --- a/docs/ru/docs/tutorial/query-params-str-validations.md +++ b/docs/ru/docs/tutorial/query-params-str-validations.md @@ -4,25 +4,11 @@ Давайте рассмотрим следующий пример: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial001.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial001_py310.py hl[7] *} Query-параметр `q` имеет тип `Union[str, None]` (или `str | None` в Python 3.10). Это означает, что входной параметр будет типа `str`, но может быть и `None`. Ещё параметр имеет значение по умолчанию `None`, из-за чего FastAPI определит параметр как необязательный. -/// note | "Технические детали" +/// note | Технические детали FastAPI определит параметр `q` как необязательный, потому что его значение по умолчанию `= None`. @@ -113,21 +99,7 @@ q: Annotated[Union[str, None]] = None Теперь, когда у нас есть `Annotated`, где мы можем добавить больше метаданных, добавим `Query` со значением параметра `max_length` равным 50: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial002_an.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial002_an_py310.py hl[9] *} Обратите внимание, что значение по умолчанию всё ещё `None`, так что параметр остаётся необязательным. @@ -143,7 +115,7 @@ q: Annotated[Union[str, None]] = None В предыдущих версиях FastAPI (ниже 0.95.0) необходимо было использовать `Query` как значение по умолчанию для query-параметра. Так было вместо размещения его в `Annotated`, так что велика вероятность, что вам встретится такой код. Сейчас объясню. -/// tip | "Подсказка" +/// tip | Подсказка При написании нового кода и везде где это возможно, используйте `Annotated`, как было описано ранее. У этого способа есть несколько преимуществ (о них дальше) и никаких недостатков. 🍰 @@ -151,21 +123,7 @@ q: Annotated[Union[str, None]] = None Вот как вы могли бы использовать `Query()` в качестве значения по умолчанию параметра вашей функции, установив для параметра `max_length` значение 50: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial002.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial002_py310.py hl[7] *} В таком случае (без использования `Annotated`), мы заменили значение по умолчанию с `None` на `Query()` в функции. Теперь нам нужно установить значение по умолчанию для query-параметра `Query(default=None)`, что необходимо для тех же целей, как когда ранее просто указывалось значение по умолчанию (по крайней мере, для FastAPI). @@ -195,7 +153,7 @@ q: str | None = None Но он явно объявляет его как query-параметр. -/// info | "Дополнительная информация" +/// info | Дополнительная информация Запомните, важной частью объявления параметра как необязательного является: @@ -265,113 +223,13 @@ q: str = Query(default="rick") Вы также можете добавить параметр `min_length`: -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | "Подсказка" - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | "Подсказка" - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial003.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial003_an_py310.py hl[10] *} ## Регулярные выражения Вы можете определить регулярное выражение, которому должен соответствовать параметр: -//// tab | Python 3.10+ - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="12" -{!> ../../docs_src/query_params_str_validations/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | "Подсказка" - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | "Подсказка" - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial004.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial004_an_py310.py hl[11] *} Данное регулярное выражение проверяет, что полученное значение параметра: @@ -389,37 +247,9 @@ q: str = Query(default="rick") Например, вы хотите для параметра запроса `q` указать, что он должен состоять минимум из 3 символов (`min_length=3`) и иметь значение по умолчанию `"fixedquery"`: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial005_an.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial005_an_py39.py hl[9] *} -//// tab | Python 3.8+ без Annotated - -/// tip | "Подсказка" - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial005.py!} -``` - -//// - -/// note | "Технические детали" +/// note | Технические детали Наличие значения по умолчанию делает параметр необязательным. @@ -459,79 +289,15 @@ q: Union[str, None] = Query(default=None, min_length=3) В таком случае, чтобы сделать query-параметр `Query` обязательным, вы можете просто не указывать значение по умолчанию: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | "Подсказка" - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial006.py!} -``` - -/// tip | "Подсказка" - -Обратите внимание, что даже когда `Query()` используется как значение по умолчанию для параметра функции, мы не передаём `default=None` в `Query()`. - -Лучше будет использовать версию с `Annotated`. 😉 - -/// - -//// +{* ../../docs_src/query_params_str_validations/tutorial006_an_py39.py hl[9] *} ### Обязательный параметр с Ellipsis (`...`) Альтернативный способ указать обязательность параметра запроса - это указать параметр `default` через многоточие `...`: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial006b_an.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | "Подсказка" - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial006b.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial006b_an_py39.py hl[9] *} -/// info | "Дополнительная информация" +/// info | Дополнительная информация Если вы ранее не сталкивались с `...`: это специальное значение, часть языка Python и называется "Ellipsis". @@ -547,59 +313,9 @@ q: Union[str, None] = Query(default=None, min_length=3) Чтобы этого добиться, вам нужно определить `None` как валидный тип для параметра запроса, но также указать `default=...`: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial006c_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial006c_an_py310.py hl[9] *} -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial006c_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | "Подсказка" - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial006c_py310.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | "Подсказка" - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial006c.py!} -``` - -//// - -/// tip | "Подсказка" +/// tip | Подсказка Pydantic, мощь которого используется в FastAPI для валидации и сериализации, имеет специальное поведение для `Optional` или `Union[Something, None]` без значения по умолчанию. Вы можете узнать об этом больше в документации Pydantic, раздел Обязательные Опциональные поля. @@ -609,37 +325,9 @@ Pydantic, мощь которого используется в FastAPI для Если вас смущает `...`, вы можете использовать `Required` из Pydantic: -//// tab | Python 3.9+ - -```Python hl_lines="4 10" -{!> ../../docs_src/query_params_str_validations/tutorial006d_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="2 9" -{!> ../../docs_src/query_params_str_validations/tutorial006d_an.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated +{* ../../docs_src/query_params_str_validations/tutorial006d_an_py39.py hl[4,10] *} -/// tip | "Подсказка" - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="2 8" -{!> ../../docs_src/query_params_str_validations/tutorial006d.py!} -``` - -//// - -/// tip | "Подсказка" +/// tip | Подсказка Запомните, когда вам необходимо объявить query-параметр обязательным, вы можете просто не указывать параметр `default`. Таким образом, вам редко придётся использовать `...` или `Required`. @@ -651,71 +339,7 @@ Pydantic, мощь которого используется в FastAPI для Например, query-параметр `q` может быть указан в URL несколько раз. И если вы ожидаете такой формат запроса, то можете указать это следующим образом: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial011_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial011_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial011_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | "Подсказка" - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial011_py310.py!} -``` - -//// - -//// tab | Python 3.9+ без Annotated - -/// tip | "Подсказка" - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial011_py39.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | "Подсказка" - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial011.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial011_an_py310.py hl[9] *} Затем, получив такой URL: @@ -736,7 +360,7 @@ http://localhost:8000/items/?q=foo&q=bar } ``` -/// tip | "Подсказка" +/// tip | Подсказка Чтобы объявить query-параметр типом `list`, как в примере выше, вам нужно явно использовать `Query`, иначе он будет интерпретирован как тело запроса. @@ -750,49 +374,7 @@ http://localhost:8000/items/?q=foo&q=bar Вы также можете указать тип `list` со списком значений по умолчанию на случай, если вам их не предоставят: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial012_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial012_an.py!} -``` - -//// - -//// tab | Python 3.9+ без Annotated - -/// tip | "Подсказка" - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial012_py39.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | "Подсказка" - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial012.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial012_an_py39.py hl[9] *} Если вы перейдёте по ссылке: @@ -815,37 +397,9 @@ http://localhost:8000/items/ Вы также можете использовать `list` напрямую вместо `List[str]` (или `list[str]` в Python 3.9+): -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial013_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial013_an.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | "Подсказка" - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial013.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial013_an_py39.py hl[9] *} -//// - -/// note | "Технические детали" +/// note | Технические детали Запомните, что в таком случае, FastAPI не будет проверять содержимое списка. @@ -859,7 +413,7 @@ http://localhost:8000/items/ Указанная информация будет включена в генерируемую OpenAPI документацию и использована в пользовательском интерфейсе и внешних инструментах. -/// note | "Технические детали" +/// note | Технические детали Имейте в виду, что разные инструменты могут иметь разные уровни поддержки OpenAPI. @@ -869,111 +423,11 @@ http://localhost:8000/items/ Вы можете указать название query-параметра, используя параметр `title`: -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial007_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial007_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial007_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | "Подсказка" - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial007_py310.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | "Подсказка" - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial007.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial007_an_py310.py hl[10] *} Добавить описание, используя параметр `description`: -//// tab | Python 3.10+ - -```Python hl_lines="14" -{!> ../../docs_src/query_params_str_validations/tutorial008_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="14" -{!> ../../docs_src/query_params_str_validations/tutorial008_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="15" -{!> ../../docs_src/query_params_str_validations/tutorial008_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | "Подсказка" - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial008_py310.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | "Подсказка" - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="13" -{!> ../../docs_src/query_params_str_validations/tutorial008.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial008_an_py310.py hl[14] *} ## Псевдонимы параметров @@ -993,57 +447,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems Тогда вы можете объявить `псевдоним`, и этот псевдоним будет использоваться для поиска значения параметра запроса: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial009_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial009_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial009_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | "Подсказка" - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial009_py310.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | "Подсказка" - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial009.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial009_an_py310.py hl[9] *} ## Устаревшие параметры @@ -1053,57 +457,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems Тогда для `Query` укажите параметр `deprecated=True`: -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/query_params_str_validations/tutorial010_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="19" -{!> ../../docs_src/query_params_str_validations/tutorial010_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20" -{!> ../../docs_src/query_params_str_validations/tutorial010_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | "Подсказка" - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="16" -{!> ../../docs_src/query_params_str_validations/tutorial010_py310.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | "Подсказка" - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="18" -{!> ../../docs_src/query_params_str_validations/tutorial010.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial010_an_py310.py hl[19] *} В документации это будет отображено следующим образом: @@ -1113,57 +467,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems Чтобы исключить query-параметр из генерируемой OpenAPI схемы (а также из системы автоматической генерации документации), укажите в `Query` параметр `include_in_schema=False`: -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial014_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial014_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial014_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | "Подсказка" - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial014_py310.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | "Подсказка" - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial014.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial014_an_py310.py hl[10] *} ## Резюме diff --git a/docs/ru/docs/tutorial/query-params.md b/docs/ru/docs/tutorial/query-params.md index edf06746b974f..547d9831dd198 100644 --- a/docs/ru/docs/tutorial/query-params.md +++ b/docs/ru/docs/tutorial/query-params.md @@ -2,9 +2,7 @@ Когда вы объявляете параметры функции, которые не являются параметрами пути, они автоматически интерпретируются как "query"-параметры. -```Python hl_lines="9" -{!../../docs_src/query_params/tutorial001.py!} -``` +{* ../../docs_src/query_params/tutorial001.py hl[9] *} Query-параметры представляют из себя набор пар ключ-значение, которые идут после знака `?` в URL-адресе, разделенные символами `&`. @@ -63,25 +61,11 @@ http://127.0.0.1:8000/items/?skip=20 Аналогично, вы можете объявлять необязательные query-параметры, установив их значение по умолчанию, равное `None`: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/query_params/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params/tutorial002.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial002_py310.py hl[7] *} В этом случае, параметр `q` будет не обязательным и будет иметь значение `None` по умолчанию. -/// check | "Важно" +/// check | Важно Также обратите внимание, что **FastAPI** достаточно умён чтобы заметить, что параметр `item_id` является path-параметром, а `q` нет, поэтому, это параметр запроса. @@ -91,21 +75,7 @@ http://127.0.0.1:8000/items/?skip=20 Вы также можете объявлять параметры с типом `bool`, которые будут преобразованы соответственно: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/query_params/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params/tutorial003.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial003_py310.py hl[7] *} В этом случае, если вы сделаете запрос: @@ -148,21 +118,7 @@ http://127.0.0.1:8000/items/foo?short=yes Они будут обнаружены по именам: -//// tab | Python 3.10+ - -```Python hl_lines="6 8" -{!> ../../docs_src/query_params/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8 10" -{!> ../../docs_src/query_params/tutorial004.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial004_py310.py hl[6,8] *} ## Обязательные query-параметры @@ -172,9 +128,7 @@ http://127.0.0.1:8000/items/foo?short=yes Но если вы хотите сделать query-параметр обязательным, вы можете просто не указывать значение по умолчанию: -```Python hl_lines="6-7" -{!../../docs_src/query_params/tutorial005.py!} -``` +{* ../../docs_src/query_params/tutorial005.py hl[6:7] *} Здесь параметр запроса `needy` является обязательным параметром с типом данных `str`. @@ -218,21 +172,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy Конечно, вы можете определить некоторые параметры как обязательные, некоторые - со значением по умполчанию, а некоторые - полностью необязательные: -//// tab | Python 3.10+ - -```Python hl_lines="8" -{!> ../../docs_src/query_params/tutorial006_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params/tutorial006.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial006_py310.py hl[8] *} В этом примере, у нас есть 3 параметра запроса: @@ -240,7 +180,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy * `skip`, типа `int` и со значением по умолчанию `0`. * `limit`, необязательный `int`. -/// tip | "Подсказка" +/// tip | Подсказка Вы можете использовать класс `Enum` также, как ранее применяли его с [Path-параметрами](path-params.md#_7){.internal-link target=_blank}. diff --git a/docs/ru/docs/tutorial/request-files.md b/docs/ru/docs/tutorial/request-files.md index 34b9c94fa2835..2cfa4e1dce1ef 100644 --- a/docs/ru/docs/tutorial/request-files.md +++ b/docs/ru/docs/tutorial/request-files.md @@ -2,7 +2,7 @@ Используя класс `File`, мы можем позволить клиентам загружать файлы. -/// info | "Дополнительная информация" +/// info | Дополнительная информация Чтобы получать загруженные файлы, сначала установите `python-multipart`. @@ -16,71 +16,15 @@ Импортируйте `File` и `UploadFile` из модуля `fastapi`: -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/request_files/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="1" -{!> ../../docs_src/request_files/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | "Подсказка" - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/request_files/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[3] *} ## Определите параметры `File` Создайте параметры `File` так же, как вы это делаете для `Body` или `Form`: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/request_files/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="8" -{!> ../../docs_src/request_files/tutorial001_an.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[9] *} -//// tab | Python 3.6+ без Annotated - -/// tip | "Подсказка" - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/request_files/tutorial001.py!} -``` - -//// - -/// info | "Дополнительная информация" +/// info | Дополнительная информация `File` - это класс, который наследуется непосредственно от `Form`. @@ -88,7 +32,7 @@ /// -/// tip | "Подсказка" +/// tip | Подсказка Для объявления тела файла необходимо использовать `File`, поскольку в противном случае параметры будут интерпретироваться как параметры запроса или параметры тела (JSON). @@ -106,35 +50,7 @@ Определите параметр файла с типом `UploadFile`: -//// tab | Python 3.9+ - -```Python hl_lines="14" -{!> ../../docs_src/request_files/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="13" -{!> ../../docs_src/request_files/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | "Подсказка" - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="12" -{!> ../../docs_src/request_files/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[14] *} Использование `UploadFile` имеет ряд преимуществ перед `bytes`: @@ -177,13 +93,13 @@ contents = await myfile.read() contents = myfile.file.read() ``` -/// note | "Технические детали `async`" +/// note | Технические детали `async` При использовании методов `async` **FastAPI** запускает файловые методы в пуле потоков и ожидает их. /// -/// note | "Технические детали Starlette" +/// note | Технические детали Starlette **FastAPI** наследует `UploadFile` непосредственно из **Starlette**, но добавляет некоторые детали для совместимости с **Pydantic** и другими частями FastAPI. @@ -195,7 +111,7 @@ contents = myfile.file.read() **FastAPI** позаботится о том, чтобы считать эти данные из нужного места, а не из JSON. -/// note | "Технические детали" +/// note | Технические детали Данные из форм обычно кодируются с использованием "media type" `application/x-www-form-urlencoded` когда он не включает файлы. @@ -205,7 +121,7 @@ contents = myfile.file.read() /// -/// warning | "Внимание" +/// warning | Внимание В операции *функции операции пути* можно объявить несколько параметров `File` и `Form`, но нельзя также объявлять поля `Body`, которые предполагается получить в виде JSON, поскольку тело запроса будет закодировано с помощью `multipart/form-data`, а не `application/json`. @@ -217,91 +133,13 @@ contents = myfile.file.read() Вы можете сделать загрузку файла необязательной, используя стандартные аннотации типов и установив значение по умолчанию `None`: -//// tab | Python 3.10+ - -```Python hl_lines="9 17" -{!> ../../docs_src/request_files/tutorial001_02_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9 17" -{!> ../../docs_src/request_files/tutorial001_02_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="10 18" -{!> ../../docs_src/request_files/tutorial001_02_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | "Подсказка" - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="7 15" -{!> ../../docs_src/request_files/tutorial001_02_py310.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | "Подсказка" - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="9 17" -{!> ../../docs_src/request_files/tutorial001_02.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *} ## `UploadFile` с дополнительными метаданными Вы также можете использовать `File()` вместе с `UploadFile`, например, для установки дополнительных метаданных: -//// tab | Python 3.9+ - -```Python hl_lines="9 15" -{!> ../../docs_src/request_files/tutorial001_03_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="8 14" -{!> ../../docs_src/request_files/tutorial001_03_an.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | "Подсказка" - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="7 13" -{!> ../../docs_src/request_files/tutorial001_03.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_03_an_py39.py hl[9,15] *} ## Загрузка нескольких файлов @@ -311,53 +149,11 @@ contents = myfile.file.read() Для этого необходимо объявить список `bytes` или `UploadFile`: -//// tab | Python 3.9+ - -```Python hl_lines="10 15" -{!> ../../docs_src/request_files/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="11 16" -{!> ../../docs_src/request_files/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.9+ без Annotated - -/// tip | "Подсказка" - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="8 13" -{!> ../../docs_src/request_files/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | "Подсказка" - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="10 15" -{!> ../../docs_src/request_files/tutorial002.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial002_an_py39.py hl[10,15] *} Вы получите, как и было объявлено, список `list` из `bytes` или `UploadFile`. -/// note | "Technical Details" +/// note | Technical Details Можно также использовать `from starlette.responses import HTMLResponse`. @@ -369,49 +165,7 @@ contents = myfile.file.read() Так же, как и раньше, вы можете использовать `File()` для задания дополнительных параметров, даже для `UploadFile`: -//// tab | Python 3.9+ - -```Python hl_lines="11 18-20" -{!> ../../docs_src/request_files/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="12 19-21" -{!> ../../docs_src/request_files/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.9+ без Annotated - -/// tip | "Подсказка" - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="9 16" -{!> ../../docs_src/request_files/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | "Подсказка" - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="11 18" -{!> ../../docs_src/request_files/tutorial003.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial003_an_py39.py hl[11,18:20] *} ## Резюме diff --git a/docs/ru/docs/tutorial/request-forms-and-files.md b/docs/ru/docs/tutorial/request-forms-and-files.md index 9b449bcd9bba7..116c0cdb1c813 100644 --- a/docs/ru/docs/tutorial/request-forms-and-files.md +++ b/docs/ru/docs/tutorial/request-forms-and-files.md @@ -2,7 +2,7 @@ Вы можете определять файлы и поля формы одновременно, используя `File` и `Form`. -/// info | "Дополнительная информация" +/// info | Дополнительная информация Чтобы получать загруженные файлы и/или данные форм, сначала установите `python-multipart`. @@ -12,75 +12,19 @@ ## Импортируйте `File` и `Form` -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="1" -{!> ../../docs_src/request_forms_and_files/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | "Подсказка" - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/request_forms_and_files/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[3] *} ## Определите параметры `File` и `Form` Создайте параметры файла и формы таким же образом, как для `Body` или `Query`: -//// tab | Python 3.9+ - -```Python hl_lines="10-12" -{!> ../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="9-11" -{!> ../../docs_src/request_forms_and_files/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | "Подсказка" - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="8" -{!> ../../docs_src/request_forms_and_files/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[10:12] *} Файлы и поля формы будут загружены в виде данных формы, и вы получите файлы и поля формы. Вы можете объявить некоторые файлы как `bytes`, а некоторые - как `UploadFile`. -/// warning | "Внимание" +/// warning | Внимание Вы можете объявить несколько параметров `File` и `Form` в операции *path*, но вы не можете также объявить поля `Body`, которые вы ожидаете получить в виде JSON, так как запрос будет иметь тело, закодированное с помощью `multipart/form-data` вместо `application/json`. diff --git a/docs/ru/docs/tutorial/request-forms.md b/docs/ru/docs/tutorial/request-forms.md index 93b44437b2215..b33ea044be4d1 100644 --- a/docs/ru/docs/tutorial/request-forms.md +++ b/docs/ru/docs/tutorial/request-forms.md @@ -2,7 +2,7 @@ Когда вам нужно получить поля формы вместо JSON, вы можете использовать `Form`. -/// info | "Дополнительная информация" +/// info | Дополнительная информация Чтобы использовать формы, сначала установите `python-multipart`. @@ -14,69 +14,13 @@ Импортируйте `Form` из `fastapi`: -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/request_forms/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1" -{!> ../../docs_src/request_forms/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | "Подсказка" - -Рекомендуется использовать 'Annotated' версию, если это возможно. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/request_forms/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[3] *} ## Определение параметров `Form` Создайте параметры формы так же, как это делается для `Body` или `Query`: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/request_forms/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/request_forms/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | "Подсказка" - -Рекомендуется использовать 'Annotated' версию, если это возможно. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/request_forms/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[9] *} Например, в одном из способов использования спецификации OAuth2 (называемом "потоком пароля") требуется отправить `username` и `password` в виде полей формы. @@ -84,13 +28,13 @@ Вы можете настроить `Form` точно так же, как настраиваете и `Body` ( `Query`, `Path`, `Cookie`), включая валидации, примеры, псевдонимы (например, `user-name` вместо `username`) и т.д. -/// info | "Дополнительная информация" +/// info | Дополнительная информация `Form` - это класс, который наследуется непосредственно от `Body`. /// -/// tip | "Подсказка" +/// tip | Подсказка Вам необходимо явно указывать параметр `Form` при объявлении каждого поля, иначе поля будут интерпретироваться как параметры запроса или параметры тела (JSON). @@ -102,7 +46,7 @@ **FastAPI** гарантирует правильное чтение этих данных из соответствующего места, а не из JSON. -/// note | "Технические детали" +/// note | Технические детали Данные из форм обычно кодируются с использованием "типа медиа" `application/x-www-form-urlencoded`. @@ -112,7 +56,7 @@ /// -/// warning | "Предупреждение" +/// warning | Предупреждение Вы можете объявлять несколько параметров `Form` в *операции пути*, но вы не можете одновременно с этим объявлять поля `Body`, которые вы ожидаете получить в виде JSON, так как запрос будет иметь тело, закодированное с использованием `application/x-www-form-urlencoded`, а не `application/json`. diff --git a/docs/ru/docs/tutorial/response-model.md b/docs/ru/docs/tutorial/response-model.md index 363e64676ffe2..b3c29281c9f50 100644 --- a/docs/ru/docs/tutorial/response-model.md +++ b/docs/ru/docs/tutorial/response-model.md @@ -4,29 +4,7 @@ FastAPI позволяет использовать **аннотации типов** таким же способом, как и для ввода данных в **параметры** функции, вы можете использовать модели Pydantic, списки, словари, скалярные типы (такие, как int, bool и т.д.). -//// tab | Python 3.10+ - -```Python hl_lines="16 21" -{!> ../../docs_src/response_model/tutorial001_01_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="18 23" -{!> ../../docs_src/response_model/tutorial001_01_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18 23" -{!> ../../docs_src/response_model/tutorial001_01.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial001_01_py310.py hl[16,21] *} FastAPI будет использовать этот возвращаемый тип для: @@ -59,31 +37,9 @@ FastAPI будет использовать этот возвращаемый т * `@app.delete()` * и др. -//// tab | 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!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="17 22 24-27" -{!> ../../docs_src/response_model/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17 22 24-27" -{!> ../../docs_src/response_model/tutorial001.py!} -``` - -//// - -/// note | "Технические детали" +/// note | Технические детали Помните, что параметр `response_model` является параметром именно декоратора http-методов (`get`, `post`, и т.п.). Не следует его указывать для *функций операций пути*, как вы бы поступили с другими параметрами или с телом запроса. @@ -93,7 +49,7 @@ FastAPI будет использовать этот возвращаемый т FastAPI будет использовать значение `response_model` для того, чтобы автоматически генерировать документацию, производить валидацию и т.п. А также для **конвертации и фильтрации выходных данных** в объявленный тип. -/// tip | "Подсказка" +/// tip | Подсказка Если вы используете анализаторы типов со строгой проверкой (например, mypy), можно указать `Any` в качестве типа возвращаемого значения функции. @@ -113,23 +69,9 @@ FastAPI будет использовать значение `response_model` д Здесь мы объявили модель `UserIn`, которая хранит пользовательский пароль в открытом виде: -//// tab | Python 3.10+ - -```Python hl_lines="7 9" -{!> ../../docs_src/response_model/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 11" -{!> ../../docs_src/response_model/tutorial002.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial002_py310.py hl[7,9] *} -/// info | "Информация" +/// info | Информация Чтобы использовать `EmailStr`, прежде необходимо установить `email-validator`. Используйте `pip install email-validator` @@ -139,21 +81,7 @@ FastAPI будет использовать значение `response_model` д Далее мы используем нашу модель в аннотациях типа как для аргумента функции, так и для выходного значения: -//// tab | Python 3.10+ - -```Python hl_lines="16" -{!> ../../docs_src/response_model/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18" -{!> ../../docs_src/response_model/tutorial002.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial002_py310.py hl[16] *} Теперь всякий раз, когда клиент создает пользователя с паролем, API будет возвращать его пароль в ответе. @@ -161,7 +89,7 @@ FastAPI будет использовать значение `response_model` д Но что если мы захотим использовать эту модель для какой-либо другой *операции пути*? Мы можем, сами того не желая, отправить пароль любому другому пользователю. -/// danger | "Осторожно" +/// danger | Осторожно Никогда не храните пароли пользователей в открытом виде, а также никогда не возвращайте их в ответе, как в примере выше. В противном случае - убедитесь, что вы хорошо продумали и учли все возможные риски такого подхода и вам известно, что вы делаете. @@ -171,57 +99,15 @@ FastAPI будет использовать значение `response_model` д Вместо этого мы можем создать входную модель, хранящую пароль в открытом виде и выходную модель без пароля: -//// tab | Python 3.10+ - -```Python hl_lines="9 11 16" -{!> ../../docs_src/response_model/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 11 16" -{!> ../../docs_src/response_model/tutorial003.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_py310.py hl[9,11,16] *} В таком случае, даже несмотря на то, что наша *функция операции пути* возвращает тот же самый объект пользователя с паролем, полученным на вход: -//// tab | Python 3.10+ - -```Python hl_lines="24" -{!> ../../docs_src/response_model/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24" -{!> ../../docs_src/response_model/tutorial003.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_py310.py hl[24] *} ...мы указали в `response_model` модель `UserOut`, в которой отсутствует поле, содержащее пароль - и он будет исключен из ответа: -//// tab | Python 3.10+ - -```Python hl_lines="22" -{!> ../../docs_src/response_model/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="22" -{!> ../../docs_src/response_model/tutorial003.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_py310.py hl[22] *} Таким образом **FastAPI** позаботится о фильтрации ответа и исключит из него всё, что не указано в выходной модели (при помощи Pydantic). @@ -245,21 +131,7 @@ FastAPI будет использовать значение `response_model` д И в таких случаях мы можем использовать классы и наследование, чтобы пользоваться преимуществами **аннотаций типов** и получать более полную статическую проверку типов. Но при этом все так же получать **фильтрацию ответа** от FastAPI. -//// tab | Python 3.10+ - -```Python hl_lines="7-10 13-14 18" -{!> ../../docs_src/response_model/tutorial003_01_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9-13 15-16 20" -{!> ../../docs_src/response_model/tutorial003_01.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_01_py310.py hl[7:10,13:14,18] *} Таким образом, мы получаем поддержку редактора кода и mypy в части типов, сохраняя при этом фильтрацию данных от FastAPI. @@ -301,9 +173,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма Самый частый сценарий использования - это [возвращать Response напрямую, как описано в расширенной документации](../advanced/response-directly.md){.internal-link target=_blank}. -```Python hl_lines="8 10-11" -{!> ../../docs_src/response_model/tutorial003_02.py!} -``` +{* ../../docs_src/response_model/tutorial003_02.py hl[8,10:11] *} Это поддерживается FastAPI по-умолчанию, т.к. аннотация проставлена в классе (или подклассе) `Response`. @@ -313,9 +183,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма Вы также можете указать подкласс `Response` в аннотации типа: -```Python hl_lines="8-9" -{!> ../../docs_src/response_model/tutorial003_03.py!} -``` +{* ../../docs_src/response_model/tutorial003_03.py hl[8:9] *} Это сработает, потому что `RedirectResponse` является подклассом `Response` и FastAPI автоматически обработает этот простейший случай. @@ -325,21 +193,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма То же самое произошло бы, если бы у вас было что-то вроде Union различных типов и один или несколько из них не являлись бы допустимыми типами для Pydantic. Например, такой вариант приведет к ошибке 💥: -//// tab | Python 3.10+ - -```Python hl_lines="8" -{!> ../../docs_src/response_model/tutorial003_04_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/response_model/tutorial003_04.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_04_py310.py hl[8] *} ...такой код вызовет ошибку, потому что в аннотации указан неподдерживаемый Pydantic тип. А также этот тип не является классом или подклассом `Response`. @@ -351,21 +205,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма В таком случае, вы можете отключить генерацию модели ответа, указав `response_model=None`: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/response_model/tutorial003_05_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/response_model/tutorial003_05.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_05_py310.py hl[7] *} Тогда FastAPI не станет генерировать модель ответа и вы сможете сохранить такую аннотацию типа, которая вам требуется, никак не влияя на работу FastAPI. 🤓 @@ -373,29 +213,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма Модель ответа может иметь значения по умолчанию, например: -//// tab | Python 3.10+ - -```Python hl_lines="9 11-12" -{!> ../../docs_src/response_model/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="11 13-14" -{!> ../../docs_src/response_model/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11 13-14" -{!> ../../docs_src/response_model/tutorial004.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial004_py310.py hl[9,11:12] *} * `description: Union[str, None] = None` (или `str | None = None` в Python 3.10), где `None` является значением по умолчанию. * `tax: float = 10.5`, где `10.5` является значением по умолчанию. @@ -409,29 +227,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма Установите для *декоратора операции пути* параметр `response_model_exclude_unset=True`: -//// tab | Python 3.10+ - -```Python hl_lines="22" -{!> ../../docs_src/response_model/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="24" -{!> ../../docs_src/response_model/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24" -{!> ../../docs_src/response_model/tutorial004.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial004_py310.py hl[22] *} и тогда значения по умолчанию не будут включены в ответ. В нем будут только те поля, значения которых фактически были установлены. @@ -444,13 +240,13 @@ FastAPI совместно с Pydantic выполнит некоторую ма } ``` -/// info | "Информация" +/// info | Информация "Под капотом" FastAPI использует метод `.dict()` у объектов моделей Pydantic с параметром `exclude_unset`, чтобы достичь такого эффекта. /// -/// info | "Информация" +/// info | Информация Вы также можете использовать: @@ -494,7 +290,7 @@ FastAPI достаточно умен (на самом деле, это засл И поэтому, они также будут включены в JSON ответа. -/// tip | "Подсказка" +/// tip | Подсказка Значением по умолчанию может быть что угодно, не только `None`. @@ -510,7 +306,7 @@ FastAPI достаточно умен (на самом деле, это засл Это можно использовать как быстрый способ исключить данные из ответа, не создавая отдельную модель Pydantic. -/// tip | "Подсказка" +/// tip | Подсказка Но по-прежнему рекомендуется следовать изложенным выше советам и использовать несколько моделей вместо данных параметров. @@ -520,23 +316,9 @@ FastAPI достаточно умен (на самом деле, это засл /// -//// tab | Python 3.10+ +{* ../../docs_src/response_model/tutorial005_py310.py hl[29,35] *} -```Python hl_lines="29 35" -{!> ../../docs_src/response_model/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="31 37" -{!> ../../docs_src/response_model/tutorial005.py!} -``` - -//// - -/// tip | "Подсказка" +/// tip | Подсказка При помощи кода `{"name","description"}` создается объект множества (`set`) с двумя строковыми значениями. @@ -548,21 +330,7 @@ FastAPI достаточно умен (на самом деле, это засл Если вы забыли про `set` и использовали структуру `list` или `tuple`, FastAPI автоматически преобразует этот объект в `set`, чтобы обеспечить корректную работу: -//// tab | Python 3.10+ - -```Python hl_lines="29 35" -{!> ../../docs_src/response_model/tutorial006_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="31 37" -{!> ../../docs_src/response_model/tutorial006.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial006_py310.py hl[29,35] *} ## Резюме diff --git a/docs/ru/docs/tutorial/response-status-code.md b/docs/ru/docs/tutorial/response-status-code.md index 48808bea77cce..b46f656f3f527 100644 --- a/docs/ru/docs/tutorial/response-status-code.md +++ b/docs/ru/docs/tutorial/response-status-code.md @@ -8,11 +8,9 @@ * `@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` и т.д.), а не *функции-обработчика пути* в отличие от всех остальных параметров и тела запроса. @@ -20,7 +18,7 @@ Параметр `status_code` принимает число, обозначающее HTTP код статуса ответа. -/// info | "Информация" +/// info | Информация В качестве значения параметра `status_code` также может использоваться `IntEnum`, например, из библиотеки `http.HTTPStatus` в Python. @@ -33,7 +31,7 @@ -/// note | "Примечание" +/// note | Примечание Некоторые коды статуса ответа (см. следующий раздел) указывают на то, что ответ не имеет тела. @@ -43,7 +41,7 @@ FastAPI знает об этом и создаст документацию Open ## Об HTTP кодах статуса ответа -/// note | "Примечание" +/// note | Примечание Если вы уже знаете, что представляют собой HTTP коды статуса ответа, можете перейти к следующему разделу. @@ -66,7 +64,7 @@ FastAPI знает об этом и создаст документацию Open * Для общих ошибок со стороны клиента можно просто использовать код `400`. * `5XX` – статус-коды, сообщающие о серверной ошибке. Они почти никогда не используются разработчиками напрямую. Когда что-то идет не так в какой-то части кода вашего приложения или на сервере, он автоматически вернёт один из 5XX кодов. -/// tip | "Подсказка" +/// tip | Подсказка Чтобы узнать больше о HTTP кодах статуса и о том, для чего каждый из них предназначен, ознакомьтесь с документацией MDN об HTTP кодах статуса ответа. @@ -76,9 +74,7 @@ FastAPI знает об этом и создаст документацию Open Рассмотрим предыдущий пример еще раз: -```Python hl_lines="6" -{!../../docs_src/response_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_status_code/tutorial001.py hl[6] *} `201` – это код статуса "Создано". @@ -86,15 +82,13 @@ FastAPI знает об этом и создаст документацию Open Для удобства вы можете использовать переменные из `fastapi.status`. -```Python hl_lines="1 6" -{!../../docs_src/response_status_code/tutorial002.py!} -``` +{* ../../docs_src/response_status_code/tutorial002.py hl[1,6] *} Они содержат те же числовые значения, но позволяют использовать подсказки редактора для выбора кода статуса: -/// note | "Технические детали" +/// note | Технические детали Вы также можете использовать `from starlette import status` вместо `from fastapi import status`. diff --git a/docs/ru/docs/tutorial/schema-extra-example.md b/docs/ru/docs/tutorial/schema-extra-example.md index daa264afc8691..f17b24349de84 100644 --- a/docs/ru/docs/tutorial/schema-extra-example.md +++ b/docs/ru/docs/tutorial/schema-extra-example.md @@ -8,21 +8,7 @@ Вы можете объявить ключ `example` для модели Pydantic, используя класс `Config` и переменную `schema_extra`, как описано в Pydantic документации: Настройка схемы: -//// tab | Python 3.10+ - -```Python hl_lines="13-21" -{!> ../../docs_src/schema_extra_example/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="15-23" -{!> ../../docs_src/schema_extra_example/tutorial001.py!} -``` - -//// +{* ../../docs_src/schema_extra_example/tutorial001_py310.py hl[13:21] *} Эта дополнительная информация будет включена в **JSON Schema** выходных данных для этой модели, и она будет использоваться в документации к API. @@ -40,21 +26,7 @@ Вы можете использовать это, чтобы добавить аргумент `example` для каждого поля: -//// tab | Python 3.10+ - -```Python hl_lines="2 8-11" -{!> ../../docs_src/schema_extra_example/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4 10-13" -{!> ../../docs_src/schema_extra_example/tutorial002.py!} -``` - -//// +{* ../../docs_src/schema_extra_example/tutorial002_py310.py hl[2,8:11] *} /// warning | Внимание @@ -80,57 +52,7 @@ Здесь мы передаём аргумент `example`, как пример данных ожидаемых в параметре `Body()`: -//// tab | Python 3.10+ - -```Python hl_lines="22-27" -{!> ../../docs_src/schema_extra_example/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="22-27" -{!> ../../docs_src/schema_extra_example/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="23-28" -{!> ../../docs_src/schema_extra_example/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Заметка - -Рекомендуется использовать версию с `Annotated`, если это возможно. - -/// - -```Python hl_lines="18-23" -{!> ../../docs_src/schema_extra_example/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Заметка - -Рекомендуется использовать версию с `Annotated`, если это возможно. - -/// - -```Python hl_lines="20-25" -{!> ../../docs_src/schema_extra_example/tutorial003.py!} -``` - -//// +{* ../../docs_src/schema_extra_example/tutorial003_an_py310.py hl[22:27] *} ### Аргумент "example" в UI документации @@ -151,57 +73,7 @@ * `value`: Это конкретный пример, который отображается, например, в виде типа `dict`. * `externalValue`: альтернатива параметру `value`, URL-адрес, указывающий на пример. Хотя это может не поддерживаться таким же количеством инструментов разработки и тестирования API, как параметр `value`. -//// tab | Python 3.10+ - -```Python hl_lines="23-49" -{!> ../../docs_src/schema_extra_example/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="23-49" -{!> ../../docs_src/schema_extra_example/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24-50" -{!> ../../docs_src/schema_extra_example/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Заметка - -Рекомендуется использовать версию с `Annotated`, если это возможно. - -/// - -```Python hl_lines="19-45" -{!> ../../docs_src/schema_extra_example/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Заметка - -Рекомендуется использовать версию с `Annotated`, если это возможно. - -/// - -```Python hl_lines="21-47" -{!> ../../docs_src/schema_extra_example/tutorial004.py!} -``` - -//// +{* ../../docs_src/schema_extra_example/tutorial004_an_py310.py hl[23:49] *} ### Аргумент "examples" в UI документации diff --git a/docs/ru/docs/tutorial/security/first-steps.md b/docs/ru/docs/tutorial/security/first-steps.md index c98ce2c60a0bb..e55f48b899e41 100644 --- a/docs/ru/docs/tutorial/security/first-steps.md +++ b/docs/ru/docs/tutorial/security/first-steps.md @@ -20,39 +20,11 @@ Скопируйте пример в файл `main.py`: -//// tab | Python 3.9+ - -```Python -{!> ../../docs_src/security/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python -{!> ../../docs_src/security/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | "Подсказка" - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python -{!> ../../docs_src/security/tutorial001.py!} -``` - -//// +{* ../../docs_src/security/tutorial001_an_py39.py *} ## Запуск -/// info | "Дополнительная информация" +/// info | Дополнительная информация Вначале, установите библиотеку `python-multipart`. @@ -82,7 +54,7 @@ $ uvicorn main:app --reload -/// check | "Кнопка авторизации!" +/// check | Кнопка авторизации! У вас уже появилась новая кнопка "Authorize". @@ -94,7 +66,7 @@ $ uvicorn main:app --reload -/// note | "Технические детали" +/// note | Технические детали Неважно, что вы введете в форму, она пока не будет работать. Но мы к этому еще придем. @@ -140,7 +112,7 @@ OAuth2 был разработан для того, чтобы бэкэнд ил В данном примере мы будем использовать **OAuth2**, с аутентификацией по паролю, используя токен **Bearer**. Для этого мы используем класс `OAuth2PasswordBearer`. -/// info | "Дополнительная информация" +/// info | Дополнительная информация Токен "bearer" - не единственный вариант, но для нашего случая он является наилучшим. @@ -152,37 +124,9 @@ OAuth2 был разработан для того, чтобы бэкэнд ил При создании экземпляра класса `OAuth2PasswordBearer` мы передаем в него параметр `tokenUrl`. Этот параметр содержит URL, который клиент (фронтенд, работающий в браузере пользователя) будет использовать для отправки `имени пользователя` и `пароля` с целью получения токена. -//// tab | Python 3.9+ - -```Python hl_lines="8" -{!> ../../docs_src/security/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="7" -{!> ../../docs_src/security/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | "Подсказка" - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="6" -{!> ../../docs_src/security/tutorial001.py!} -``` - -//// +{* ../../docs_src/security/tutorial001_an_py39.py hl[8] *} -/// tip | "Подсказка" +/// tip | Подсказка Здесь `tokenUrl="token"` ссылается на относительный URL `token`, который мы еще не создали. Поскольку это относительный URL, он эквивалентен `./token`. @@ -196,7 +140,7 @@ OAuth2 был разработан для того, чтобы бэкэнд ил Вскоре мы создадим и саму операцию пути. -/// info | "Дополнительная информация" +/// info | Дополнительная информация Если вы очень строгий "питонист", то вам может не понравиться стиль названия параметра `tokenUrl` вместо `token_url`. @@ -218,41 +162,13 @@ oauth2_scheme(some, parameters) Теперь вы можете передать ваш `oauth2_scheme` в зависимость с помощью `Depends`. -//// tab | Python 3.9+ - -```Python hl_lines="12" -{!> ../../docs_src/security/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/security/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | "Подсказка" - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/security/tutorial001.py!} -``` - -//// +{* ../../docs_src/security/tutorial001_an_py39.py hl[12] *} Эта зависимость будет предоставлять `строку`, которая присваивается параметру `token` в *функции операции пути*. **FastAPI** будет знать, что он может использовать эту зависимость для определения "схемы безопасности" в схеме OpenAPI (и автоматической документации по API). -/// info | "Технические детали" +/// info | Технические детали **FastAPI** будет знать, что он может использовать класс `OAuth2PasswordBearer` (объявленный в зависимости) для определения схемы безопасности в OpenAPI, поскольку он наследуется от `fastapi.security.oauth2.OAuth2`, который, в свою очередь, наследуется от `fastapi.security.base.SecurityBase`. diff --git a/docs/ru/docs/tutorial/security/index.md b/docs/ru/docs/tutorial/security/index.md index bd512fde3c6fe..e4969c4cf04c6 100644 --- a/docs/ru/docs/tutorial/security/index.md +++ b/docs/ru/docs/tutorial/security/index.md @@ -32,7 +32,7 @@ OAuth2 включает в себя способы аутентификации OAuth2 не указывает, как шифровать сообщение, он ожидает, что ваше приложение будет обслуживаться по протоколу HTTPS. -/// tip | "Подсказка" +/// tip | Подсказка В разделе **Развертывание** вы увидите [как настроить протокол HTTPS бесплатно, используя Traefik и Let's Encrypt.](https://fastapi.tiangolo.com/ru/deployment/https/) @@ -89,7 +89,7 @@ OpenAPI может использовать следующие схемы авт * Это автоматическое обнаружение определено в спецификации OpenID Connect. -/// tip | "Подсказка" +/// tip | Подсказка Интеграция сторонних сервисов для аутентификации/авторизации таких как Google, Facebook, Twitter, GitHub и т.д. осуществляется достаточно легко. diff --git a/docs/ru/docs/tutorial/static-files.md b/docs/ru/docs/tutorial/static-files.md index 4734554f30b73..c06eb858bf468 100644 --- a/docs/ru/docs/tutorial/static-files.md +++ b/docs/ru/docs/tutorial/static-files.md @@ -7,11 +7,9 @@ * Импортируйте `StaticFiles`. * "Примонтируйте" экземпляр `StaticFiles()` с указанием определенной директории. -```Python hl_lines="2 6" -{!../../docs_src/static_files/tutorial001.py!} -``` +{* ../../docs_src/static_files/tutorial001.py hl[2,6] *} -/// note | "Технические детали" +/// note | Технические детали Вы также можете использовать `from starlette.staticfiles import StaticFiles`. diff --git a/docs/ru/docs/tutorial/testing.md b/docs/ru/docs/tutorial/testing.md index ae045bbbee5d1..2c0f93d485c33 100644 --- a/docs/ru/docs/tutorial/testing.md +++ b/docs/ru/docs/tutorial/testing.md @@ -8,7 +8,7 @@ ## Использование класса `TestClient` -/// info | "Информация" +/// info | Информация Для использования класса `TestClient` необходимо установить библиотеку `httpx`. @@ -26,11 +26,9 @@ Напишите простое утверждение с `assert` дабы проверить истинность Python-выражения (это тоже стандарт `pytest`). -```Python hl_lines="2 12 15-18" -{!../../docs_src/app_testing/tutorial001.py!} -``` +{* ../../docs_src/app_testing/tutorial001.py hl[2,12,15:18] *} -/// tip | "Подсказка" +/// tip | Подсказка Обратите внимание, что тестирующая функция является обычной `def`, а не асинхронной `async def`. @@ -40,7 +38,7 @@ /// -/// note | "Технические детали" +/// note | Технические детали Также можно написать `from starlette.testclient import TestClient`. @@ -48,7 +46,7 @@ /// -/// tip | "Подсказка" +/// tip | Подсказка Если для тестирования Вам, помимо запросов к приложению FastAPI, необходимо вызывать асинхронные функции (например, для подключения к базе данных с помощью асинхронного драйвера), то ознакомьтесь со страницей [Асинхронное тестирование](../advanced/async-tests.md){.internal-link target=_blank} в расширенном руководстве. @@ -74,9 +72,7 @@ Здесь файл `main.py` является "точкой входа" в Ваше приложение и содержит инициализацию Вашего приложения **FastAPI**: -```Python -{!../../docs_src/app_testing/main.py!} -``` +{* ../../docs_src/app_testing/main.py *} ### Файл тестов @@ -92,9 +88,8 @@ Так как оба файла находятся в одной директории, для импорта объекта приложения из файла `main` в файл `test_main` Вы можете использовать относительный импорт: -```Python hl_lines="3" -{!../../docs_src/app_testing/test_main.py!} -``` +{* ../../docs_src/app_testing/test_main.py hl[3] *} + ...и писать дальше тесты, как и раньше. @@ -148,7 +143,7 @@ //// tab | Python 3.10+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка По возможности используйте версию с `Annotated`. @@ -162,7 +157,7 @@ //// tab | Python 3.8+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка По возможности используйте версию с `Annotated`. @@ -178,9 +173,8 @@ Теперь обновим файл `test_main.py`, добавив в него тестов: -```Python -{!> ../../docs_src/app_testing/app_b/test_main.py!} -``` +{* ../../docs_src/app_testing/app_b/test_main.py *} + Если Вы не знаете, как передать информацию в запросе, можете воспользоваться поисковиком (погуглить) и задать вопрос: "Как передать информацию в запросе с помощью `httpx`", можно даже спросить: "Как передать информацию в запросе с помощью `requests`", поскольку дизайн HTTPX основан на дизайне Requests. @@ -196,7 +190,7 @@ Для получения дополнительной информации о передаче данных на бэкенд с помощью `httpx` или `TestClient` ознакомьтесь с документацией HTTPX. -/// info | "Информация" +/// info | Информация Обратите внимание, что `TestClient` принимает данные, которые можно конвертировать в JSON, но не модели Pydantic. diff --git a/docs/tr/docs/advanced/index.md b/docs/tr/docs/advanced/index.md index 6c057162e2f38..836e63c8ab44e 100644 --- a/docs/tr/docs/advanced/index.md +++ b/docs/tr/docs/advanced/index.md @@ -6,7 +6,7 @@ İlerleyen bölümlerde diğer seçenekler, konfigürasyonlar ve ek özellikleri göreceğiz. -/// tip | "İpucu" +/// tip | İpucu Sonraki bölümler **mutlaka "gelişmiş" olmak zorunda değildir**. diff --git a/docs/tr/docs/advanced/security/index.md b/docs/tr/docs/advanced/security/index.md index 227674bd47e5a..709f74c7210b4 100644 --- a/docs/tr/docs/advanced/security/index.md +++ b/docs/tr/docs/advanced/security/index.md @@ -4,7 +4,7 @@ [Tutorial - User Guide: Security](../../tutorial/security/index.md){.internal-link target=_blank} sayfasında ele alınanların dışında güvenlikle ilgili bazı ek özellikler vardır. -/// tip | "İpucu" +/// tip | İpucu Sonraki bölümler **mutlaka "gelişmiş" olmak zorunda değildir**. diff --git a/docs/tr/docs/advanced/testing-websockets.md b/docs/tr/docs/advanced/testing-websockets.md index aa8a040d0e828..ddacca449881a 100644 --- a/docs/tr/docs/advanced/testing-websockets.md +++ b/docs/tr/docs/advanced/testing-websockets.md @@ -4,11 +4,9 @@ WebSockets testi yapmak için `TestClient`'ı kullanabilirsiniz. Bu işlem için, `TestClient`'ı bir `with` ifadesinde kullanarak WebSocket'e bağlanabilirsiniz: -```Python hl_lines="27-31" -{!../../docs_src/app_testing/tutorial002.py!} -``` +{* ../../docs_src/app_testing/tutorial002.py hl[27:31] *} -/// note | "Not" +/// note | Not Daha fazla detay için Starlette'in Websockets'i Test Etmek dokümantasyonunu inceleyin. diff --git a/docs/tr/docs/advanced/wsgi.md b/docs/tr/docs/advanced/wsgi.md index bc8da16df380a..00815a4b2f4bf 100644 --- a/docs/tr/docs/advanced/wsgi.md +++ b/docs/tr/docs/advanced/wsgi.md @@ -12,9 +12,7 @@ Ardından WSGI (örneğin Flask) uygulamanızı middleware ile sarmalayın. Son olarak da bir yol altında bağlama işlemini gerçekleştirin. -```Python hl_lines="2-3 23" -{!../../docs_src/wsgi/tutorial001.py!} -``` +{* ../../docs_src/wsgi/tutorial001.py hl[2:3,23] *} ## Kontrol Edelim diff --git a/docs/tr/docs/alternatives.md b/docs/tr/docs/alternatives.md index 286b7897a155a..c98b966b5d45d 100644 --- a/docs/tr/docs/alternatives.md +++ b/docs/tr/docs/alternatives.md @@ -30,13 +30,13 @@ Django REST framework'ü, Django'nun API kabiliyetlerini arttırmak için arka p **Otomatik API dökümantasyonu**nun ilk örneklerinden biri olduğu için, **FastAPI** arayışına ilham veren ilk fikirlerden biri oldu. -/// note | "Not" +/// note | Not Django REST Framework'ü, aynı zamanda **FastAPI**'ın dayandığı Starlette ve Uvicorn'un da yaratıcısı olan Tom Christie tarafından geliştirildi. /// -/// check | "**FastAPI**'a nasıl ilham verdi?" +/// check | **FastAPI**'a nasıl ilham verdi? Kullanıcılar için otomatik API dökümantasyonu sunan bir web arayüzüne sahip olmalı. @@ -56,7 +56,7 @@ Uygulama parçalarının böyle ayrılıyor oluşu ve istenilen özelliklerle ge Flask'ın basitliği göz önünde bulundurulduğu zaman, API geliştirmek için iyi bir seçim gibi görünüyordu. Sıradaki şey ise Flask için bir "Django REST Framework"! -/// check | "**FastAPI**'a nasıl ilham verdi?" +/// check | **FastAPI**'a nasıl ilham verdi? Gereken araçları ve parçaları birleştirip eşleştirmeyi kolaylaştıracak bir mikro framework olmalı. @@ -98,7 +98,7 @@ def read_url(): `requests.get(...)` ile `@app.get(...)` arasındaki benzerliklere bakın. -/// check | "**FastAPI**'a nasıl ilham verdi?" +/// check | **FastAPI**'a nasıl ilham verdi? * Basit ve sezgisel bir API'ya sahip olmalı. * HTTP metot isimlerini (işlemlerini) anlaşılır olacak bir şekilde, direkt kullanmalı. @@ -118,7 +118,7 @@ Swagger bir noktada Linux Foundation'a verildi ve adı OpenAPI olarak değiştir İşte bu yüzden versiyon 2.0 hakkında konuşurken "Swagger", versiyon 3 ve üzeri için ise "OpenAPI" adını kullanmak daha yaygın. -/// check | "**FastAPI**'a nasıl ilham verdi?" +/// check | **FastAPI**'a nasıl ilham verdi? API spesifikasyonları için özel bir şema yerine bir açık standart benimseyip kullanmalı. @@ -147,7 +147,7 @@ Marshmallow bu özellikleri sağlamak için geliştirilmişti. Benim de geçmiş Ama... Python'un tip belirteçleri gelmeden önce oluşturulmuştu. Yani her şemayı tanımlamak için Marshmallow'un sunduğu spesifik araçları ve sınıfları kullanmanız gerekiyordu. -/// check | "**FastAPI**'a nasıl ilham verdi?" +/// check | **FastAPI**'a nasıl ilham verdi? Kod kullanarak otomatik olarak veri tipini ve veri doğrulamayı belirten "şemalar" tanımlamalı. @@ -163,13 +163,13 @@ Veri doğrulama için arka planda Marshmallow kullanıyor, hatta aynı geliştir Webargs da harika bir araç ve onu da geçmişte henüz **FastAPI** yokken çok kullandım. -/// info | "Bilgi" +/// info | Bilgi Webargs aynı Marshmallow geliştirileri tarafından oluşturuldu. /// -/// check | "**FastAPI**'a nasıl ilham verdi?" +/// check | **FastAPI**'a nasıl ilham verdi? Gelen istek verisi için otomatik veri doğrulamaya sahip olmalı. @@ -191,13 +191,13 @@ Fakat sonrasında yine mikro sözdizimi problemiyle karşılaşıyoruz. Python m Editör bu konuda pek yardımcı olamaz. Üstelik eğer parametreleri ya da Marshmallow şemalarını değiştirip YAML kodunu güncellemeyi unutursak artık döküman geçerliliğini yitiriyor. -/// info | "Bilgi" +/// info | Bilgi APISpec de aynı Marshmallow geliştiricileri tarafından oluşturuldu. /// -/// check | "**FastAPI**'a nasıl ilham verdi?" +/// check | **FastAPI**'a nasıl ilham verdi? API'lar için açık standart desteği olmalı (OpenAPI gibi). @@ -223,13 +223,13 @@ Bunu kullanmak, bir kaç `uvloop` kullanıldı. Hızının asıl kaynağı buydu. @@ -269,7 +269,7 @@ Uvicorn ve Starlette'e ilham kaynağı olduğu oldukça açık, şu anda ikisi d /// -/// check | "**FastAPI**'a nasıl ilham oldu?" +/// check | **FastAPI**'a nasıl ilham oldu? Uçuk performans sağlayacak bir yol bulmalı. @@ -285,7 +285,7 @@ Falcon ise bir diğer yüksek performanslı Python framework'ü. Minimal olacak Yani veri doğrulama, veri dönüştürme ve dökümantasyonun hepsi kodda yer almalı, otomatik halledemiyoruz. Ya da Falcon üzerine bir framework olarak uygulanmaları gerekiyor, aynı Hug'da olduğu gibi. Bu ayrım Falcon'un tasarımından esinlenen, istek ve cevap objelerini parametre olarak işleyen diğer kütüphanelerde de yer alıyor. -/// check | "**FastAPI**'a nasıl ilham oldu?" +/// check | **FastAPI**'a nasıl ilham oldu? Harika bir performans'a sahip olmanın yollarını bulmalı. @@ -311,7 +311,7 @@ Biraz daha detaylı ayarlamalara gerek duyuyor. Ayrıca Yol'lar fonksiyonun üstünde endpoint'i işleyen dekoratörler yerine farklı yerlerde tanımlanan fonksiyonlarla belirlenir. Bu Flask (ve Starlette) yerine daha çok Django'nun yaklaşımına daha yakın bir metot. Bu, kodda nispeten birbiriyle sıkı ilişkili olan şeyleri ayırmaya sebep oluyor. -/// check | "**FastAPI**'a nasıl ilham oldu?" +/// check | **FastAPI**'a nasıl ilham oldu? Model özelliklerinin "standart" değerlerini kullanarak veri tipleri için ekstra veri doğrulama koşulları tanımlamalı. Bu editör desteğini geliştiriyor ve daha önceden Pydantic'te yoktu. @@ -333,13 +333,13 @@ Ayrıca ilginç ve çok rastlanmayan bir özelliği vardı: aynı framework'ü k Senkron çalışan Python web framework'lerinin standardına (WSGI) dayandığından dolayı Websocket'leri ve diğer şeyleri işleyemiyor, ancak yine de yüksek performansa sahip. -/// info | "Bilgi" +/// info | Bilgi Hug, Python dosyalarında bulunan dahil etme satırlarını otomatik olarak sıralayan harika bir araç olan `isort`'un geliştiricisi Timothy Crosley tarafından geliştirildi. /// -/// check | "**FastAPI**'a nasıl ilham oldu?" +/// check | **FastAPI**'a nasıl ilham oldu? Hug, APIStar'ın çeşitli kısımlarında esin kaynağı oldu ve APIStar'la birlikte en umut verici bulduğum araçlardan biriydi. @@ -373,7 +373,7 @@ Geliştiricinin Starlette'e odaklanması gerekince proje de artık bir API web f Artık APIStar, OpenAPI özelliklerini doğrulamak için bir dizi araç sunan bir proje haline geldi. -/// info | "Bilgi" +/// info | Bilgi APIStar, aşağıdaki projeleri de üreten Tom Christie tarafından geliştirildi: @@ -383,7 +383,7 @@ APIStar, aşağıdaki projeleri de üreten Tom Christie tarafından geliştirild /// -/// check | "**FastAPI**'a nasıl ilham oldu?" +/// check | **FastAPI**'a nasıl ilham oldu? Var oldu. @@ -407,7 +407,7 @@ Tip belirteçleri kullanıyor olması onu aşırı sezgisel yapıyor. Marshmallow ile karşılaştırılabilir. Ancak karşılaştırmalarda Marshmallowdan daha hızlı görünüyor. Aynı Python tip belirteçlerine dayanıyor ve editör desteği de harika. -/// check | "**FastAPI** nerede kullanıyor?" +/// check | **FastAPI** nerede kullanıyor? Bütün veri doğrulama, veri dönüştürme ve JSON Şemasına bağlı otomatik model dökümantasyonunu halletmek için! @@ -442,7 +442,7 @@ Ancak otomatik veri doğrulama, veri dönüştürme ve dökümantasyon sağlamyo Bu, **FastAPI**'ın onun üzerine tamamen Python tip belirteçlerine bağlı olarak eklediği (Pydantic ile) ana şeylerden biri. **FastAPI** bunun yanında artı olarak bağımlılık enjeksiyonu sistemi, güvenlik araçları, OpenAPI şema üretimi ve benzeri özellikler de ekliyor. -/// note | "Teknik Detaylar" +/// note | Teknik Detaylar ASGI, Django'nun ana ekibi tarafından geliştirilen yeni bir "standart". Bir "Python standardı" (PEP) olma sürecinde fakat henüz bir standart değil. @@ -450,7 +450,7 @@ Bununla birlikte, halihazırda birçok araç tarafından bir "standart" olarak k /// -/// check | "**FastAPI** nerede kullanıyor?" +/// check | **FastAPI** nerede kullanıyor? Tüm temel web kısımlarında üzerine özellikler eklenerek kullanılmakta. @@ -468,7 +468,7 @@ Bir web framework'ünden ziyade bir sunucudur, yani yollara bağlı yönlendirme Starlette ve **FastAPI** için tavsiye edilen sunucu Uvicorndur. -/// check | "**FastAPI** neden tavsiye ediyor?" +/// check | **FastAPI** neden tavsiye ediyor? **FastAPI** uygulamalarını çalıştırmak için ana web sunucusu Uvicorn! diff --git a/docs/tr/docs/async.md b/docs/tr/docs/async.md index 0d463a2f03389..558a79cb71017 100644 --- a/docs/tr/docs/async.md +++ b/docs/tr/docs/async.md @@ -21,7 +21,7 @@ async def read_results(): return results ``` -/// note | "Not" +/// note | Not Sadece `async def` ile tanımlanan fonksiyonlar içinde `await` kullanabilirsiniz. diff --git a/docs/tr/docs/how-to/index.md b/docs/tr/docs/how-to/index.md index 798adca611ec1..26dd9026ced45 100644 --- a/docs/tr/docs/how-to/index.md +++ b/docs/tr/docs/how-to/index.md @@ -6,7 +6,7 @@ Bu fikirlerin büyük bir kısmı aşağı yukarı **bağımsız** olacaktır, Projeniz için ilginç ve yararlı görünen bir şey varsa devam edin ve inceleyin, aksi halde bunları atlayabilirsiniz. -/// tip | "İpucu" +/// tip | İpucu **FastAPI**'ı düzgün (ve önerilen) şekilde öğrenmek istiyorsanız [Öğretici - Kullanıcı Rehberi](../tutorial/index.md){.internal-link target=_blank}'ni bölüm bölüm okuyun. diff --git a/docs/tr/docs/python-types.md b/docs/tr/docs/python-types.md index 9584a57322aa7..b44aa3b9d59f2 100644 --- a/docs/tr/docs/python-types.md +++ b/docs/tr/docs/python-types.md @@ -12,7 +12,7 @@ Bu pythonda tip belirteçleri için **hızlı bir başlangıç / bilgi tazeleme **FastAPI** kullanmayacak olsanız bile tür belirteçleri hakkında bilgi edinmenizde fayda var. -/// note | "Not" +/// note | Not Python uzmanıysanız ve tip belirteçleri ilgili her şeyi zaten biliyorsanız, sonraki bölüme geçin. @@ -22,9 +22,8 @@ Python uzmanıysanız ve tip belirteçleri ilgili her şeyi zaten biliyorsanız, Basit bir örnek ile başlayalım: -```Python -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py *} + Programın çıktısı: @@ -38,9 +37,8 @@ Fonksiyon sırayla şunları yapar: * `title()` ile değişkenlerin ilk karakterlerini büyütür. * Değişkenleri aralarında bir boşlukla beraber Birleştirir. -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py hl[2] *} + ### Düzenle @@ -82,9 +80,8 @@ Bu kadar. İşte bunlar "tip belirteçleri": -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial002.py!} -``` +{* ../../docs_src/python_types/tutorial002.py hl[1] *} + Bu, aşağıdaki gibi varsayılan değerleri bildirmekle aynı şey değildir: @@ -112,9 +109,8 @@ Aradığınızı bulana kadar seçenekleri kaydırabilirsiniz: Bu fonksiyon, zaten tür belirteçlerine sahip: -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial003.py!} -``` +{* ../../docs_src/python_types/tutorial003.py hl[1] *} + Editör değişkenlerin tiplerini bildiğinden, yalnızca otomatik tamamlama değil, hata kontrolleri de sağlar: @@ -122,9 +118,8 @@ Editör değişkenlerin tiplerini bildiğinden, yalnızca otomatik tamamlama de Artık `age` değişkenini `str(age)` olarak kullanmanız gerektiğini biliyorsunuz: -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial004.py!} -``` +{* ../../docs_src/python_types/tutorial004.py hl[2] *} + ## Tip bildirme @@ -143,9 +138,8 @@ Yalnızca `str` değil, tüm standart Python tiplerinin bildirebilirsiniz. * `bool` * `bytes` -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial005.py!} -``` +{* ../../docs_src/python_types/tutorial005.py hl[1] *} + ### Tip parametreleri ile Generic tipler @@ -161,9 +155,8 @@ Bu tür tip belirteçlerini desteklemek için özel olarak mevcuttur. From `typing`, import `List` (büyük harf olan `L` ile): -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial006.py!} -``` +{* ../../docs_src/python_types/tutorial006.py hl[1] *} + Değişkenin tipini yine iki nokta üstüste (`:`) ile belirleyin. @@ -171,11 +164,10 @@ 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" +/// tip | Ipucu Köşeli parantez içindeki bu dahili tiplere "tip parametreleri" denir. @@ -199,9 +191,8 @@ Ve yine, editör bunun bir `str` ​​olduğunu biliyor ve bunun için destek s `Tuple` ve `set`lerin tiplerini bildirmek için de aynısını yapıyoruz: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial007.py!} -``` +{* ../../docs_src/python_types/tutorial007.py hl[1,4] *} + Bu şu anlama geliyor: @@ -216,9 +207,8 @@ Bir `dict` tanımlamak için virgülle ayrılmış iki parametre verebilirsiniz. İkinci parametre ise `dict` değerinin `value` değeri içindir: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial008.py!} -``` +{* ../../docs_src/python_types/tutorial008.py hl[1,4] *} + Bu şu anlama gelir: @@ -255,15 +245,13 @@ Bir değişkenin tipini bir sınıf ile bildirebilirsiniz. Diyelim ki `name` değerine sahip `Person` sınıfınız var: -```Python hl_lines="1-3" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[1:3] *} + Sonra bir değişkeni 'Person' tipinde tanımlayabilirsiniz: -```Python hl_lines="6" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[6] *} + Ve yine bütün editör desteğini alırsınız: @@ -283,9 +271,8 @@ Ve ortaya çıkan nesne üzerindeki bütün editör desteğini alırsınız. Resmi Pydantic dokümanlarından alınmıştır: -```Python -{!../../docs_src/python_types/tutorial011.py!} -``` +{* ../../docs_src/python_types/tutorial011.py *} + /// info diff --git a/docs/tr/docs/tutorial/cookie-params.md b/docs/tr/docs/tutorial/cookie-params.md index 895cf9b03250e..f07508c2fded7 100644 --- a/docs/tr/docs/tutorial/cookie-params.md +++ b/docs/tr/docs/tutorial/cookie-params.md @@ -6,57 +6,7 @@ Öncelikle, `Cookie`'yi projenize dahil edin: -//// tab | Python 3.10+ - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | "İpucu" - -Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/cookie_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | "İpucu" - -Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. - -/// - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[3] *} ## `Cookie` Parametrelerini Tanımlayın @@ -64,59 +14,9 @@ Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. İlk değer varsayılan değerdir; tüm ekstra doğrulama veya belirteç parametrelerini kullanabilirsiniz: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/cookie_params/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | "İpucu" - -Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/cookie_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | "İpucu" - -Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[9] *} -/// note | "Teknik Detaylar" +/// note | Teknik Detaylar `Cookie` sınıfı `Path` ve `Query` sınıflarının kardeşidir. Diğerleri gibi `Param` sınıfını miras alan bir sınıftır. @@ -124,7 +24,7 @@ Ancak `fastapi`'dan projenize dahil ettiğiniz `Query`, `Path`, `Cookie` ve diğ /// -/// info | "Bilgi" +/// info | Bilgi Çerez tanımlamak için `Cookie` sınıfını kullanmanız gerekmektedir, aksi taktirde parametreler sorgu parametreleri olarak yorumlanır. diff --git a/docs/tr/docs/tutorial/first-steps.md b/docs/tr/docs/tutorial/first-steps.md index 335fcaeced3a7..2d2949b503c3b 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,7 +22,7 @@ $ uvicorn main:app --reload -/// note | "Not" +/// note | Not `uvicorn main:app` komutunu şu şekilde açıklayabiliriz: @@ -133,13 +131,11 @@ 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" +/// note | Teknik Detaylar `FastAPI` doğrudan `Starlette`'i miras alan bir sınıftır. @@ -149,9 +145,7 @@ Ayrıca, API'ınızla iletişim kuracak önyüz, mobil veya IoT uygulamaları gi ### Adım 2: Bir `FastAPI` "Örneği" Oluşturalım -```Python hl_lines="3" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[3] *} Burada `app` değişkeni `FastAPI` sınıfının bir örneği olacaktır. @@ -171,9 +165,7 @@ $ uvicorn main:app --reload Uygulamanızı aşağıdaki gibi oluşturursanız: -```Python hl_lines="3" -{!../../docs_src/first_steps/tutorial002.py!} -``` +{* ../../docs_src/first_steps/tutorial002.py hl[3] *} Ve bunu `main.py` dosyasına yerleştirirseniz eğer `uvicorn` komutunu şu şekilde çalıştırabilirsiniz: @@ -205,7 +197,7 @@ https://example.com/items/foo /items/foo ``` -/// info | "Bilgi" +/// info | Bilgi "Yol" genellikle "endpoint" veya "route" olarak adlandırılır. @@ -250,16 +242,14 @@ 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" +/// info | `@decorator` Bilgisi Python'da `@something` sözdizimi "dekoratör" olarak adlandırılır. @@ -286,7 +276,7 @@ Daha az kullanılanları da kullanabilirsiniz: * `@app.patch()` * `@app.trace()` -/// tip | "İpucu" +/// tip | İpucu Her işlemi (HTTP metod) istediğiniz gibi kullanmakta özgürsünüz. @@ -306,9 +296,7 @@ Aşağıdaki, bizim **yol operasyonu fonksiyonumuzdur**: * **operasyon**: `get` * **fonksiyon**: "dekoratör"ün (`@app.get("/")`'in) altındaki fonksiyondur. -```Python hl_lines="7" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[7] *} Bu bir Python fonksiyonudur. @@ -320,11 +308,9 @@ 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. @@ -332,9 +318,7 @@ Eğer farkı bilmiyorsanız, [Async: *"Aceleniz mi var?"*](../async.md#in-a-hurr ### Adım 5: İçeriği Geri Döndürün -```Python hl_lines="8" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[8] *} Bir `dict`, `list` veya `str`, `int` gibi tekil değerler döndürebilirsiniz. diff --git a/docs/tr/docs/tutorial/path-params.md b/docs/tr/docs/tutorial/path-params.md index 9017d99abd37f..e1707a5d9e85f 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,13 +16,11 @@ Eğer bu örneği çalıştırıp http://127.0.0.1:8000/items/4.2 sayfasında olduğu gibi `int` yerine `float` bir değer verseydik de ortaya çıkardı. -/// check | "Ek bilgi" +/// check | Ek bilgi Böylece, aynı Python tip tanımlaması ile birlikte, **FastAPI** veri doğrulama özelliği sağlar. @@ -87,7 +83,7 @@ Ayrıca, tarayıcınızı -/// check | "Ek bilgi" +/// check | Ek bilgi Üstelik, sadece aynı Python tip tanımlaması ile, **FastAPI** size otomatik ve interaktif (Swagger UI ile entegre) bir dokümantasyon sağlar. @@ -123,17 +119,13 @@ Benzer şekilde `/users/{user_id}` gibi tanımlanmış ve belirli bir kullanıc *Yol operasyonları* sıralı bir şekilde gözden geçirildiğinden dolayı `/users/me` yolunun `/users/{user_id}` yolundan önce tanımlanmış olmasından emin olmanız gerekmektedir: -```Python hl_lines="6 11" -{!../../docs_src/path_params/tutorial003.py!} -``` +{* ../../docs_src/path_params/tutorial003.py hl[6,11] *} Aksi halde, `/users/{user_id}` yolu `"me"` değerinin `user_id` parametresi için gönderildiğini "düşünerek" `/users/me` ile de eşleşir. Benzer şekilde, bir yol operasyonunu yeniden tanımlamanız mümkün değildir: -```Python hl_lines="6 11" -{!../../docs_src/path_params/tutorial003b.py!} -``` +{* ../../docs_src/path_params/tutorial003b.py hl[6,11] *} Yol, ilk kısım ile eşleştiğinden dolayı her koşulda ilk yol operasyonu kullanılacaktır. @@ -149,17 +141,15 @@ Eğer *yol parametresi* alan bir *yol operasyonunuz* varsa ve alabileceği *yol Sonrasında, sınıf içerisinde, mevcut ve geçerli değerler olacak olan sabit değerli özelliklerini oluşturalım: -```Python hl_lines="1 6-9" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[1,6:9] *} -/// info | "Bilgi" +/// info | Bilgi 3.4 sürümünden beri enumerationlar (ya da enumlar) Python'da mevcuttur. /// -/// tip | "İpucu" +/// tip | İpucu Merak ediyorsanız söyleyeyim, "AlexNet", "ResNet" ve "LeNet" isimleri Makine Öğrenmesi modellerini temsil eder. @@ -169,9 +159,7 @@ Merak ediyorsanız söyleyeyim, "AlexNet", "ResNet" ve "LeNet" isimleri Makine Sonrasında, yarattığımız enum sınıfını (`ModelName`) kullanarak tip belirteci aracılığıyla bir *yol parametresi* oluşturalım: -```Python hl_lines="16" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[16] *} ### Dokümana Göz Atalım @@ -187,19 +175,15 @@ Sonrasında, yarattığımız enum sınıfını (`ModelName`) kullanarak tip bel Parametreyi, yarattığınız enum olan `ModelName` içerisindeki *enumeration üyesi* ile karşılaştırabilirsiniz: -```Python hl_lines="17" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[17] *} #### *Enumeration Değerini* Edinelim `model_name.value` veya genel olarak `your_enum_member.value` tanımlarını kullanarak (bu durumda bir `str` olan) gerçek değere ulaşabilirsiniz: -```Python hl_lines="20" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[20] *} -/// tip | "İpucu" +/// tip | İpucu `"lenet"` değerine `ModelName.lenet.value` tanımı ile de ulaşabilirsiniz. @@ -211,9 +195,7 @@ JSON gövdesine (örneğin bir `dict`) gömülü olsalar bile *yol operasyonunda Bu üyeler istemciye iletilmeden önce kendilerine karşılık gelen değerlerine (bu durumda string) dönüştürüleceklerdir: -```Python hl_lines="18 21 23" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[18,21,23] *} İstemci tarafında şuna benzer bir JSON yanıtı ile karşılaşırsınız: @@ -252,11 +234,9 @@ Bu durumda, parametrenin adı `file_path` olacaktır ve son kısım olan `:path` Böylece şunun gibi bir kullanım yapabilirsiniz: -```Python hl_lines="6" -{!../../docs_src/path_params/tutorial004.py!} -``` +{* ../../docs_src/path_params/tutorial004.py hl[6] *} -/// tip | "İpucu" +/// tip | İpucu Parametrenin başında `/home/johndoe/myfile.txt` yolunda olduğu gibi (`/`) işareti ile birlikte kullanmanız gerektiği durumlar olabilir. diff --git a/docs/tr/docs/tutorial/query-params.md b/docs/tr/docs/tutorial/query-params.md index 886f5783f4e8c..4aa0a82b1bed0 100644 --- a/docs/tr/docs/tutorial/query-params.md +++ b/docs/tr/docs/tutorial/query-params.md @@ -2,9 +2,7 @@ Fonksiyonda yol parametrelerinin parçası olmayan diğer tanımlamalar otomatik olarak "sorgu" parametresi olarak yorumlanır. -```Python hl_lines="9" -{!../../docs_src/query_params/tutorial001.py!} -``` +{* ../../docs_src/query_params/tutorial001.py hl[9] *} Sorgu, bağlantıdaki `?` kısmından sonra gelen ve `&` işareti ile ayrılan anahtar-değer çiftlerinin oluşturduğu bir kümedir. @@ -63,25 +61,11 @@ Fonksiyonunuzdaki parametre değerleri aşağıdaki gibi olacaktır: Aynı şekilde, varsayılan değerlerini `None` olarak atayarak isteğe bağlı parametreler tanımlayabilirsiniz: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/query_params/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params/tutorial002.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial002_py310.py hl[7] *} Bu durumda, `q` fonksiyon parametresi isteğe bağlı olacak ve varsayılan değer olarak `None` alacaktır. -/// check | "Ek bilgi" +/// check | Ek bilgi Ayrıca, dikkatinizi çekerim ki; **FastAPI**, `item_id` parametresinin bir yol parametresi olduğunu ve `q` parametresinin yol değil bir sorgu parametresi olduğunu fark edecek kadar beceriklidir. @@ -91,21 +75,7 @@ Ayrıca, dikkatinizi çekerim ki; **FastAPI**, `item_id` parametresinin bir yol Aşağıda görüldüğü gibi dönüştürülmek üzere `bool` tipleri de tanımlayabilirsiniz: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/query_params/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params/tutorial003.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial003_py310.py hl[7] *} Bu durumda, eğer şu adrese giderseniz: @@ -148,21 +118,7 @@ Ve parametreleri, herhangi bir sıraya koymanıza da gerek yoktur. İsimlerine göre belirleneceklerdir: -//// tab | Python 3.10+ - -```Python hl_lines="6 8" -{!> ../../docs_src/query_params/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8 10" -{!> ../../docs_src/query_params/tutorial004.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial004_py310.py hl[6,8] *} ## Zorunlu Sorgu Parametreleri @@ -172,9 +128,7 @@ Parametre için belirli bir değer atamak istemeyip parametrenin sadece isteğe Fakat, bir sorgu parametresini zorunlu yapmak istiyorsanız varsayılan bir değer atamamanız yeterli olacaktır: -```Python hl_lines="6-7" -{!../../docs_src/query_params/tutorial005.py!} -``` +{* ../../docs_src/query_params/tutorial005.py hl[6:7] *} Burada `needy` parametresi `str` tipinden oluşan zorunlu bir sorgu parametresidir. @@ -220,21 +174,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy Ve elbette, bazı parametreleri zorunlu, bazılarını varsayılan değerli ve bazılarını tamamen opsiyonel olarak tanımlayabilirsiniz: -//// tab | Python 3.10+ - -```Python hl_lines="8" -{!> ../../docs_src/query_params/tutorial006_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params/tutorial006.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial006_py310.py hl[8] *} Bu durumda, 3 tane sorgu parametresi var olacaktır: @@ -242,7 +182,7 @@ Bu durumda, 3 tane sorgu parametresi var olacaktır: * `skip`, varsayılan değeri `0` olan bir `int`. * `limit`, isteğe bağlı bir `int`. -/// tip | "İpucu" +/// tip | İpucu Ayrıca, [Yol Parametrelerinde](path-params.md#on-tanml-degerler){.internal-link target=_blank} de kullanıldığı şekilde `Enum` sınıfından faydalanabilirsiniz. diff --git a/docs/tr/docs/tutorial/request-forms.md b/docs/tr/docs/tutorial/request-forms.md index 19b6150ffa0c7..e4e04f5f99948 100644 --- a/docs/tr/docs/tutorial/request-forms.md +++ b/docs/tr/docs/tutorial/request-forms.md @@ -2,7 +2,7 @@ İstek gövdesinde JSON verisi yerine form alanlarını karşılamanız gerketiğinde `Form` sınıfını kullanabilirsiniz. -/// info | "Bilgi" +/// info | Bilgi Formları kullanmak için öncelikle `python-multipart` paketini indirmeniz gerekmektedir. @@ -14,69 +14,13 @@ Formları kullanmak için öncelikle ../../docs_src/request_forms/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1" -{!> ../../docs_src/request_forms/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/request_forms/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[3] *} ## `Form` Parametrelerini Tanımlayın Form parametrelerini `Body` veya `Query` için yaptığınız gibi oluşturun: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/request_forms/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/request_forms/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/request_forms/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[9] *} Örneğin, OAuth2 spesifikasyonunun kullanılabileceği ("şifre akışı" olarak adlandırılan) yollardan birinde, form alanları olarak "username" ve "password" gönderilmesi gerekir. @@ -84,13 +28,13 @@ Bu spesifikasyon form alanlar `Form` sınıfıyla tanımlama yaparken `Body`, `Query`, `Path` ve `Cookie` sınıflarında kullandığınız aynı validasyon, örnekler, isimlendirme (örneğin `username` yerine `user-name` kullanımı) ve daha fazla konfigurasyonu kullanabilirsiniz. -/// info | "Bilgi" +/// info | Bilgi `Form` doğrudan `Body` sınıfını miras alan bir sınıftır. /// -/// tip | "İpucu" +/// tip | İpucu Form gövdelerini tanımlamak için `Form` sınıfını kullanmanız gerekir; çünkü bu olmadan parametreler sorgu parametreleri veya gövde (JSON) parametreleri olarak yorumlanır. @@ -102,7 +46,7 @@ HTML formlarının (`
`) verileri sunucuya gönderirken JSON'dan far **FastAPI** bu verilerin JSON yerine doğru şekilde okunmasını sağlayacaktır. -/// note | "Teknik Detaylar" +/// note | Teknik Detaylar Form verileri normalde `application/x-www-form-urlencoded` medya tipiyle kodlanır. @@ -112,7 +56,7 @@ Form kodlama türleri ve form alanları hakkında daha fazla bilgi edinmek istiy /// -/// warning | "Uyarı" +/// warning | Uyarı *Yol operasyonları* içerisinde birden fazla `Form` parametresi tanımlayabilirsiniz ancak bunlarla birlikte JSON verisi kabul eden `Body` alanları tanımlayamazsınız çünkü bu durumda istek gövdesi `application/json` yerine `application/x-www-form-urlencoded` ile kodlanmış olur. diff --git a/docs/tr/docs/tutorial/static-files.md b/docs/tr/docs/tutorial/static-files.md index 8bff59744e884..db30f13bc8037 100644 --- a/docs/tr/docs/tutorial/static-files.md +++ b/docs/tr/docs/tutorial/static-files.md @@ -7,11 +7,9 @@ * `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" +/// note | Teknik Detaylar Projenize dahil etmek için `from starlette.staticfiles import StaticFiles` kullanabilirsiniz. diff --git a/docs/uk/docs/alternatives.md b/docs/uk/docs/alternatives.md index 6821ffe705e2a..1acbe237af594 100644 --- a/docs/uk/docs/alternatives.md +++ b/docs/uk/docs/alternatives.md @@ -30,13 +30,13 @@ Це був один із перших прикладів **автоматичної документації API**, і саме це була одна з перших ідей, яка надихнула на «пошук» **FastAPI**. -/// note | "Примітка" +/// note | Примітка Django REST Framework створив Том Крісті. Той самий творець Starlette і Uvicorn, на яких базується **FastAPI**. /// -/// check | "Надихнуло **FastAPI** на" +/// check | Надихнуло **FastAPI** на Мати автоматичний веб-інтерфейс документації API. @@ -56,7 +56,7 @@ Flask — це «мікрофреймворк», він не включає ін Враховуючи простоту Flask, він здавався хорошим підходом для створення API. Наступним, що знайшов, був «Django REST Framework» для Flask. -/// check | "Надихнуло **FastAPI** на" +/// check | Надихнуло **FastAPI** на Бути мікрофреймоворком. Зробити легким комбінування та поєднання необхідних інструментів та частин. @@ -98,7 +98,7 @@ def read_url(): Зверніть увагу на схожість у `requests.get(...)` і `@app.get(...)`. -/// check | "Надихнуло **FastAPI** на" +/// check | Надихнуло **FastAPI** на * Майте простий та інтуїтивно зрозумілий API. * Використовуйте імена (операції) методів HTTP безпосередньо, простим та інтуїтивно зрозумілим способом. @@ -118,7 +118,7 @@ def read_url(): Тому, коли говорять про версію 2.0, прийнято говорити «Swagger», а про версію 3+ «OpenAPI». -/// check | "Надихнуло **FastAPI** на" +/// check | Надихнуло **FastAPI** на Прийняти і використовувати відкритий стандарт для специфікацій API замість спеціальної схеми. @@ -147,7 +147,7 @@ Marshmallow створено для забезпечення цих функці Але він був створений до того, як існували підказки типу Python. Отже, щоб визначити кожну схему, вам потрібно використовувати спеціальні утиліти та класи, надані Marshmallow. -/// check | "Надихнуло **FastAPI** на" +/// check | Надихнуло **FastAPI** на Використовувати код для автоматичного визначення "схем", які надають типи даних і перевірку. @@ -163,13 +163,13 @@ Webargs — це інструмент, створений, щоб забезпе Це чудовий інструмент, і я також часто використовував його, перш ніж створити **FastAPI**. -/// info | "Інформація" +/// info | Інформація Webargs був створений тими ж розробниками Marshmallow. /// -/// check | "Надихнуло **FastAPI** на" +/// check | Надихнуло **FastAPI** на Мати автоматичну перевірку даних вхідного запиту. @@ -193,13 +193,13 @@ Marshmallow і Webargs забезпечують перевірку, аналіз Редактор тут нічим не може допомогти. І якщо ми змінимо параметри чи схеми Marshmallow і забудемо також змінити цю строку документа YAML, згенерована схема буде застарілою. -/// info | "Інформація" +/// info | Інформація APISpec був створений тими ж розробниками Marshmallow. /// -/// check | "Надихнуло **FastAPI** на" +/// check | Надихнуло **FastAPI** на Підтримувати відкритий стандарт API, OpenAPI. @@ -225,13 +225,13 @@ APISpec був створений тими ж розробниками Marshmall І ці самі генератори повного стеку були основою [**FastAPI** генераторів проектів](project-generation.md){.internal-link target=_blank}. -/// info | "Інформація" +/// info | Інформація Flask-apispec був створений тими ж розробниками Marshmallow. /// -/// check | "Надихнуло **FastAPI** на" +/// check | Надихнуло **FastAPI** на Створення схеми OpenAPI автоматично з того самого коду, який визначає серіалізацію та перевірку. @@ -251,7 +251,7 @@ Flask-apispec був створений тими ж розробниками Mar Він не дуже добре обробляє вкладені моделі. Отже, якщо тіло JSON у запиті є об’єктом JSON із внутрішніми полями, які, у свою чергу, є вкладеними об’єктами JSON, його неможливо належним чином задокументувати та перевірити. -/// check | "Надихнуло **FastAPI** на" +/// check | Надихнуло **FastAPI** на Використовувати типи Python, щоб мати чудову підтримку редактора. @@ -263,7 +263,7 @@ Flask-apispec був створений тими ж розробниками Mar Це був один із перших надзвичайно швидких фреймворків Python на основі `asyncio`. Він був дуже схожий на Flask. -/// note | "Технічні деталі" +/// note | Технічні деталі Він використовував
`uvloop` замість стандартного циклу Python `asyncio`. Ось що зробило його таким швидким. @@ -271,7 +271,7 @@ Flask-apispec був створений тими ж розробниками Mar /// -/// check | "Надихнуло **FastAPI** на" +/// check | Надихнуло **FastAPI** на Знайти спосіб отримати божевільну продуктивність. @@ -287,7 +287,7 @@ Falcon — ще один високопродуктивний фреймворк Таким чином, перевірка даних, серіалізація та документація повинні виконуватися в коді, а не автоматично. Або вони повинні бути реалізовані як фреймворк поверх Falcon, як Hug. Така сама відмінність спостерігається в інших фреймворках, натхненних дизайном Falcon, що мають один об’єкт запиту та один об’єкт відповіді як параметри. -/// check | "Надихнуло **FastAPI** на" +/// check | Надихнуло **FastAPI** на Знайти способи отримати чудову продуктивність. @@ -313,7 +313,7 @@ Falcon — ще один високопродуктивний фреймворк Маршрути оголошуються в одному місці з використанням функцій, оголошених в інших місцях (замість використання декораторів, які можна розмістити безпосередньо поверх функції, яка обробляє кінцеву точку). Це ближче до того, як це робить Django, ніж до Flask (і Starlette). Він розділяє в коді речі, які відносно тісно пов’язані. -/// check | "Надихнуло **FastAPI** на" +/// check | Надихнуло **FastAPI** на Визначити додаткові перевірки для типів даних, використовуючи значення "за замовчуванням" атрибутів моделі. Це покращує підтримку редактора, а раніше вона була недоступна в Pydantic. @@ -335,13 +335,13 @@ Hug був одним із перших фреймворків, який реа Оскільки він заснований на попередньому стандарті для синхронних веб-фреймворків Python (WSGI), він не може працювати з Websockets та іншими речами, хоча він також має високу продуктивність. -/// info | "Інформація" +/// info | Інформація Hug створив Тімоті Крослі, той самий творець `isort`, чудовий інструмент для автоматичного сортування імпорту у файлах Python. /// -/// check | "Надихнуло **FastAPI** на" +/// check | Надихнуло **FastAPI** на Hug надихнув частину APIStar і був одним із найбільш перспективних інструментів, поряд із APIStar. @@ -375,7 +375,7 @@ Hug надихнув частину APIStar і був одним із найбі Тепер APIStar — це набір інструментів для перевірки специфікацій OpenAPI, а не веб-фреймворк. -/// info | "Інформація" +/// info | Інформація APIStar створив Том Крісті. Той самий хлопець, який створив: @@ -385,7 +385,7 @@ APIStar створив Том Крісті. Той самий хлопець, я /// -/// check | "Надихнуло **FastAPI** на" +/// check | Надихнуло **FastAPI** на Існувати. @@ -407,7 +407,7 @@ Pydantic — це бібліотека для визначення переві Його можна порівняти з Marshmallow. Хоча він швидший за Marshmallow у тестах. Оскільки він базується на тих самих підказках типу Python, підтримка редактора чудова. -/// check | "**FastAPI** використовує його для" +/// check | **FastAPI** використовує його для Виконання перевірки всіх даних, серіалізації даних і автоматичної документацію моделі (на основі схеми JSON). @@ -442,7 +442,7 @@ Starlette надає всі основні функції веб-мікрофр Це одна з головних речей, які **FastAPI** додає зверху, все на основі підказок типу Python (з використанням Pydantic). Це, а також система впровадження залежностей, утиліти безпеки, створення схеми OpenAPI тощо. -/// note | "Технічні деталі" +/// note | Технічні деталі ASGI — це новий «стандарт», який розробляється членами основної команди Django. Це ще не «стандарт Python» (PEP), хоча вони в процесі цього. @@ -450,7 +450,7 @@ ASGI — це новий «стандарт», який розробляєтьс /// -/// check | "**FastAPI** використовує його для" +/// check | **FastAPI** використовує його для Керування всіма основними веб-частинами. Додавання функцій зверху. @@ -468,7 +468,7 @@ Uvicorn — це блискавичний сервер ASGI, побудован Це рекомендований сервер для Starlette і **FastAPI**. -/// check | "**FastAPI** рекомендує це як" +/// check | **FastAPI** рекомендує це як Основний веб-сервер для запуску програм **FastAPI**. diff --git a/docs/uk/docs/python-types.md b/docs/uk/docs/python-types.md index 573b5372c5803..676bafb15ccd9 100644 --- a/docs/uk/docs/python-types.md +++ b/docs/uk/docs/python-types.md @@ -22,9 +22,8 @@ Python підтримує додаткові "підказки типу" ("type Давайте почнемо з простого прикладу: -```Python -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py *} + Виклик цієї програми виводить: @@ -38,9 +37,8 @@ John Doe * Конвертує кожну літеру кожного слова у верхній регістр за допомогою `title()`. * Конкатенує їх разом із пробілом по середині. -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py hl[2] *} + ### Редагуйте це @@ -82,9 +80,8 @@ John Doe Це "type hints": -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial002.py!} -``` +{* ../../docs_src/python_types/tutorial002.py hl[1] *} + Це не те саме, що оголошення значень за замовчуванням, як це було б з: @@ -112,9 +109,8 @@ John Doe Перевірте цю функцію, вона вже має анотацію типу: -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial003.py!} -``` +{* ../../docs_src/python_types/tutorial003.py hl[1] *} + Оскільки редактор знає типи змінних, ви не тільки отримаєте автозаповнення, ви також отримаєте перевірку помилок: @@ -122,9 +118,8 @@ John Doe Тепер ви знаєте, щоб виправити це, вам потрібно перетворити `age` у строку з допомогою `str(age)`: -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial004.py!} -``` +{* ../../docs_src/python_types/tutorial004.py hl[2] *} + ## Оголошення типів @@ -143,9 +138,8 @@ John Doe * `bool` * `bytes` -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial005.py!} -``` +{* ../../docs_src/python_types/tutorial005.py hl[1] *} + ### Generic-типи з параметрами типів @@ -406,15 +400,13 @@ John Doe Скажімо, у вас є клас `Person` з імʼям: -```Python hl_lines="1-3" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[1:3] *} + Потім ви можете оголосити змінну типу `Person`: -```Python hl_lines="6" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[6] *} + І знову ж таки, ви отримуєте всю підтримку редактора: diff --git a/docs/uk/docs/tutorial/body-fields.md b/docs/uk/docs/tutorial/body-fields.md index b1f6459321a44..7ddd9d104b5c5 100644 --- a/docs/uk/docs/tutorial/body-fields.md +++ b/docs/uk/docs/tutorial/body-fields.md @@ -6,57 +6,7 @@ Спочатку вам потрібно імпортувати це: -//// tab | Python 3.10+ - -```Python hl_lines="4" -{!> ../../docs_src/body_fields/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="4" -{!> ../../docs_src/body_fields/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4" -{!> ../../docs_src/body_fields/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Варто користуватись `Annotated` версією, якщо це можливо. - -/// - -```Python hl_lines="2" -{!> ../../docs_src/body_fields/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Варто користуватись `Annotated` версією, якщо це можливо. - -/// - -```Python hl_lines="4" -{!> ../../docs_src/body_fields/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[4] *} /// warning @@ -68,61 +18,11 @@ Ви можете використовувати `Field` з атрибутами моделі: -//// tab | Python 3.10+ - -```Python hl_lines="11-14" -{!> ../../docs_src/body_fields/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="11-14" -{!> ../../docs_src/body_fields/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="12-15" -{!> ../../docs_src/body_fields/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Варто користуватись `Annotated` версією, якщо це можливо.. - -/// - -```Python hl_lines="9-12" -{!> ../../docs_src/body_fields/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Варто користуватись `Annotated` версією, якщо це можливо.. - -/// - -```Python hl_lines="11-14" -{!> ../../docs_src/body_fields/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[11:14] *} `Field` працює так само, як `Query`, `Path` і `Body`, у нього такі самі параметри тощо. -/// note | "Технічні деталі" +/// note | Технічні деталі Насправді, `Query`, `Path` та інші, що ви побачите далі, створюють об'єкти підкласів загального класу `Param`, котрий сам є підкласом класу `FieldInfo` з Pydantic. diff --git a/docs/uk/docs/tutorial/body.md b/docs/uk/docs/tutorial/body.md index 1e41888310ab6..38fed7bb8d205 100644 --- a/docs/uk/docs/tutorial/body.md +++ b/docs/uk/docs/tutorial/body.md @@ -22,21 +22,7 @@ Спочатку вам потрібно імпортувати `BaseModel` з `pydantic`: -//// tab | Python 3.8 і вище - -```Python hl_lines="4" -{!> ../../docs_src/body/tutorial001.py!} -``` - -//// - -//// tab | Python 3.10 і вище - -```Python hl_lines="2" -{!> ../../docs_src/body/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/body/tutorial001.py hl[4] *} ## Створіть свою модель даних @@ -44,21 +30,7 @@ Використовуйте стандартні типи Python для всіх атрибутів: -//// tab | Python 3.8 і вище - -```Python hl_lines="7-11" -{!> ../../docs_src/body/tutorial001.py!} -``` - -//// - -//// tab | Python 3.10 і вище - -```Python hl_lines="5-9" -{!> ../../docs_src/body/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/body/tutorial001.py hl[7:11] *} Так само, як і при оголошенні параметрів запиту, коли атрибут моделі має значення за замовчуванням, він не є обов’язковим. В іншому випадку це потрібно. Використовуйте `None`, щоб зробити його необов'язковим. @@ -86,21 +58,7 @@ Щоб додати модель даних до вашої *операції шляху*, оголосіть її так само, як ви оголосили параметри шляху та запиту: -//// tab | Python 3.8 і вище - -```Python hl_lines="18" -{!> ../../docs_src/body/tutorial001.py!} -``` - -//// - -//// tab | Python 3.10 і вище - -```Python hl_lines="16" -{!> ../../docs_src/body/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/body/tutorial001.py hl[18] *} ...і вкажіть її тип як модель, яку ви створили, `Item`. @@ -167,21 +125,7 @@ Усередині функції ви можете отримати прямий доступ до всіх атрибутів об’єкта моделі: -//// tab | Python 3.8 і вище - -```Python hl_lines="21" -{!> ../../docs_src/body/tutorial002.py!} -``` - -//// - -//// tab | Python 3.10 і вище - -```Python hl_lines="19" -{!> ../../docs_src/body/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/body/tutorial002.py hl[21] *} ## Тіло запиту + параметри шляху @@ -189,21 +133,7 @@ **FastAPI** розпізнає, що параметри функції, які відповідають параметрам шляху, мають бути **взяті з шляху**, а параметри функції, які оголошуються як моделі Pydantic, **взяті з тіла запиту**. -//// tab | Python 3.8 і вище - -```Python hl_lines="17-18" -{!> ../../docs_src/body/tutorial003.py!} -``` - -//// - -//// tab | Python 3.10 і вище - -```Python hl_lines="15-16" -{!> ../../docs_src/body/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/body/tutorial003.py hl[17:18] *} ## Тіло запиту + шлях + параметри запиту @@ -211,21 +141,7 @@ **FastAPI** розпізнає кожен з них і візьме дані з потрібного місця. -//// tab | Python 3.8 і вище - -```Python hl_lines="18" -{!> ../../docs_src/body/tutorial004.py!} -``` - -//// - -//// tab | Python 3.10 і вище - -```Python hl_lines="16" -{!> ../../docs_src/body/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/body/tutorial004.py hl[18] *} Параметри функції будуть розпізнаватися наступним чином: diff --git a/docs/uk/docs/tutorial/cookie-params.md b/docs/uk/docs/tutorial/cookie-params.md index 40ca4f6e6c76f..b320645cb3093 100644 --- a/docs/uk/docs/tutorial/cookie-params.md +++ b/docs/uk/docs/tutorial/cookie-params.md @@ -6,57 +6,7 @@ Спочатку імпортуйте `Cookie`: -//// tab | Python 3.10+ - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Бажано використовувати `Annotated` версію, якщо це можливо. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/cookie_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Бажано використовувати `Annotated` версію, якщо це можливо. - -/// - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[3] *} ## Визначення параметрів `Cookie` @@ -64,59 +14,9 @@ Перше значення це значення за замовчуванням, ви можете також передати всі додаткові параметри валідації чи анотації: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/cookie_params/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Бажано використовувати `Annotated` версію, якщо це можливо. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/cookie_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Бажано використовувати `Annotated` версію, якщо це можливо. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[9] *} -/// note | "Технічні Деталі" +/// note | Технічні Деталі `Cookie` це "сестра" класів `Path` і `Query`. Вони наслідуються від одного батьківського класу `Param`. Але пам'ятайте, що коли ви імпортуєте `Query`, `Path`, `Cookie` та інше з `fastapi`, це фактично функції, що повертають спеціальні класи. diff --git a/docs/uk/docs/tutorial/encoder.md b/docs/uk/docs/tutorial/encoder.md index 39dca9be8b235..f202c7989ed1b 100644 --- a/docs/uk/docs/tutorial/encoder.md +++ b/docs/uk/docs/tutorial/encoder.md @@ -20,21 +20,7 @@ Вона приймає об'єкт, такий як Pydantic model, і повертає його версію, сумісну з JSON: -//// tab | Python 3.10+ - -```Python hl_lines="4 21" -{!> ../../docs_src/encoder/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="5 22" -{!> ../../docs_src/encoder/tutorial001.py!} -``` - -//// +{* ../../docs_src/encoder/tutorial001_py310.py hl[4,21] *} У цьому прикладі вона конвертує Pydantic model у `dict`, а `datetime` у `str`. @@ -42,7 +28,7 @@ Вона не повертає велику строку `str`, яка містить дані у форматі JSON (як строка). Вона повертає стандартну структуру даних Python (наприклад `dict`) із значеннями та підзначеннями, які є сумісними з JSON. -/// note | "Примітка" +/// note | Примітка `jsonable_encoder` фактично використовується **FastAPI** внутрішньо для перетворення даних. Проте вона корисна в багатьох інших сценаріях. diff --git a/docs/uk/docs/tutorial/extra-data-types.md b/docs/uk/docs/tutorial/extra-data-types.md index 5e6c364e45021..5da942b6e0c58 100644 --- a/docs/uk/docs/tutorial/extra-data-types.md +++ b/docs/uk/docs/tutorial/extra-data-types.md @@ -55,108 +55,8 @@ Ось приклад *path operation* з параметрами, використовуючи деякі з вищезазначених типів. -//// tab | Python 3.10+ - -```Python hl_lines="1 3 12-16" -{!> ../../docs_src/extra_data_types/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="1 3 12-16" -{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 3 13-17" -{!> ../../docs_src/extra_data_types/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Бажано використовувати `Annotated` версію, якщо це можливо. - -/// - -```Python hl_lines="1 2 11-15" -{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Бажано використовувати `Annotated` версію, якщо це можливо. - -/// - -```Python hl_lines="1 2 12-16" -{!> ../../docs_src/extra_data_types/tutorial001.py!} -``` - -//// +{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[1,3,12:16] *} Зверніть увагу, що параметри всередині функції мають свій звичайний тип даних, і ви можете, наприклад, виконувати звичайні маніпуляції з датами, такі як: -//// tab | Python 3.10+ - -```Python hl_lines="18-19" -{!> ../../docs_src/extra_data_types/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="18-19" -{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="19-20" -{!> ../../docs_src/extra_data_types/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Бажано використовувати `Annotated` версію, якщо це можливо. - -/// - -```Python hl_lines="17-18" -{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Бажано використовувати `Annotated` версію, якщо це можливо. - -/// - -```Python hl_lines="18-19" -{!> ../../docs_src/extra_data_types/tutorial001.py!} -``` - -//// +{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[18:19] *} diff --git a/docs/uk/docs/tutorial/first-steps.md b/docs/uk/docs/tutorial/first-steps.md index 6f79c0d1d6992..e910c4ccc18b6 100644 --- a/docs/uk/docs/tutorial/first-steps.md +++ b/docs/uk/docs/tutorial/first-steps.md @@ -2,9 +2,7 @@ Найпростіший файл FastAPI може виглядати так: -```Python -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py *} Скопіюйте це до файлу `main.py`. @@ -157,13 +155,11 @@ OpenAPI описує схему для вашого API. І ця схема вк ### Крок 1: імпортуємо `FastAPI` -```Python hl_lines="1" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[1] *} `FastAPI` це клас у Python, який надає всю функціональність для API. -/// note | "Технічні деталі" +/// note | Технічні деталі `FastAPI` це клас, який успадковується безпосередньо від `Starlette`. @@ -173,9 +169,7 @@ OpenAPI описує схему для вашого API. І ця схема вк ### Крок 2: створюємо екземпляр `FastAPI` -```Python hl_lines="3" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[3] *} Змінна `app` є екземпляром класу `FastAPI`. Це буде головна точка для створення і взаємодії з API. @@ -198,7 +192,7 @@ https://example.com/items/foo /items/foo ``` -/// info | "Додаткова інформація" +/// info | Додаткова інформація "Шлях" (path) також зазвичай називають "ендпоінтом" (endpoint) або "маршрутом" (route). @@ -242,15 +236,13 @@ https://example.com/items/foo #### Визначте декоратор операції шляху (path operation decorator) -```Python hl_lines="6" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[6] *} Декоратор `@app.get("/")` вказує **FastAPI**, що функція нижче, відповідає за обробку запитів, які надходять до неї: * шлях `/` * використовуючи get операцію -/// info | "`@decorator` Додаткова інформація" +/// info | `@decorator` Додаткова інформація Синтаксис `@something` у Python називається "декоратором". @@ -277,7 +269,7 @@ https://example.com/items/foo * `@app.patch()` * `@app.trace()` -/// tip | "Порада" +/// tip | Порада Ви можете використовувати кожну операцію (HTTP-метод) на свій розсуд. @@ -297,9 +289,7 @@ https://example.com/items/foo * **операція**: це `get`. * **функція**: це функція, яка знаходиться нижче "декоратора" (нижче `@app.get("/")`). -```Python hl_lines="7" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[7] *} Це звичайна функція Python. @@ -311,11 +301,9 @@ 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}. @@ -323,9 +311,7 @@ FastAPI викликатиме її щоразу, коли отримає зап ### Крок 5: поверніть результат -```Python hl_lines="8" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[8] *} Ви можете повернути `dict`, `list`, а також окремі значення `str`, `int`, ітд. diff --git a/docs/vi/docs/python-types.md b/docs/vi/docs/python-types.md index 275b0eb3908d3..403e89930023d 100644 --- a/docs/vi/docs/python-types.md +++ b/docs/vi/docs/python-types.md @@ -22,9 +22,8 @@ Nếu bạn là một chuyên gia về Python, và bạn đã biết mọi thứ Hãy bắt đầu với một ví dụ đơn giản: -```Python -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py *} + Kết quả khi gọi chương trình này: @@ -38,9 +37,8 @@ Hàm thực hiện như sau: * Chuyển đổi kí tự đầu tiên của mỗi biến sang kiểu chữ hoa với `title()`. * Nối chúng lại với nhau bằng một kí tự trắng ở giữa. -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py hl[2] *} + ### Sửa đổi @@ -82,9 +80,8 @@ Chính là nó. Những thứ đó là "type hints": -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial002.py!} -``` +{* ../../docs_src/python_types/tutorial002.py hl[1] *} + Đó không giống như khai báo những giá trị mặc định giống như: @@ -112,9 +109,8 @@ Với cái đó, bạn có thể cuộn, nhìn thấy các lựa chọn, cho đ Kiểm tra hàm này, nó đã có gợi ý kiểu dữ liệu: -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial003.py!} -``` +{* ../../docs_src/python_types/tutorial003.py hl[1] *} + Bởi vì trình soạn thảo biết kiểu dữ liệu của các biến, bạn không chỉ có được completion, bạn cũng được kiểm tra lỗi: @@ -122,9 +118,8 @@ Bởi vì trình soạn thảo biết kiểu dữ liệu của các biến, bạ Bây giờ bạn biết rằng bạn phải sửa nó, chuyển `age` sang một xâu với `str(age)`: -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial004.py!} -``` +{* ../../docs_src/python_types/tutorial004.py hl[2] *} + ## Khai báo các kiểu dữ liệu @@ -143,9 +138,8 @@ Bạn có thể sử dụng, ví dụ: * `bool` * `bytes` -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial005.py!} -``` +{* ../../docs_src/python_types/tutorial005.py hl[1] *} + ### Các kiểu dữ liệu tổng quát với tham số kiểu dữ liệu @@ -374,9 +368,8 @@ Nó chỉ là về các từ và tên. Nhưng những từ đó có thể ảnh Cho một ví dụ, hãy để ý hàm này: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial009c.py!} -``` +{* ../../docs_src/python_types/tutorial009c.py hl[1,4] *} + Tham số `name` được định nghĩa là `Optional[str]`, nhưng nó **không phải là tùy chọn**, bạn không thể gọi hàm mà không có tham số: @@ -392,9 +385,8 @@ say_hi(name=None) # This works, None is valid 🎉 Tin tốt là, khi bạn sử dụng Python 3.10, bạn sẽ không phải lo lắng về điều đó, bạn sẽ có thể sử dụng `|` để định nghĩa hợp của các kiểu dữ liệu một cách đơn giản: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial009c_py310.py!} -``` +{* ../../docs_src/python_types/tutorial009c_py310.py hl[1,4] *} + Và sau đó, bạn sẽ không phải lo rằng những cái tên như `Optional` và `Union`. 😎 @@ -457,15 +449,13 @@ Bạn cũng có thể khai báo một lớp như là kiểu dữ liệu của m Hãy nói rằng bạn muốn có một lớp `Person` với một tên: -```Python hl_lines="1-3" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[1:3] *} + Sau đó bạn có thể khai báo một biến có kiểu là `Person`: -```Python hl_lines="6" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[6] *} + Và lại một lần nữa, bạn có được tất cả sự hỗ trợ từ trình soạn thảo: diff --git a/docs/vi/docs/tutorial/first-steps.md b/docs/vi/docs/tutorial/first-steps.md index d80d78506827d..901c8fd5935be 100644 --- a/docs/vi/docs/tutorial/first-steps.md +++ b/docs/vi/docs/tutorial/first-steps.md @@ -2,9 +2,7 @@ Tệp tin FastAPI đơn giản nhất có thể trông như này: -```Python -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py *} Sao chép sang một tệp tin `main.py`. @@ -133,13 +131,11 @@ 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" +/// note | Chi tiết kĩ thuật `FastAPI` là một class kế thừa trực tiếp `Starlette`. @@ -149,9 +145,7 @@ Bạn cũng có thể sử dụng tất cả TL;DR:
+ +如果你正在使用要求你以 `await` 語法呼叫的第三方函式庫,例如: + +```Python +results = await some_library() +``` + +然後,使用 `async def` 宣告你的*路徑操作函式*: + + +```Python hl_lines="2" +@app.get('/') +async def read_results(): + results = await some_library() + return results +``` + +/// note | 注意 + +你只能在 `async def` 建立的函式內使用 `await`。 + +/// + +--- + +如果你使用的是第三方函式庫並且它需要與某些外部資源(例如資料庫、API、檔案系統等)進行通訊,但不支援 `await`(目前大多數資料庫函式庫都是這樣),在這種情況下,你可以像平常一樣使用 `def` 宣告*路徑操作函式*,如下所示: + +```Python hl_lines="2" +@app.get('/') +def results(): + results = some_library() + return results +``` + +--- + +如果你的應用程式不需要與外部資源進行任何通訊並等待其回應,請使用 `async def`。 + +--- + +如果你不確定該用哪個,直接用 `def` 就好。 + +--- + +**注意**:你可以在*路徑操作函式*中混合使用 `def` 和 `async def` ,並使用最適合你需求的方式來定義每個函式。FastAPI 會幫你做正確的處理。 + +無論如何,在上述哪種情況下,FastAPI 仍將以非同步方式運行,並且速度非常快。 + +但透過遵循上述步驟,它將能進行一些效能最佳化。 + +## 技術細節 + +現代版本的 Python 支援使用 **「協程」** 的 **`async` 和 `await`** 語法來寫 **「非同步程式碼」**。 + +接下來我們逐一介紹: + +* **非同步程式碼** +* **`async` 和 `await`** +* **協程** + +## 非同步程式碼 + +非同步程式碼僅意味著程式語言 💬 有辦法告訴電腦/程式 🤖 在程式碼中的某個點,它 🤖 需要等待某些事情完成。讓我們假設這些事情被稱為「慢速檔案」📝。 + +因此,在等待「慢速檔案」📝 完成的這段時間,電腦可以去處理一些其他工作。 + +接著程式 🤖 會在有空檔時回來查看是否有等待的工作已經完成,並執行必要的後續操作。 + +接下來,它 🤖 完成第一個工作(例如我們的「慢速檔案」📝)並繼續執行相關的所有操作。 +這個「等待其他事情」通常指的是一些相對較慢的(與處理器和 RAM 記憶體的速度相比)的 I/O 操作,比如說: + +* 透過網路傳送來自用戶端的資料 +* 從網路接收來自用戶端的資料 +* 從磁碟讀取檔案內容 +* 將內容寫入磁碟 +* 遠端 API 操作 +* 資料庫操作 +* 資料庫查詢 +* 等等 + +由於大部分的執行時間都消耗在等待 I/O 操作上,因此這些操作被稱為 "I/O 密集型" 操作。 + +之所以稱為「非同步」,是因為電腦/程式不需要與那些耗時的任務「同步」,等待任務完成的精確時間,然後才能取得結果並繼續工作。 + +相反地,非同步系統在任務完成後,可以讓任務稍微等一下(幾微秒),等待電腦/程式完成手頭上的其他工作,然後再回來取得結果繼續進行。 + +相對於「非同步」(asynchronous),「同步」(synchronous)也常被稱作「順序性」(sequential),因為電腦/程式會依序執行所有步驟,即便這些步驟涉及等待,才會切換到其他任務。 + +### 並行與漢堡 + +上述非同步程式碼的概念有時也被稱為「並行」,它不同於「平行」。 + +並行和平行都與 "不同的事情或多或少同時發生" 有關。 + +但並行和平行之間的細節是完全不同的。 + +為了理解差異,請想像以下有關漢堡的故事: + +### 並行漢堡 + +你和你的戀人去速食店,排隊等候時,收銀員正在幫排在你前面的人點餐。😍 + + + +輪到你了,你給你與你的戀人點了兩個豪華漢堡。🍔🍔 + + + +收銀員通知廚房準備你的漢堡(儘管他們還在為前面其他顧客準備食物)。 + + + +之後你完成付款。💸 + +收銀員給你一個號碼牌。 + + + +在等待漢堡的同時,你可以與戀人選一張桌子,然後坐下來聊很長一段時間(因為漢堡十分豪華,準備特別費工。) + +這段時間,你還能欣賞你的戀人有多麼的可愛、聰明與迷人。✨😍✨ + + + +當你和戀人邊聊天邊等待時,你會不時地查看櫃檯上的顯示的號碼,確認是否已經輪到你了。 + +然後在某個時刻,終於輪到你了。你走到櫃檯,拿了漢堡,然後回到桌子上。 + + + +你和戀人享用這頓大餐,整個過程十分開心✨ + + + +/// info + +漂亮的插畫來自 Ketrina Thompson. 🎨 + +/// + +--- + +想像你是故事中的電腦或程式 🤖。 + +當你排隊時,你在放空😴,等待輪到你,沒有做任何「生產性」的事情。但這沒關係,因為收銀員只是接單(而不是準備食物),所以排隊速度很快。 + +然後,當輪到你時,你開始做真正「有生產力」的工作,處理菜單,決定你想要什麼,替戀人選擇餐點,付款,確認你給了正確的帳單或信用卡,檢查你是否被正確收費,確認訂單中的項目是否正確等等。 + +但是,即使你還沒有拿到漢堡,你與收銀員的工作已經「暫停」了 ⏸,因為你必須等待 🕙 漢堡準備好。 + +但當你離開櫃檯,坐到桌子旁,拿著屬於你的號碼等待時,你可以把注意力 🔀 轉移到戀人身上,並開始「工作」⏯ 🤓——也就是和戀人調情 😍。這時你又開始做一些非常「有生產力」的事情。 + +接著,收銀員 💁 將你的號碼顯示在櫃檯螢幕上,並告訴你「漢堡已經做好了」。但你不會瘋狂地立刻跳起來,因為顯示的號碼變成了你的。你知道沒有人會搶走你的漢堡,因為你有自己的號碼,他們也有他們的號碼。 + +所以你會等戀人講完故事(完成當前的工作 ⏯/正在進行的任務 🤓),然後微笑著溫柔地說你要去拿漢堡了 ⏸。 + +然後你走向櫃檯 🔀,回到已經完成的最初任務 ⏯,拿起漢堡,說聲謝謝,並帶回桌上。這就結束了與櫃檯的互動步驟/任務 ⏹,接下來會產生一個新的任務,「吃漢堡」 🔀 ⏯,而先前的「拿漢堡」任務已經完成了 ⏹。 + +### 平行漢堡 + +現在,讓我們來想像這裡不是「並行漢堡」,而是「平行漢堡」。 + +你和戀人一起去吃平行的速食餐。 + +你們站在隊伍中,前面有幾位(假設有 8 位)既是收銀員又是廚師的員工,他們同時接單並準備餐點。 + +所有排在你前面的人都在等著他們的漢堡準備好後才會離開櫃檯,因為每位收銀員在接完單後,馬上會去準備漢堡,然後才回來處理下一個訂單。 + + + +終於輪到你了,你為你和你的戀人點了兩個非常豪華的漢堡。 + +你付款了 💸。 + + + +收銀員走進廚房準備食物。 + +你站在櫃檯前等待 🕙,以免其他人先拿走你的漢堡,因為這裡沒有號碼牌系統。 + + + +由於你和戀人都忙著不讓別人搶走你的漢堡,等漢堡準備好時,你根本無法專心和戀人互動。😞 + +這是「同步」(synchronous)工作,你和收銀員/廚師 👨‍🍳 是「同步化」的。你必須等到 🕙 收銀員/廚師 👨‍🍳 完成漢堡並交給你的那一刻,否則別人可能會拿走你的餐點。 + + + +最終,經過長時間的等待 🕙,收銀員/廚師 👨‍🍳 拿著漢堡回來了。 + + + +你拿著漢堡,和你的戀人回到餐桌。 + +你們僅僅是吃完漢堡,然後就結束了。⏹ + + + +整個過程中沒有太多的談情說愛,因為大部分時間 🕙 都花在櫃檯前等待。😞 + +/// info + +漂亮的插畫來自 Ketrina Thompson. 🎨 + +/// + +--- + +在這個平行漢堡的情境下,你是一個程式 🤖 且有兩個處理器(你和戀人),兩者都在等待 🕙 並專注於等待櫃檯上的餐點 🕙,等待的時間非常長。 + +這家速食店有 8 個處理器(收銀員/廚師)。而並行漢堡店可能只有 2 個處理器(一位收銀員和一位廚師)。 + +儘管如此,最終的體驗並不是最理想的。😞 + +--- + +這是與漢堡類似的故事。🍔 + +一個更「現實」的例子,想像一間銀行。 + +直到最近,大多數銀行都有多位出納員 👨‍💼👨‍💼👨‍💼👨‍💼,以及一條長長的隊伍 🕙🕙🕙🕙🕙🕙🕙🕙。 + +所有的出納員都在一個接一個地滿足每位客戶的所有需求 👨‍💼⏯。 + +你必須長時間排隊 🕙,不然就會失去機會。 + +所以,你不會想帶你的戀人 😍 一起去銀行辦事 🏦。 + +### 漢堡結論 + +在「和戀人一起吃速食漢堡」的這個場景中,由於有大量的等待 🕙,使用並行系統 ⏸🔀⏯ 更有意義。 + +這也是大多數 Web 應用的情況。 + +許多用戶正在使用你的應用程式,而你的伺服器則在等待 🕙 這些用戶不那麼穩定的網路來傳送請求。 + +接著,再次等待 🕙 回應。 + +這種「等待」 🕙 通常以微秒來衡量,但累加起來,最終還是花費了很多等待時間。 + +這就是為什麼對於 Web API 來說,使用非同步程式碼 ⏸🔀⏯ 是非常有意義的。 + +這種類型的非同步性正是 NodeJS 成功的原因(儘管 NodeJS 不是平行的),這也是 Go 語言作為程式語言的一個強大優勢。 + +這與 **FastAPI** 所能提供的性能水平相同。 + +你可以同時利用並行性和平行性,進一步提升效能,這比大多數已測試的 NodeJS 框架都更快,並且與 Go 語言相當,而 Go 是一種更接近 C 的編譯語言(感謝 Starlette)。 + +### 並行比平行更好嗎? + +不是的!這不是故事的本意。 + +並行與平行不同。並行在某些 **特定** 的需要大量等待的情境下表現更好。正因如此,並行在 Web 應用程式開發中通常比平行更有優勢。但並不是所有情境都如此。 + +因此,為了平衡報導,想像下面這個短故事 + +> 你需要打掃一間又大又髒的房子。 + +*是的,這就是全部的故事。* + +--- + +這裡沒有任何需要等待 🕙 的地方,只需要在房子的多個地方進行大量的工作。 + +你可以像漢堡的例子那樣輪流進行,先打掃客廳,再打掃廚房,但由於你不需要等待 🕙 任何事情,只需要持續地打掃,輪流並不會影響任何結果。 + +無論輪流執行與否(並行),你都需要相同的工時完成任務,同時需要執行相同工作量。 + +但是,在這種情境下,如果你可以邀請8位前收銀員/廚師(現在是清潔工)來幫忙,每個人(加上你)負責房子的某個區域,這樣你就可以 **平行** 地更快完成工作。 + +在這個場景中,每個清潔工(包括你)都是一個處理器,完成工作的一部分。 + +由於大多數的執行時間都花在實際的工作上(而不是等待),而電腦中的工作由 CPU 完成,因此這些問題被稱為「CPU 密集型」。 + +--- + +常見的 CPU 密集型操作範例包括那些需要進行複雜數學計算的任務。 + +例如: + +* **音訊**或**圖像處理**; +* **電腦視覺**:一張圖片由數百萬個像素組成,每個像素有 3 個值/顏色,處理這些像素通常需要同時進行大量計算; +* **機器學習**: 通常需要大量的「矩陣」和「向量」運算。想像一個包含數字的巨大電子表格,並所有的數字同時相乘; +* **深度學習**: 這是機器學習的子領域,同樣適用。只不過這不僅僅是一張數字表格,而是大量的數據集合,並且在很多情況下,你會使用特殊的處理器來構建或使用這些模型。 + +### 並行 + 平行: Web + 機器學習 + +使用 **FastAPI**,你可以利用並行的優勢,這在 Web 開發中非常常見(這也是 NodeJS 的最大吸引力)。 + +但你也可以利用平行與多行程 (multiprocessing)(讓多個行程同時運行) 的優勢來處理機器學習系統中的 **CPU 密集型**工作。 + +這一點,再加上 Python 是 **資料科學**、機器學習,尤其是深度學習的主要語言,讓 **FastAPI** 成為資料科學/機器學習 Web API 和應用程式(以及許多其他應用程式)的絕佳選擇。 + +想了解如何在生產環境中實現這種平行性,請參見 [部屬](deployment/index.md){.internal-link target=_blank}。 + +## `async` 和 `await` + +現代 Python 版本提供一種非常直觀的方式定義非同步程式碼。這使得它看起來就像正常的「順序」程式碼,並在適當的時機「等待」。 + +當某個操作需要等待才能回傳結果,並且支援這些新的 Python 特性時,你可以像這樣編寫程式碼: + +```Python +burgers = await get_burgers(2) +``` + +這裡的關鍵是 `await`。它告訴 Python 必須等待 ⏸ `get_burgers(2)` 完成它的工作 🕙, 然後將結果儲存在 `burgers` 中。如此,Python 就可以在此期間去處理其他事情 🔀 ⏯ (例如接收另一個請求)。 + +要讓 `await` 運作,它必須位於支持非同步功能的函式內。為此,只需使用 `async def` 宣告函式: + +```Python hl_lines="1" +async def get_burgers(number: int): + # Do some asynchronous stuff to create the burgers + return burgers +``` + +...而不是 `def`: + +```Python hl_lines="2" +# This is not asynchronous +def get_sequential_burgers(number: int): + # Do some sequential stuff to create the burgers + return burgers +``` + +使用 `async def`,Python Python 知道在該函式內需要注意 `await`,並且它可以「暫停」 ⏸ 執行該函式,然後執行其他任務 🔀 後回來。 + +當你想要呼叫 `async def` 函式時,必須使用「await」。因此,這樣寫將無法運行: + +```Python +# This won't work, because get_burgers was defined with: async def +burgers = get_burgers(2) +``` + +--- + +如果你正在使用某個函式庫,它告訴你可以使用 `await` 呼叫它,那麼你需要用 `async def` 定義*路徑操作函式*,如: + +```Python hl_lines="2-3" +@app.get('/burgers') +async def read_burgers(): + burgers = await get_burgers(2) + return burgers +``` + +### 更多技術細節 + +你可能已經注意到,`await` 只能在 `async def` 定義的函式內使用。 + +但同時,使用 `async def` 定義的函式本身也必須被「等待」。所以,帶有 `async def` 函式只能在其他使用 `async def` 定義的函式內呼叫。 + +那麼,這就像「先有雞還是先有蛋」的問題,要如何呼叫第一個 `async` 函式呢? + +如果你使用 FastAPI,無需擔心這個問題,因為「第一個」函式將是你的*路徑操作函式*,FastAPI 會知道如何正確處理這個問題。 + +但如果你想在沒有 FastAPI 的情況下使用 `async` / `await`,你也可以這樣做。 + +### 編寫自己的非同步程式碼 + +Starlette (和 **FastAPI**) 是基於 AnyIO 實作的,這使得它們與 Python 標準函式庫相容 asyncioTrio。 + +特別是,你可以直接使用 AnyIO 來處理更複雜的並行使用案例,這些案例需要你在自己的程式碼中使用更高階的模式。 + +即使你不使用 **FastAPI**,你也可以使用 AnyIO 來撰寫自己的非同步應用程式,並獲得高相容性及一些好處(例如結構化並行)。 + +### 其他形式的非同步程式碼 + +使用 `async` 和 `await` 的風格在語言中相對較新。 + +但它使處理異步程式碼變得更加容易。 + +相同的語法(或幾乎相同的語法)最近也被包含在現代 JavaScript(無論是瀏覽器還是 NodeJS)中。 + +但在此之前,處理異步程式碼要更加複雜和困難。 + +在較舊的 Python 版本中,你可能會使用多執行緒或 Gevent。但這些程式碼要更難以理解、調試和思考。 + +在較舊的 NodeJS / 瀏覽器 JavaScript 中,你會使用「回呼」,這可能會導致回呼地獄。 + +## 協程 + +**協程** 只是 `async def` 函式所回傳的非常特殊的事物名稱。Python 知道它是一個類似函式的東西,可以啟動它,並且在某個時刻它會結束,但它也可能在內部暫停 ⏸,只要遇到 `await`。 + +這種使用 `async` 和 `await` 的非同步程式碼功能通常被概括為「協程」。這與 Go 語言的主要特性「Goroutines」相似。 + +## 結論 + +讓我們再次回顧之前的句子: + +> 現代版本的 Python 支持使用 **"協程"** 的 **`async` 和 `await`** 語法來寫 **"非同步程式碼"**。 + +現在應該能明白其含意了。✨ + +這些就是驅動 FastAPI(通過 Starlette)運作的原理,也讓它擁有如此驚人的效能。 + +## 非常技術性的細節 + +/// warning + +你大概可以跳過這段。 + +這裡是有關 FastAPI 內部技術細節。 + +如果你有相當多的技術背景(例如協程、執行緒、阻塞等),並且對 FastAPI 如何處理 `async def` 與常規 `def` 感到好奇,請繼續閱讀。 + +/// + +### 路徑操作函数 + +當你使用 `def` 而不是 `async def` 宣告*路徑操作函式*時,該函式會在外部的執行緒池(threadpool)中執行,然後等待結果,而不是直接呼叫(因為這樣會阻塞伺服器)。 + +如果你來自於其他不以這種方式運作的非同步框架,而且你習慣於使用普通的 `def` 定義僅進行簡單計算的*路徑操作函式*,目的是獲得微小的性能增益(大約 100 奈秒),請注意,在 FastAPI 中,效果會完全相反。在這些情況下,最好使用 `async def`除非你的*路徑操作函式*執行阻塞的 I/O 的程式碼。 + +不過,在這兩種情況下,**FastAPI** [仍然很快](index.md#_11){.internal-link target=_blank}至少與你之前的框架相當(或者更快)。 + +### 依賴項(Dependencies) + +同樣適用於[依賴項](tutorial/dependencies/index.md){.internal-link target=_blank}。如果依賴項是一個標準的 `def` 函式,而不是 `async def`,那麼它在外部的執行緒池被運行。 + +### 子依賴項 + +你可以擁有多個相互依賴的依賴項和[子依賴項](tutorial/dependencies/sub-dependencies.md){.internal-link target=_blank} (作為函式定義的參數),其中一些可能是用 `async def` 宣告,也可能是用 `def` 宣告。它們仍然可以正常運作,用 `def` 定義的那些將會在外部的執行緒中呼叫(來自執行緒池),而不是被「等待」。 + +### 其他輔助函式 + +你可以直接呼叫任何使用 `def` 或 `async def` 建立的其他輔助函式,FastAPI 不會影響你呼叫它們的方式。 + +這與 FastAPI 為你呼叫*路徑操作函式*和依賴項的邏輯有所不同。 + +如果你的輔助函式是用 `def` 宣告的,它將會被直接呼叫(按照你在程式碼中撰寫的方式),而不是在執行緒池中。如果該函式是用 `async def` 宣告,那麼你在呼叫時應該使用 `await` 等待其結果。 + +--- + +再一次強調,這些都是非常技術性的細節,如果你特地在尋找這些資訊,這些內容可能會對你有幫助。 + +否則,只需遵循上面提到的指引即可:趕時間嗎?. diff --git a/docs/zh-hant/docs/environment-variables.md b/docs/zh-hant/docs/environment-variables.md new file mode 100644 index 0000000000000..a1598fc018547 --- /dev/null +++ b/docs/zh-hant/docs/environment-variables.md @@ -0,0 +1,298 @@ +# 環境變數 + +/// tip + +如果你已經知道什麼是「環境變數」並且知道如何使用它們,你可以放心跳過這一部分。 + +/// + +環境變數(也稱為「**env var**」)是一個獨立於 Python 程式碼**之外**的變數,它存在於**作業系統**中,可以被你的 Python 程式碼(或其他程式)讀取。 + +環境變數對於處理應用程式**設定**(作為 Python **安裝**的一部分等方面)非常有用。 + +## 建立和使用環境變數 + +你在 **shell(終端機)**中就可以**建立**和使用環境變數,並不需要用到 Python: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +// 你可以使用以下指令建立一個名為 MY_NAME 的環境變數 +$ export MY_NAME="Wade Wilson" + +// 然後,你可以在其他程式中使用它,例如 +$ echo "Hello $MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +// 建立一個名為 MY_NAME 的環境變數 +$ $Env:MY_NAME = "Wade Wilson" + +// 在其他程式中使用它,例如 +$ echo "Hello $Env:MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +## 在 Python 中讀取環境變數 + +你也可以在 Python **之外**的終端機中建立環境變數(或使用其他方法),然後在 Python 中**讀取**它們。 + +例如,你可以建立一個名為 `main.py` 的檔案,其中包含以下內容: + +```Python hl_lines="3" +import os + +name = os.getenv("MY_NAME", "World") +print(f"Hello {name} from Python") +``` + +/// tip + +第二個參數是 `os.getenv()` 的預設回傳值。 + +如果沒有提供,預設值為 `None`,這裡我們提供 `"World"` 作為預設值。 + +/// + +然後你可以呼叫這個 Python 程式: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +// 這裡我們還沒有設定環境變數 +$ python main.py + +// 因為我們沒有設定環境變數,所以我們得到的是預設值 + +Hello World from Python + +// 但是如果我們事先建立過一個環境變數 +$ export MY_NAME="Wade Wilson" + +// 然後再次呼叫程式 +$ python main.py + +// 現在就可以讀取到環境變數了 + +Hello Wade Wilson from Python +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +// 這裡我們還沒有設定環境變數 +$ python main.py + +// 因為我們沒有設定環境變數,所以我們得到的是預設值 + +Hello World from Python + +// 但是如果我們事先建立過一個環境變數 +$ $Env:MY_NAME = "Wade Wilson" + +// 然後再次呼叫程式 +$ python main.py + +// 現在就可以讀取到環境變數了 + +Hello Wade Wilson from Python +``` + +
+ +//// + +由於環境變數可以在程式碼之外設定,但可以被程式碼讀取,並且不必與其他檔案一起儲存(提交到 `git`),因此通常用於配置或**設定**。 + +你還可以為**特定的程式呼叫**建立特定的環境變數,該環境變數僅對該程式可用,且僅在其執行期間有效。 + +要實現這一點,只需在同一行內(程式本身之前)建立它: + +
+ +```console +// 在這個程式呼叫的同一行中建立一個名為 MY_NAME 的環境變數 +$ MY_NAME="Wade Wilson" python main.py + +// 現在就可以讀取到環境變數了 + +Hello Wade Wilson from Python + +// 在此之後這個環境變數將不再存在 +$ python main.py + +Hello World from Python +``` + +
+ +/// tip + +你可以在 The Twelve-Factor App: 配置中了解更多資訊。 + +/// + +## 型別和驗證 + +這些環境變數只能處理**文字字串**,因為它們是位於 Python 範疇之外的,必須與其他程式和作業系統的其餘部分相容(甚至與不同的作業系統相容,如 Linux、Windows、macOS)。 + +這意味著從環境變數中讀取的**任何值**在 Python 中都將是一個 `str`,任何型別轉換或驗證都必須在程式碼中完成。 + +你將在[進階使用者指南 - 設定和環境變數](./advanced/settings.md)中了解更多關於使用環境變數處理**應用程式設定**的資訊。 + +## `PATH` 環境變數 + +有一個**特殊的**環境變數稱為 **`PATH`**,作業系統(Linux、macOS、Windows)用它來查找要執行的程式。 + +`PATH` 變數的值是一個長字串,由 Linux 和 macOS 上的冒號 `:` 分隔的目錄組成,而在 Windows 上則是由分號 `;` 分隔的。 + +例如,`PATH` 環境變數可能如下所示: + +//// tab | Linux, macOS + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +這意味著系統應該在以下目錄中查找程式: + +- `/usr/local/bin` +- `/usr/bin` +- `/bin` +- `/usr/sbin` +- `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32 +``` + +這意味著系統應該在以下目錄中查找程式: + +- `C:\Program Files\Python312\Scripts` +- `C:\Program Files\Python312` +- `C:\Windows\System32` + +//// + +當你在終端機中輸入一個**指令**時,作業系統會在 `PATH` 環境變數中列出的**每個目錄**中**查找**程式。 + +例如,當你在終端機中輸入 `python` 時,作業系統會在該列表中的**第一個目錄**中查找名為 `python` 的程式。 + +如果找到了,那麼作業系統將**使用它**;否則,作業系統會繼續在**其他目錄**中查找。 + +### 安裝 Python 並更新 `PATH` + +安裝 Python 時,可能會詢問你是否要更新 `PATH` 環境變數。 + +//// tab | Linux, macOS + +假設你安裝了 Python,並將其安裝在目錄 `/opt/custompython/bin` 中。 + +如果你選擇更新 `PATH` 環境變數,那麼安裝程式會將 `/opt/custompython/bin` 加入到 `PATH` 環境變數中。 + +它看起來大致會是這樣: + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/custompython/bin +``` + +如此一來,當你在終端機輸入 `python` 時,系統會在 `/opt/custompython/bin` 中找到 Python 程式(最後一個目錄)並使用它。 + +//// + +//// tab | Windows + +假設你安裝了 Python,並將其安裝在目錄 `C:\opt\custompython\bin` 中。 + +如果你選擇更新 `PATH` 環境變數(在 Python 安裝程式中,這個選項是名為 `Add Python x.xx to PATH` 的勾選框——譯者註),那麼安裝程式會將 `C:\opt\custompython\bin` 加入到 `PATH` 環境變數中。 + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32;C:\opt\custompython\bin +``` + +如此一來,當你在終端機輸入 `python` 時,系統會在 `C:\opt\custompython\bin` 中找到 Python 程式(最後一個目錄)並使用它。 + +//// + +因此,如果你輸入: + +
+ +```console +$ python +``` + +
+ +//// tab | Linux, macOS + +系統會在 `/opt/custompython/bin` 中**找到** `python` 程式並執行它。 + +這大致等同於輸入以下指令: + +
+ +```console +$ /opt/custompython/bin/python +``` + +
+ +//// + +//// tab | Windows + +系統會在 `C:\opt\custompython\bin\python` 中**找到** `python` 程式並執行它。 + +這大致等同於輸入以下指令: + +
+ +```console +$ C:\opt\custompython\bin\python +``` + +
+ +//// + +當學習[虛擬環境](virtual-environments.md)時,這些資訊將會很有用。 + +## 結論 + +透過這個教學,你應該對**環境變數**是什麼以及如何在 Python 中使用它們有了基本的了解。 + +你也可以在環境變數 - 維基百科 (Wikipedia for Environment Variable) 中了解更多關於它們的資訊。 + +在許多情況下,環境變數的用途和適用性可能不會立刻顯現。但是在開發過程中,它們會在許多不同的場景中出現,因此瞭解它們是非常必要的。 + +例如,你在接下來的[虛擬環境](virtual-environments.md)章節中將需要這些資訊。 diff --git a/docs/zh-hant/docs/tutorial/query-param-models.md b/docs/zh-hant/docs/tutorial/query-param-models.md new file mode 100644 index 0000000000000..76ee740169121 --- /dev/null +++ b/docs/zh-hant/docs/tutorial/query-param-models.md @@ -0,0 +1,68 @@ +# 查詢參數模型 + +如果你有一組具有相關性的**查詢參數**,你可以建立一個 **Pydantic 模型**來聲明它們。 + +這將允許你在**多個地方**去**重複使用模型**,並且一次性為所有參數聲明驗證和元資料 (metadata)。😎 + +/// note + +FastAPI 從 `0.115.0` 版本開始支援這個特性。🤓 + +/// + +## 使用 Pydantic 模型的查詢參數 + +在一個 **Pydantic 模型**中聲明你需要的**查詢參數**,然後將參數聲明為 `Query`: + +{* ../../docs_src/query_param_models/tutorial001_an_py310.py hl[9:13,17] *} + +**FastAPI** 將會從請求的**查詢參數**中**提取**出**每個欄位**的資料,並將其提供給你定義的 Pydantic 模型。 + +## 查看文件 + +你可以在 `/docs` 頁面的 UI 中查看查詢參數: + +
+ +
+ +## 禁止額外的查詢參數 + +在一些特殊的使用場景中(可能不是很常見),你可能希望**限制**你要收到的查詢參數。 + +你可以使用 Pydantic 的模型設定來 `forbid`(禁止)任何 `extra`(額外)欄位: + +{* ../../docs_src/query_param_models/tutorial002_an_py310.py hl[10] *} + +如果客戶端嘗試在**查詢參數**中發送一些**額外的**資料,他們將會收到一個**錯誤**回應。 + +例如,如果客戶端嘗試發送一個值為 `plumbus` 的 `tool` 查詢參數,如: + +```http +https://example.com/items/?limit=10&tool=plumbus +``` + +他們將收到一個**錯誤**回應,告訴他們查詢參數 `tool` 是不允許的: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["query", "tool"], + "msg": "Extra inputs are not permitted", + "input": "plumbus" + } + ] +} +``` + +## 總結 + +你可以使用 **Pydantic 模型**在 **FastAPI** 中聲明**查詢參數**。😎 + +/// tip + +劇透警告:你也可以使用 Pydantic 模型來聲明 cookie 和 headers,但你將在本教學的後面部分閱讀到這部分內容。🤫 + +/// diff --git a/docs/zh/docs/advanced/additional-responses.md b/docs/zh/docs/advanced/additional-responses.md index f051b12a4d4c6..362ef9460a23b 100644 --- a/docs/zh/docs/advanced/additional-responses.md +++ b/docs/zh/docs/advanced/additional-responses.md @@ -16,9 +16,7 @@ **FastAPI**将采用该模型,生成其`JSON Schema`并将其包含在`OpenAPI`中的正确位置。 例如,要声明另一个具有状态码 `404` 和`Pydantic`模型 `Message` 的响应,可以写: -```Python hl_lines="18 22" -{!../../docs_src/additional_responses/tutorial001.py!} -``` +{* ../../docs_src/additional_responses/tutorial001.py hl[18,22] *} /// note @@ -163,9 +161,7 @@ 例如,您可以添加一个额外的媒体类型` image/png` ,声明您的路径操作可以返回JSON对象(媒体类型 `application/json` )或PNG图像: -```Python hl_lines="19-24 28" -{!../../docs_src/additional_responses/tutorial002.py!} -``` +{* ../../docs_src/additional_responses/tutorial002.py hl[19:24,28] *} /// note @@ -191,9 +187,7 @@ 以及一个状态码为 `200` 的响应,它使用您的 `response_model` ,但包含自定义的 `example` : -```Python hl_lines="20-31" -{!../../docs_src/additional_responses/tutorial003.py!} -``` +{* ../../docs_src/additional_responses/tutorial003.py hl[20:31] *} 所有这些都将被合并并包含在您的OpenAPI中,并在API文档中显示: @@ -219,9 +213,7 @@ new_dict = {**old_dict, "new key": "new value"} ``` 您可以使用该技术在路径操作中重用一些预定义的响应,并将它们与其他自定义响应相结合。 **例如:** -```Python hl_lines="13-17 26" -{!../../docs_src/additional_responses/tutorial004.py!} -``` +{* ../../docs_src/additional_responses/tutorial004.py hl[13:17,26] *} ## 有关OpenAPI响应的更多信息 要了解您可以在响应中包含哪些内容,您可以查看OpenAPI规范中的以下部分: diff --git a/docs/zh/docs/advanced/additional-status-codes.md b/docs/zh/docs/advanced/additional-status-codes.md index f79b853ef8353..b048a2a170ffe 100644 --- a/docs/zh/docs/advanced/additional-status-codes.md +++ b/docs/zh/docs/advanced/additional-status-codes.md @@ -14,11 +14,9 @@ 要实现它,导入 `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 | "警告" +/// warning | 警告 当你直接返回一个像上面例子中的 `Response` 对象时,它会直接返回。 @@ -28,7 +26,7 @@ FastAPI 不会用模型等对该响应进行序列化。 /// -/// note | "技术细节" +/// note | 技术细节 你也可以使用 `from starlette.responses import JSONResponse`。  diff --git a/docs/zh/docs/advanced/advanced-dependencies.md b/docs/zh/docs/advanced/advanced-dependencies.md index f3fe1e395d834..8375bd48eabb1 100644 --- a/docs/zh/docs/advanced/advanced-dependencies.md +++ b/docs/zh/docs/advanced/advanced-dependencies.md @@ -18,9 +18,7 @@ Python 可以把类实例变为**可调用项**。 为此,需要声明 `__call__` 方法: -```Python hl_lines="10" -{!../../docs_src/dependencies/tutorial011.py!} -``` +{* ../../docs_src/dependencies/tutorial011.py hl[10] *} 本例中,**FastAPI** 使用 `__call__` 检查附加参数及子依赖项,稍后,还要调用它向*路径操作函数*传递值。 @@ -28,9 +26,7 @@ Python 可以把类实例变为**可调用项**。 接下来,使用 `__init__` 声明用于**参数化**依赖项的实例参数: -```Python hl_lines="7" -{!../../docs_src/dependencies/tutorial011.py!} -``` +{* ../../docs_src/dependencies/tutorial011.py hl[7] *} 本例中,**FastAPI** 不使用 `__init__`,我们要直接在代码中使用。 @@ -38,9 +34,7 @@ Python 可以把类实例变为**可调用项**。 使用以下代码创建类实例: -```Python hl_lines="16" -{!../../docs_src/dependencies/tutorial011.py!} -``` +{* ../../docs_src/dependencies/tutorial011.py hl[16] *} 这样就可以**参数化**依赖项,它包含 `checker.fixed_content` 的属性 - `"bar"`。 @@ -56,11 +50,9 @@ 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/zh/docs/advanced/behind-a-proxy.md b/docs/zh/docs/advanced/behind-a-proxy.md index 8c4b6bb0417dd..f8f61c8a36a51 100644 --- a/docs/zh/docs/advanced/behind-a-proxy.md +++ b/docs/zh/docs/advanced/behind-a-proxy.md @@ -37,7 +37,7 @@ browser --> proxy proxy --> server ``` -/// tip | "提示" +/// tip | 提示 IP `0.0.0.0` 常用于指程序监听本机或服务器上的所有有效 IP。 @@ -78,7 +78,7 @@ $ uvicorn main:app --root-path /api/v1 Hypercorn 也支持 `--root-path `选项。 -/// note | "技术细节" +/// note | 技术细节 ASGI 规范定义的 `root_path` 就是为了这种用例。 @@ -92,9 +92,7 @@ ASGI 规范定义的 `root_path` 就是为了这种用例。 我们在这里的信息里包含 `roo_path` 只是为了演示。 -```Python hl_lines="8" -{!../../docs_src/behind_a_proxy/tutorial001.py!} -``` +{* ../../docs_src/behind_a_proxy/tutorial001.py hl[8] *} 然后,用以下命令启动 Uvicorn: @@ -121,9 +119,7 @@ $ uvicorn main:app --root-path /api/v1 还有一种方案,如果不能提供 `--root-path` 或等效的命令行选项,则在创建 FastAPI 应用时要设置 `root_path` 参数。 -```Python hl_lines="3" -{!../../docs_src/behind_a_proxy/tutorial002.py!} -``` +{* ../../docs_src/behind_a_proxy/tutorial002.py hl[3] *} 传递 `root_path` 给 `FastAPI` 与传递 `--root-path` 命令行选项给 Uvicorn 或 Hypercorn 一样。 @@ -172,7 +168,7 @@ Uvicorn 预期代理在 `http://127.0.0.1:8000/app` 访问 Uvicorn,而在顶 这个文件把 Traefik 监听端口设置为 `9999`,并设置要使用另一个文件 `routes.toml`。 -/// tip | "提示" +/// tip | 提示 使用端口 9999 代替标准的 HTTP 端口 80,这样就不必使用管理员权限运行(`sudo`)。 @@ -242,7 +238,7 @@ $ uvicorn main:app --root-path /api/v1 } ``` -/// tip | "提示" +/// tip | 提示 注意,就算访问 `http://127.0.0.1:8000/app`,也显示从选项 `--root-path` 中提取的 `/api/v1`,这是 `root_path` 的值。 @@ -289,7 +285,7 @@ $ uvicorn main:app --root-path /api/v1 ## 附加的服务器 -/// warning | "警告" +/// warning | 警告 此用例较难,可以跳过。 @@ -303,9 +299,7 @@ $ uvicorn main:app --root-path /api/v1 例如: -```Python hl_lines="4-7" -{!../../docs_src/behind_a_proxy/tutorial003.py!} -``` +{* ../../docs_src/behind_a_proxy/tutorial003.py hl[4:7] *} 这段代码生产如下 OpenAPI 概图: @@ -332,7 +326,7 @@ $ uvicorn main:app --root-path /api/v1 } ``` -/// tip | "提示" +/// tip | 提示 注意,自动生成服务器时,`url` 的值 `/api/v1` 提取自 `roog_path`。 @@ -342,7 +336,7 @@ $ uvicorn main:app --root-path /api/v1 -/// tip | "提示" +/// tip | 提示 API 文档与所选的服务器进行交互。 @@ -352,9 +346,7 @@ API 文档与所选的服务器进行交互。 如果不想让 **FastAPI** 包含使用 `root_path` 的自动服务器,则要使用参数 `root_path_in_servers=False`: -```Python hl_lines="9" -{!../../docs_src/behind_a_proxy/tutorial004.py!} -``` +{* ../../docs_src/behind_a_proxy/tutorial004.py hl[9] *} 这样,就不会在 OpenAPI 概图中包含服务器了。 diff --git a/docs/zh/docs/advanced/custom-response.md b/docs/zh/docs/advanced/custom-response.md index 27c026904da73..22a9b4b5100f0 100644 --- a/docs/zh/docs/advanced/custom-response.md +++ b/docs/zh/docs/advanced/custom-response.md @@ -12,7 +12,7 @@ 并且如果该 `Response` 有一个 JSON 媒体类型(`application/json`),比如使用 `JSONResponse` 或者 `UJSONResponse` 的时候,返回的数据将使用你在路径操作装饰器中声明的任何 Pydantic 的 `response_model` 自动转换(和过滤)。 -/// note | "说明" +/// note | 说明 如果你使用不带有任何媒体类型的响应类,FastAPI 认为你的响应没有任何内容,所以不会在生成的OpenAPI文档中记录响应格式。 @@ -24,11 +24,9 @@ 导入你想要使用的 `Response` 类(子类)然后在 *路径操作装饰器* 中声明它。 -```Python hl_lines="2 7" -{!../../docs_src/custom_response/tutorial001b.py!} -``` +{* ../../docs_src/custom_response/tutorial001b.py hl[2,7] *} -/// info | "提示" +/// info | 提示 参数 `response_class` 也会用来定义响应的「媒体类型」。 @@ -38,7 +36,7 @@ /// -/// tip | "小贴士" +/// tip | 小贴士 `ORJSONResponse` 目前只在 FastAPI 中可用,而在 Starlette 中不可用。 @@ -51,11 +49,9 @@ * 导入 `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 | "提示" +/// info | 提示 参数 `response_class` 也会用来定义响应的「媒体类型」。 @@ -71,17 +67,15 @@ 和上面一样的例子,返回一个 `HTMLResponse` 看起来可能是这样: -```Python hl_lines="2 7 19" -{!../../docs_src/custom_response/tutorial003.py!} -``` +{* ../../docs_src/custom_response/tutorial003.py hl[2,7,19] *} -/// warning | "警告" +/// warning | 警告 *路径操作函数* 直接返回的 `Response` 不会被 OpenAPI 的文档记录(比如,`Content-Type` 不会被文档记录),并且在自动化交互文档中也是不可见的。 /// -/// info | "提示" +/// info | 提示 当然,实际的 `Content-Type` 头,状态码等等,将来自于你返回的 `Response` 对象。 @@ -97,9 +91,7 @@ 比如像这样: -```Python hl_lines="7 23 21" -{!../../docs_src/custom_response/tutorial004.py!} -``` +{* ../../docs_src/custom_response/tutorial004.py hl[7,23,21] *} 在这个例子中,函数 `generate_html_response()` 已经生成并返回 `Response` 对象而不是在 `str` 中返回 HTML。 @@ -115,7 +107,7 @@ 要记得你可以使用 `Response` 来返回任何其他东西,甚至创建一个自定义的子类。 -/// note | "技术细节" +/// note | 技术细节 你也可以使用 `from starlette.responses import HTMLResponse`。 @@ -139,9 +131,7 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它还将包含一个基于 media_type 的 Content-Type 头,并为文本类型附加一个字符集。 -```Python hl_lines="1 18" -{!../../docs_src/response_directly/tutorial002.py!} -``` +{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *} ### `HTMLResponse` @@ -151,9 +141,7 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它 接受文本或字节并返回纯文本响应。 -```Python hl_lines="2 7 9" -{!../../docs_src/custom_response/tutorial005.py!} -``` +{* ../../docs_src/custom_response/tutorial005.py hl[2,7,9] *} ### `JSONResponse` @@ -170,17 +158,15 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它 `UJSONResponse` 是一个使用 `ujson` 的可选 JSON 响应。 -/// warning | "警告" +/// warning | 警告 在处理某些边缘情况时,`ujson` 不如 Python 的内置实现那么谨慎。 /// -```Python hl_lines="2 7" -{!../../docs_src/custom_response/tutorial001.py!} -``` +{* ../../docs_src/custom_response/tutorial001.py hl[2,7] *} -/// tip | "小贴士" +/// tip | 小贴士 `ORJSONResponse` 可能是一个更快的选择。 @@ -190,17 +176,13 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它 返回 HTTP 重定向。默认情况下使用 307 状态代码(临时重定向)。 -```Python hl_lines="2 9" -{!../../docs_src/custom_response/tutorial006.py!} -``` +{* ../../docs_src/custom_response/tutorial006.py hl[2,9] *} ### `StreamingResponse` 采用异步生成器或普通生成器/迭代器,然后流式传输响应主体。 -```Python hl_lines="2 14" -{!../../docs_src/custom_response/tutorial007.py!} -``` +{* ../../docs_src/custom_response/tutorial007.py hl[2,14] *} #### 对类似文件的对象使用 `StreamingResponse` @@ -208,11 +190,9 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它 包括许多与云存储,视频处理等交互的库。 -```Python hl_lines="2 10-12 14" -{!../../docs_src/custom_response/tutorial008.py!} -``` +{* ../../docs_src/custom_response/tutorial008.py hl[2,10:12,14] *} -/// tip | "小贴士" +/// tip | 小贴士 注意在这里,因为我们使用的是不支持 `async` 和 `await` 的标准 `open()`,我们使用普通的 `def` 声明了路径操作。 @@ -231,9 +211,7 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它 文件响应将包含适当的 `Content-Length`,`Last-Modified` 和 `ETag` 的响应头。 -```Python hl_lines="2 10" -{!../../docs_src/custom_response/tutorial009.py!} -``` +{* ../../docs_src/custom_response/tutorial009.py hl[2,10] *} ## 额外文档 diff --git a/docs/zh/docs/advanced/dataclasses.md b/docs/zh/docs/advanced/dataclasses.md index f33c05ff47f53..c74ce65c3ee53 100644 --- a/docs/zh/docs/advanced/dataclasses.md +++ b/docs/zh/docs/advanced/dataclasses.md @@ -4,9 +4,7 @@ FastAPI 基于 **Pydantic** 构建,前文已经介绍过如何使用 Pydantic 但 FastAPI 还可以使用数据类(`dataclasses`): -```Python hl_lines="1 7-12 19-20" -{!../../docs_src/dataclasses/tutorial001.py!} -``` +{* ../../docs_src/dataclasses/tutorial001.py hl[1,7:12,19:20] *} 这还是借助于 **Pydantic** 及其内置的 `dataclasses`。 @@ -20,7 +18,7 @@ FastAPI 基于 **Pydantic** 构建,前文已经介绍过如何使用 Pydantic 数据类的和运作方式与 Pydantic 模型相同。实际上,它的底层使用的也是 Pydantic。 -/// info | "说明" +/// info | 说明 注意,数据类不支持 Pydantic 模型的所有功能。 @@ -34,9 +32,7 @@ FastAPI 基于 **Pydantic** 构建,前文已经介绍过如何使用 Pydantic 在 `response_model` 参数中使用 `dataclasses`: -```Python hl_lines="1 7-13 19" -{!../../docs_src/dataclasses/tutorial002.py!} -``` +{* ../../docs_src/dataclasses/tutorial002.py hl[1,7:13,19] *} 本例把数据类自动转换为 Pydantic 数据类。 diff --git a/docs/zh/docs/advanced/events.md b/docs/zh/docs/advanced/events.md index e5b44f32175b0..66f5af2e3402a 100644 --- a/docs/zh/docs/advanced/events.md +++ b/docs/zh/docs/advanced/events.md @@ -4,7 +4,7 @@ 事件函数既可以声明为异步函数(`async def`),也可以声明为普通函数(`def`)。 -/// warning | "警告" +/// warning | 警告 **FastAPI** 只执行主应用中的事件处理器,不执行[子应用 - 挂载](sub-applications.md){.internal-link target=_blank}中的事件处理器。 @@ -14,9 +14,7 @@ 使用 `startup` 事件声明 `app` 启动前运行的函数: -```Python hl_lines="8" -{!../../docs_src/events/tutorial001.py!} -``` +{* ../../docs_src/events/tutorial001.py hl[8] *} 本例中,`startup` 事件处理器函数为项目数据库(只是**字典**)提供了一些初始值。 @@ -28,19 +26,17 @@ 使用 `shutdown` 事件声明 `app` 关闭时运行的函数: -```Python hl_lines="6" -{!../../docs_src/events/tutorial002.py!} -``` +{* ../../docs_src/events/tutorial002.py hl[6] *} 此处,`shutdown` 事件处理器函数在 `log.txt` 中写入一行文本 `Application shutdown`。 -/// info | "说明" +/// info | 说明 `open()` 函数中,`mode="a"` 指的是**追加**。因此这行文本会添加在文件已有内容之后,不会覆盖之前的内容。 /// -/// tip | "提示" +/// tip | 提示 注意,本例使用 Python `open()` 标准函数与文件交互。 @@ -52,7 +48,7 @@ /// -/// info | "说明" +/// info | 说明 有关事件处理器的详情,请参阅 Starlette 官档 - 事件。 diff --git a/docs/zh/docs/advanced/generate-clients.md b/docs/zh/docs/advanced/generate-clients.md index baf13136137cc..bcb9ba2bf7e65 100644 --- a/docs/zh/docs/advanced/generate-clients.md +++ b/docs/zh/docs/advanced/generate-clients.md @@ -16,21 +16,7 @@ 让我们从一个简单的 FastAPI 应用开始: -//// tab | Python 3.9+ - -```Python hl_lines="7-9 12-13 16-17 21" -{!> ../../docs_src/generate_clients/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9-11 14-15 18 19 23" -{!> ../../docs_src/generate_clients/tutorial001.py!} -``` - -//// +{* ../../docs_src/generate_clients/tutorial001_py39.py hl[7:9,12:13,16:17,21] *} 请注意,*路径操作* 定义了他们所用于请求数据和回应数据的模型,所使用的模型是`Item` 和 `ResponseMessage`。 @@ -135,21 +121,7 @@ frontend-app@1.0.0 generate-client /home/user/code/frontend-app 例如,您可以有一个用 `items` 的部分和另一个用于 `users` 的部分,它们可以用标签来分隔: -//// tab | Python 3.9+ - -```Python hl_lines="21 26 34" -{!> ../../docs_src/generate_clients/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="23 28 36" -{!> ../../docs_src/generate_clients/tutorial002.py!} -``` - -//// +{* ../../docs_src/generate_clients/tutorial002_py39.py hl[21,26,34] *} ### 生成带有标签的 TypeScript 客户端 @@ -196,21 +168,7 @@ FastAPI为每个*路径操作*使用一个**唯一ID**,它用于**操作ID** 然后,你可以将这个自定义函数作为 `generate_unique_id_function` 参数传递给 **FastAPI**: -//// tab | Python 3.9+ - -```Python hl_lines="6-7 10" -{!> ../../docs_src/generate_clients/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8-9 12" -{!> ../../docs_src/generate_clients/tutorial003.py!} -``` - -//// +{* ../../docs_src/generate_clients/tutorial003_py39.py hl[6:7,10] *} ### 使用自定义操作ID生成TypeScript客户端 @@ -232,9 +190,7 @@ FastAPI为每个*路径操作*使用一个**唯一ID**,它用于**操作ID** 我们可以将 OpenAPI JSON 下载到一个名为`openapi.json`的文件中,然后使用以下脚本**删除此前缀的标签**: -```Python -{!../../docs_src/generate_clients/tutorial004.py!} -``` +{* ../../docs_src/generate_clients/tutorial004.py *} 通过这样做,操作ID将从类似于 `items-get_items` 的名称重命名为 `get_items` ,这样客户端生成器就可以生成更简洁的方法名称。 diff --git a/docs/zh/docs/advanced/middleware.md b/docs/zh/docs/advanced/middleware.md index 525dc89ac5f20..c7b15b929ba2e 100644 --- a/docs/zh/docs/advanced/middleware.md +++ b/docs/zh/docs/advanced/middleware.md @@ -43,7 +43,7 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") **FastAPI** 为常见用例提供了一些中间件,下面介绍怎么使用这些中间件。 -/// note | "技术细节" +/// note | 技术细节 以下几个示例中也可以使用 `from starlette.middleware.something import SomethingMiddleware`。 @@ -57,17 +57,13 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") 任何传向 `http` 或 `ws` 的请求都会被重定向至安全方案。 -```Python hl_lines="2 6" -{!../../docs_src/advanced_middleware/tutorial001.py!} -``` +{* ../../docs_src/advanced_middleware/tutorial001.py hl[2,6] *} ## `TrustedHostMiddleware` 强制所有传入请求都必须正确设置 `Host` 请求头,以防 HTTP 主机头攻击。 -```Python hl_lines="2 6-8" -{!../../docs_src/advanced_middleware/tutorial002.py!} -``` +{* ../../docs_src/advanced_middleware/tutorial002.py hl[2,6:8] *} 支持以下参数: @@ -81,9 +77,7 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") 中间件会处理标准响应与流响应。 -```Python hl_lines="2 6" -{!../../docs_src/advanced_middleware/tutorial003.py!} -``` +{* ../../docs_src/advanced_middleware/tutorial003.py hl[2,6] *} 支持以下参数: diff --git a/docs/zh/docs/advanced/openapi-callbacks.md b/docs/zh/docs/advanced/openapi-callbacks.md index dc1c2539ba45f..f021eb10aeabc 100644 --- a/docs/zh/docs/advanced/openapi-callbacks.md +++ b/docs/zh/docs/advanced/openapi-callbacks.md @@ -31,11 +31,9 @@ API 的用户 (外部开发者)要在您的 API 内使用 POST 请求创建 这部分代码很常规,您对绝大多数代码应该都比较熟悉了: -```Python hl_lines="10-14 37-54" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[10:14,37:54] *} -/// tip | "提示" +/// tip | 提示 `callback_url` 查询参数使用 Pydantic 的 URL 类型。 @@ -64,7 +62,7 @@ requests.post(callback_url, json={"description": "Invoice paid", "paid": True}) 本例没有实现回调本身(只是一行代码),只有文档部分。 -/// tip | "提示" +/// tip | 提示 实际的回调只是 HTTP 请求。 @@ -80,7 +78,7 @@ requests.post(callback_url, json={"description": "Invoice paid", "paid": True}) 我们要使用与存档*外部 API* 相同的知识……通过创建外部 API 要实现的*路径操作*(您的 API 要调用的)。 -/// tip | "提示" +/// tip | 提示 编写存档回调的代码时,假设您是*外部开发者*可能会用的上。并且您当前正在实现的是*外部 API*,不是*您自己的 API*。 @@ -92,9 +90,7 @@ requests.post(callback_url, json={"description": "Invoice paid", "paid": True}) 首先,新建包含一些用于回调的 `APIRouter`。 -```Python hl_lines="5 26" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[5,26] *} ### 创建回调*路径操作* @@ -105,9 +101,7 @@ requests.post(callback_url, json={"description": "Invoice paid", "paid": True}) * 声明要接收的请求体,例如,`body: InvoiceEvent` * 还要声明要返回的响应,例如,`response_model=InvoiceEventReceived` -```Python hl_lines="17-19 22-23 29-33" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[17:19,22:23,29:33] *} 回调*路径操作*与常规*路径操作*有两点主要区别: @@ -163,7 +157,7 @@ JSON 请求体包含如下内容: } ``` -/// tip | "提示" +/// tip | 提示 注意,回调 URL包含 `callback_url` (`https://www.external.org/events`)中的查询参数,还有 JSON 请求体内部的发票 ID(`2expen51ve`)。 @@ -175,11 +169,9 @@ JSON 请求体包含如下内容: 现在使用 API *路径操作装饰器*的参数 `callbacks`,从回调路由传递属性 `.routes`(实际上只是路由/路径操作的**列表**): -```Python hl_lines="36" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[36] *} -/// tip | "提示" +/// tip | 提示 注意,不能把路由本身(`invoices_callback_router`)传递给 `callback=`,要传递 `invoices_callback_router.routes` 中的 `.routes` 属性。 diff --git a/docs/zh/docs/advanced/path-operation-advanced-configuration.md b/docs/zh/docs/advanced/path-operation-advanced-configuration.md index 0d77dd69e80aa..12600eddb11d1 100644 --- a/docs/zh/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/zh/docs/advanced/path-operation-advanced-configuration.md @@ -12,9 +12,7 @@ 务必确保每个操作路径的 `operation_id` 都是唯一的。 -```Python hl_lines="6" -{!../../docs_src/path_operation_advanced_configuration/tutorial001.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial001.py hl[6] *} ### 使用 *路径操作函数* 的函数名作为 operationId @@ -22,9 +20,7 @@ 你应该在添加了所有 *路径操作* 之后执行此操作。 -```Python hl_lines="2 12 13 14 15 16 17 18 19 20 21 24" -{!../../docs_src/path_operation_advanced_configuration/tutorial002.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial002.py hl[2,12,13,14,15,16,17,18,19,20,21,24] *} /// tip @@ -44,9 +40,7 @@ 使用参数 `include_in_schema` 并将其设置为 `False` ,来从生成的 OpenAPI 方案中排除一个 *路径操作*(这样一来,就从自动化文档系统中排除掉了)。 -```Python hl_lines="6" -{!../../docs_src/path_operation_advanced_configuration/tutorial003.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial003.py hl[6] *} ## docstring 的高级描述 @@ -57,6 +51,4 @@ 剩余部分不会出现在文档中,但是其他工具(比如 Sphinx)可以使用剩余部分。 -```Python hl_lines="19 20 21 22 23 24 25 26 27 28 29" -{!../../docs_src/path_operation_advanced_configuration/tutorial004.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial004.py hl[19,20,21,22,23,24,25,26,27,28,29] *} diff --git a/docs/zh/docs/advanced/response-change-status-code.md b/docs/zh/docs/advanced/response-change-status-code.md index c38f80f1f1f2c..cc1f2a73ebc1f 100644 --- a/docs/zh/docs/advanced/response-change-status-code.md +++ b/docs/zh/docs/advanced/response-change-status-code.md @@ -20,9 +20,7 @@ 然后你可以在这个*临时*响应对象中设置`status_code`。 -```Python hl_lines="1 9 12" -{!../../docs_src/response_change_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_change_status_code/tutorial001.py hl[1,9,12] *} 然后你可以像平常一样返回任何你需要的对象(例如一个`dict`或者一个数据库模型)。如果你声明了一个`response_model`,它仍然会被用来过滤和转换你返回的对象。 diff --git a/docs/zh/docs/advanced/response-cookies.md b/docs/zh/docs/advanced/response-cookies.md index 5772664b0302e..d4b93d003fed9 100644 --- a/docs/zh/docs/advanced/response-cookies.md +++ b/docs/zh/docs/advanced/response-cookies.md @@ -4,9 +4,7 @@ 你可以在 *路径函数* 中定义一个类型为 `Response`的参数,这样你就可以在这个临时响应对象中设置cookie了。 -```Python hl_lines="1 8-9" -{!../../docs_src/response_cookies/tutorial002.py!} -``` +{* ../../docs_src/response_cookies/tutorial002.py hl[1,8:9] *} 而且你还可以根据你的需要响应不同的对象,比如常用的 `dict`,数据库model等。 @@ -24,9 +22,7 @@ 然后设置Cookies,并返回: -```Python hl_lines="10-12" -{!../../docs_src/response_cookies/tutorial001.py!} -``` +{* ../../docs_src/response_cookies/tutorial001.py hl[10:12] *} /// tip @@ -40,7 +36,7 @@ ### 更多信息 -/// note | "技术细节" +/// note | 技术细节 你也可以使用`from starlette.responses import Response` 或者 `from starlette.responses import JSONResponse`。 diff --git a/docs/zh/docs/advanced/response-directly.md b/docs/zh/docs/advanced/response-directly.md index 9d191c62239b0..4d9cd53f2f915 100644 --- a/docs/zh/docs/advanced/response-directly.md +++ b/docs/zh/docs/advanced/response-directly.md @@ -14,7 +14,7 @@ 事实上,你可以返回任意 `Response` 或者任意 `Response` 的子类。 -/// tip | "小贴士" +/// tip | 小贴士 `JSONResponse` 本身是一个 `Response` 的子类。 @@ -35,11 +35,9 @@ 对于这些情况,在将数据传递给响应之前,你可以使用 `jsonable_encoder` 来转换你的数据。 -```Python hl_lines="4 6 20 21" -{!../../docs_src/response_directly/tutorial001.py!} -``` +{* ../../docs_src/response_directly/tutorial001.py hl[4,6,20,21] *} -/// note | "技术细节" +/// note | 技术细节 你也可以使用 `from starlette.responses import JSONResponse`。 @@ -57,9 +55,7 @@ 你可以把你的 XML 内容放到一个字符串中,放到一个 `Response` 中,然后返回。 -```Python hl_lines="1 18" -{!../../docs_src/response_directly/tutorial002.py!} -``` +{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *} ## 说明 diff --git a/docs/zh/docs/advanced/response-headers.md b/docs/zh/docs/advanced/response-headers.md index d593fdccc0dc3..fe2cb0da89042 100644 --- a/docs/zh/docs/advanced/response-headers.md +++ b/docs/zh/docs/advanced/response-headers.md @@ -5,9 +5,7 @@ 你可以在你的*路径操作函数*中声明一个`Response`类型的参数(就像你可以为cookies做的那样)。 然后你可以在这个*临时*响应对象中设置头部。 -```Python hl_lines="1 7-8" -{!../../docs_src/response_headers/tutorial002.py!} -``` +{* ../../docs_src/response_headers/tutorial002.py hl[1,7:8] *} 然后你可以像平常一样返回任何你需要的对象(例如一个`dict`或者一个数据库模型)。如果你声明了一个`response_model`,它仍然会被用来过滤和转换你返回的对象。 @@ -20,12 +18,11 @@ 你也可以在直接返回`Response`时添加头部。 按照[直接返回响应](response-directly.md){.internal-link target=_blank}中所述创建响应,并将头部作为附加参数传递: -```Python hl_lines="10-12" -{!../../docs_src/response_headers/tutorial001.py!} -``` +{* ../../docs_src/response_headers/tutorial001.py hl[10:12] *} -/// note | "技术细节" + +/// note | 技术细节 你也可以使用`from starlette.responses import Response`或`from starlette.responses import JSONResponse`。 diff --git a/docs/zh/docs/advanced/security/http-basic-auth.md b/docs/zh/docs/advanced/security/http-basic-auth.md index 06c6dbbab5b64..599429f9d2797 100644 --- a/docs/zh/docs/advanced/security/http-basic-auth.md +++ b/docs/zh/docs/advanced/security/http-basic-auth.md @@ -20,35 +20,7 @@ HTTP 基础授权让浏览器显示内置的用户名与密码提示。 * 返回类型为 `HTTPBasicCredentials` 的对象: * 包含发送的 `username` 与 `password` -//// tab | Python 3.9+ - -```Python hl_lines="4 8 12" -{!> ../../docs_src/security/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="2 7 11" -{!> ../../docs_src/security/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -尽可能选择使用 `Annotated` 的版本。 - -/// - -```Python hl_lines="2 6 10" -{!> ../../docs_src/security/tutorial006.py!} -``` - -//// +{* ../../docs_src/security/tutorial006_an_py39.py hl[4,8,12] *} 第一次打开 URL(或在 API 文档中点击 **Execute** 按钮)时,浏览器要求输入用户名与密码: @@ -68,35 +40,7 @@ HTTP 基础授权让浏览器显示内置的用户名与密码提示。 然后我们可以使用 `secrets.compare_digest()` 来确保 `credentials.username` 是 `"stanleyjobson"`,且 `credentials.password` 是`"swordfish"`。 -//// tab | Python 3.9+ - -```Python hl_lines="1 12-24" -{!> ../../docs_src/security/tutorial007_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 12-24" -{!> ../../docs_src/security/tutorial007_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -尽可能选择使用 `Annotated` 的版本。 - -/// - -```Python hl_lines="1 11-21" -{!> ../../docs_src/security/tutorial007.py!} -``` - -//// +{* ../../docs_src/security/tutorial007_an_py39.py hl[1,12:24] *} 这类似于: @@ -160,32 +104,4 @@ if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish": 检测到凭证不正确后,返回 `HTTPException` 及状态码 401(与无凭证时返回的内容一样),并添加请求头 `WWW-Authenticate`,让浏览器再次显示登录提示: -//// tab | Python 3.9+ - -```Python hl_lines="26-30" -{!> ../../docs_src/security/tutorial007_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="26-30" -{!> ../../docs_src/security/tutorial007_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -尽可能选择使用 `Annotated` 的版本。 - -/// - -```Python hl_lines="23-27" -{!> ../../docs_src/security/tutorial007.py!} -``` - -//// +{* ../../docs_src/security/tutorial007_an_py39.py hl[26:30] *} diff --git a/docs/zh/docs/advanced/security/index.md b/docs/zh/docs/advanced/security/index.md index 836086ae273bf..267e7ced7078c 100644 --- a/docs/zh/docs/advanced/security/index.md +++ b/docs/zh/docs/advanced/security/index.md @@ -4,7 +4,7 @@ 除 [教程 - 用户指南: 安全性](../../tutorial/security/index.md){.internal-link target=_blank} 中涵盖的功能之外,还有一些额外的功能来处理安全性. -/// tip | "小贴士" +/// tip | 小贴士 接下来的章节 **并不一定是 "高级的"**. diff --git a/docs/zh/docs/advanced/security/oauth2-scopes.md b/docs/zh/docs/advanced/security/oauth2-scopes.md index d6354230e797f..c3f593684deb6 100644 --- a/docs/zh/docs/advanced/security/oauth2-scopes.md +++ b/docs/zh/docs/advanced/security/oauth2-scopes.md @@ -10,7 +10,7 @@ OAuth2 也是脸书、谷歌、GitHub、微软、推特等第三方身份验证 本章介绍如何在 **FastAPI** 应用中使用 OAuth2 作用域管理验证与授权。 -/// warning | "警告" +/// warning | 警告 本章内容较难,刚接触 FastAPI 的新手可以跳过。 @@ -46,7 +46,7 @@ OpenAPI 中(例如 API 文档)可以定义**安全方案**。 * 脸书和 Instagram 使用 `instagram_basic` * 谷歌使用 `https://www.googleapis.com/auth/drive` -/// info | "说明" +/// info | 说明 OAuth2 中,**作用域**只是声明特定权限的字符串。 @@ -62,9 +62,7 @@ OAuth2 中,**作用域**只是声明特定权限的字符串。 首先,快速浏览一下以下代码与**用户指南**中 [OAuth2 实现密码哈希与 Bearer JWT 令牌验证](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank}一章中代码的区别。以下代码使用 OAuth2 作用域: -```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 153" -{!../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[2,4,8,12,46,64,105,107:115,121:124,128:134,139,153] *} 下面,我们逐步说明修改的代码内容。 @@ -74,9 +72,7 @@ OAuth2 中,**作用域**只是声明特定权限的字符串。 `scopes` 参数接收**字典**,键是作用域、值是作用域的描述: -```Python hl_lines="62-65" -{!../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[62:65] *} 因为声明了作用域,所以登录或授权时会在 API 文档中显示。 @@ -94,7 +90,7 @@ OAuth2 中,**作用域**只是声明特定权限的字符串。 这样,返回的 JWT 令牌中就包含了作用域。 -/// danger | "危险" +/// danger | 危险 为了简明起见,本例把接收的作用域直接添加到了令牌里。 @@ -102,9 +98,7 @@ OAuth2 中,**作用域**只是声明特定权限的字符串。 /// -```Python hl_lines="153" -{!../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[153] *} ## 在*路径操作*与依赖项中声明作用域 @@ -122,7 +116,7 @@ OAuth2 中,**作用域**只是声明特定权限的字符串。 本例要求使用作用域 `me`(还可以使用更多作用域)。 -/// note | "笔记" +/// note | 笔记 不必在不同位置添加不同的作用域。 @@ -130,11 +124,9 @@ OAuth2 中,**作用域**只是声明特定权限的字符串。 /// -```Python hl_lines="4 139 166" -{!../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[4,139,166] *} -/// info | "技术细节" +/// info | 技术细节 `Security` 实际上是 `Depends` 的子类,而且只比 `Depends` 多一个参数。 @@ -158,9 +150,7 @@ OAuth2 中,**作用域**只是声明特定权限的字符串。 `SecuriScopes` 类与 `Request` 类似(`Request` 用于直接提取请求对象)。 -```Python hl_lines="8 105" -{!../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[8,105] *} ## 使用 `scopes` @@ -174,9 +164,7 @@ OAuth2 中,**作用域**只是声明特定权限的字符串。 该异常包含了作用域所需的(如有),以空格分割的字符串(使用 `scope_str`)。该字符串要放到包含作用域的 `WWW-Authenticate` 请求头中(这也是规范的要求)。 -```Python hl_lines="105 107-115" -{!../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[105,107:115] *} ## 校验 `username` 与数据形状 @@ -192,9 +180,7 @@ OAuth2 中,**作用域**只是声明特定权限的字符串。 还可以使用用户名验证用户,如果没有用户,也会触发之前创建的异常。 -```Python hl_lines="46 116-127" -{!../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[46,116:127] *} ## 校验 `scopes` @@ -202,9 +188,7 @@ OAuth2 中,**作用域**只是声明特定权限的字符串。 为此,要使用包含所有作用域**字符串列表**的 `security_scopes.scopes`, 。 -```Python hl_lines="128-134" -{!../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[128:134] *} ## 依赖项树与作用域 @@ -231,7 +215,7 @@ OAuth2 中,**作用域**只是声明特定权限的字符串。 * `security_scopes.scopes` 包含*路径操作* `read_users_me` 的 `["me"]`,因为它在依赖项里被声明 * `security_scopes.scopes` 包含用于*路径操作* `read_system_status` 的 `[]`(空列表),并且它的依赖项 `get_current_user` 也没有声明任何 `scope` -/// tip | "提示" +/// tip | 提示 此处重要且**神奇**的事情是,`get_current_user` 检查每个*路径操作*时可以使用不同的 `scopes` 列表。 @@ -275,7 +259,7 @@ OAuth2 中,**作用域**只是声明特定权限的字符串。 最安全的是代码流,但实现起来更复杂,而且需要更多步骤。因为它更复杂,很多第三方身份验证应用最终建议使用隐式流。 -/// note | "笔记" +/// note | 笔记 每个身份验证应用都会采用不同方式会命名流,以便融合入自己的品牌。 diff --git a/docs/zh/docs/advanced/settings.md b/docs/zh/docs/advanced/settings.md index 4d35731cb23e1..e33da136fa1ab 100644 --- a/docs/zh/docs/advanced/settings.md +++ b/docs/zh/docs/advanced/settings.md @@ -150,9 +150,7 @@ Hello World from Python 您可以使用与 Pydantic 模型相同的验证功能和工具,比如不同的数据类型和使用 `Field()` 进行附加验证。 -```Python hl_lines="2 5-8 11" -{!../../docs_src/settings/tutorial001.py!} -``` +{* ../../docs_src/settings/tutorial001.py hl[2,5:8,11] *} /// tip @@ -168,9 +166,7 @@ Hello World from Python 然后,您可以在应用程序中使用新的 `settings` 对象: -```Python hl_lines="18-20" -{!../../docs_src/settings/tutorial001.py!} -``` +{* ../../docs_src/settings/tutorial001.py hl[18:20] *} ### 运行服务器 @@ -204,15 +200,11 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app 例如,您可以创建一个名为 `config.py` 的文件,其中包含以下内容: -```Python -{!../../docs_src/settings/app01/config.py!} -``` +{* ../../docs_src/settings/app01/config.py *} 然后在一个名为 `main.py` 的文件中使用它: -```Python hl_lines="3 11-13" -{!../../docs_src/settings/app01/main.py!} -``` +{* ../../docs_src/settings/app01/main.py hl[3,11:13] *} /// tip @@ -230,9 +222,7 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app 根据前面的示例,您的 `config.py` 文件可能如下所示: -```Python hl_lines="10" -{!../../docs_src/settings/app02/config.py!} -``` +{* ../../docs_src/settings/app02/config.py hl[10] *} 请注意,现在我们不创建默认实例 `settings = Settings()`。 @@ -240,35 +230,7 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app 现在我们创建一个依赖项,返回一个新的 `config.Settings()`。 -//// tab | Python 3.9+ - -```Python hl_lines="6 12-13" -{!> ../../docs_src/settings/app02_an_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="6 12-13" -{!> ../../docs_src/settings/app02_an/main.py!} -``` - -//// - -//// tab | Python 3.8+ 非注解版本 - -/// tip - -如果可能,请尽量使用 `Annotated` 版本。 - -/// - -```Python hl_lines="5 11-12" -{!> ../../docs_src/settings/app02/main.py!} -``` - -//// +{* ../../docs_src/settings/app02_an_py39/main.py hl[6,12:13] *} /// tip @@ -280,43 +242,13 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app 然后,我们可以将其作为依赖项从“路径操作函数”中引入,并在需要时使用它。 -//// tab | Python 3.9+ - -```Python hl_lines="17 19-21" -{!> ../../docs_src/settings/app02_an_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17 19-21" -{!> ../../docs_src/settings/app02_an/main.py!} -``` - -//// - -//// tab | Python 3.8+ 非注解版本 - -/// tip - -如果可能,请尽量使用 `Annotated` 版本。 - -/// - -```Python hl_lines="16 18-20" -{!> ../../docs_src/settings/app02/main.py!} -``` - -//// +{* ../../docs_src/settings/app02_an_py39/main.py hl[17,19:21] *} ### 设置和测试 然后,在测试期间,通过创建 `get_settings` 的依赖项覆盖,很容易提供一个不同的设置对象: -```Python hl_lines="9-10 13 21" -{!../../docs_src/settings/app02/test_main.py!} -``` +{* ../../docs_src/settings/app02/test_main.py hl[9:10,13,21] *} 在依赖项覆盖中,我们在创建新的 `Settings` 对象时为 `admin_email` 设置了一个新值,然后返回该新对象。 @@ -357,9 +289,7 @@ APP_NAME="ChimichangApp" 然后,您可以使用以下方式更新您的 `config.py`: -```Python hl_lines="9-10" -{!../../docs_src/settings/app03/config.py!} -``` +{* ../../docs_src/settings/app03/config.py hl[9:10] *} 在这里,我们在 Pydantic 的 `Settings` 类中创建了一个名为 `Config` 的类,并将 `env_file` 设置为我们想要使用的 dotenv 文件的文件名。 @@ -392,35 +322,7 @@ def get_settings(): 但是,由于我们在顶部使用了 `@lru_cache` 装饰器,因此只有在第一次调用它时,才会创建 `Settings` 对象一次。 ✔️ -//// tab | Python 3.9+ - -```Python hl_lines="1 11" -{!> ../../docs_src/settings/app03_an_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 11" -{!> ../../docs_src/settings/app03_an/main.py!} -``` - -//// - -//// tab | Python 3.8+ 非注解版本 - -/// tip - -如果可能,请尽量使用 `Annotated` 版本。 - -/// - -```Python hl_lines="1 10" -{!> ../../docs_src/settings/app03/main.py!} -``` - -//// +{* ../../docs_src/settings/app03_an_py39/main.py hl[1,11] *} 然后,在下一次请求的依赖项中对 `get_settings()` 进行任何后续调用时,它不会执行 `get_settings()` 的内部代码并创建新的 `Settings` 对象,而是返回在第一次调用时返回的相同对象,一次又一次。 diff --git a/docs/zh/docs/advanced/sub-applications.md b/docs/zh/docs/advanced/sub-applications.md index f93ab1d242741..c42be2849aeb4 100644 --- a/docs/zh/docs/advanced/sub-applications.md +++ b/docs/zh/docs/advanced/sub-applications.md @@ -10,9 +10,7 @@ 首先,创建主(顶层)**FastAPI** 应用及其*路径操作*: -```Python hl_lines="3 6-8" -{!../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[3,6:8] *} ### 子应用 @@ -20,9 +18,7 @@ 子应用只是另一个标准 FastAPI 应用,但这个应用是被**挂载**的应用: -```Python hl_lines="11 14-16" -{!../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[11,14:16] *} ### 挂载子应用 @@ -30,9 +26,7 @@ 本例的子应用挂载在 `/subapi` 路径下: -```Python hl_lines="11 19" -{!../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[11,19] *} ### 查看文档 diff --git a/docs/zh/docs/advanced/templates.md b/docs/zh/docs/advanced/templates.md index 1159302a93ccd..8b7019ede50df 100644 --- a/docs/zh/docs/advanced/templates.md +++ b/docs/zh/docs/advanced/templates.md @@ -27,24 +27,22 @@ $ pip install jinja2 * 在返回模板的*路径操作*中声明 `Request` 参数 * 使用 `templates` 渲染并返回 `TemplateResponse`, 传递模板的名称、request对象以及一个包含多个键值对(用于Jinja2模板)的"context"字典, -```Python hl_lines="4 11 15-16" -{!../../docs_src/templates/tutorial001.py!} -``` +{* ../../docs_src/templates/tutorial001.py hl[4,11,15:16] *} -/// note | "笔记" +/// note | 笔记 在FastAPI 0.108.0,Starlette 0.29.0之前,`name`是第一个参数。 并且,在此之前,`request`对象是作为context的一部分以键值对的形式传递的。 /// -/// tip | "提示" +/// tip | 提示 通过声明 `response_class=HTMLResponse`,API 文档就能识别响应的对象是 HTML。 /// -/// note | "技术细节" +/// note | 技术细节 您还可以使用 `from starlette.templating import Jinja2Templates`。 diff --git a/docs/zh/docs/advanced/testing-dependencies.md b/docs/zh/docs/advanced/testing-dependencies.md index c3d912e2f68a1..620539fd1e3ef 100644 --- a/docs/zh/docs/advanced/testing-dependencies.md +++ b/docs/zh/docs/advanced/testing-dependencies.md @@ -28,11 +28,9 @@ 这样一来,**FastAPI** 就会调用覆盖依赖项,不再调用原依赖项。 -```Python hl_lines="26-27 30" -{!../../docs_src/dependency_testing/tutorial001.py!} -``` +{* ../../docs_src/dependency_testing/tutorial001.py hl[26:27,30] *} -/// tip | "提示" +/// tip | 提示 **FastAPI** 应用中的任何位置都可以实现覆盖依赖项。 @@ -48,7 +46,7 @@ FastAPI 可以覆盖这些位置的依赖项。 app.dependency_overrides = {} ``` -/// tip | "提示" +/// tip | 提示 如果只在某些测试时覆盖依赖项,您可以在测试开始时(在测试函数内)设置覆盖依赖项,并在结束时(在测试函数结尾)重置覆盖依赖项。 diff --git a/docs/zh/docs/advanced/testing-events.md b/docs/zh/docs/advanced/testing-events.md index 00e661cd21e31..71b3739c3dbcf 100644 --- a/docs/zh/docs/advanced/testing-events.md +++ b/docs/zh/docs/advanced/testing-events.md @@ -2,6 +2,4 @@ 使用 `TestClient` 和 `with` 语句,在测试中运行事件处理器(`startup` 与 `shutdown`)。 -```Python hl_lines="9-12 20-24" -{!../../docs_src/app_testing/tutorial003.py!} -``` +{* ../../docs_src/app_testing/tutorial003.py hl[9:12,20:24] *} diff --git a/docs/zh/docs/advanced/testing-websockets.md b/docs/zh/docs/advanced/testing-websockets.md index a69053f243868..5d713d5f79b5c 100644 --- a/docs/zh/docs/advanced/testing-websockets.md +++ b/docs/zh/docs/advanced/testing-websockets.md @@ -4,11 +4,9 @@ 为此,要在 `with` 语句中使用 `TestClient` 连接 WebSocket。 -```Python hl_lines="27-31" -{!../../docs_src/app_testing/tutorial002.py!} -``` +{* ../../docs_src/app_testing/tutorial002.py hl[27:31] *} -/// note | "笔记" +/// note | 笔记 更多细节详见 Starlette 官档 - 测试 WebSockets。 diff --git a/docs/zh/docs/advanced/using-request-directly.md b/docs/zh/docs/advanced/using-request-directly.md index 992458217f473..db0fcafdfee1c 100644 --- a/docs/zh/docs/advanced/using-request-directly.md +++ b/docs/zh/docs/advanced/using-request-directly.md @@ -29,13 +29,11 @@ 此时,需要直接访问请求。 -```Python hl_lines="1 7-8" -{!../../docs_src/using_request_directly/tutorial001.py!} -``` +{* ../../docs_src/using_request_directly/tutorial001.py hl[1,7:8] *} 把*路径操作函数*的参数类型声明为 `Request`,**FastAPI** 就能把 `Request` 传递到参数里。 -/// tip | "提示" +/// tip | 提示 注意,本例除了声明请求参数之外,还声明了路径参数。 @@ -49,7 +47,7 @@ 更多细节详见 Starlette 官档 - `Request` 对象。 -/// note | "技术细节" +/// note | 技术细节 您也可以使用 `from starlette.requests import Request`。 diff --git a/docs/zh/docs/advanced/websockets.md b/docs/zh/docs/advanced/websockets.md index 15ae84c5815a3..d91aacc034bfc 100644 --- a/docs/zh/docs/advanced/websockets.md +++ b/docs/zh/docs/advanced/websockets.md @@ -34,19 +34,15 @@ $ pip install websockets 但这是一种专注于 WebSockets 的服务器端并提供一个工作示例的最简单方式: -```Python hl_lines="2 6-38 41-43" -{!../../docs_src/websockets/tutorial001.py!} -``` +{* ../../docs_src/websockets/tutorial001.py hl[2,6:38,41:43] *} ## 创建 `websocket` 在您的 **FastAPI** 应用程序中,创建一个 `websocket`: -```Python hl_lines="1 46-47" -{!../../docs_src/websockets/tutorial001.py!} -``` +{* ../../docs_src/websockets/tutorial001.py hl[1,46:47] *} -/// note | "技术细节" +/// note | 技术细节 您也可以使用 `from starlette.websockets import WebSocket`。 @@ -58,9 +54,7 @@ $ pip install websockets 在您的 WebSocket 路由中,您可以使用 `await` 等待消息并发送消息。 -```Python hl_lines="48-52" -{!../../docs_src/websockets/tutorial001.py!} -``` +{* ../../docs_src/websockets/tutorial001.py hl[48:52] *} 您可以接收和发送二进制、文本和 JSON 数据。 @@ -109,57 +103,7 @@ $ uvicorn main:app --reload 它们的工作方式与其他 FastAPI 端点/ *路径操作* 相同: -//// tab | Python 3.10+ - -```Python hl_lines="68-69 82" -{!> ../../docs_src/websockets/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="68-69 82" -{!> ../../docs_src/websockets/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="69-70 83" -{!> ../../docs_src/websockets/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ 非带注解版本 - -/// tip - -如果可能,请尽量使用 `Annotated` 版本。 - -/// - -```Python hl_lines="66-67 79" -{!> ../../docs_src/websockets/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ 非带注解版本 - -/// tip - -如果可能,请尽量使用 `Annotated` 版本。 - -/// - -```Python hl_lines="68-69 81" -{!> ../../docs_src/websockets/tutorial002.py!} -``` - -//// +{* ../../docs_src/websockets/tutorial002_an_py310.py hl[68:69,82] *} /// info @@ -200,21 +144,7 @@ $ uvicorn main:app --reload 当 WebSocket 连接关闭时,`await websocket.receive_text()` 将引发 `WebSocketDisconnect` 异常,您可以捕获并处理该异常,就像本示例中的示例一样。 -//// tab | Python 3.9+ - -```Python hl_lines="79-81" -{!> ../../docs_src/websockets/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="81-83" -{!> ../../docs_src/websockets/tutorial003.py!} -``` - -//// +{* ../../docs_src/websockets/tutorial003_py39.py hl[79:81] *} 尝试以下操作: diff --git a/docs/zh/docs/advanced/wsgi.md b/docs/zh/docs/advanced/wsgi.md index 92bd998d0b017..363025a34314b 100644 --- a/docs/zh/docs/advanced/wsgi.md +++ b/docs/zh/docs/advanced/wsgi.md @@ -12,9 +12,7 @@ 之后将其挂载到某一个路径下。 -```Python hl_lines="2-3 22" -{!../../docs_src/wsgi/tutorial001.py!} -``` +{* ../../docs_src/wsgi/tutorial001.py hl[2:3,22] *} ## 检查 diff --git a/docs/zh/docs/contributing.md b/docs/zh/docs/contributing.md deleted file mode 100644 index 85b341a8d64e6..0000000000000 --- a/docs/zh/docs/contributing.md +++ /dev/null @@ -1,472 +0,0 @@ -# 开发 - 贡献 - -首先,你可能想了解 [帮助 FastAPI 及获取帮助](help-fastapi.md){.internal-link target=_blank}的基本方式。 - -## 开发 - -如果你已经克隆了源码仓库,并且需要深入研究代码,下面是设置开发环境的指南。 - -### 通过 `venv` 管理虚拟环境 - -你可以使用 Python 的 `venv` 模块在一个目录中创建虚拟环境: - -
- -```console -$ python -m venv env -``` - -
- -这将使用 Python 程序创建一个 `./env/` 目录,然后你将能够为这个隔离的环境安装软件包。 - -### 激活虚拟环境 - -使用以下方法激活新环境: - -//// tab | Linux, macOS - -
- -```console -$ source ./env/bin/activate -``` - -
- -//// - -//// tab | Windows PowerShell - -
- -```console -$ .\env\Scripts\Activate.ps1 -``` - -
- -//// - -//// tab | Windows Bash - -Or if you use Bash for Windows (e.g. Git Bash): - -
- -```console -$ source ./env/Scripts/activate -``` - -
- -//// - -要检查操作是否成功,运行: - -//// tab | Linux, macOS, Windows Bash - -
- -```console -$ which pip - -some/directory/fastapi/env/bin/pip -``` - -
- -//// - -//// tab | Windows PowerShell - -
- -```console -$ Get-Command pip - -some/directory/fastapi/env/bin/pip -``` - -
- -//// - -如果显示 `pip` 程序文件位于 `env/bin/pip` 则说明激活成功。 🎉 - -确保虚拟环境中的 pip 版本是最新的,以避免后续步骤出现错误: - -
- -```console -$ python -m pip install --upgrade pip - ----> 100% -``` - -
- -/// tip - -每一次你在该环境下使用 `pip` 安装了新软件包时,请再次激活该环境。 - -这样可以确保你在使用由该软件包安装的终端程序时使用的是当前虚拟环境中的程序,而不是其他的可能是全局安装的程序。 - -/// - -### pip - -如上所述激活环境后: - -
- -```console -$ pip install -r requirements.txt - ----> 100% -``` - -
- -这将在虚拟环境中安装所有依赖和本地版本的 FastAPI。 - -#### 使用本地 FastAPI - -如果你创建一个导入并使用 FastAPI 的 Python 文件,然后使用虚拟环境中的 Python 运行它,它将使用你本地的 FastAPI 源码。 - -并且如果你更改该本地 FastAPI 的源码,由于它是通过 `-e` 安装的,当你再次运行那个 Python 文件,它将使用你刚刚编辑过的最新版本的 FastAPI。 - -这样,你不必再去重新"安装"你的本地版本即可测试所有更改。 - -/// note | "技术细节" - -仅当你使用此项目中的 `requirements.txt` 安装而不是直接使用 `pip install fastapi` 安装时,才会发生这种情况。 - -这是因为在 `requirements.txt` 中,本地的 FastAPI 是使用“可编辑” (`-e`)选项安装的 - -/// - -### 格式化 - -你可以运行下面的脚本来格式化和清理所有代码: - -
- -```console -$ bash scripts/format.sh -``` - -
- -它还会自动对所有导入代码进行排序整理。 - -为了使整理正确进行,你需要在当前环境中安装本地的 FastAPI,即在运行上述段落中的命令时添加 `-e`。 - -## 文档 - -首先,请确保按上述步骤设置好环境,这将安装所有需要的依赖。 - -### 实时文档 - -在本地开发时,可以使用该脚本构建站点并检查所做的任何更改,并实时重载: - -
- -```console -$ python ./scripts/docs.py live - -[INFO] Serving on http://127.0.0.1:8008 -[INFO] Start watching changes -[INFO] Start detecting changes -``` - -
- -文档服务将运行在 `http://127.0.0.1:8008`。 - -这样,你可以编辑文档 / 源文件并实时查看更改。 - -/// tip - -或者你也可以手动执行和该脚本一样的操作 - -进入语言目录,如果是英文文档,目录则是 `docs/en/`: - -```console -$ cd docs/en/ -``` - -在该目录执行 `mkdocs` 命令 - -```console -$ mkdocs serve --dev-addr 8008 -``` - -/// - -#### Typer CLI (可选) - -本指引向你展示了如何直接用 `python` 运行 `./scripts/docs.py` 中的脚本。 - -但你也可以使用 Typer CLI,而且在安装了补全功能后,你将可以在终端中对命令进行自动补全。 - -如果你已经安装 Typer CLI ,则可以使用以下命令安装自动补全功能: - -
- -```console -$ typer --install-completion - -zsh completion installed in /home/user/.bashrc. -Completion will take effect once you restart the terminal. -``` - -
- -### 文档架构 - -文档使用 MkDocs 生成。 - -在 `./scripts/docs.py` 中还有额外工具 / 脚本来处理翻译。 - -/// tip - -你不需要去了解 `./scripts/docs.py` 中的代码,只需在命令行中使用它即可。 - -/// - -所有文档均在 `./docs/en/` 目录中以 Markdown 文件格式保存。 - -许多的教程中都有一些代码块,大多数情况下,这些代码是可以直接运行的,因为这些代码不是写在 Markdown 文件里的,而是写在 `./docs_src/` 目录中的 Python 文件里。 - -在生成站点的时候,这些 Python 文件会被打包进文档中。 - -### 测试文档 - -大多数的测试实际上都是针对文档中的示例源文件运行的。 - -这有助于确保: - -* 文档始终是最新的。 -* 文档示例可以直接运行。 -* 绝大多数特性既在文档中得以阐述,又通过测试覆盖进行保障。 - - -### 应用和文档同时运行 - -如果你使用以下方式运行示例程序: - -
- -```console -$ uvicorn tutorial001:app --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -
- -由于 Uvicorn 默认使用 `8000` 端口 ,因此运行在 `8008` 端口上的文档不会与之冲突。 - -### 翻译 - -**非常感谢**你能够参与文档的翻译!这项工作需要社区的帮助才能完成。 🌎 🚀 - -以下是参与帮助翻译的步骤。 - -#### 建议和指南 - -* 在当前 已有的 pull requests 中查找你使用的语言,添加要求修改或同意合并的评审意见。 - -/// tip - -你可以为已有的 pull requests 添加包含修改建议的评论。 - -详情可查看关于 添加 pull request 评审意见 以同意合并或要求修改的文档。 - -/// - -* 检查在 GitHub Discussion 是否有关于你所用语言的协作翻译。 如果有,你可以订阅它,当有一条新的 PR 请求需要评审时,系统会自动将其添加到讨论中,你也会收到对应的推送。 - -* 每翻译一个页面新增一个 pull request。这将使其他人更容易对其进行评审。 - -对于我(译注:作者使用西班牙语和英语)不懂的语言,我将在等待其他人评审翻译之后将其合并。 - -* 你还可以查看是否有你所用语言的翻译,并对其进行评审,这将帮助我了解翻译是否正确以及能否将其合并。 - * 可以在 GitHub Discussions 中查看。 - * 也可以在现有 PR 中通过你使用的语言标签来筛选对应的 PR,举个例子,对于西班牙语,标签是 `lang-es`。 - -* 请使用相同的 Python 示例,且只需翻译文档中的文本,不用修改其它东西。 - -* 请使用相同的图片、文件名以及链接地址,不用修改其它东西。 - -* 你可以从 ISO 639-1 代码列表 表中查找你想要翻译语言的两位字母代码。 - -#### 已有的语言 - -假设你想将某个页面翻译成已经翻译了一些页面的语言,例如西班牙语。 - -对于西班牙语来说,它的两位字母代码是 `es`。所以西班牙语翻译的目录位于 `docs/es/`。 - -/// tip - -默认语言是英语,位于 `docs/en/`目录。 - -/// - -现在为西班牙语文档运行实时服务器: - -
- -```console -// Use the command "live" and pass the language code as a CLI argument -$ python ./scripts/docs.py live es - -[INFO] Serving on http://127.0.0.1:8008 -[INFO] Start watching changes -[INFO] Start detecting changes -``` - -
- -/// tip - -或者你也可以手动执行和该脚本一样的操作 - -进入语言目录,对于西班牙语的翻译,目录是 `docs/es/`: - -```console -$ cd docs/es/ -``` - -在该目录执行 `mkdocs` 命令 - -```console -$ mkdocs serve --dev-addr 8008 -``` - -/// - -现在你可以访问 http://127.0.0.1:8008 实时查看你所做的更改。 - -如果你查看 FastAPI 的线上文档网站,会看到每种语言都有所有的文档页面,但是某些页面并未被翻译并且会有一处关于缺少翻译的提示。(但是当你像上面这样在本地运行文档时,你只会看到已经翻译的页面。) - -现在假设你要为 [Features](features.md){.internal-link target=_blank} 章节添加翻译。 - -* 复制下面的文件: - -``` -docs/en/docs/features.md -``` - -* 粘贴到你想要翻译语言目录的相同位置,比如: - -``` -docs/es/docs/features.md -``` - -/// tip - -注意路径和文件名的唯一变化是语言代码,从 `en` 更改为 `es`。 - -/// - -回到浏览器你就可以看到刚刚更新的章节了。🎉 - -现在,你可以翻译这些内容并在保存文件后进行预览。 - -#### 新语言 - -假设你想要为尚未有任何页面被翻译的语言添加翻译。 - -假设你想要添加克里奥尔语翻译,而且文档中还没有该语言的翻译。 - -点击上面提到的“ISO 639-1 代码列表”链接,可以查到“克里奥尔语”的代码为 `ht`。 - -下一步是运行脚本以生成新的翻译目录: - -
- -```console -// Use the command new-lang, pass the language code as a CLI argument -$ python ./scripts/docs.py new-lang ht - -Successfully initialized: docs/ht -``` - -
- -现在,你可以在编辑器中查看新创建的目录 `docs/ht/`。 - -这条命令会生成一个从 `en` 版本继承了所有属性的配置文件 `docs/ht/mkdocs.yml`: - -```yaml -INHERIT: ../en/mkdocs.yml -``` - -/// tip - -你也可以自己手动创建包含这些内容的文件。 - -/// - -这条命令还会生成一个文档主页 `docs/ht/index.md`,你可以从这个文件开始翻译。 - -然后,你可以根据上面的"已有语言"的指引继续进行翻译。 - -翻译完成后,你就可以用 `docs/ht/mkdocs.yml` 和 `docs/ht/index.md` 发起 PR 了。🎉 - -#### 预览结果 - -你可以执行 `./scripts/docs.py live` 命令来预览结果(或者 `mkdocs serve`)。 - -但是当你完成翻译后,你可以像在线上展示一样测试所有内容,包括所有其他语言。 - -为此,首先构建所有文档: - -
- -```console -// Use the command "build-all", this will take a bit -$ python ./scripts/docs.py build-all - -Building docs for: en -Building docs for: es -Successfully built docs for: es -``` - -
- -这样会对每一种语言构建一个独立的文档站点,并最终把这些站点全部打包输出到 `./site/` 目录。 - - - -然后你可以使用命令 `serve` 来运行生成的站点: - -
- -```console -// Use the command "serve" after running "build-all" -$ python ./scripts/docs.py serve - -Warning: this is a very simple server. For development, use mkdocs serve instead. -This is here only to preview a site with translations already built. -Make sure you run the build-all command first. -Serving at: http://127.0.0.1:8008 -``` - -
- -## 测试 - -你可以在本地运行下面的脚本来测试所有代码并生成 HTML 格式的覆盖率报告: - -
- -```console -$ bash scripts/test-cov-html.sh -``` - -
- -该命令生成了一个 `./htmlcov/` 目录,如果你在浏览器中打开 `./htmlcov/index.html` 文件,你可以交互式地浏览被测试所覆盖的代码区块,并注意是否缺少了任何区块。 diff --git a/docs/zh/docs/environment-variables.md b/docs/zh/docs/environment-variables.md new file mode 100644 index 0000000000000..812278051acf1 --- /dev/null +++ b/docs/zh/docs/environment-variables.md @@ -0,0 +1,298 @@ +# 环境变量 + +/// tip + +如果你已经知道什么是“环境变量”并且知道如何使用它们,你可以放心跳过这一部分。 + +/// + +环境变量(也称为“**env var**”)是一个独立于 Python 代码**之外**的变量,它存在于**操作系统**中,可以被你的 Python 代码(或其他程序)读取。 + +环境变量对于处理应用程序**设置**、作为 Python **安装**的一部分等方面非常有用。 + +## 创建和使用环境变量 + +你在 **shell(终端)**中就可以**创建**和使用环境变量,并不需要用到 Python: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +// 你可以使用以下命令创建一个名为 MY_NAME 的环境变量 +$ export MY_NAME="Wade Wilson" + +// 然后,你可以在其他程序中使用它,例如 +$ echo "Hello $MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +// 创建一个名为 MY_NAME 的环境变量 +$ $Env:MY_NAME = "Wade Wilson" + +// 在其他程序中使用它,例如 +$ echo "Hello $Env:MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +## 在 Python 中读取环境变量 + +你也可以在 Python **之外**的终端中创建环境变量(或使用任何其他方法),然后在 Python 中**读取**它们。 + +例如,你可以创建一个名为 `main.py` 的文件,其中包含以下内容: + +```Python hl_lines="3" +import os + +name = os.getenv("MY_NAME", "World") +print(f"Hello {name} from Python") +``` + +/// tip + +第二个参数是 `os.getenv()` 的默认返回值。 + +如果没有提供,默认值为 `None`,这里我们提供 `"World"` 作为默认值。 + +/// + +然后你可以调用这个 Python 程序: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +// 这里我们还没有设置环境变量 +$ python main.py + +// 因为我们没有设置环境变量,所以我们得到的是默认值 + +Hello World from Python + +// 但是如果我们事先创建过一个环境变量 +$ export MY_NAME="Wade Wilson" + +// 然后再次调用程序 +$ python main.py + +// 现在就可以读取到环境变量了 + +Hello Wade Wilson from Python +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +// 这里我们还没有设置环境变量 +$ python main.py + +// 因为我们没有设置环境变量,所以我们得到的是默认值 + +Hello World from Python + +// 但是如果我们事先创建过一个环境变量 +$ $Env:MY_NAME = "Wade Wilson" + +// 然后再次调用程序 +$ python main.py + +// 现在就可以读取到环境变量了 + +Hello Wade Wilson from Python +``` + +
+ +//// + +由于环境变量可以在代码之外设置、但可以被代码读取,并且不必与其他文件一起存储(提交到 `git`),因此通常用于配置或**设置**。 + +你还可以为**特定的程序调用**创建特定的环境变量,该环境变量仅对该程序可用,且仅在其运行期间有效。 + +要实现这一点,只需在同一行内、程序本身之前创建它: + +
+ +```console +// 在这个程序调用的同一行中创建一个名为 MY_NAME 的环境变量 +$ MY_NAME="Wade Wilson" python main.py + +// 现在就可以读取到环境变量了 + +Hello Wade Wilson from Python + +// 在此之后这个环境变量将不会依然存在 +$ python main.py + +Hello World from Python +``` + +
+ +/// tip + +你可以在 The Twelve-Factor App: 配置中了解更多信息。 + +/// + +## 类型和验证 + +这些环境变量只能处理**文本字符串**,因为它们是处于 Python 范畴之外的,必须与其他程序和操作系统的其余部分兼容(甚至与不同的操作系统兼容,如 Linux、Windows、macOS)。 + +这意味着从环境变量中读取的**任何值**在 Python 中都将是一个 `str`,任何类型转换或验证都必须在代码中完成。 + +你将在[高级用户指南 - 设置和环境变量](./advanced/settings.md)中了解更多关于使用环境变量处理**应用程序设置**的信息。 + +## `PATH` 环境变量 + +有一个**特殊的**环境变量称为 **`PATH`**,操作系统(Linux、macOS、Windows)用它来查找要运行的程序。 + +`PATH` 变量的值是一个长字符串,由 Linux 和 macOS 上的冒号 `:` 分隔的目录组成,而在 Windows 上则是由分号 `;` 分隔的。 + +例如,`PATH` 环境变量可能如下所示: + +//// tab | Linux, macOS + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +这意味着系统应该在以下目录中查找程序: + +- `/usr/local/bin` +- `/usr/bin` +- `/bin` +- `/usr/sbin` +- `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32 +``` + +这意味着系统应该在以下目录中查找程序: + +- `C:\Program Files\Python312\Scripts` +- `C:\Program Files\Python312` +- `C:\Windows\System32` + +//// + +当你在终端中输入一个**命令**时,操作系统会在 `PATH` 环境变量中列出的**每个目录**中**查找**程序。 + +例如,当你在终端中输入 `python` 时,操作系统会在该列表中的**第一个目录**中查找名为 `python` 的程序。 + +如果找到了,那么操作系统将**使用它**;否则,操作系统会继续在**其他目录**中查找。 + +### 安装 Python 和更新 `PATH` + +安装 Python 时,可能会询问你是否要更新 `PATH` 环境变量。 + +//// tab | Linux, macOS + +假设你安装 Python 并最终将其安装在了目录 `/opt/custompython/bin` 中。 + +如果你同意更新 `PATH` 环境变量,那么安装程序将会将 `/opt/custompython/bin` 添加到 `PATH` 环境变量中。 + +它看起来大概会像这样: + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/custompython/bin +``` + +如此一来,当你在终端中输入 `python` 时,系统会在 `/opt/custompython/bin` 中找到 Python 程序(最后一个目录)并使用它。 + +//// + +//// tab | Windows + +假设你安装 Python 并最终将其安装在了目录 `C:\opt\custompython\bin` 中。 + +如果你同意更新 `PATH` 环境变量 (在 Python 安装程序中,这个操作是名为 `Add Python x.xx to PATH` 的复选框 —— 译者注),那么安装程序将会将 `C:\opt\custompython\bin` 添加到 `PATH` 环境变量中。 + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32;C:\opt\custompython\bin +``` + +如此一来,当你在终端中输入 `python` 时,系统会在 `C:\opt\custompython\bin` 中找到 Python 程序(最后一个目录)并使用它。 + +//// + +因此,如果你输入: + +
+ +```console +$ python +``` + +
+ +//// tab | Linux, macOS + +系统会在 `/opt/custompython/bin` 中**找到** `python` 程序并运行它。 + +这和输入以下命令大致等价: + +
+ +```console +$ /opt/custompython/bin/python +``` + +
+ +//// + +//// tab | Windows + +系统会在 `C:\opt\custompython\bin\python` 中**找到** `python` 程序并运行它。 + +这和输入以下命令大致等价: + +
+ +```console +$ C:\opt\custompython\bin\python +``` + +
+ +//// + +当学习[虚拟环境](virtual-environments.md)时,这些信息将会很有用。 + +## 结论 + +通过这个教程,你应该对**环境变量**是什么以及如何在 Python 中使用它们有了基本的了解。 + +你也可以在环境变量 - 维基百科 (Wikipedia for Environment Variable) 中了解更多关于它们的信息。 + +在许多情况下,环境变量的用途和适用性并不是很明显。但是在开发过程中,它们会在许多不同的场景中出现,因此了解它们是很有必要的。 + +例如,你将在下一节关于[虚拟环境](virtual-environments.md)中需要这些信息。 diff --git a/docs/zh/docs/fastapi-cli.md b/docs/zh/docs/fastapi-cli.md index 00235bd022a95..f532c7fb7de10 100644 --- a/docs/zh/docs/fastapi-cli.md +++ b/docs/zh/docs/fastapi-cli.md @@ -80,7 +80,7 @@ FastAPI CLI 接收你的 Python 程序路径,自动检测包含 FastAPI 的变 在大多数情况下,你会(且应该)有一个“终止代理”在上层为你处理 HTTPS,这取决于你如何部署应用程序,你的服务提供商可能会为你处理此事,或者你可能需要自己设置。 -/// tip | "提示" +/// tip | 提示 你可以在 [deployment documentation](deployment/index.md){.internal-link target=_blank} 获得更多信息。 diff --git a/docs/zh/docs/help-fastapi.md b/docs/zh/docs/help-fastapi.md index fc47ed89de9e1..09f37a44b1da5 100644 --- a/docs/zh/docs/help-fastapi.md +++ b/docs/zh/docs/help-fastapi.md @@ -108,7 +108,7 @@ 快加入 👥 Discord 聊天服务器 👥 和 FastAPI 社区里的小伙伴一起哈皮吧。 -/// tip | "提示" +/// tip | 提示 如有问题,请在 GitHub Issues 里提问,在这里更容易得到 [FastAPI 专家](fastapi-people.md#_3){.internal-link target=_blank}的帮助。 diff --git a/docs/zh/docs/how-to/configure-swagger-ui.md b/docs/zh/docs/how-to/configure-swagger-ui.md index 1a2daeec19976..108e0cb95abe7 100644 --- a/docs/zh/docs/how-to/configure-swagger-ui.md +++ b/docs/zh/docs/how-to/configure-swagger-ui.md @@ -18,9 +18,7 @@ FastAPI会将这些配置转换为 **JSON**,使其与 JavaScript 兼容,因 但是你可以通过设置 `syntaxHighlight` 为 `False` 来禁用 Swagger UI 中的语法高亮: -```Python hl_lines="3" -{!../../docs_src/configure_swagger_ui/tutorial001.py!} -``` +{* ../../docs_src/configure_swagger_ui/tutorial001.py hl[3] *} ...在此之后,Swagger UI 将不会高亮代码: @@ -30,9 +28,7 @@ FastAPI会将这些配置转换为 **JSON**,使其与 JavaScript 兼容,因 同样地,你也可以通过设置键 `"syntaxHighlight.theme"` 来设置语法高亮主题(注意中间有一个点): -```Python hl_lines="3" -{!../../docs_src/configure_swagger_ui/tutorial002.py!} -``` +{* ../../docs_src/configure_swagger_ui/tutorial002.py hl[3] *} 这个配置会改变语法高亮主题: @@ -44,17 +40,13 @@ FastAPI 包含了一些默认配置参数,适用于大多数用例。 其包括这些默认配置参数: -```Python -{!../../fastapi/openapi/docs.py[ln:7-23]!} -``` +{* ../../fastapi/openapi/docs.py ln[7:23] *} 你可以通过在 `swagger_ui_parameters` 中设置不同的值来覆盖它们。 比如,如果要禁用 `deepLinking`,你可以像这样传递设置到 `swagger_ui_parameters` 中: -```Python hl_lines="3" -{!../../docs_src/configure_swagger_ui/tutorial003.py!} -``` +{* ../../docs_src/configure_swagger_ui/tutorial003.py hl[3] *} ## 其他 Swagger UI 参数 diff --git a/docs/zh/docs/python-types.md b/docs/zh/docs/python-types.md index dab6bd4c011e2..5126cb847e342 100644 --- a/docs/zh/docs/python-types.md +++ b/docs/zh/docs/python-types.md @@ -22,9 +22,8 @@ 让我们从一个简单的例子开始: -```Python -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py *} + 运行这段程序将输出: @@ -38,9 +37,8 @@ John Doe * 通过 `title()` 将每个参数的第一个字母转换为大写形式。 * 中间用一个空格来拼接它们。 -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py hl[2] *} + ### 修改示例 @@ -82,9 +80,8 @@ John Doe 这些就是"类型提示": -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial002.py!} -``` +{* ../../docs_src/python_types/tutorial002.py hl[1] *} + 这和声明默认值是不同的,例如: @@ -112,9 +109,8 @@ John Doe 下面是一个已经有类型提示的函数: -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial003.py!} -``` +{* ../../docs_src/python_types/tutorial003.py hl[1] *} + 因为编辑器已经知道了这些变量的类型,所以不仅能对代码进行补全,还能检查其中的错误: @@ -122,9 +118,8 @@ John Doe 现在你知道了必须先修复这个问题,通过 `str(age)` 把 `age` 转换成字符串: -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial004.py!} -``` +{* ../../docs_src/python_types/tutorial004.py hl[2] *} + ## 声明类型 @@ -143,9 +138,8 @@ John Doe * `bool` * `bytes` -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial005.py!} -``` +{* ../../docs_src/python_types/tutorial005.py hl[1] *} + ### 嵌套类型 @@ -161,9 +155,8 @@ John Doe 从 `typing` 模块导入 `List`(注意是大写的 `L`): -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial006.py!} -``` +{* ../../docs_src/python_types/tutorial006.py hl[1] *} + 同样以冒号(`:`)来声明这个变量。 @@ -171,9 +164,8 @@ John Doe 由于列表是带有"子类型"的类型,所以我们把子类型放在方括号中: -```Python hl_lines="4" -{!../../docs_src/python_types/tutorial006.py!} -``` +{* ../../docs_src/python_types/tutorial006.py hl[4] *} + 这表示:"变量 `items` 是一个 `list`,并且这个列表里的每一个元素都是 `str`"。 @@ -191,9 +183,8 @@ John Doe 声明 `tuple` 和 `set` 的方法也是一样的: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial007.py!} -``` +{* ../../docs_src/python_types/tutorial007.py hl[1,4] *} + 这表示: @@ -208,9 +199,8 @@ John Doe 第二个子类型声明 `dict` 的所有值: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial008.py!} -``` +{* ../../docs_src/python_types/tutorial008.py hl[1,4] *} + 这表示: @@ -224,15 +214,13 @@ John Doe 假设你有一个名为 `Person` 的类,拥有 name 属性: -```Python hl_lines="1-3" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[1:3] *} + 接下来,你可以将一个变量声明为 `Person` 类型: -```Python hl_lines="6" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[6] *} + 然后,你将再次获得所有的编辑器支持: @@ -252,9 +240,8 @@ John Doe 下面的例子来自 Pydantic 官方文档: -```Python -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py *} + /// info diff --git a/docs/zh/docs/tutorial/background-tasks.md b/docs/zh/docs/tutorial/background-tasks.md index fc9312bc5ee6c..40e61add7fd6b 100644 --- a/docs/zh/docs/tutorial/background-tasks.md +++ b/docs/zh/docs/tutorial/background-tasks.md @@ -15,9 +15,7 @@ 首先导入 `BackgroundTasks` 并在 *路径操作函数* 中使用类型声明 `BackgroundTasks` 定义一个参数: -```Python hl_lines="1 13" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[1, 13] *} **FastAPI** 会创建一个 `BackgroundTasks` 类型的对象并作为该参数传入。 @@ -33,17 +31,13 @@ 由于写操作不使用 `async` 和 `await`,我们用普通的 `def` 定义函数: -```Python hl_lines="6-9" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *} ## 添加后台任务 在你的 *路径操作函数* 里,用 `.add_task()` 方法将任务函数传到 *后台任务* 对象中: -```Python hl_lines="14" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[14] *} `.add_task()` 接收以下参数: @@ -59,25 +53,19 @@ //// tab | Python 3.10+ -```Python hl_lines="13 15 22 25" -{!> ../../docs_src/background_tasks/tutorial002_an_py310.py!} -``` +{* ../../docs_src/background_tasks/tutorial002_an_py310.py hl[13, 15, 22, 25] *} //// //// tab | Python 3.9+ -```Python hl_lines="13 15 22 25" -{!> ../../docs_src/background_tasks/tutorial002_an_py39.py!} -``` +{* ../../docs_src/background_tasks/tutorial002_an_py39.py hl[13, 15, 22, 25] *} //// //// tab | Python 3.8+ -```Python hl_lines="14 16 23 26" -{!> ../../docs_src/background_tasks/tutorial002_an.py!} -``` +{* ../../docs_src/background_tasks/tutorial002_an.py hl[14, 16, 23, 26] *} //// @@ -89,9 +77,7 @@ /// -```Python hl_lines="11 13 20 23" -{!> ../../docs_src/background_tasks/tutorial002_py310.py!} -``` +{* ../../docs_src/background_tasks/tutorial002_py310.py hl[11, 13, 20, 23] *} //// @@ -103,9 +89,7 @@ /// -```Python hl_lines="13 15 22 25" -{!> ../../docs_src/background_tasks/tutorial002.py!} -``` +{* ../../docs_src/background_tasks/tutorial002.py hl[13, 15, 22, 25] *} //// @@ -133,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 64afd99afeb5b..318e10fd75bba 100644 --- a/docs/zh/docs/tutorial/bigger-applications.md +++ b/docs/zh/docs/tutorial/bigger-applications.md @@ -414,7 +414,7 @@ from .routers.users import router 它将包含来自该路由器的所有路由作为其一部分。 -/// note | "技术细节" +/// note | 技术细节 实际上,它将在内部为声明在 `APIRouter` 中的每个*路径操作*创建一个*路径操作*。 @@ -477,7 +477,7 @@ from .routers.users import router 它将与通过 `app.include_router()` 添加的所有其他*路径操作*一起正常运行。 -/// info | "特别的技术细节" +/// info | 特别的技术细节 **注意**:这是一个非常技术性的细节,你也许可以**直接跳过**。 diff --git a/docs/zh/docs/tutorial/body-fields.md b/docs/zh/docs/tutorial/body-fields.md index ac59d7e6aa289..4cff58bfc59bf 100644 --- a/docs/zh/docs/tutorial/body-fields.md +++ b/docs/zh/docs/tutorial/body-fields.md @@ -6,59 +6,9 @@ 首先,从 Pydantic 中导入 `Field`: -//// tab | Python 3.10+ +{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[4] *} -```Python hl_lines="4" -{!> ../../docs_src/body_fields/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="4" -{!> ../../docs_src/body_fields/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4" -{!> ../../docs_src/body_fields/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -尽可能选择使用 `Annotated` 的版本。 - -/// - -```Python hl_lines="2" -{!> ../../docs_src/body_fields/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -尽可能选择使用 `Annotated` 的版本。 - -/// - -```Python hl_lines="4" -{!> ../../docs_src/body_fields/tutorial001.py!} -``` - -//// - -/// warning | "警告" +/// warning | 警告 注意,与从 `fastapi` 导入 `Query`,`Path`、`Body` 不同,要直接从 `pydantic` 导入 `Field` 。 @@ -68,61 +18,11 @@ 然后,使用 `Field` 定义模型的属性: -//// tab | Python 3.10+ - -```Python hl_lines="11-14" -{!> ../../docs_src/body_fields/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="11-14" -{!> ../../docs_src/body_fields/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="12-15" -{!> ../../docs_src/body_fields/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9-12" -{!> ../../docs_src/body_fields/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="11-14" -{!> ../../docs_src/body_fields/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[11:14] *} `Field` 的工作方式和 `Query`、`Path`、`Body` 相同,参数也相同。 -/// note | "技术细节" +/// note | 技术细节 实际上,`Query`、`Path` 都是 `Params` 的子类,而 `Params` 类又是 Pydantic 中 `FieldInfo` 的子类。 @@ -134,7 +34,7 @@ Pydantic 的 `Field` 返回也是 `FieldInfo` 的类实例。 /// -/// tip | "提示" +/// tip | 提示 注意,模型属性的类型、默认值及 `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 c3bc0db9e543d..b4356fdcb4624 100644 --- a/docs/zh/docs/tutorial/body-multiple-params.md +++ b/docs/zh/docs/tutorial/body-multiple-params.md @@ -8,57 +8,7 @@ 你还可以通过将默认值设置为 `None` 来将请求体参数声明为可选参数: -//// tab | Python 3.10+ - -```Python hl_lines="18-20" -{!> ../../docs_src/body_multiple_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="18-20" -{!> ../../docs_src/body_multiple_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="19-21" -{!> ../../docs_src/body_multiple_params/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -尽可能选择使用 `Annotated` 的版本。 - -/// - -```Python hl_lines="17-19" -{!> ../../docs_src/body_multiple_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -尽可能选择使用 `Annotated` 的版本。 - -/// - -```Python hl_lines="19-21" -{!> ../../docs_src/body_multiple_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial001_an_py310.py hl[18:20] *} /// note @@ -81,21 +31,7 @@ 但是你也可以声明多个请求体参数,例如 `item` 和 `user`: -//// tab | Python 3.10+ - -```Python hl_lines="20" -{!> ../../docs_src/body_multiple_params/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="22" -{!> ../../docs_src/body_multiple_params/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial002_py310.py hl[20] *} 在这种情况下,**FastAPI** 将注意到该函数中有多个请求体参数(两个 Pydantic 模型参数)。 @@ -137,57 +73,7 @@ 但是你可以使用 `Body` 指示 **FastAPI** 将其作为请求体的另一个键进行处理。 -//// tab | Python 3.10+ - -```Python hl_lines="23" -{!> ../../docs_src/body_multiple_params/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="23" -{!> ../../docs_src/body_multiple_params/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24" -{!> ../../docs_src/body_multiple_params/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -尽可能选择使用 `Annotated` 的版本。 - -/// - -```Python hl_lines="20" -{!> ../../docs_src/body_multiple_params/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -尽可能选择使用 `Annotated` 的版本。 - -/// - -```Python hl_lines="22" -{!> ../../docs_src/body_multiple_params/tutorial003.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial003_an_py310.py hl[23] *} 在这种情况下,**FastAPI** 将期望像这样的请求体: @@ -222,57 +108,7 @@ q: str = None 比如: -//// tab | Python 3.10+ - -```Python hl_lines="27" -{!> ../../docs_src/body_multiple_params/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="27" -{!> ../../docs_src/body_multiple_params/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="28" -{!> ../../docs_src/body_multiple_params/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -尽可能选择使用 `Annotated` 的版本。 - -/// - -```Python hl_lines="25" -{!> ../../docs_src/body_multiple_params/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -尽可能选择使用 `Annotated` 的版本。 - -/// - -```Python hl_lines="27" -{!> ../../docs_src/body_multiple_params/tutorial004.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[27] *} /// info @@ -294,57 +130,7 @@ item: Item = Body(embed=True) 比如: -//// tab | Python 3.10+ - -```Python hl_lines="17" -{!> ../../docs_src/body_multiple_params/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="17" -{!> ../../docs_src/body_multiple_params/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18" -{!> ../../docs_src/body_multiple_params/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -尽可能选择使用 `Annotated` 的版本。 - -/// - -```Python hl_lines="15" -{!> ../../docs_src/body_multiple_params/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -尽可能选择使用 `Annotated` 的版本。 - -/// - -```Python hl_lines="17" -{!> ../../docs_src/body_multiple_params/tutorial005.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial005_an_py310.py hl[17] *} 在这种情况下,**FastAPI** 将期望像这样的请求体: diff --git a/docs/zh/docs/tutorial/body-nested-models.md b/docs/zh/docs/tutorial/body-nested-models.md index 316ba9878dfa8..df96d96b4bfff 100644 --- a/docs/zh/docs/tutorial/body-nested-models.md +++ b/docs/zh/docs/tutorial/body-nested-models.md @@ -6,21 +6,7 @@ 你可以将一个属性定义为拥有子元素的类型。例如 Python `list`: -//// tab | Python 3.10+ - -```Python hl_lines="12" -{!> ../../docs_src/body_nested_models/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial001_py310.py hl[12] *} 这将使 `tags` 成为一个由元素组成的列表。不过它没有声明每个元素的类型。 @@ -32,9 +18,7 @@ 首先,从 Python 的标准库 `typing` 模块中导入 `List`: -```Python hl_lines="1" -{!> ../../docs_src/body_nested_models/tutorial002.py!} -``` +{* ../../docs_src/body_nested_models/tutorial002.py hl[1] *} ### 声明具有子类型的 List @@ -55,29 +39,7 @@ my_list: List[str] 因此,在我们的示例中,我们可以将 `tags` 明确地指定为一个「字符串列表」: -//// tab | Python 3.10+ - -```Python hl_lines="12" -{!> ../../docs_src/body_nested_models/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial002_py310.py hl[12] *} ## Set 类型 @@ -87,29 +49,7 @@ Python 具有一种特殊的数据类型来保存一组唯一的元素,即 `se 然后我们可以导入 `Set` 并将 `tag` 声明为一个由 `str` 组成的 `set`: -//// tab | Python 3.10+ - -```Python hl_lines="12" -{!> ../../docs_src/body_nested_models/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 14" -{!> ../../docs_src/body_nested_models/tutorial003.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial003_py310.py hl[12] *} 这样,即使你收到带有重复数据的请求,这些数据也会被转换为一组唯一项。 @@ -131,57 +71,13 @@ Pydantic 模型的每个属性都具有类型。 例如,我们可以定义一个 `Image` 模型: -//// tab | Python 3.10+ - -```Python hl_lines="7-9" -{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9-11" -{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9-11" -{!> ../../docs_src/body_nested_models/tutorial004.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[7:9] *} ### 将子模型用作类型 然后我们可以将其用作一个属性的类型: -//// tab | Python 3.10+ - -```Python hl_lines="18" -{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial004.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[18] *} 这意味着 **FastAPI** 将期望类似于以下内容的请求体: @@ -214,29 +110,7 @@ Pydantic 模型的每个属性都具有类型。 例如,在 `Image` 模型中我们有一个 `url` 字段,我们可以把它声明为 Pydantic 的 `HttpUrl`,而不是 `str`: -//// tab | Python 3.10+ - -```Python hl_lines="2 8" -{!> ../../docs_src/body_nested_models/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="4 10" -{!> ../../docs_src/body_nested_models/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4 10" -{!> ../../docs_src/body_nested_models/tutorial005.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial005_py310.py hl[2,8] *} 该字符串将被检查是否为有效的 URL,并在 JSON Schema / OpenAPI 文档中进行记录。 @@ -244,29 +118,7 @@ Pydantic 模型的每个属性都具有类型。 你还可以将 Pydantic 模型用作 `list`、`set` 等的子类型: -//// tab | Python 3.10+ - -```Python hl_lines="18" -{!> ../../docs_src/body_nested_models/tutorial006_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial006_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial006.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial006_py310.py hl[18] *} 这将期望(转换,校验,记录文档等)下面这样的 JSON 请求体: @@ -304,29 +156,7 @@ Pydantic 模型的每个属性都具有类型。 你可以定义任意深度的嵌套模型: -//// tab | Python 3.10+ - -```Python hl_lines="7 12 18 21 25" -{!> ../../docs_src/body_nested_models/tutorial007_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9 14 20 23 27" -{!> ../../docs_src/body_nested_models/tutorial007_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 14 20 23 27" -{!> ../../docs_src/body_nested_models/tutorial007.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial007_py310.py hl[7,12,18,21,25] *} /// info @@ -344,21 +174,7 @@ images: List[Image] 例如: -//// tab | Python 3.9+ - -```Python hl_lines="13" -{!> ../../docs_src/body_nested_models/tutorial008_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="15" -{!> ../../docs_src/body_nested_models/tutorial008.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial008_py39.py hl[13] *} ## 无处不在的编辑器支持 @@ -388,21 +204,7 @@ images: List[Image] 在下面的例子中,你将接受任意键为 `int` 类型并且值为 `float` 类型的 `dict`: -//// tab | Python 3.9+ - -```Python hl_lines="7" -{!> ../../docs_src/body_nested_models/tutorial009_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/body_nested_models/tutorial009.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial009_py39.py hl[7] *} /// tip diff --git a/docs/zh/docs/tutorial/body-updates.md b/docs/zh/docs/tutorial/body-updates.md index 5e9008d6a1954..87f88f25533c9 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,7 +32,7 @@ 即,只发送要更新的数据,其余数据保持不变。 -/// note | "笔记" +/// note | 笔记 `PATCH` 没有 `PUT` 知名,也怎么不常用。 @@ -56,9 +54,7 @@ 然后再用它生成一个只含已设置(在请求中所发送)数据,且省略了默认值的 `dict`: -```Python hl_lines="34" -{!../../docs_src/body_updates/tutorial002.py!} -``` +{* ../../docs_src/body_updates/tutorial002.py hl[34] *} ### 使用 Pydantic 的 `update` 参数 @@ -66,9 +62,7 @@ 例如,`stored_item_model.copy(update=update_data)`: -```Python hl_lines="35" -{!../../docs_src/body_updates/tutorial002.py!} -``` +{* ../../docs_src/body_updates/tutorial002.py hl[35] *} ### 更新部分数据小结 @@ -85,18 +79,16 @@ * 把数据保存至数据库; * 返回更新后的模型。 -```Python hl_lines="30-37" -{!../../docs_src/body_updates/tutorial002.py!} -``` +{* ../../docs_src/body_updates/tutorial002.py hl[30:37] *} -/// tip | "提示" +/// tip | 提示 实际上,HTTP `PUT` 也可以完成相同的操作。 但本节以 `PATCH` 为例的原因是,该操作就是为了这种用例创建的。 /// -/// note | "笔记" +/// note | 笔记 注意,输入模型仍需验证。 diff --git a/docs/zh/docs/tutorial/body.md b/docs/zh/docs/tutorial/body.md index 67a7f28e0a2c3..3820fc74774f9 100644 --- a/docs/zh/docs/tutorial/body.md +++ b/docs/zh/docs/tutorial/body.md @@ -8,7 +8,7 @@ API 基本上肯定要发送**响应体**,但是客户端不一定发送**请 使用 Pydantic 模型声明**请求体**,能充分利用它的功能和优点。 -/// info | "说明" +/// info | 说明 发送数据使用 `POST`(最常用)、`PUT`、`DELETE`、`PATCH` 等操作。 @@ -22,21 +22,7 @@ API 基本上肯定要发送**响应体**,但是客户端不一定发送**请 从 `pydantic` 中导入 `BaseModel`: -//// tab | Python 3.10+ - -```Python hl_lines="2" -{!> ../../docs_src/body/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4" -{!> ../../docs_src/body/tutorial001.py!} -``` - -//// +{* ../../docs_src/body/tutorial001_py310.py hl[2] *} ## 创建数据模型 @@ -44,21 +30,7 @@ API 基本上肯定要发送**响应体**,但是客户端不一定发送**请 使用 Python 标准类型声明所有属性: -//// tab | Python 3.10+ - -```Python hl_lines="5-9" -{!> ../../docs_src/body/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="7-11" -{!> ../../docs_src/body/tutorial001.py!} -``` - -//// +{* ../../docs_src/body/tutorial001_py310.py hl[5:9] *} 与声明查询参数一样,包含默认值的模型属性是可选的,否则就是必选的。默认值为 `None` 的模型属性也是可选的。 @@ -86,21 +58,7 @@ API 基本上肯定要发送**响应体**,但是客户端不一定发送**请 使用与声明路径和查询参数相同的方式声明请求体,把请求体添加至*路径操作*: -//// tab | Python 3.10+ - -```Python hl_lines="16" -{!> ../../docs_src/body/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18" -{!> ../../docs_src/body/tutorial001.py!} -``` - -//// +{* ../../docs_src/body/tutorial001_py310.py hl[16] *} ……此处,请求体参数的类型为 `Item` 模型。 @@ -149,7 +107,7 @@ Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文 -/// tip | "提示" +/// tip | 提示 使用 PyCharm 编辑器时,推荐安装 Pydantic PyCharm 插件。 @@ -167,21 +125,7 @@ Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文 在*路径操作*函数内部直接访问模型对象的属性: -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/body/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="21" -{!> ../../docs_src/body/tutorial002.py!} -``` - -//// +{* ../../docs_src/body/tutorial002_py310.py hl[19] *} ## 请求体 + 路径参数 @@ -189,21 +133,7 @@ Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文 **FastAPI** 能识别与**路径参数**匹配的函数参数,还能识别从**请求体**中获取的类型为 Pydantic 模型的函数参数。 -//// tab | Python 3.10+ - -```Python hl_lines="15-16" -{!> ../../docs_src/body/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17-18" -{!> ../../docs_src/body/tutorial003.py!} -``` - -//// +{* ../../docs_src/body/tutorial003_py310.py hl[15:16] *} ## 请求体 + 路径参数 + 查询参数 @@ -211,21 +141,7 @@ Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文 **FastAPI** 能够正确识别这三种参数,并从正确的位置获取数据。 -//// tab | Python 3.10+ - -```Python hl_lines="16" -{!> ../../docs_src/body/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18" -{!> ../../docs_src/body/tutorial004.py!} -``` - -//// +{* ../../docs_src/body/tutorial004_py310.py hl[16] *} 函数参数按如下规则进行识别: @@ -233,7 +149,7 @@ Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文 - 类型是(`int`、`float`、`str`、`bool` 等)**单类型**的参数,是**查询**参数 - 类型是 **Pydantic 模型**的参数,是**请求体** -/// note | "笔记" +/// note | 笔记 因为默认值是 `None`, FastAPI 会把 `q` 当作可选参数。 diff --git a/docs/zh/docs/tutorial/cookie-params.md b/docs/zh/docs/tutorial/cookie-params.md index b01c28238afb3..4956008149ad4 100644 --- a/docs/zh/docs/tutorial/cookie-params.md +++ b/docs/zh/docs/tutorial/cookie-params.md @@ -6,57 +6,7 @@ 首先,导入 `Cookie`: -//// tab | Python 3.10+ - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -尽可能选择使用 `Annotated` 的版本。 - -/// - -```Python hl_lines="1" -{!> ../../docs_src/cookie_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -尽可能选择使用 `Annotated` 的版本。 - -/// - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[3] *} ## 声明 `Cookie` 参数 @@ -65,59 +15,9 @@ 第一个值是默认值,还可以传递所有验证参数或注释参数: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/cookie_params/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -尽可能选择使用 `Annotated` 的版本。 - -/// - -```Python hl_lines="7" -{!> ../../docs_src/cookie_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -尽可能选择使用 `Annotated` 的版本。 - -/// - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[9] *} -/// note | "技术细节" +/// note | 技术细节 `Cookie` 、`Path` 、`Query` 是**兄弟类**,都继承自共用的 `Param` 类。 @@ -125,7 +25,7 @@ /// -/// info | "说明" +/// info | 说明 必须使用 `Cookie` 声明 cookie 参数,否则该参数会被解释为查询参数。 diff --git a/docs/zh/docs/tutorial/cors.md b/docs/zh/docs/tutorial/cors.md index 1166d5c97b64e..a4f15f6478383 100644 --- a/docs/zh/docs/tutorial/cors.md +++ b/docs/zh/docs/tutorial/cors.md @@ -46,9 +46,7 @@ * 特定的 HTTP 方法(`POST`,`PUT`)或者使用通配符 `"*"` 允许所有方法。 * 特定的 HTTP headers 或者使用通配符 `"*"` 允许所有 headers。 -```Python hl_lines="2 6-11 13-19" -{!../../docs_src/cors/tutorial001.py!} -``` +{* ../../docs_src/cors/tutorial001.py hl[2,6:11,13:19] *} 默认情况下,这个 `CORSMiddleware` 实现所使用的默认参数较为保守,所以你需要显式地启用特定的源、方法或者 headers,以便浏览器能够在跨域上下文中使用它们。 @@ -78,7 +76,7 @@ 更多关于 CORS 的信息,请查看 Mozilla CORS 文档。 -/// note | "技术细节" +/// note | 技术细节 你也可以使用 `from starlette.middleware.cors import CORSMiddleware`。 diff --git a/docs/zh/docs/tutorial/debugging.md b/docs/zh/docs/tutorial/debugging.md index a5afa1aaa2c8e..734b85565316c 100644 --- a/docs/zh/docs/tutorial/debugging.md +++ b/docs/zh/docs/tutorial/debugging.md @@ -6,9 +6,7 @@ 在你的 FastAPI 应用中直接导入 `uvicorn` 并运行: -```Python hl_lines="1 15" -{!../../docs_src/debugging/tutorial001.py!} -``` +{* ../../docs_src/debugging/tutorial001.py hl[1,15] *} ### 关于 `__name__ == "__main__"` diff --git a/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md index 917459d1d0473..f07280790c7f2 100644 --- a/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md @@ -6,21 +6,7 @@ 在前面的例子中, 我们从依赖项 ("可依赖对象") 中返回了一个 `dict`: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_py310.py hl[7] *} 但是后面我们在路径操作函数的参数 `commons` 中得到了一个 `dict`。 @@ -83,57 +69,15 @@ fluffy = Cat(name="Mr Fluffy") 所以,我们可以将上面的依赖项 "可依赖对象" `common_parameters` 更改为类 `CommonQueryParams`: -//// tab | Python 3.10+ - -```Python hl_lines="9-13" -{!> ../../docs_src/dependencies/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11-15" -{!> ../../docs_src/dependencies/tutorial002.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial002_py310.py hl[9:13] *} 注意用于创建类实例的 `__init__` 方法: -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/dependencies/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="12" -{!> ../../docs_src/dependencies/tutorial002.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial002_py310.py hl[10] *} ...它与我们以前的 `common_parameters` 具有相同的参数: -//// tab | Python 3.10+ - -```Python hl_lines="6" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="9" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_py310.py hl[6] *} 这些参数就是 **FastAPI** 用来 "处理" 依赖项的。 @@ -149,21 +93,7 @@ fluffy = Cat(name="Mr Fluffy") 现在,您可以使用这个类来声明你的依赖项了。 -//// tab | Python 3.10+ - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial002.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial002_py310.py hl[17] *} **FastAPI** 调用 `CommonQueryParams` 类。这将创建该类的一个 "实例",该实例将作为参数 `commons` 被传递给你的函数。 @@ -203,21 +133,7 @@ commons = Depends(CommonQueryParams) ..就像: -//// tab | Python 3.10+ - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial003.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial003_py310.py hl[17] *} 但是声明类型是被鼓励的,因为那样你的编辑器就会知道将传递什么作为参数 `commons` ,然后它可以帮助你完成代码,类型检查,等等: @@ -251,21 +167,7 @@ commons: CommonQueryParams = Depends() 同样的例子看起来像这样: -//// tab | Python 3.10+ - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial004.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial004_py310.py hl[17] *} ... **FastAPI** 会知道怎么处理。 diff --git a/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index c7cfe0531a259..51b3e9fc39c70 100644 --- a/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -14,13 +14,11 @@ 该参数的值是由 `Depends()` 组成的 `list`: -```Python hl_lines="17" -{!../../docs_src/dependencies/tutorial006.py!} -``` +{* ../../docs_src/dependencies/tutorial006.py hl[17] *} 路径操作装饰器依赖项(以下简称为**“路径装饰器依赖项”**)的执行或解析方式和普通依赖项一样,但就算这些依赖项会返回值,它们的值也不会传递给*路径操作函数*。 -/// tip | "提示" +/// tip | 提示 有些编辑器会检查代码中没使用过的函数参数,并显示错误提示。 @@ -30,7 +28,7 @@ /// -/// info | "说明" +/// info | 说明 本例中,使用的是自定义响应头 `X-Key` 和 `X-Token`。 @@ -46,17 +44,13 @@ 路径装饰器依赖项可以声明请求的需求项(比如响应头)或其他子依赖项: -```Python hl_lines="6 11" -{!../../docs_src/dependencies/tutorial006.py!} -``` +{* ../../docs_src/dependencies/tutorial006.py hl[6,11] *} ### 触发异常 路径装饰器依赖项与正常的依赖项一样,可以 `raise` 异常: -```Python hl_lines="8 13" -{!../../docs_src/dependencies/tutorial006.py!} -``` +{* ../../docs_src/dependencies/tutorial006.py hl[8,13] *} ### 返回值 @@ -64,9 +58,7 @@ 因此,可以复用在其他位置使用过的、(能返回值的)普通依赖项,即使没有使用这个值,也会执行该依赖项: -```Python hl_lines="9 14" -{!../../docs_src/dependencies/tutorial006.py!} -``` +{* ../../docs_src/dependencies/tutorial006.py hl[9,14] *} ## 为一组路径操作定义依赖项 diff --git a/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md index a30313719c602..a863bb861ec67 100644 --- a/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md @@ -10,7 +10,7 @@ FastAPI支持在完成后执行一些 ../../docs_src/dependencies/tutorial008_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="5 13 21" -{!> ../../docs_src/dependencies/tutorial008_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | 提示 - -如果可以,请尽量使用 `Annotated` 版本。 - -/// - -```Python hl_lines="4 12 20" -{!> ../../docs_src/dependencies/tutorial008.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial008_an_py39.py hl[6,14,22] *} 所有这些依赖都可以使用 `yield`。 @@ -110,35 +74,7 @@ FastAPI支持在完成后执行一些上下文管理器完成的。 @@ -170,35 +106,7 @@ FastAPI支持在完成后执行一些 ../../docs_src/dependencies/tutorial008c_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="14-15" -{!> ../../docs_src/dependencies/tutorial008c_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | 提示 - -如果可以,请尽量使用 `Annotated` 版本。 - -/// - -```Python hl_lines="13-14" -{!> ../../docs_src/dependencies/tutorial008c.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial008c_an_py39.py hl[15:16] *} 在示例代码的情况下,客户端将会收到 *HTTP 500 Internal Server Error* 的响应,因为我们没有抛出 `HTTPException` 或者类似的异常,并且服务器也 **不会有任何日志** 或者其他提示来告诉我们错误是什么。😱 @@ -244,35 +124,7 @@ FastAPI支持在完成后执行一些