diff --git a/.github/actions/people/app/main.py b/.github/actions/people/app/main.py
index 33156f1ca..b752d9d2b 100644
--- a/.github/actions/people/app/main.py
+++ b/.github/actions/people/app/main.py
@@ -515,9 +515,9 @@ def get_individual_sponsors(settings: Settings):
tiers: DefaultDict[float, Dict[str, SponsorEntity]] = defaultdict(dict)
for node in nodes:
- tiers[node.tier.monthlyPriceInDollars][
- node.sponsorEntity.login
- ] = node.sponsorEntity
+ tiers[node.tier.monthlyPriceInDollars][node.sponsorEntity.login] = (
+ node.sponsorEntity
+ )
return tiers
diff --git a/.github/labeler.yml b/.github/labeler.yml
new file mode 100644
index 000000000..c5b1f84f3
--- /dev/null
+++ b/.github/labeler.yml
@@ -0,0 +1,38 @@
+docs:
+ - all:
+ - changed-files:
+ - any-glob-to-any-file:
+ - docs/en/docs/**
+ - docs_src/**
+ - all-globs-to-all-files:
+ - '!fastapi/**'
+ - '!pyproject.toml'
+ - '!docs/en/data/sponsors.yml'
+ - '!docs/en/overrides/main.html'
+
+lang-all:
+ - all:
+ - changed-files:
+ - any-glob-to-any-file:
+ - docs/*/docs/**
+ - all-globs-to-all-files:
+ - '!docs/en/docs/**'
+ - '!fastapi/**'
+ - '!pyproject.toml'
+
+internal:
+ - all:
+ - changed-files:
+ - any-glob-to-any-file:
+ - .github/**
+ - scripts/**
+ - .gitignore
+ - .pre-commit-config.yaml
+ - pdm_build.py
+ - requirements*.txt
+ - docs/en/data/sponsors.yml
+ - docs/en/overrides/main.html
+ - all-globs-to-all-files:
+ - '!docs/*/docs/**'
+ - '!fastapi/**'
+ - '!pyproject.toml'
diff --git a/.github/workflows/add-to-project.yml b/.github/workflows/add-to-project.yml
new file mode 100644
index 000000000..dccea83f3
--- /dev/null
+++ b/.github/workflows/add-to-project.yml
@@ -0,0 +1,18 @@
+name: Add to Project
+
+on:
+ pull_request_target:
+ issues:
+ types:
+ - opened
+ - reopened
+
+jobs:
+ add-to-project:
+ name: Add to project
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/add-to-project@v1.0.2
+ with:
+ project-url: https://github.com/orgs/fastapi/projects/2
+ github-token: ${{ secrets.PROJECTS_TOKEN }}
diff --git a/.github/workflows/build-docs.yml b/.github/workflows/build-docs.yml
index 262c7fa5c..52c34a49e 100644
--- a/.github/workflows/build-docs.yml
+++ b/.github/workflows/build-docs.yml
@@ -18,7 +18,7 @@ jobs:
docs: ${{ steps.filter.outputs.docs }}
steps:
- uses: actions/checkout@v4
- # For pull requests it's not necessary to checkout the code but for master it is
+ # For pull requests it's not necessary to checkout the code but for the main branch it is
- uses: dorny/paths-filter@v3
id: filter
with:
@@ -28,9 +28,12 @@ jobs:
- docs/**
- docs_src/**
- requirements-docs.txt
+ - requirements-docs-insiders.txt
- pyproject.toml
- mkdocs.yml
- mkdocs.insiders.yml
+ - mkdocs.maybe-insiders.yml
+ - mkdocs.no-insiders.yml
- .github/workflows/build-docs.yml
- .github/workflows/deploy-docs.yml
langs:
@@ -49,17 +52,16 @@ jobs:
id: cache
with:
path: ${{ env.pythonLocation }}
- key: ${{ runner.os }}-python-docs-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml', 'requirements-docs.txt', 'requirements-docs-tests.txt') }}-v07
+ key: ${{ runner.os }}-python-docs-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml', 'requirements-docs.txt', 'requirements-docs-insiders.txt', 'requirements-docs-tests.txt') }}-v08
- name: Install docs extras
if: steps.cache.outputs.cache-hit != 'true'
run: pip install -r requirements-docs.txt
# Install MkDocs Material Insiders here just to put it in the cache for the rest of the steps
- name: Install Material for MkDocs Insiders
if: ( github.event_name != 'pull_request' || github.secret_source == 'Actions' ) && steps.cache.outputs.cache-hit != 'true'
- run: |
- pip install git+https://${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}@github.com/squidfunk/mkdocs-material-insiders.git
- pip install git+https://${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}@github.com/pawamoy-insiders/griffe-typing-deprecated.git
- pip install git+https://${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}@github.com/pawamoy-insiders/mkdocstrings-python.git
+ run: pip install -r requirements-docs-insiders.txt
+ env:
+ TOKEN: ${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}
- name: Verify Docs
run: python ./scripts/docs.py verify-docs
- name: Export Language Codes
@@ -90,16 +92,15 @@ jobs:
id: cache
with:
path: ${{ env.pythonLocation }}
- key: ${{ runner.os }}-python-docs-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml', 'requirements-docs.txt', 'requirements-docs-tests.txt') }}-v08
+ key: ${{ runner.os }}-python-docs-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml', 'requirements-docs.txt', 'requirements-docs-insiders.txt', 'requirements-docs-tests.txt') }}-v08
- name: Install docs extras
if: steps.cache.outputs.cache-hit != 'true'
run: pip install -r requirements-docs.txt
- name: Install Material for MkDocs Insiders
if: ( github.event_name != 'pull_request' || github.secret_source == 'Actions' ) && steps.cache.outputs.cache-hit != 'true'
- run: |
- pip install git+https://${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}@github.com/squidfunk/mkdocs-material-insiders.git
- pip install git+https://${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}@github.com/pawamoy-insiders/griffe-typing-deprecated.git
- pip install git+https://${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}@github.com/pawamoy-insiders/mkdocstrings-python.git
+ run: pip install -r requirements-docs-insiders.txt
+ env:
+ TOKEN: ${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}
- name: Update Languages
run: python ./scripts/docs.py update-languages
- uses: actions/cache@v4
@@ -112,6 +113,7 @@ jobs:
with:
name: docs-site-${{ matrix.lang }}
path: ./site/**
+ include-hidden-files: true
# https://github.com/marketplace/actions/alls-green#why
docs-all-green: # This job does nothing and is only used for the branch protection
diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml
index 7d8846bb3..22dc89dff 100644
--- a/.github/workflows/deploy-docs.yml
+++ b/.github/workflows/deploy-docs.yml
@@ -10,6 +10,7 @@ permissions:
deployments: write
issues: write
pull-requests: write
+ statuses: write
jobs:
deploy-docs:
@@ -20,6 +21,25 @@ jobs:
GITHUB_CONTEXT: ${{ toJson(github) }}
run: echo "$GITHUB_CONTEXT"
- uses: actions/checkout@v4
+ - name: Set up Python
+ uses: actions/setup-python@v5
+ with:
+ python-version: "3.11"
+ - uses: actions/cache@v4
+ id: cache
+ with:
+ path: ${{ env.pythonLocation }}
+ key: ${{ runner.os }}-python-github-actions-${{ env.pythonLocation }}-${{ hashFiles('requirements-github-actions.txt') }}-v01
+ - name: Install GitHub Actions dependencies
+ if: steps.cache.outputs.cache-hit != 'true'
+ run: pip install -r requirements-github-actions.txt
+ - name: Deploy Docs Status Pending
+ run: python ./scripts/deploy_docs_status.py
+ env:
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ COMMIT_SHA: ${{ github.event.workflow_run.head_sha }}
+ RUN_ID: ${{ github.run_id }}
+
- name: Clean site
run: |
rm -rf ./site
@@ -35,30 +55,19 @@ jobs:
# hashFiles returns an empty string if there are no files
if: hashFiles('./site/*')
id: deploy
- uses: cloudflare/pages-action@v1
+ env:
+ PROJECT_NAME: fastapitiangolo
+ BRANCH: ${{ ( github.event.workflow_run.head_repository.full_name == github.repository && github.event.workflow_run.head_branch == 'master' && 'main' ) || ( github.event.workflow_run.head_sha ) }}
+ uses: cloudflare/wrangler-action@v3
with:
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
- projectName: fastapitiangolo
- directory: './site'
- gitHubToken: ${{ secrets.GITHUB_TOKEN }}
- branch: ${{ ( github.event.workflow_run.head_repository.full_name == github.repository && github.event.workflow_run.head_branch == 'master' && 'main' ) || ( github.event.workflow_run.head_sha ) }}
- - name: Set up Python
- uses: actions/setup-python@v5
- with:
- python-version: "3.11"
- - uses: actions/cache@v4
- id: cache
- with:
- path: ${{ env.pythonLocation }}
- key: ${{ runner.os }}-python-github-actions-${{ env.pythonLocation }}-${{ hashFiles('requirements-github-actions.txt') }}-v01
- - name: Install GitHub Actions dependencies
- if: steps.cache.outputs.cache-hit != 'true'
- run: pip install -r requirements-github-actions.txt
+ command: pages deploy ./site --project-name=${{ env.PROJECT_NAME }} --branch=${{ env.BRANCH }}
- name: Comment Deploy
- if: steps.deploy.outputs.url != ''
- run: python ./scripts/comment_docs_deploy_url_in_pr.py
+ run: python ./scripts/deploy_docs_status.py
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- DEPLOY_URL: ${{ steps.deploy.outputs.url }}
+ DEPLOY_URL: ${{ steps.deploy.outputs.deployment-url }}
COMMIT_SHA: ${{ github.event.workflow_run.head_sha }}
+ RUN_ID: ${{ github.run_id }}
+ IS_DONE: "true"
diff --git a/.github/workflows/issue-manager.yml b/.github/workflows/issue-manager.yml
index d5b947a9c..439084434 100644
--- a/.github/workflows/issue-manager.yml
+++ b/.github/workflows/issue-manager.yml
@@ -2,7 +2,7 @@ name: Issue Manager
on:
schedule:
- - cron: "10 3 * * *"
+ - cron: "13 22 * * *"
issue_comment:
types:
- created
@@ -16,6 +16,7 @@ on:
permissions:
issues: write
+ pull-requests: write
jobs:
issue-manager:
@@ -26,7 +27,7 @@ jobs:
env:
GITHUB_CONTEXT: ${{ toJson(github) }}
run: echo "$GITHUB_CONTEXT"
- - uses: tiangolo/issue-manager@0.5.0
+ - uses: tiangolo/issue-manager@0.5.1
with:
token: ${{ secrets.GITHUB_TOKEN }}
config: >
@@ -35,8 +36,8 @@ jobs:
"delay": 864000,
"message": "Assuming the original need was handled, this will be automatically closed now. But feel free to add more comments or create new issues or PRs."
},
- "changes-requested": {
+ "waiting": {
"delay": 2628000,
- "message": "As this PR had requested changes to be applied but has been inactive for a while, it's now going to be closed. But if there's anyone interested, feel free to create a new PR."
+ "message": "As this PR has been waiting for the original user for a while but seems to be inactive, it's now going to be closed. But if there's anyone interested, feel free to create a new PR."
}
}
diff --git a/.github/workflows/labeler.yml b/.github/workflows/labeler.yml
new file mode 100644
index 000000000..e8e58015a
--- /dev/null
+++ b/.github/workflows/labeler.yml
@@ -0,0 +1,33 @@
+name: Labels
+on:
+ pull_request_target:
+ types:
+ - opened
+ - synchronize
+ - reopened
+ # For label-checker
+ - labeled
+ - unlabeled
+
+jobs:
+ labeler:
+ permissions:
+ contents: read
+ pull-requests: write
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/labeler@v5
+ if: ${{ github.event.action != 'labeled' && github.event.action != 'unlabeled' }}
+ - run: echo "Done adding labels"
+ # Run this after labeler applied labels
+ check-labels:
+ needs:
+ - labeler
+ permissions:
+ pull-requests: read
+ runs-on: ubuntu-latest
+ steps:
+ - uses: docker://agilepathway/pull-request-label-checker:latest
+ with:
+ one_of: breaking,security,feature,bug,refactor,upgrade,docs,lang-all,internal
+ repo_token: ${{ secrets.GITHUB_TOKEN }}
diff --git a/.github/workflows/latest-changes.yml b/.github/workflows/latest-changes.yml
index 27e062d09..16da3bc63 100644
--- a/.github/workflows/latest-changes.yml
+++ b/.github/workflows/latest-changes.yml
@@ -34,8 +34,7 @@ jobs:
if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled == 'true' }}
with:
limit-access-to-actor: true
- - uses: docker://tiangolo/latest-changes:0.3.0
- # - uses: tiangolo/latest-changes@main
+ - uses: tiangolo/latest-changes@0.3.1
with:
token: ${{ secrets.GITHUB_TOKEN }}
latest_changes_file: docs/en/docs/release-notes.md
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml
index e7c69befc..c8ea4e18c 100644
--- a/.github/workflows/publish.yml
+++ b/.github/workflows/publish.yml
@@ -35,7 +35,7 @@ jobs:
TIANGOLO_BUILD_PACKAGE: ${{ matrix.package }}
run: python -m build
- name: Publish
- uses: pypa/gh-action-pypi-publish@v1.8.14
+ uses: pypa/gh-action-pypi-publish@v1.10.3
- name: Dump GitHub context
env:
GITHUB_CONTEXT: ${{ toJson(github) }}
diff --git a/.github/workflows/test-redistribute.yml b/.github/workflows/test-redistribute.yml
index 0cc5f866e..693f0c603 100644
--- a/.github/workflows/test-redistribute.yml
+++ b/.github/workflows/test-redistribute.yml
@@ -55,3 +55,15 @@ jobs:
env:
GITHUB_CONTEXT: ${{ toJson(github) }}
run: echo "$GITHUB_CONTEXT"
+
+ # https://github.com/marketplace/actions/alls-green#why
+ test-redistribute-alls-green: # This job does nothing and is only used for the branch protection
+ if: always()
+ needs:
+ - test-redistribute
+ runs-on: ubuntu-latest
+ steps:
+ - name: Decide whether the needed jobs succeeded or failed
+ uses: re-actors/alls-green@release/v1
+ with:
+ jobs: ${{ toJSON(needs) }}
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index a33b6a68a..fb4b083c4 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -37,7 +37,7 @@ jobs:
if: steps.cache.outputs.cache-hit != 'true'
run: pip install -r requirements-tests.txt
- name: Install Pydantic v2
- run: pip install "pydantic>=2.0.2,<3.0.0"
+ run: pip install --upgrade "pydantic>=2.0.2,<3.0.0"
- name: Lint
run: bash scripts/lint.sh
@@ -79,7 +79,7 @@ jobs:
run: pip install "pydantic>=1.10.0,<2.0.0"
- name: Install Pydantic v2
if: matrix.pydantic-version == 'pydantic-v2'
- run: pip install "pydantic>=2.0.2,<3.0.0"
+ run: pip install --upgrade "pydantic>=2.0.2,<3.0.0"
- run: mkdir coverage
- name: Test
run: bash scripts/test.sh
@@ -91,6 +91,7 @@ jobs:
with:
name: coverage-${{ matrix.python-version }}-${{ matrix.pydantic-version }}
path: coverage
+ include-hidden-files: true
coverage-combine:
needs: [test]
@@ -117,12 +118,13 @@ jobs:
- run: ls -la coverage
- run: coverage combine coverage
- run: coverage report
- - run: coverage html --show-contexts --title "Coverage for ${{ github.sha }}"
+ - run: coverage html --title "Coverage for ${{ github.sha }}"
- name: Store coverage HTML
uses: actions/upload-artifact@v4
with:
name: coverage-html
path: htmlcov
+ include-hidden-files: true
# https://github.com/marketplace/actions/alls-green#why
check: # This job does nothing and is only used for the branch protection
diff --git a/.gitignore b/.gitignore
index 9be494cec..ef6364a9a 100644
--- a/.gitignore
+++ b/.gitignore
@@ -7,7 +7,7 @@ __pycache__
htmlcov
dist
site
-.coverage
+.coverage*
coverage.xml
.netlify
test.db
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 4d49845d6..a62acccfe 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -4,7 +4,7 @@ default_language_version:
python: python3.10
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
- rev: v4.4.0
+ rev: v5.0.0
hooks:
- id: check-added-large-files
- id: check-toml
@@ -13,8 +13,8 @@ repos:
- --unsafe
- id: end-of-file-fixer
- id: trailing-whitespace
-- repo: https://github.com/charliermarsh/ruff-pre-commit
- rev: v0.2.0
+- repo: https://github.com/astral-sh/ruff-pre-commit
+ rev: v0.6.9
hooks:
- id: ruff
args:
diff --git a/README.md b/README.md
index aa70ff2da..f274265de 100644
--- a/README.md
+++ b/README.md
@@ -52,11 +52,9 @@ The key features are:
-
+
-
-
@@ -132,6 +130,8 @@ FastAPI stands on the shoulders of giants:
## Installation
+Create and activate a virtual environment and then install FastAPI:
+
email_validator - for email validation.
+* email-validator - for email validation.
Used by Starlette:
diff --git a/docs/az/docs/fastapi-people.md b/docs/az/docs/fastapi-people.md
deleted file mode 100644
index 9bb7ad6ea..000000000
--- a/docs/az/docs/fastapi-people.md
+++ /dev/null
@@ -1,185 +0,0 @@
----
-hide:
- - navigation
----
-
-# FastAPI İnsanlar
-
-FastAPI-ın bütün mənşəli insanları qəbul edən heyrətamiz icması var.
-
-
-
-## Yaradıcı - İcraçı
-
-Salam! 👋
-
-Bu mənəm:
-
-{% if people %}
-email_validator - e-poçtun yoxlanılması üçün.
+* email-validator - e-poçtun yoxlanılması üçün.
* pydantic-settings - parametrlərin idarə edilməsi üçün.
* pydantic-extra-types - Pydantic ilə istifadə edilə bilən əlavə tiplər üçün.
diff --git a/docs/bn/docs/index.md b/docs/bn/docs/index.md
index 042cf9399..c882506ff 100644
--- a/docs/bn/docs/index.md
+++ b/docs/bn/docs/index.md
@@ -439,7 +439,7 @@ item: Item
Pydantic দ্বারা ব্যবহৃত:
-- email_validator - ইমেল যাচাইকরণের জন্য।
+- email-validator - ইমেল যাচাইকরণের জন্য।
স্টারলেট দ্বারা ব্যবহৃত:
diff --git a/docs/bn/docs/python-types.md b/docs/bn/docs/python-types.md
index 6923363dd..4a602b679 100644
--- a/docs/bn/docs/python-types.md
+++ b/docs/bn/docs/python-types.md
@@ -12,15 +12,18 @@ Python-এ ঐচ্ছিক "টাইপ হিন্ট" (যা "টাই
তবে, আপনি যদি কখনো **FastAPI** ব্যবহার নাও করেন, তবুও এগুলি সম্পর্কে একটু শেখা আপনার উপকারে আসবে।
-!!! Note
- যদি আপনি একজন Python বিশেষজ্ঞ হন, এবং টাইপ হিন্ট সম্পর্কে সবকিছু জানেন, তাহলে পরবর্তী অধ্যায়ে চলে যান।
+/// note
+
+যদি আপনি একজন Python বিশেষজ্ঞ হন, এবং টাইপ হিন্ট সম্পর্কে সবকিছু জানেন, তাহলে পরবর্তী অধ্যায়ে চলে যান।
+
+///
## প্রেরণা
চলুন একটি সাধারণ উদাহরণ দিয়ে শুরু করি:
```Python
-{!../../../docs_src/python_types/tutorial001.py!}
+{!../../docs_src/python_types/tutorial001.py!}
```
এই প্রোগ্রামটি কল করলে আউটপুট হয়:
@@ -36,7 +39,7 @@ John Doe
* তাদেরকে মাঝখানে একটি স্পেস দিয়ে concatenate করে।
```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial001.py!}
+{!../../docs_src/python_types/tutorial001.py!}
```
### এটি সম্পাদনা করুন
@@ -80,7 +83,7 @@ John Doe
এগুলিই "টাইপ হিন্ট":
```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial002.py!}
+{!../../docs_src/python_types/tutorial002.py!}
```
এটি ডিফল্ট ভ্যালু ঘোষণা করার মত নয় যেমন:
@@ -110,7 +113,7 @@ John Doe
এই ফাংশনটি দেখুন, এটিতে ইতিমধ্যে টাইপ হিন্ট রয়েছে:
```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial003.py!}
+{!../../docs_src/python_types/tutorial003.py!}
```
এডিটর ভেরিয়েবলগুলির টাইপ জানার কারণে, আপনি শুধুমাত্র অটোকমপ্লিশনই পান না, আপনি এরর চেকও পান:
@@ -120,7 +123,7 @@ John Doe
এখন আপনি জানেন যে আপনাকে এটি ঠিক করতে হবে, `age`-কে একটি স্ট্রিং হিসেবে রূপান্তর করতে `str(age)` ব্যবহার করতে হবে:
```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial004.py!}
+{!../../docs_src/python_types/tutorial004.py!}
```
## টাইপ ঘোষণা
@@ -141,7 +144,7 @@ John Doe
* `bytes`
```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial005.py!}
+{!../../docs_src/python_types/tutorial005.py!}
```
### টাইপ প্যারামিটার সহ জেনেরিক টাইপ
@@ -170,45 +173,55 @@ Python যত এগিয়ে যাচ্ছে, **নতুন সংস্
উদাহরণস্বরূপ, একটি ভেরিয়েবলকে `str`-এর একটি `list` হিসেবে সংজ্ঞায়িত করা যাক।
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ভেরিয়েবলটি ঘোষণা করুন, একই কোলন (`:`) সিনট্যাক্স ব্যবহার করে।
+ভেরিয়েবলটি ঘোষণা করুন, একই কোলন (`:`) সিনট্যাক্স ব্যবহার করে।
- টাইপ হিসেবে, `list` ব্যবহার করুন।
+টাইপ হিসেবে, `list` ব্যবহার করুন।
- যেহেতু লিস্ট এমন একটি টাইপ যা অভ্যন্তরীণ টাইপগুলি ধারণ করে, আপনি তাদের স্কোয়ার ব্রাকেটের ভিতরে ব্যবহার করুন:
+যেহেতু লিস্ট এমন একটি টাইপ যা অভ্যন্তরীণ টাইপগুলি ধারণ করে, আপনি তাদের স্কোয়ার ব্রাকেটের ভিতরে ব্যবহার করুন:
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial006_py39.py!}
- ```
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial006_py39.py!}
+```
-=== "Python 3.8+"
+////
- `typing` থেকে `List` (বড় হাতের `L` দিয়ে) ইমপোর্ট করুন:
+//// tab | Python 3.8+
- ``` Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial006.py!}
- ```
+`typing` থেকে `List` (বড় হাতের `L` দিয়ে) ইমপোর্ট করুন:
- ভেরিয়েবলটি ঘোষণা করুন, একই কোলন (`:`) সিনট্যাক্স ব্যবহার করে।
+``` Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial006.py!}
+```
- টাইপ হিসেবে, `typing` থেকে আপনার ইম্পোর্ট করা `List` ব্যবহার করুন।
+ভেরিয়েবলটি ঘোষণা করুন, একই কোলন (`:`) সিনট্যাক্স ব্যবহার করে।
- যেহেতু লিস্ট এমন একটি টাইপ যা অভ্যন্তরীণ টাইপগুলি ধারণ করে, আপনি তাদের স্কোয়ার ব্রাকেটের ভিতরে করুন:
+টাইপ হিসেবে, `typing` থেকে আপনার ইম্পোর্ট করা `List` ব্যবহার করুন।
- ```Python hl_lines="4"
- {!> ../../../docs_src/python_types/tutorial006.py!}
- ```
+যেহেতু লিস্ট এমন একটি টাইপ যা অভ্যন্তরীণ টাইপগুলি ধারণ করে, আপনি তাদের স্কোয়ার ব্রাকেটের ভিতরে করুন:
-!!! Info
- স্কোয়ার ব্রাকেট এর ভিতরে ব্যবহৃত এইসব অভন্তরীন টাইপগুলোকে "ইন্টারনাল টাইপ" বলে।
+```Python hl_lines="4"
+{!> ../../docs_src/python_types/tutorial006.py!}
+```
- এই উদাহরণে, এটি হচ্ছে `List`(অথবা পাইথন ৩.৯ বা তার উপরের সংস্করণের ক্ষেত্রে `list`) এ পাস করা টাইপ প্যারামিটার।
+////
+
+/// info
+
+স্কোয়ার ব্রাকেট এর ভিতরে ব্যবহৃত এইসব অভন্তরীন টাইপগুলোকে "ইন্টারনাল টাইপ" বলে।
+
+এই উদাহরণে, এটি হচ্ছে `List`(অথবা পাইথন ৩.৯ বা তার উপরের সংস্করণের ক্ষেত্রে `list`) এ পাস করা টাইপ প্যারামিটার।
+
+///
এর অর্থ হচ্ছে: "ভেরিয়েবল `items` একটি `list`, এবং এই লিস্টের প্রতিটি আইটেম একটি `str`।"
-!!! Tip
- যদি আপনি Python 3.9 বা তার উপরে ব্যবহার করেন, আপনার `typing` থেকে `List` আমদানি করতে হবে না, আপনি সাধারণ `list` ওই টাইপের পরিবর্তে ব্যবহার করতে পারেন।
+/// tip
+
+যদি আপনি Python 3.9 বা তার উপরে ব্যবহার করেন, আপনার `typing` থেকে `List` আমদানি করতে হবে না, আপনি সাধারণ `list` ওই টাইপের পরিবর্তে ব্যবহার করতে পারেন।
+
+///
এর মাধ্যমে, আপনার এডিটর লিস্ট থেকে আইটেম প্রসেস করার সময় সাপোর্ট প্রদান করতে পারবে:
@@ -224,17 +237,21 @@ Python যত এগিয়ে যাচ্ছে, **নতুন সংস্
আপনি `tuple` এবং `set` ঘোষণা করার জন্য একই প্রক্রিয়া অনুসরণ করবেন:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial007_py39.py!}
- ```
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial007_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial007.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial007.py!}
+```
+
+////
এর মানে হল:
@@ -249,18 +266,21 @@ Python যত এগিয়ে যাচ্ছে, **নতুন সংস্
দ্বিতীয় টাইপ প্যারামিটারটি হল `dict`-এর মানগুলির জন্য:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial008_py39.py!}
- ```
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial008_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial008.py!}
- ```
+//// tab | Python 3.8+
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial008.py!}
+```
+
+////
এর মানে হল:
@@ -276,17 +296,21 @@ Python 3.6 এবং তার উপরের সংস্করণগুলি
Python 3.10-এ একটি **নতুন সিনট্যাক্স** আছে যেখানে আপনি সম্ভাব্য টাইপগুলিকে একটি ভার্টিকাল বার (`|`) দ্বারা পৃথক করতে পারেন।
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial008b_py310.py!}
- ```
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial008b_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial008b.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial008b.py!}
+```
+
+////
উভয় ক্ষেত্রেই এর মানে হল যে `item` হতে পারে একটি `int` অথবা `str`।
@@ -297,7 +321,7 @@ Python 3.10-এ একটি **নতুন সিনট্যাক্স** আ
Python 3.6 এবং তার উপরের সংস্করণগুলিতে (Python 3.10 অনতর্ভুক্ত) আপনি `typing` মডিউল থেকে `Optional` ইমপোর্ট করে এটি ঘোষণা এবং ব্যবহার করতে পারেন।
```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009.py!}
+{!../../docs_src/python_types/tutorial009.py!}
```
`Optional[str]` ব্যবহার করা মানে হল শুধু `str` নয়, এটি হতে পারে `None`-ও, যা আপনার এডিটরকে সেই ত্রুটিগুলি শনাক্ত করতে সাহায্য করবে যেখানে আপনি ধরে নিচ্ছেন যে একটি মান সবসময় `str` হবে, অথচ এটি `None`-ও হতে পারেও।
@@ -306,23 +330,29 @@ Python 3.6 এবং তার উপরের সংস্করণগুলি
এর মানে হল, Python 3.10-এ, আপনি টাইপগুলির ইউনিয়ন ঘোষণা করতে `Something | None` ব্যবহার করতে পারেন:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial009_py310.py!}
- ```
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial009_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial009.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ বিকল্প"
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial009.py!}
+```
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial009b.py!}
- ```
+////
+
+//// tab | Python 3.8+ বিকল্প
+
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial009b.py!}
+```
+
+////
#### `Union` বা `Optional` ব্যবহার
@@ -340,7 +370,7 @@ Python 3.6 এবং তার উপরের সংস্করণগুলি
একটি উদাহরণ হিসেবে, এই ফাংশনটি নিন:
```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009c.py!}
+{!../../docs_src/python_types/tutorial009c.py!}
```
`name` প্যারামিটারটি `Optional[str]` হিসেবে সংজ্ঞায়িত হয়েছে, কিন্তু এটি **অপশনাল নয়**, আপনি প্যারামিটার ছাড়া ফাংশনটি কল করতে পারবেন না:
@@ -358,7 +388,7 @@ 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!}
```
এবং তারপর আপনাকে নামগুলি যেমন `Optional` এবং `Union` নিয়ে আর চিন্তা করতে হবে না। 😎
@@ -367,46 +397,53 @@ say_hi(name=None) # এটি কাজ করে, None বৈধ 🎉
স্কোয়ার ব্র্যাকেটে টাইপ প্যারামিটার নেওয়া এই টাইপগুলিকে **জেনেরিক টাইপ** বা **জেনেরিকস** বলা হয়, যেমন:
-=== "Python 3.10+"
- আপনি সেই একই বিল্টইন টাইপ জেনেরিক্স হিসেবে ব্যবহার করতে পারবেন(ভিতরে টাইপ সহ স্কয়ারে ব্রাকেট দিয়ে):
+//// tab | Python 3.10+
- * `list`
- * `tuple`
- * `set`
- * `dict`
+আপনি সেই একই বিল্টইন টাইপ জেনেরিক্স হিসেবে ব্যবহার করতে পারবেন(ভিতরে টাইপ সহ স্কয়ারে ব্রাকেট দিয়ে):
- এবং Python 3.8 এর মতোই, `typing` মডিউল থেকে:
+* `list`
+* `tuple`
+* `set`
+* `dict`
- * `Union`
- * `Optional` (Python 3.8 এর মতোই)
- * ...এবং অন্যান্য।
+এবং Python 3.8 এর মতোই, `typing` মডিউল থেকে:
- Python 3.10-এ, `Union` এবং `Optional` জেনেরিকস ব্যবহার করার বিকল্প হিসেবে, আপনি টাইপগুলির ইউনিয়ন ঘোষণা করতে ভার্টিকাল বার (`|`) ব্যবহার করতে পারেন, যা ওদের থেকে অনেক ভালো এবং সহজ।
+* `Union`
+* `Optional` (Python 3.8 এর মতোই)
+* ...এবং অন্যান্য।
-=== "Python 3.9+"
+Python 3.10-এ, `Union` এবং `Optional` জেনেরিকস ব্যবহার করার বিকল্প হিসেবে, আপনি টাইপগুলির ইউনিয়ন ঘোষণা করতে ভার্টিকাল বার (`|`) ব্যবহার করতে পারেন, যা ওদের থেকে অনেক ভালো এবং সহজ।
- আপনি সেই একই বিল্টইন টাইপ জেনেরিক্স হিসেবে ব্যবহার করতে পারবেন(ভিতরে টাইপ সহ স্কয়ারে ব্রাকেট দিয়ে):
+////
- * `list`
- * `tuple`
- * `set`
- * `dict`
+//// tab | Python 3.9+
- এবং Python 3.8 এর মতোই, `typing` মডিউল থেকে:
+আপনি সেই একই বিল্টইন টাইপ জেনেরিক্স হিসেবে ব্যবহার করতে পারবেন(ভিতরে টাইপ সহ স্কয়ারে ব্রাকেট দিয়ে):
- * `Union`
- * `Optional`
- * ...এবং অন্যান্য।
+* `list`
+* `tuple`
+* `set`
+* `dict`
-=== "Python 3.8+"
+এবং Python 3.8 এর মতোই, `typing` মডিউল থেকে:
- * `List`
- * `Tuple`
- * `Set`
- * `Dict`
- * `Union`
- * `Optional`
- * ...এবং অন্যান্য।
+* `Union`
+* `Optional`
+* ...এবং অন্যান্য।
+
+////
+
+//// tab | Python 3.8+
+
+* `List`
+* `Tuple`
+* `Set`
+* `Dict`
+* `Union`
+* `Optional`
+* ...এবং অন্যান্য।
+
+////
### ক্লাস হিসেবে টাইপস
@@ -415,13 +452,13 @@ say_hi(name=None) # এটি কাজ করে, None বৈধ 🎉
ধরুন আপনার কাছে `Person` নামে একটি ক্লাস আছে, যার একটি নাম আছে:
```Python hl_lines="1-3"
-{!../../../docs_src/python_types/tutorial010.py!}
+{!../../docs_src/python_types/tutorial010.py!}
```
তারপর আপনি একটি ভেরিয়েবলকে `Person` টাইপের হিসেবে ঘোষণা করতে পারেন:
```Python hl_lines="6"
-{!../../../docs_src/python_types/tutorial010.py!}
+{!../../docs_src/python_types/tutorial010.py!}
```
এবং তারপর, আবার, আপনি এডিটর সাপোর্ট পেয়ে যাবেন:
@@ -446,55 +483,71 @@ say_hi(name=None) # এটি কাজ করে, None বৈধ 🎉
অফিসিয়াল Pydantic ডক্স থেকে একটি উদাহরণ:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python
- {!> ../../../docs_src/python_types/tutorial011_py310.py!}
- ```
+```Python
+{!> ../../docs_src/python_types/tutorial011_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python
- {!> ../../../docs_src/python_types/tutorial011_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python
+{!> ../../docs_src/python_types/tutorial011_py39.py!}
+```
- ```Python
- {!> ../../../docs_src/python_types/tutorial011.py!}
- ```
+////
-!!! Info
- [Pydantic সম্পর্কে আরও জানতে, এর ডকুমেন্টেশন দেখুন](https://docs.pydantic.dev/)।
+//// tab | Python 3.8+
+
+```Python
+{!> ../../docs_src/python_types/tutorial011.py!}
+```
+
+////
+
+/// info
+
+[Pydantic সম্পর্কে আরও জানতে, এর ডকুমেন্টেশন দেখুন](https://docs.pydantic.dev/)।
+
+///
**FastAPI** মূলত Pydantic-এর উপর নির্মিত।
আপনি এই সমস্ত কিছুর অনেক বাস্তবসম্মত উদাহরণ পাবেন [টিউটোরিয়াল - ইউজার গাইডে](https://fastapi.tiangolo.com/tutorial/)।
-!!! Tip
- যখন আপনি `Optional` বা `Union[Something, None]` ব্যবহার করেন এবং কোনো ডিফল্ট মান না থাকে, Pydantic-এর একটি বিশেষ আচরণ রয়েছে, আপনি Pydantic ডকুমেন্টেশনে [Required Optional fields](https://docs.pydantic.dev/latest/concepts/models/#required-optional-fields) সম্পর্কে আরও পড়তে পারেন।
+/// tip
+
+যখন আপনি `Optional` বা `Union[Something, None]` ব্যবহার করেন এবং কোনো ডিফল্ট মান না থাকে, Pydantic-এর একটি বিশেষ আচরণ রয়েছে, আপনি Pydantic ডকুমেন্টেশনে [Required Optional fields](https://docs.pydantic.dev/latest/concepts/models/#required-optional-fields) সম্পর্কে আরও পড়তে পারেন।
+
+///
## মেটাডাটা অ্যানোটেশন সহ টাইপ হিন্টস
Python-এ এমন একটি ফিচার আছে যা `Annotated` ব্যবহার করে এই টাইপ হিন্টগুলিতে **অতিরিক্ত মেটাডাটা** রাখতে দেয়।
-=== "Python 3.9+"
+//// tab | Python 3.9+
- Python 3.9-এ, `Annotated` স্ট্যান্ডার্ড লাইব্রেরিতে অন্তর্ভুক্ত, তাই আপনি এটি `typing` থেকে ইমপোর্ট করতে পারেন।
+Python 3.9-এ, `Annotated` স্ট্যান্ডার্ড লাইব্রেরিতে অন্তর্ভুক্ত, তাই আপনি এটি `typing` থেকে ইমপোর্ট করতে পারেন।
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial013_py39.py!}
- ```
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial013_py39.py!}
+```
-=== "Python 3.8+"
+////
- Python 3.9-এর নীচের সংস্করণগুলিতে, আপনি `Annotated`-কে `typing_extensions` থেকে ইমপোর্ট করেন।
+//// tab | Python 3.8+
- এটি **FastAPI** এর সাথে ইতিমদ্ধে ইনস্টল হয়ে থাকবে।
+Python 3.9-এর নীচের সংস্করণগুলিতে, আপনি `Annotated`-কে `typing_extensions` থেকে ইমপোর্ট করেন।
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial013.py!}
- ```
+এটি **FastAPI** এর সাথে ইতিমদ্ধে ইনস্টল হয়ে থাকবে।
+
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial013.py!}
+```
+
+////
Python নিজে এই `Annotated` দিয়ে কিছুই করে না। এবং এডিটর এবং অন্যান্য টুলগুলির জন্য, টাইপটি এখনও `str`।
@@ -506,10 +559,13 @@ Python নিজে এই `Annotated` দিয়ে কিছুই করে
পরবর্তীতে আপনি দেখবেন এটি কতটা **শক্তিশালী** হতে পারে।
-!!! Tip
- এটি **স্ট্যান্ডার্ড Python** হওয়ার মানে হল আপনি আপনার এডিটরে, আপনি যে টুলগুলি কোড বিশ্লেষণ এবং রিফ্যাক্টর করার জন্য ব্যবহার করেন তাতে **সেরা সম্ভাব্য ডেভেলপার এক্সপেরিয়েন্স** পাবেন। ✨
+/// tip
- এবং এছাড়াও আপনার কোড অন্যান্য অনেক Python টুল এবং লাইব্রেরিগুলির সাথে খুব সামঞ্জস্যপূর্ণ হবে। 🚀
+এটি **স্ট্যান্ডার্ড Python** হওয়ার মানে হল আপনি আপনার এডিটরে, আপনি যে টুলগুলি কোড বিশ্লেষণ এবং রিফ্যাক্টর করার জন্য ব্যবহার করেন তাতে **সেরা সম্ভাব্য ডেভেলপার এক্সপেরিয়েন্স** পাবেন। ✨
+
+এবং এছাড়াও আপনার কোড অন্যান্য অনেক Python টুল এবং লাইব্রেরিগুলির সাথে খুব সামঞ্জস্যপূর্ণ হবে। 🚀
+
+///
## **FastAPI**-এ টাইপ হিন্টস
@@ -533,5 +589,8 @@ Python নিজে এই `Annotated` দিয়ে কিছুই করে
গুরুত্বপূর্ণ বিষয় হল, আপনি যদি স্ট্যান্ডার্ড Python টাইপগুলি ব্যবহার করেন, তবে আরও বেশি ক্লাস, ডেকোরেটর ইত্যাদি যোগ না করেই একই স্থানে **FastAPI** আপনার অনেক কাজ করে দিবে।
-!!! Info
- যদি আপনি টিউটোরিয়ালের সমস্ত বিষয় পড়ে ফেলে থাকেন এবং টাইপ সম্পর্কে আরও জানতে চান, তবে একটি ভালো রিসোর্স হল [mypy এর "cheat sheet"](https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html)। এই "cheat sheet" এ আপনি Python টাইপ হিন্ট সম্পর্কে বেসিক থেকে উন্নত লেভেলের ধারণা পেতে পারেন, যা আপনার কোডে টাইপ সেফটি এবং স্পষ্টতা বাড়াতে সাহায্য করবে।
+/// info
+
+যদি আপনি টিউটোরিয়ালের সমস্ত বিষয় পড়ে ফেলে থাকেন এবং টাইপ সম্পর্কে আরও জানতে চান, তবে একটি ভালো রিসোর্স হল [mypy এর "cheat sheet"](https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html)। এই "cheat sheet" এ আপনি Python টাইপ হিন্ট সম্পর্কে বেসিক থেকে উন্নত লেভেলের ধারণা পেতে পারেন, যা আপনার কোডে টাইপ সেফটি এবং স্পষ্টতা বাড়াতে সাহায্য করবে।
+
+///
diff --git a/docs/de/docs/advanced/additional-responses.md b/docs/de/docs/advanced/additional-responses.md
index 2bfcfab33..a87c56491 100644
--- a/docs/de/docs/advanced/additional-responses.md
+++ b/docs/de/docs/advanced/additional-responses.md
@@ -1,9 +1,12 @@
# Zusätzliche Responses in OpenAPI
-!!! warning "Achtung"
- Dies ist ein eher fortgeschrittenes Thema.
+/// warning | "Achtung"
- Wenn Sie mit **FastAPI** beginnen, benötigen Sie dies möglicherweise nicht.
+Dies ist ein eher fortgeschrittenes Thema.
+
+Wenn Sie mit **FastAPI** beginnen, benötigen Sie dies möglicherweise nicht.
+
+///
Sie können zusätzliche Responses mit zusätzlichen Statuscodes, Medientypen, Beschreibungen, usw. deklarieren.
@@ -24,23 +27,29 @@ 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!}
```
-!!! note "Hinweis"
- Beachten Sie, dass Sie die `JSONResponse` direkt zurückgeben müssen.
+/// note | "Hinweis"
-!!! info
- Der `model`-Schlüssel ist nicht Teil von OpenAPI.
+Beachten Sie, dass Sie die `JSONResponse` direkt zurückgeben müssen.
- **FastAPI** nimmt das Pydantic-Modell von dort, generiert das JSON-Schema und fügt es an der richtigen Stelle ein.
+///
- Die richtige Stelle ist:
+/// info
- * Im Schlüssel `content`, der als Wert ein weiteres JSON-Objekt (`dict`) hat, welches Folgendes enthält:
- * Ein Schlüssel mit dem Medientyp, z. B. `application/json`, der als Wert ein weiteres JSON-Objekt hat, welches Folgendes enthält:
- * Ein Schlüssel `schema`, der als Wert das JSON-Schema aus dem Modell hat, hier ist die richtige Stelle.
- * **FastAPI** fügt hier eine Referenz auf die globalen JSON-Schemas an einer anderen Stelle in Ihrer OpenAPI hinzu, anstatt es direkt einzubinden. Auf diese Weise können andere Anwendungen und Clients diese JSON-Schemas direkt verwenden, bessere Tools zur Codegenerierung bereitstellen, usw.
+Der `model`-Schlüssel ist nicht Teil von OpenAPI.
+
+**FastAPI** nimmt das Pydantic-Modell von dort, generiert das JSON-Schema und fügt es an der richtigen Stelle ein.
+
+Die richtige Stelle ist:
+
+* Im Schlüssel `content`, der als Wert ein weiteres JSON-Objekt (`dict`) hat, welches Folgendes enthält:
+ * Ein Schlüssel mit dem Medientyp, z. B. `application/json`, der als Wert ein weiteres JSON-Objekt hat, welches Folgendes enthält:
+ * Ein Schlüssel `schema`, der als Wert das JSON-Schema aus dem Modell hat, hier ist die richtige Stelle.
+ * **FastAPI** fügt hier eine Referenz auf die globalen JSON-Schemas an einer anderen Stelle in Ihrer OpenAPI hinzu, anstatt es direkt einzubinden. Auf diese Weise können andere Anwendungen und Clients diese JSON-Schemas direkt verwenden, bessere Tools zur Codegenerierung bereitstellen, usw.
+
+///
Die generierten Responses in der OpenAPI für diese *Pfadoperation* lauten:
@@ -169,16 +178,22 @@ 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!}
```
-!!! note "Hinweis"
- Beachten Sie, dass Sie das Bild direkt mit einer `FileResponse` zurückgeben müssen.
+/// note | "Hinweis"
-!!! info
- Sofern Sie in Ihrem Parameter `responses` nicht explizit einen anderen Medientyp angeben, geht FastAPI davon aus, dass die Response denselben Medientyp wie die Haupt-Response-Klasse hat (Standardmäßig `application/json`).
+Beachten Sie, dass Sie das Bild direkt mit einer `FileResponse` zurückgeben müssen.
- Wenn Sie jedoch eine benutzerdefinierte Response-Klasse mit `None` als Medientyp angegeben haben, verwendet FastAPI `application/json` für jede zusätzliche Response, die über ein zugehöriges Modell verfügt.
+///
+
+/// info
+
+Sofern Sie in Ihrem Parameter `responses` nicht explizit einen anderen Medientyp angeben, geht FastAPI davon aus, dass die Response denselben Medientyp wie die Haupt-Response-Klasse hat (Standardmäßig `application/json`).
+
+Wenn Sie jedoch eine benutzerdefinierte Response-Klasse mit `None` als Medientyp angegeben haben, verwendet FastAPI `application/json` für jede zusätzliche Response, die über ein zugehöriges Modell verfügt.
+
+///
## Informationen kombinieren
@@ -193,7 +208,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!}
```
Es wird alles kombiniert und in Ihre OpenAPI eingebunden und in der API-Dokumentation angezeigt:
@@ -229,7 +244,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!}
```
## Weitere Informationen zu OpenAPI-Responses
diff --git a/docs/de/docs/advanced/additional-status-codes.md b/docs/de/docs/advanced/additional-status-codes.md
index e9de267cf..fc8d09e4c 100644
--- a/docs/de/docs/advanced/additional-status-codes.md
+++ b/docs/de/docs/advanced/additional-status-codes.md
@@ -14,53 +14,75 @@ Sie möchten aber auch, dass sie neue Artikel akzeptiert. Und wenn die Elemente
Um dies zu erreichen, importieren Sie `JSONResponse`, und geben Sie Ihren Inhalt direkt zurück, indem Sie den gewünschten `status_code` setzen:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="4 25"
- {!> ../../../docs_src/additional_status_codes/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="4 25"
+{!> ../../docs_src/additional_status_codes/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="4 25"
- {!> ../../../docs_src/additional_status_codes/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="4 25"
+{!> ../../docs_src/additional_status_codes/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="4 26"
- {!> ../../../docs_src/additional_status_codes/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="4 26"
+{!> ../../docs_src/additional_status_codes/tutorial001_an.py!}
+```
- ```Python hl_lines="2 23"
- {!> ../../../docs_src/additional_status_codes/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="4 25"
- {!> ../../../docs_src/additional_status_codes/tutorial001.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-!!! warning "Achtung"
- Wenn Sie eine `Response` direkt zurückgeben, wie im obigen Beispiel, wird sie direkt zurückgegeben.
+///
- Sie wird nicht mit einem Modell usw. serialisiert.
+```Python hl_lines="2 23"
+{!> ../../docs_src/additional_status_codes/tutorial001_py310.py!}
+```
- Stellen Sie sicher, dass sie die gewünschten Daten enthält und dass die Werte gültiges JSON sind (wenn Sie `JSONResponse` verwenden).
+////
-!!! note "Technische Details"
- Sie können auch `from starlette.responses import JSONResponse` verwenden.
+//// tab | Python 3.8+ nicht annotiert
- **FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. Das Gleiche gilt für `status`.
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="4 25"
+{!> ../../docs_src/additional_status_codes/tutorial001.py!}
+```
+
+////
+
+/// warning | "Achtung"
+
+Wenn Sie eine `Response` direkt zurückgeben, wie im obigen Beispiel, wird sie direkt zurückgegeben.
+
+Sie wird nicht mit einem Modell usw. serialisiert.
+
+Stellen Sie sicher, dass sie die gewünschten Daten enthält und dass die Werte gültiges JSON sind (wenn Sie `JSONResponse` verwenden).
+
+///
+
+/// note | "Technische Details"
+
+Sie können auch `from starlette.responses import JSONResponse` verwenden.
+
+**FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. Das Gleiche gilt für `status`.
+
+///
## OpenAPI- und API-Dokumentation
diff --git a/docs/de/docs/advanced/advanced-dependencies.md b/docs/de/docs/advanced/advanced-dependencies.md
index 33b93b332..54351714e 100644
--- a/docs/de/docs/advanced/advanced-dependencies.md
+++ b/docs/de/docs/advanced/advanced-dependencies.md
@@ -18,26 +18,35 @@ Nicht die Klasse selbst (die bereits aufrufbar ist), sondern eine Instanz dieser
Dazu deklarieren wir eine Methode `__call__`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="12"
- {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
- ```
+```Python hl_lines="12"
+{!> ../../docs_src/dependencies/tutorial011_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="11"
- {!> ../../../docs_src/dependencies/tutorial011_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ nicht annotiert"
+```Python hl_lines="11"
+{!> ../../docs_src/dependencies/tutorial011_an.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/dependencies/tutorial011.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="10"
+{!> ../../docs_src/dependencies/tutorial011.py!}
+```
+
+////
In diesem Fall ist dieses `__call__` das, was **FastAPI** verwendet, um nach zusätzlichen Parametern und Unterabhängigkeiten zu suchen, und das ist es auch, was später aufgerufen wird, um einen Wert an den Parameter in Ihrer *Pfadoperation-Funktion* zu übergeben.
@@ -45,26 +54,35 @@ In diesem Fall ist dieses `__call__` das, was **FastAPI** verwendet, um nach zus
Und jetzt können wir `__init__` verwenden, um die Parameter der Instanz zu deklarieren, die wir zum `Parametrisieren` der Abhängigkeit verwenden können:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="9"
- {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/dependencies/tutorial011_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/dependencies/tutorial011_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ nicht annotiert"
+```Python hl_lines="8"
+{!> ../../docs_src/dependencies/tutorial011_an.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/dependencies/tutorial011.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="7"
+{!> ../../docs_src/dependencies/tutorial011.py!}
+```
+
+////
In diesem Fall wird **FastAPI** `__init__` nie berühren oder sich darum kümmern, wir werden es direkt in unserem Code verwenden.
@@ -72,26 +90,35 @@ In diesem Fall wird **FastAPI** `__init__` nie berühren oder sich darum kümmer
Wir könnten eine Instanz dieser Klasse erstellen mit:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="18"
- {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
- ```
+```Python hl_lines="18"
+{!> ../../docs_src/dependencies/tutorial011_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial011_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ nicht annotiert"
+```Python hl_lines="17"
+{!> ../../docs_src/dependencies/tutorial011_an.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="16"
- {!> ../../../docs_src/dependencies/tutorial011.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="16"
+{!> ../../docs_src/dependencies/tutorial011.py!}
+```
+
+////
Und auf diese Weise können wir unsere Abhängigkeit „parametrisieren“, die jetzt `"bar"` enthält, als das Attribut `checker.fixed_content`.
@@ -107,32 +134,44 @@ checker(q="somequery")
... und übergibt, was immer das als Wert dieser Abhängigkeit in unserer *Pfadoperation-Funktion* zurückgibt, als den Parameter `fixed_content_included`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="22"
- {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
- ```
+```Python hl_lines="22"
+{!> ../../docs_src/dependencies/tutorial011_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="21"
- {!> ../../../docs_src/dependencies/tutorial011_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ nicht annotiert"
+```Python hl_lines="21"
+{!> ../../docs_src/dependencies/tutorial011_an.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="20"
- {!> ../../../docs_src/dependencies/tutorial011.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
-!!! tip "Tipp"
- Das alles mag gekünstelt wirken. Und es ist möglicherweise noch nicht ganz klar, welchen Nutzen das hat.
+/// tip | "Tipp"
- Diese Beispiele sind bewusst einfach gehalten, zeigen aber, wie alles funktioniert.
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- In den Kapiteln zum Thema Sicherheit gibt es Hilfsfunktionen, die auf die gleiche Weise implementiert werden.
+///
- Wenn Sie das hier alles verstanden haben, wissen Sie bereits, wie diese Sicherheits-Hilfswerkzeuge unter der Haube funktionieren.
+```Python hl_lines="20"
+{!> ../../docs_src/dependencies/tutorial011.py!}
+```
+
+////
+
+/// tip | "Tipp"
+
+Das alles mag gekünstelt wirken. Und es ist möglicherweise noch nicht ganz klar, welchen Nutzen das hat.
+
+Diese Beispiele sind bewusst einfach gehalten, zeigen aber, wie alles funktioniert.
+
+In den Kapiteln zum Thema Sicherheit gibt es Hilfsfunktionen, die auf die gleiche Weise implementiert werden.
+
+Wenn Sie das hier alles verstanden haben, wissen Sie bereits, wie diese Sicherheits-Hilfswerkzeuge unter der Haube funktionieren.
+
+///
diff --git a/docs/de/docs/advanced/async-tests.md b/docs/de/docs/advanced/async-tests.md
index 2e2c22210..93ff84b8a 100644
--- a/docs/de/docs/advanced/async-tests.md
+++ b/docs/de/docs/advanced/async-tests.md
@@ -33,13 +33,13 @@ 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
@@ -61,16 +61,19 @@ $ pytest
Der Marker `@pytest.mark.anyio` teilt pytest mit, dass diese Testfunktion asynchron aufgerufen werden soll:
```Python hl_lines="7"
-{!../../../docs_src/async_tests/test_main.py!}
+{!../../docs_src/async_tests/test_main.py!}
```
-!!! tip "Tipp"
- Beachten Sie, dass die Testfunktion jetzt `async def` ist und nicht nur `def` wie zuvor, wenn Sie den `TestClient` verwenden.
+/// tip | "Tipp"
+
+Beachten Sie, dass die Testfunktion jetzt `async def` ist und nicht nur `def` wie zuvor, wenn Sie den `TestClient` verwenden.
+
+///
Dann können wir einen `AsyncClient` mit der App erstellen und mit `await` asynchrone Requests an ihn senden.
-```Python hl_lines="9-10"
-{!../../../docs_src/async_tests/test_main.py!}
+```Python hl_lines="9-12"
+{!../../docs_src/async_tests/test_main.py!}
```
Das ist das Äquivalent zu:
@@ -81,15 +84,24 @@ response = client.get('/')
... welches wir verwendet haben, um unsere Requests mit dem `TestClient` zu machen.
-!!! tip "Tipp"
- Beachten Sie, dass wir async/await mit dem neuen `AsyncClient` verwenden – der Request ist asynchron.
+/// tip | "Tipp"
-!!! 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.
+Beachten Sie, dass wir async/await mit dem neuen `AsyncClient` verwenden – der Request ist asynchron.
+
+///
+
+/// warning | "Achtung"
+
+Falls Ihre Anwendung auf Lifespan-Events angewiesen ist, der `AsyncClient` löst diese Events nicht aus. Um sicherzustellen, dass sie ausgelöst werden, verwenden Sie `LifespanManager` von florimondmanca/asgi-lifespan.
+
+///
## Andere asynchrone Funktionsaufrufe
Da die Testfunktion jetzt asynchron ist, können Sie in Ihren Tests neben dem Senden von Requests an Ihre FastAPI-Anwendung jetzt auch andere `async`hrone Funktionen aufrufen (und `await`en), genau so, wie Sie diese an anderer Stelle in Ihrem Code aufrufen würden.
-!!! tip "Tipp"
- Wenn Sie einen `RuntimeError: Task attached to a different loop` erhalten, wenn Sie asynchrone Funktionsaufrufe in Ihre Tests integrieren (z. B. bei Verwendung von MongoDBs MotorClient), dann denken Sie daran, Objekte zu instanziieren, die einen Event Loop nur innerhalb asynchroner Funktionen benötigen, z. B. einen `@app.on_event("startup")`-Callback.
+/// tip | "Tipp"
+
+Wenn Sie einen `RuntimeError: Task attached to a different loop` erhalten, wenn Sie asynchrone Funktionsaufrufe in Ihre Tests integrieren (z. B. bei Verwendung von MongoDBs MotorClient), dann denken Sie daran, Objekte zu instanziieren, die einen Event Loop nur innerhalb asynchroner Funktionen benötigen, z. B. einen `@app.on_event("startup")`-Callback.
+
+///
diff --git a/docs/de/docs/advanced/behind-a-proxy.md b/docs/de/docs/advanced/behind-a-proxy.md
index ad0a92e28..74b25308a 100644
--- a/docs/de/docs/advanced/behind-a-proxy.md
+++ b/docs/de/docs/advanced/behind-a-proxy.md
@@ -19,7 +19,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!}
```
Und der Proxy würde das **Pfadpräfix** on-the-fly **"entfernen**", bevor er die Anfrage an Uvicorn übermittelt, dafür sorgend, dass Ihre Anwendung davon überzeugt ist, dass sie unter `/app` bereitgestellt wird, sodass Sie nicht Ihren gesamten Code dahingehend aktualisieren müssen, das Präfix `/api/v1` zu verwenden.
@@ -43,8 +43,11 @@ browser --> proxy
proxy --> server
```
-!!! tip "Tipp"
- Die IP `0.0.0.0` wird üblicherweise verwendet, um anzudeuten, dass das Programm alle auf diesem Computer/Server verfügbaren IPs abhört.
+/// tip | "Tipp"
+
+Die IP `0.0.0.0` wird üblicherweise verwendet, um anzudeuten, dass das Programm alle auf diesem Computer/Server verfügbaren IPs abhört.
+
+///
Die Benutzeroberfläche der Dokumentation würde benötigen, dass das OpenAPI-Schema deklariert, dass sich dieser API-`server` unter `/api/v1` (hinter dem Proxy) befindet. Zum Beispiel:
@@ -81,10 +84,13 @@ $ uvicorn main:app --root-path /api/v1
Falls Sie Hypercorn verwenden, das hat auch die Option `--root-path`.
-!!! note "Technische Details"
- Die ASGI-Spezifikation definiert einen `root_path` für diesen Anwendungsfall.
+/// note | "Technische Details"
- Und die Kommandozeilenoption `--root-path` stellt diesen `root_path` bereit.
+Die ASGI-Spezifikation definiert einen `root_path` für diesen Anwendungsfall.
+
+Und die Kommandozeilenoption `--root-path` stellt diesen `root_path` bereit.
+
+///
### Überprüfen des aktuellen `root_path`
@@ -93,7 +99,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!}
```
Wenn Sie Uvicorn dann starten mit:
@@ -122,7 +128,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!}
```
Die Übergabe des `root_path` an `FastAPI` wäre das Äquivalent zur Übergabe der `--root-path`-Kommandozeilenoption an Uvicorn oder Hypercorn.
@@ -172,8 +178,11 @@ Dann erstellen Sie eine Datei `traefik.toml` mit:
Dadurch wird Traefik angewiesen, Port 9999 abzuhören und eine andere Datei `routes.toml` zu verwenden.
-!!! tip "Tipp"
- Wir verwenden Port 9999 anstelle des Standard-HTTP-Ports 80, damit Sie ihn nicht mit Administratorrechten (`sudo`) ausführen müssen.
+/// tip | "Tipp"
+
+Wir verwenden Port 9999 anstelle des Standard-HTTP-Ports 80, damit Sie ihn nicht mit Administratorrechten (`sudo`) ausführen müssen.
+
+///
Erstellen Sie nun die andere Datei `routes.toml`:
@@ -239,8 +248,11 @@ Wenn Sie nun zur URL mit dem Port für Uvicorn gehen: http://127.0.0.1:9999/api/v1/app.
@@ -283,8 +295,11 @@ Dies liegt daran, dass FastAPI diesen `root_path` verwendet, um den Default-`ser
## Zusätzliche Server
-!!! warning "Achtung"
- Dies ist ein fortgeschrittener Anwendungsfall. Überspringen Sie das gerne.
+/// warning | "Achtung"
+
+Dies ist ein fortgeschrittener Anwendungsfall. Überspringen Sie das gerne.
+
+///
Standardmäßig erstellt **FastAPI** einen `server` im OpenAPI-Schema mit der URL für den `root_path`.
@@ -295,7 +310,7 @@ Wenn Sie eine benutzerdefinierte Liste von Servern (`servers`) übergeben und es
Zum Beispiel:
```Python hl_lines="4-7"
-{!../../../docs_src/behind_a_proxy/tutorial003.py!}
+{!../../docs_src/behind_a_proxy/tutorial003.py!}
```
Erzeugt ein OpenAPI-Schema, wie:
@@ -323,22 +338,28 @@ Erzeugt ein OpenAPI-Schema, wie:
}
```
-!!! tip "Tipp"
- Beachten Sie den automatisch generierten Server mit dem `URL`-Wert `/api/v1`, welcher vom `root_path` stammt.
+/// tip | "Tipp"
+
+Beachten Sie den automatisch generierten Server mit dem `URL`-Wert `/api/v1`, welcher vom `root_path` stammt.
+
+///
In der Dokumentationsoberfläche unter http://127.0.0.1:9999/api/v1/docs würde es so aussehen:
-!!! tip "Tipp"
- Die Dokumentationsoberfläche interagiert mit dem von Ihnen ausgewählten Server.
+/// tip | "Tipp"
+
+Die Dokumentationsoberfläche interagiert mit dem von Ihnen ausgewählten Server.
+
+///
### Den automatischen Server von `root_path` deaktivieren
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!}
```
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 68c037ad7..357d2c562 100644
--- a/docs/de/docs/advanced/custom-response.md
+++ b/docs/de/docs/advanced/custom-response.md
@@ -12,8 +12,11 @@ Der Inhalt, den Sie von Ihrer *Pfadoperation-Funktion* zurückgeben, wird in die
Und wenn diese `Response` einen JSON-Medientyp (`application/json`) hat, wie es bei `JSONResponse` und `UJSONResponse` der Fall ist, werden die von Ihnen zurückgegebenen Daten automatisch mit jedem Pydantic `response_model` konvertiert (und gefiltert), das Sie im *Pfadoperation-Dekorator* deklariert haben.
-!!! note "Hinweis"
- Wenn Sie eine Response-Klasse ohne Medientyp verwenden, erwartet FastAPI, dass Ihre Response keinen Inhalt hat, und dokumentiert daher das Format der Response nicht in deren generierter OpenAPI-Dokumentation.
+/// note | "Hinweis"
+
+Wenn Sie eine Response-Klasse ohne Medientyp verwenden, erwartet FastAPI, dass Ihre Response keinen Inhalt hat, und dokumentiert daher das Format der Response nicht in deren generierter OpenAPI-Dokumentation.
+
+///
## `ORJSONResponse` verwenden
@@ -28,18 +31,24 @@ 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!}
```
-!!! info
- Der Parameter `response_class` wird auch verwendet, um den „Medientyp“ der Response zu definieren.
+/// info
- In diesem Fall wird der HTTP-Header `Content-Type` auf `application/json` gesetzt.
+Der Parameter `response_class` wird auch verwendet, um den „Medientyp“ der Response zu definieren.
- Und er wird als solcher in OpenAPI dokumentiert.
+In diesem Fall wird der HTTP-Header `Content-Type` auf `application/json` gesetzt.
-!!! tip "Tipp"
- Die `ORJSONResponse` ist derzeit nur in FastAPI verfügbar, nicht in Starlette.
+Und er wird als solcher in OpenAPI dokumentiert.
+
+///
+
+/// tip | "Tipp"
+
+Die `ORJSONResponse` ist derzeit nur in FastAPI verfügbar, nicht in Starlette.
+
+///
## HTML-Response
@@ -49,15 +58,18 @@ Um eine Response mit HTML direkt von **FastAPI** zurückzugeben, verwenden Sie `
* Ü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!}
```
-!!! info
- Der Parameter `response_class` wird auch verwendet, um den „Medientyp“ der Response zu definieren.
+/// info
- In diesem Fall wird der HTTP-Header `Content-Type` auf `text/html` gesetzt.
+Der Parameter `response_class` wird auch verwendet, um den „Medientyp“ der Response zu definieren.
- Und er wird als solcher in OpenAPI dokumentiert.
+In diesem Fall wird der HTTP-Header `Content-Type` auf `text/html` gesetzt.
+
+Und er wird als solcher in OpenAPI dokumentiert.
+
+///
### Eine `Response` zurückgeben
@@ -66,14 +78,20 @@ 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!}
```
-!!! warning "Achtung"
- Eine `Response`, die direkt von Ihrer *Pfadoperation-Funktion* zurückgegeben wird, wird in OpenAPI nicht dokumentiert (zum Beispiel wird der `Content-Type` nicht dokumentiert) und ist in der automatischen interaktiven Dokumentation nicht sichtbar.
+/// warning | "Achtung"
-!!! info
- Natürlich stammen der eigentliche `Content-Type`-Header, der Statuscode, usw., aus dem `Response`-Objekt, das Sie zurückgegeben haben.
+Eine `Response`, die direkt von Ihrer *Pfadoperation-Funktion* zurückgegeben wird, wird in OpenAPI nicht dokumentiert (zum Beispiel wird der `Content-Type` nicht dokumentiert) und ist in der automatischen interaktiven Dokumentation nicht sichtbar.
+
+///
+
+/// info
+
+Natürlich stammen der eigentliche `Content-Type`-Header, der Statuscode, usw., aus dem `Response`-Objekt, das Sie zurückgegeben haben.
+
+///
### In OpenAPI dokumentieren und `Response` überschreiben
@@ -86,7 +104,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!}
```
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.
@@ -103,10 +121,13 @@ Hier sind einige der verfügbaren Responses.
Bedenken Sie, dass Sie `Response` verwenden können, um alles andere zurückzugeben, oder sogar eine benutzerdefinierte Unterklasse zu erstellen.
-!!! note "Technische Details"
- Sie können auch `from starlette.responses import HTMLResponse` verwenden.
+/// note | "Technische Details"
- **FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette.
+Sie können auch `from starlette.responses import HTMLResponse` verwenden.
+
+**FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette.
+
+///
### `Response`
@@ -124,7 +145,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!}
```
### `HTMLResponse`
@@ -136,7 +157,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!}
```
### `JSONResponse`
@@ -153,15 +174,21 @@ Eine schnelle alternative JSON-Response mit `ujson`.
-!!! warning "Achtung"
- `ujson` ist bei der Behandlung einiger Sonderfälle weniger sorgfältig als Pythons eingebaute Implementierung.
+/// warning | "Achtung"
+
+`ujson` ist bei der Behandlung einiger Sonderfälle weniger sorgfältig als Pythons eingebaute Implementierung.
+
+///
```Python hl_lines="2 7"
-{!../../../docs_src/custom_response/tutorial001.py!}
+{!../../docs_src/custom_response/tutorial001.py!}
```
-!!! tip "Tipp"
- Möglicherweise ist `ORJSONResponse` eine schnellere Alternative.
+/// tip | "Tipp"
+
+Möglicherweise ist `ORJSONResponse` eine schnellere Alternative.
+
+///
### `RedirectResponse`
@@ -170,7 +197,7 @@ 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!}
```
---
@@ -179,7 +206,7 @@ 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!}
```
Wenn Sie das tun, können Sie die URL direkt von Ihrer *Pfadoperation*-Funktion zurückgeben.
@@ -191,7 +218,7 @@ 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!}
```
### `StreamingResponse`
@@ -199,7 +226,7 @@ Sie können den Parameter `status_code` auch in Kombination mit dem Parameter `r
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!}
```
#### Verwendung von `StreamingResponse` mit dateiähnlichen Objekten
@@ -211,7 +238,7 @@ Auf diese Weise müssen Sie nicht alles zuerst in den Arbeitsspeicher lesen und
Das umfasst viele Bibliotheken zur Interaktion mit Cloud-Speicher, Videoverarbeitung und anderen.
```{ .python .annotate hl_lines="2 10-12 14" }
-{!../../../docs_src/custom_response/tutorial008.py!}
+{!../../docs_src/custom_response/tutorial008.py!}
```
1. Das ist die Generatorfunktion. Es handelt sich um eine „Generatorfunktion“, da sie `yield`-Anweisungen enthält.
@@ -222,8 +249,11 @@ Das umfasst viele Bibliotheken zur Interaktion mit Cloud-Speicher, Videoverarbei
Auf diese Weise können wir das Ganze in einen `with`-Block einfügen und so sicherstellen, dass das dateiartige Objekt nach Abschluss geschlossen wird.
-!!! tip "Tipp"
- Beachten Sie, dass wir, da wir Standard-`open()` verwenden, welches `async` und `await` nicht unterstützt, hier die Pfadoperation mit normalen `def` deklarieren.
+/// tip | "Tipp"
+
+Beachten Sie, dass wir, da wir Standard-`open()` verwenden, welches `async` und `await` nicht unterstützt, hier die Pfadoperation mit normalen `def` deklarieren.
+
+///
### `FileResponse`
@@ -239,13 +269,13 @@ 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!}
```
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!}
```
In diesem Fall können Sie den Dateipfad direkt von Ihrer *Pfadoperation*-Funktion zurückgeben.
@@ -261,7 +291,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!}
```
Statt:
@@ -289,11 +319,14 @@ 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!}
```
-!!! tip "Tipp"
- Sie können dennoch weiterhin `response_class` in *Pfadoperationen* überschreiben, wie bisher.
+/// tip | "Tipp"
+
+Sie können dennoch weiterhin `response_class` in *Pfadoperationen* überschreiben, wie bisher.
+
+///
## Zusätzliche Dokumentation
diff --git a/docs/de/docs/advanced/dataclasses.md b/docs/de/docs/advanced/dataclasses.md
index c78a6d3dd..573f500e8 100644
--- a/docs/de/docs/advanced/dataclasses.md
+++ b/docs/de/docs/advanced/dataclasses.md
@@ -5,7 +5,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!}
```
Das ist dank **Pydantic** ebenfalls möglich, da es `dataclasses` intern unterstützt.
@@ -20,19 +20,22 @@ Und natürlich wird das gleiche unterstützt:
Das funktioniert genauso wie mit Pydantic-Modellen. Und tatsächlich wird es unter der Haube mittels Pydantic auf die gleiche Weise bewerkstelligt.
-!!! info
- Bedenken Sie, dass Datenklassen nicht alles können, was Pydantic-Modelle können.
+/// info
- Daher müssen Sie möglicherweise weiterhin Pydantic-Modelle verwenden.
+Bedenken Sie, dass Datenklassen nicht alles können, was Pydantic-Modelle können.
- Wenn Sie jedoch eine Menge Datenklassen herumliegen haben, ist dies ein guter Trick, um sie für eine Web-API mithilfe von FastAPI zu verwenden. 🤓
+Daher müssen Sie möglicherweise weiterhin Pydantic-Modelle verwenden.
+
+Wenn Sie jedoch eine Menge Datenklassen herumliegen haben, ist dies ein guter Trick, um sie für eine Web-API mithilfe von FastAPI zu verwenden. 🤓
+
+///
## Datenklassen als `response_model`
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!}
```
Die Datenklasse wird automatisch in eine Pydantic-Datenklasse konvertiert.
@@ -50,7 +53,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!}
```
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 e29f61ab9..b0c4d3922 100644
--- a/docs/de/docs/advanced/events.md
+++ b/docs/de/docs/advanced/events.md
@@ -31,24 +31,27 @@ 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!}
```
Hier simulieren wir das langsame *Hochfahren*, das Laden des Modells, indem wir die (Fake-)Modellfunktion vor dem `yield` in das Dictionary mit Modellen für maschinelles Lernen einfügen. Dieser Code wird ausgeführt, **bevor** die Anwendung **beginnt, Requests entgegenzunehmen**, während des *Hochfahrens*.
Und dann, direkt nach dem `yield`, entladen wir das Modell. Dieser Code wird unmittelbar vor dem *Herunterfahren* ausgeführt, **nachdem** die Anwendung **die Bearbeitung von Requests abgeschlossen hat**. Dadurch könnten beispielsweise Ressourcen wie Arbeitsspeicher oder eine GPU freigegeben werden.
-!!! tip "Tipp"
- Das *Herunterfahren* würde erfolgen, wenn Sie die Anwendung **stoppen**.
+/// tip | "Tipp"
- Möglicherweise müssen Sie eine neue Version starten, oder Sie haben es einfach satt, sie auszuführen. 🤷
+Das *Herunterfahren* würde erfolgen, wenn Sie die Anwendung **stoppen**.
+
+Möglicherweise müssen Sie eine neue Version starten, oder Sie haben es einfach satt, sie auszuführen. 🤷
+
+///
### Lifespan-Funktion
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!}
```
Der erste Teil der Funktion, vor dem `yield`, wird ausgeführt **bevor** die Anwendung startet.
@@ -62,7 +65,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!}
```
Ein **Kontextmanager** in Python ist etwas, das Sie in einer `with`-Anweisung verwenden können, zum Beispiel kann `open()` als Kontextmanager verwendet werden:
@@ -86,15 +89,18 @@ 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!}
```
## Alternative Events (deprecated)
-!!! warning "Achtung"
- Der empfohlene Weg, das *Hochfahren* und *Herunterfahren* zu handhaben, ist die Verwendung des `lifespan`-Parameters der `FastAPI`-App, wie oben beschrieben. Wenn Sie einen `lifespan`-Parameter übergeben, werden die `startup`- und `shutdown`-Eventhandler nicht mehr aufgerufen. Es ist entweder alles `lifespan` oder alles Events, nicht beides.
+/// warning | "Achtung"
- Sie können diesen Teil wahrscheinlich überspringen.
+Der empfohlene Weg, das *Hochfahren* und *Herunterfahren* zu handhaben, ist die Verwendung des `lifespan`-Parameters der `FastAPI`-App, wie oben beschrieben. Wenn Sie einen `lifespan`-Parameter übergeben, werden die `startup`- und `shutdown`-Eventhandler nicht mehr aufgerufen. Es ist entweder alles `lifespan` oder alles Events, nicht beides.
+
+Sie können diesen Teil wahrscheinlich überspringen.
+
+///
Es gibt eine alternative Möglichkeit, diese Logik zu definieren, sodass sie beim *Hochfahren* und beim *Herunterfahren* ausgeführt wird.
@@ -107,7 +113,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!}
```
In diesem Fall initialisiert die Eventhandler-Funktion `startup` die „Datenbank“ der Items (nur ein `dict`) mit einigen Werten.
@@ -121,22 +127,28 @@ 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!}
```
Hier schreibt die `shutdown`-Eventhandler-Funktion eine Textzeile `"Application shutdown"` in eine Datei `log.txt`.
-!!! info
- In der Funktion `open()` bedeutet `mode="a"` „append“ („anhängen“), sodass die Zeile nach dem, was sich in dieser Datei befindet, hinzugefügt wird, ohne den vorherigen Inhalt zu überschreiben.
+/// info
-!!! tip "Tipp"
- Beachten Sie, dass wir in diesem Fall eine Standard-Python-Funktion `open()` verwenden, die mit einer Datei interagiert.
+In der Funktion `open()` bedeutet `mode="a"` „append“ („anhängen“), sodass die Zeile nach dem, was sich in dieser Datei befindet, hinzugefügt wird, ohne den vorherigen Inhalt zu überschreiben.
- Es handelt sich also um I/O (Input/Output), welches „Warten“ erfordert, bis Dinge auf die Festplatte geschrieben werden.
+///
- Aber `open()` verwendet nicht `async` und `await`.
+/// tip | "Tipp"
- Daher deklarieren wir die Eventhandler-Funktion mit Standard-`def` statt mit `async def`.
+Beachten Sie, dass wir in diesem Fall eine Standard-Python-Funktion `open()` verwenden, die mit einer Datei interagiert.
+
+Es handelt sich also um I/O (Input/Output), welches „Warten“ erfordert, bis Dinge auf die Festplatte geschrieben werden.
+
+Aber `open()` verwendet nicht `async` und `await`.
+
+Daher deklarieren wir die Eventhandler-Funktion mit Standard-`def` statt mit `async def`.
+
+///
### `startup` und `shutdown` zusammen
@@ -152,10 +164,13 @@ Nur ein technisches Detail für die neugierigen Nerds. 🤓
In der technischen ASGI-Spezifikation ist dies Teil des Lifespan Protokolls und definiert Events namens `startup` und `shutdown`.
-!!! info
- Weitere Informationen zu Starlettes `lifespan`-Handlern finden Sie in Starlettes Lifespan-Dokumentation.
+/// info
- Einschließlich, wie man Lifespan-Zustand handhabt, der in anderen Bereichen Ihres Codes verwendet werden kann.
+Weitere Informationen zu Starlettes `lifespan`-Handlern finden Sie in Starlettes Lifespan-Dokumentation.
+
+Einschließlich, wie man Lifespan-Zustand handhabt, der in anderen Bereichen Ihres Codes verwendet werden kann.
+
+///
## Unteranwendungen
diff --git a/docs/de/docs/advanced/generate-clients.md b/docs/de/docs/advanced/generate-clients.md
index d69437954..80c44b3f9 100644
--- a/docs/de/docs/advanced/generate-clients.md
+++ b/docs/de/docs/advanced/generate-clients.md
@@ -28,17 +28,21 @@ Es gibt auch mehrere andere Unternehmen, welche ähnliche Dienste anbieten und d
Beginnen wir mit einer einfachen FastAPI-Anwendung:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="7-9 12-13 16-17 21"
- {!> ../../../docs_src/generate_clients/tutorial001_py39.py!}
- ```
+```Python hl_lines="7-9 12-13 16-17 21"
+{!> ../../docs_src/generate_clients/tutorial001_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9-11 14-15 18 19 23"
- {!> ../../../docs_src/generate_clients/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="9-11 14-15 18 19 23"
+{!> ../../docs_src/generate_clients/tutorial001.py!}
+```
+
+////
Beachten Sie, dass die *Pfadoperationen* die Modelle definieren, welche diese für die Request- und Response-Payload verwenden, indem sie die Modelle `Item` und `ResponseMessage` verwenden.
@@ -123,8 +127,11 @@ Sie erhalten außerdem automatische Vervollständigung für die zu sendende Payl
-!!! tip "Tipp"
- Beachten Sie die automatische Vervollständigung für `name` und `price`, welche in der FastAPI-Anwendung im `Item`-Modell definiert wurden.
+/// tip | "Tipp"
+
+Beachten Sie die automatische Vervollständigung für `name` und `price`, welche in der FastAPI-Anwendung im `Item`-Modell definiert wurden.
+
+///
Sie erhalten Inline-Fehlerberichte für die von Ihnen gesendeten Daten:
@@ -140,17 +147,21 @@ In vielen Fällen wird Ihre FastAPI-Anwendung größer sein und Sie werden wahrs
Beispielsweise könnten Sie einen Abschnitt für **Items (Artikel)** und einen weiteren Abschnitt für **Users (Benutzer)** haben, und diese könnten durch Tags getrennt sein:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="21 26 34"
- {!> ../../../docs_src/generate_clients/tutorial002_py39.py!}
- ```
+```Python hl_lines="21 26 34"
+{!> ../../docs_src/generate_clients/tutorial002_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="23 28 36"
- {!> ../../../docs_src/generate_clients/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="23 28 36"
+{!> ../../docs_src/generate_clients/tutorial002.py!}
+```
+
+////
### Einen TypeScript-Client mit Tags generieren
@@ -197,17 +208,21 @@ Hier verwendet sie beispielsweise den ersten Tag (Sie werden wahrscheinlich nur
Anschließend können Sie diese benutzerdefinierte Funktion als Parameter `generate_unique_id_function` an **FastAPI** übergeben:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="6-7 10"
- {!> ../../../docs_src/generate_clients/tutorial003_py39.py!}
- ```
+```Python hl_lines="6-7 10"
+{!> ../../docs_src/generate_clients/tutorial003_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="8-9 12"
- {!> ../../../docs_src/generate_clients/tutorial003.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="8-9 12"
+{!> ../../docs_src/generate_clients/tutorial003.py!}
+```
+
+////
### Einen TypeScript-Client mit benutzerdefinierten Operation-IDs generieren
@@ -229,17 +244,21 @@ Aber für den generierten Client könnten wir die OpenAPI-Operation-IDs direkt v
Wir könnten das OpenAPI-JSON in eine Datei `openapi.json` herunterladen und dann mit einem Skript wie dem folgenden **den vorangestellten Tag entfernen**:
-=== "Python"
+//// tab | Python
- ```Python
- {!> ../../../docs_src/generate_clients/tutorial004.py!}
- ```
+```Python
+{!> ../../docs_src/generate_clients/tutorial004.py!}
+```
-=== "Node.js"
+////
- ```Javascript
- {!> ../../../docs_src/generate_clients/tutorial004.js!}
- ```
+//// tab | Node.js
+
+```Javascript
+{!> ../../docs_src/generate_clients/tutorial004.js!}
+```
+
+////
Damit würden die Operation-IDs von Dingen wie `items-get_items` in `get_items` umbenannt, sodass der Client-Generator einfachere Methodennamen generieren kann.
diff --git a/docs/de/docs/advanced/index.md b/docs/de/docs/advanced/index.md
index 048e31e06..953ad317d 100644
--- a/docs/de/docs/advanced/index.md
+++ b/docs/de/docs/advanced/index.md
@@ -6,10 +6,13 @@ Das Haupt-[Tutorial – Benutzerhandbuch](../tutorial/index.md){.internal-link t
In den nächsten Abschnitten sehen Sie weitere Optionen, Konfigurationen und zusätzliche Funktionen.
-!!! tip "Tipp"
- Die nächsten Abschnitte sind **nicht unbedingt „fortgeschritten“**.
+/// tip | "Tipp"
- Und es ist möglich, dass für Ihren Anwendungsfall die Lösung in einem davon liegt.
+Die nächsten Abschnitte sind **nicht unbedingt „fortgeschritten“**.
+
+Und es ist möglich, dass für Ihren Anwendungsfall die Lösung in einem davon liegt.
+
+///
## Lesen Sie zuerst das Tutorial
diff --git a/docs/de/docs/advanced/middleware.md b/docs/de/docs/advanced/middleware.md
index 2c4e8542a..b4001efda 100644
--- a/docs/de/docs/advanced/middleware.md
+++ b/docs/de/docs/advanced/middleware.md
@@ -43,10 +43,13 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow")
**FastAPI** enthält mehrere Middlewares für gängige Anwendungsfälle. Wir werden als Nächstes sehen, wie man sie verwendet.
-!!! note "Technische Details"
- Für die nächsten Beispiele könnten Sie auch `from starlette.middleware.something import SomethingMiddleware` verwenden.
+/// note | "Technische Details"
- **FastAPI** bietet mehrere Middlewares via `fastapi.middleware` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Middlewares kommen aber direkt von Starlette.
+Für die nächsten Beispiele könnten Sie auch `from starlette.middleware.something import SomethingMiddleware` verwenden.
+
+**FastAPI** bietet mehrere Middlewares via `fastapi.middleware` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Middlewares kommen aber direkt von Starlette.
+
+///
## `HTTPSRedirectMiddleware`
@@ -55,7 +58,7 @@ 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!}
```
## `TrustedHostMiddleware`
@@ -63,7 +66,7 @@ Alle eingehenden Requests an `http` oder `ws` werden stattdessen an das sichere
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!}
```
Die folgenden Argumente werden unterstützt:
@@ -79,7 +82,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!}
```
Die folgenden Argumente werden unterstützt:
@@ -92,7 +95,6 @@ Es gibt viele andere ASGI-Middlewares.
Zum Beispiel:
-* Sentry
* Uvicorns `ProxyHeadersMiddleware`
* MessagePack
diff --git a/docs/de/docs/advanced/openapi-callbacks.md b/docs/de/docs/advanced/openapi-callbacks.md
index 026fdb4fe..f407d5450 100644
--- a/docs/de/docs/advanced/openapi-callbacks.md
+++ b/docs/de/docs/advanced/openapi-callbacks.md
@@ -32,11 +32,14 @@ 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!}
```
-!!! tip "Tipp"
- Der Query-Parameter `callback_url` verwendet einen Pydantic-Url-Typ.
+/// tip | "Tipp"
+
+Der Query-Parameter `callback_url` verwendet einen Pydantic-Url-Typ.
+
+///
Das einzig Neue ist `callbacks=invoices_callback_router.routes` als Argument für den *Pfadoperation-Dekorator*. Wir werden als Nächstes sehen, was das ist.
@@ -61,10 +64,13 @@ Diese Dokumentation wird in der Swagger-Oberfläche unter `/docs` in Ihrer API a
In diesem Beispiel wird nicht der Callback selbst implementiert (das könnte nur eine Codezeile sein), sondern nur der Dokumentationsteil.
-!!! tip "Tipp"
- Der eigentliche Callback ist nur ein HTTP-Request.
+/// tip | "Tipp"
- Wenn Sie den Callback selbst implementieren, können Sie beispielsweise HTTPX oder Requests verwenden.
+Der eigentliche Callback ist nur ein HTTP-Request.
+
+Wenn Sie den Callback selbst implementieren, können Sie beispielsweise HTTPX oder Requests verwenden.
+
+///
## Schreiben des Codes, der den Callback dokumentiert
@@ -74,17 +80,20 @@ Sie wissen jedoch bereits, wie Sie mit **FastAPI** ganz einfach eine automatisch
Daher werden wir dasselbe Wissen nutzen, um zu dokumentieren, wie die *externe API* aussehen sollte ... indem wir die *Pfadoperation(en)* erstellen, welche die externe API implementieren soll (die, welche Ihre API aufruft).
-!!! tip "Tipp"
- Wenn Sie den Code zum Dokumentieren eines Callbacks schreiben, kann es hilfreich sein, sich vorzustellen, dass Sie dieser *externe Entwickler* sind. Und dass Sie derzeit die *externe API* implementieren, nicht *Ihre API*.
+/// tip | "Tipp"
- Wenn Sie diese Sichtweise (des *externen Entwicklers*) vorübergehend übernehmen, wird es offensichtlicher, wo die Parameter, das Pydantic-Modell für den Body, die Response, usw. für diese *externe API* hingehören.
+Wenn Sie den Code zum Dokumentieren eines Callbacks schreiben, kann es hilfreich sein, sich vorzustellen, dass Sie dieser *externe Entwickler* sind. Und dass Sie derzeit die *externe API* implementieren, nicht *Ihre API*.
+
+Wenn Sie diese Sichtweise (des *externen Entwicklers*) vorübergehend übernehmen, wird es offensichtlicher, wo die Parameter, das Pydantic-Modell für den Body, die Response, usw. für diese *externe API* hingehören.
+
+///
### Einen Callback-`APIRouter` erstellen
Erstellen Sie zunächst einen neuen `APIRouter`, der einen oder mehrere Callbacks enthält.
```Python hl_lines="3 25"
-{!../../../docs_src/openapi_callbacks/tutorial001.py!}
+{!../../docs_src/openapi_callbacks/tutorial001.py!}
```
### Die Callback-*Pfadoperation* erstellen
@@ -97,7 +106,7 @@ Sie sollte wie eine normale FastAPI-*Pfadoperation* aussehen:
* 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!}
```
Es gibt zwei Hauptunterschiede zu einer normalen *Pfadoperation*:
@@ -154,8 +163,11 @@ und sie würde eine Response von dieser *externen API* mit einem JSON-Body wie d
}
```
-!!! tip "Tipp"
- Beachten Sie, dass die verwendete Callback-URL die URL enthält, die als Query-Parameter in `callback_url` (`https://www.external.org/events`) empfangen wurde, und auch die Rechnungs-`id` aus dem JSON-Body (`2expen51ve`).
+/// tip | "Tipp"
+
+Beachten Sie, dass die verwendete Callback-URL die URL enthält, die als Query-Parameter in `callback_url` (`https://www.external.org/events`) empfangen wurde, und auch die Rechnungs-`id` aus dem JSON-Body (`2expen51ve`).
+
+///
### Den Callback-Router hinzufügen
@@ -164,11 +176,14 @@ 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!}
```
-!!! tip "Tipp"
- Beachten Sie, dass Sie nicht den Router selbst (`invoices_callback_router`) an `callback=` übergeben, sondern das Attribut `.routes`, wie in `invoices_callback_router.routes`.
+/// tip | "Tipp"
+
+Beachten Sie, dass Sie nicht den Router selbst (`invoices_callback_router`) an `callback=` übergeben, sondern das Attribut `.routes`, wie in `invoices_callback_router.routes`.
+
+///
### Es in der Dokumentation ansehen
diff --git a/docs/de/docs/advanced/openapi-webhooks.md b/docs/de/docs/advanced/openapi-webhooks.md
index 339218080..9f1bb6959 100644
--- a/docs/de/docs/advanced/openapi-webhooks.md
+++ b/docs/de/docs/advanced/openapi-webhooks.md
@@ -22,21 +22,27 @@ Mit **FastAPI** können Sie mithilfe von OpenAPI die Namen dieser Webhooks, die
Dies kann es Ihren Benutzern viel einfacher machen, **deren APIs zu implementieren**, um Ihre **Webhook**-Requests zu empfangen. Möglicherweise können diese sogar einen Teil des eigenem API-Codes automatisch generieren.
-!!! info
- Webhooks sind in OpenAPI 3.1.0 und höher verfügbar und werden von FastAPI `0.99.0` und höher unterstützt.
+/// info
+
+Webhooks sind in OpenAPI 3.1.0 und höher verfügbar und werden von FastAPI `0.99.0` und höher unterstützt.
+
+///
## Eine Anwendung mit Webhooks
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!}
```
Die von Ihnen definierten Webhooks landen im **OpenAPI**-Schema und der automatischen **Dokumentations-Oberfläche**.
-!!! info
- Das `app.webhooks`-Objekt ist eigentlich nur ein `APIRouter`, derselbe Typ, den Sie verwenden würden, wenn Sie Ihre Anwendung mit mehreren Dateien strukturieren.
+/// info
+
+Das `app.webhooks`-Objekt ist eigentlich nur ein `APIRouter`, derselbe Typ, den Sie verwenden würden, wenn Sie Ihre Anwendung mit mehreren Dateien strukturieren.
+
+///
Beachten Sie, dass Sie bei Webhooks tatsächlich keinen *Pfad* (wie `/items/`) deklarieren, sondern dass der Text, den Sie dort übergeben, lediglich eine **Kennzeichnung** des Webhooks (der Name des Events) ist. Zum Beispiel ist in `@app.webhooks.post("new-subscription")` der Webhook-Name `new-subscription`.
diff --git a/docs/de/docs/advanced/path-operation-advanced-configuration.md b/docs/de/docs/advanced/path-operation-advanced-configuration.md
index 406a08e9e..2d8b88be5 100644
--- a/docs/de/docs/advanced/path-operation-advanced-configuration.md
+++ b/docs/de/docs/advanced/path-operation-advanced-configuration.md
@@ -2,15 +2,18 @@
## OpenAPI operationId
-!!! warning "Achtung"
- Wenn Sie kein „Experte“ für OpenAPI sind, brauchen Sie dies wahrscheinlich nicht.
+/// warning | "Achtung"
+
+Wenn Sie kein „Experte“ für OpenAPI sind, brauchen Sie dies wahrscheinlich nicht.
+
+///
Mit dem Parameter `operation_id` können Sie die OpenAPI `operationId` festlegen, die in Ihrer *Pfadoperation* verwendet werden soll.
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!}
```
### Verwendung des Namens der *Pfadoperation-Funktion* als operationId
@@ -20,23 +23,29 @@ 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!}
```
-!!! tip "Tipp"
- Wenn Sie `app.openapi()` manuell aufrufen, sollten Sie vorher die `operationId`s aktualisiert haben.
+/// tip | "Tipp"
-!!! warning "Achtung"
- Wenn Sie dies tun, müssen Sie sicherstellen, dass jede Ihrer *Pfadoperation-Funktionen* einen eindeutigen Namen hat.
+Wenn Sie `app.openapi()` manuell aufrufen, sollten Sie vorher die `operationId`s aktualisiert haben.
- Auch wenn diese sich in unterschiedlichen Modulen (Python-Dateien) befinden.
+///
+
+/// warning | "Achtung"
+
+Wenn Sie dies tun, müssen Sie sicherstellen, dass jede Ihrer *Pfadoperation-Funktionen* einen eindeutigen Namen hat.
+
+Auch wenn diese sich in unterschiedlichen Modulen (Python-Dateien) befinden.
+
+///
## Von OpenAPI ausschließen
Um eine *Pfadoperation* aus dem generierten OpenAPI-Schema (und damit aus den automatischen Dokumentationssystemen) auszuschließen, verwenden Sie den Parameter `include_in_schema` und setzen Sie ihn auf `False`:
```Python hl_lines="6"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial003.py!}
+{!../../docs_src/path_operation_advanced_configuration/tutorial003.py!}
```
## Fortgeschrittene Beschreibung mittels Docstring
@@ -48,7 +57,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!}
```
## Zusätzliche Responses
@@ -65,8 +74,11 @@ Es gibt hier in der Dokumentation ein ganzes Kapitel darüber, Sie können es un
Wenn Sie in Ihrer Anwendung eine *Pfadoperation* deklarieren, generiert **FastAPI** automatisch die relevanten Metadaten dieser *Pfadoperation*, die in das OpenAPI-Schema aufgenommen werden sollen.
-!!! note "Technische Details"
- In der OpenAPI-Spezifikation wird das Operationsobjekt genannt.
+/// note | "Technische Details"
+
+In der OpenAPI-Spezifikation wird das Operationsobjekt genannt.
+
+///
Es hat alle Informationen zur *Pfadoperation* und wird zur Erstellung der automatischen Dokumentation verwendet.
@@ -74,10 +86,13 @@ Es enthält `tags`, `parameters`, `requestBody`, `responses`, usw.
Dieses *Pfadoperation*-spezifische OpenAPI-Schema wird normalerweise automatisch von **FastAPI** generiert, Sie können es aber auch erweitern.
-!!! tip "Tipp"
- Dies ist ein Low-Level Erweiterungspunkt.
+/// tip | "Tipp"
- Wenn Sie nur zusätzliche Responses deklarieren müssen, können Sie dies bequemer mit [Zusätzliche Responses in OpenAPI](additional-responses.md){.internal-link target=_blank} tun.
+Dies ist ein Low-Level Erweiterungspunkt.
+
+Wenn Sie nur zusätzliche Responses deklarieren müssen, können Sie dies bequemer mit [Zusätzliche Responses in OpenAPI](additional-responses.md){.internal-link target=_blank} tun.
+
+///
Sie können das OpenAPI-Schema für eine *Pfadoperation* erweitern, indem Sie den Parameter `openapi_extra` verwenden.
@@ -86,7 +101,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!}
```
Wenn Sie die automatische API-Dokumentation öffnen, wird Ihre Erweiterung am Ende der spezifischen *Pfadoperation* angezeigt.
@@ -135,7 +150,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!}
```
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.
@@ -150,20 +165,27 @@ Und Sie könnten dies auch tun, wenn der Datentyp in der Anfrage nicht JSON ist.
In der folgenden Anwendung verwenden wir beispielsweise weder die integrierte Funktionalität von FastAPI zum Extrahieren des JSON-Schemas aus Pydantic-Modellen noch die automatische Validierung für JSON. Tatsächlich deklarieren wir den Request-Content-Type als YAML und nicht als JSON:
-=== "Pydantic v2"
+//// tab | Pydantic v2
- ```Python hl_lines="17-22 24"
- {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007.py!}
- ```
+```Python hl_lines="17-22 24"
+{!> ../../docs_src/path_operation_advanced_configuration/tutorial007.py!}
+```
-=== "Pydantic v1"
+////
- ```Python hl_lines="17-22 24"
- {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!}
- ```
+//// tab | Pydantic v1
-!!! info
- In Pydantic Version 1 hieß die Methode zum Abrufen des JSON-Schemas für ein Modell `Item.schema()`, in Pydantic Version 2 heißt die Methode `Item.model_json_schema()`.
+```Python hl_lines="17-22 24"
+{!> ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!}
+```
+
+////
+
+/// info
+
+In Pydantic Version 1 hieß die Methode zum Abrufen des JSON-Schemas für ein Modell `Item.schema()`, in Pydantic Version 2 heißt die Methode `Item.model_json_schema()`.
+
+///
Obwohl wir nicht die standardmäßig integrierte Funktionalität verwenden, verwenden wir dennoch ein Pydantic-Modell, um das JSON-Schema für die Daten, die wir in YAML empfangen möchten, manuell zu generieren.
@@ -171,22 +193,32 @@ Dann verwenden wir den Request direkt und extrahieren den Body als `bytes`. Das
Und dann parsen wir in unserem Code diesen YAML-Inhalt direkt und verwenden dann wieder dasselbe Pydantic-Modell, um den YAML-Inhalt zu validieren:
-=== "Pydantic v2"
+//// tab | Pydantic v2
- ```Python hl_lines="26-33"
- {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007.py!}
- ```
+```Python hl_lines="26-33"
+{!> ../../docs_src/path_operation_advanced_configuration/tutorial007.py!}
+```
-=== "Pydantic v1"
+////
- ```Python hl_lines="26-33"
- {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!}
- ```
+//// tab | Pydantic v1
-!!! info
- In Pydantic Version 1 war die Methode zum Parsen und Validieren eines Objekts `Item.parse_obj()`, in Pydantic Version 2 heißt die Methode `Item.model_validate()`.
+```Python hl_lines="26-33"
+{!> ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!}
+```
-!!! tip "Tipp"
- Hier verwenden wir dasselbe Pydantic-Modell wieder.
+////
- Aber genauso hätten wir es auch auf andere Weise validieren können.
+/// info
+
+In Pydantic Version 1 war die Methode zum Parsen und Validieren eines Objekts `Item.parse_obj()`, in Pydantic Version 2 heißt die Methode `Item.model_validate()`.
+
+///
+
+/// tip | "Tipp"
+
+Hier verwenden wir dasselbe Pydantic-Modell wieder.
+
+Aber genauso hätten wir es auch auf andere Weise validieren können.
+
+///
diff --git a/docs/de/docs/advanced/response-change-status-code.md b/docs/de/docs/advanced/response-change-status-code.md
index bba908a3e..202df0d87 100644
--- a/docs/de/docs/advanced/response-change-status-code.md
+++ b/docs/de/docs/advanced/response-change-status-code.md
@@ -21,7 +21,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!}
```
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 0f09bd444..ba100870d 100644
--- a/docs/de/docs/advanced/response-cookies.md
+++ b/docs/de/docs/advanced/response-cookies.md
@@ -7,7 +7,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!}
```
Anschließend können Sie wie gewohnt jedes gewünschte Objekt zurückgeben (ein `dict`, ein Datenbankmodell, usw.).
@@ -27,23 +27,29 @@ 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!}
```
-!!! tip "Tipp"
- Beachten Sie, dass, wenn Sie eine Response direkt zurückgeben, anstatt den `Response`-Parameter zu verwenden, FastAPI diese direkt zurückgibt.
+/// tip | "Tipp"
- Sie müssen also sicherstellen, dass Ihre Daten vom richtigen Typ sind. Z. B. sollten diese mit JSON kompatibel sein, wenn Sie eine `JSONResponse` zurückgeben.
+Beachten Sie, dass, wenn Sie eine Response direkt zurückgeben, anstatt den `Response`-Parameter zu verwenden, FastAPI diese direkt zurückgibt.
- Und auch, dass Sie keine Daten senden, die durch ein `response_model` hätten gefiltert werden sollen.
+Sie müssen also sicherstellen, dass Ihre Daten vom richtigen Typ sind. Z. B. sollten diese mit JSON kompatibel sein, wenn Sie eine `JSONResponse` zurückgeben.
+
+Und auch, dass Sie keine Daten senden, die durch ein `response_model` hätten gefiltert werden sollen.
+
+///
### Mehr Informationen
-!!! note "Technische Details"
- Sie können auch `from starlette.responses import Response` oder `from starlette.responses import JSONResponse` verwenden.
+/// note | "Technische Details"
- **FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette.
+Sie können auch `from starlette.responses import Response` oder `from starlette.responses import JSONResponse` verwenden.
- Und da die `Response` häufig zum Setzen von Headern und Cookies verwendet wird, stellt **FastAPI** diese auch unter `fastapi.Response` bereit.
+**FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette.
+
+Und da die `Response` häufig zum Setzen von Headern und Cookies verwendet wird, stellt **FastAPI** diese auch unter `fastapi.Response` bereit.
+
+///
Um alle verfügbaren Parameter und Optionen anzuzeigen, sehen Sie sich deren Dokumentation in Starlette an.
diff --git a/docs/de/docs/advanced/response-directly.md b/docs/de/docs/advanced/response-directly.md
index 13bca7825..70c045f57 100644
--- a/docs/de/docs/advanced/response-directly.md
+++ b/docs/de/docs/advanced/response-directly.md
@@ -14,8 +14,11 @@ Das kann beispielsweise nützlich sein, um benutzerdefinierte Header oder Cookie
Tatsächlich können Sie jede `Response` oder jede Unterklasse davon zurückgeben.
-!!! tip "Tipp"
- `JSONResponse` selbst ist eine Unterklasse von `Response`.
+/// tip | "Tipp"
+
+`JSONResponse` selbst ist eine Unterklasse von `Response`.
+
+///
Und wenn Sie eine `Response` zurückgeben, wird **FastAPI** diese direkt weiterleiten.
@@ -32,13 +35,16 @@ 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!}
```
-!!! note "Technische Details"
- Sie können auch `from starlette.responses import JSONResponse` verwenden.
+/// note | "Technische Details"
- **FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette.
+Sie können auch `from starlette.responses import JSONResponse` verwenden.
+
+**FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette.
+
+///
## Eine benutzerdefinierte `Response` zurückgeben
@@ -51,7 +57,7 @@ Nehmen wir an, Sie möchten eine ../../../docs_src/security/tutorial006_an_py39.py!}
- ```
+```Python hl_lines="4 8 12"
+{!> ../../docs_src/security/tutorial006_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="2 7 11"
- {!> ../../../docs_src/security/tutorial006_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ nicht annotiert"
+```Python hl_lines="2 7 11"
+{!> ../../docs_src/security/tutorial006_an.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="2 6 10"
- {!> ../../../docs_src/security/tutorial006.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="2 6 10"
+{!> ../../docs_src/security/tutorial006.py!}
+```
+
+////
Wenn Sie versuchen, die URL zum ersten Mal zu öffnen (oder in der Dokumentation auf den Button „Execute“ zu klicken), wird der Browser Sie nach Ihrem Benutzernamen und Passwort fragen:
@@ -59,26 +68,35 @@ Um dies zu lösen, konvertieren wir zunächst den `username` und das `password`
Dann können wir `secrets.compare_digest()` verwenden, um sicherzustellen, dass `credentials.username` `"stanleyjobson"` und `credentials.password` `"swordfish"` ist.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="1 12-24"
- {!> ../../../docs_src/security/tutorial007_an_py39.py!}
- ```
+```Python hl_lines="1 12-24"
+{!> ../../docs_src/security/tutorial007_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1 12-24"
- {!> ../../../docs_src/security/tutorial007_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ nicht annotiert"
+```Python hl_lines="1 12-24"
+{!> ../../docs_src/security/tutorial007_an.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="1 11-21"
- {!> ../../../docs_src/security/tutorial007.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="1 11-21"
+{!> ../../docs_src/security/tutorial007.py!}
+```
+
+////
Dies wäre das gleiche wie:
@@ -142,23 +160,32 @@ So ist Ihr Anwendungscode, dank der Verwendung von `secrets.compare_digest()`, v
Nachdem Sie festgestellt haben, dass die Anmeldeinformationen falsch sind, geben Sie eine `HTTPException` mit dem Statuscode 401 zurück (derselbe, der auch zurückgegeben wird, wenn keine Anmeldeinformationen angegeben werden) und fügen den Header `WWW-Authenticate` hinzu, damit der Browser die Anmeldeaufforderung erneut anzeigt:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="26-30"
- {!> ../../../docs_src/security/tutorial007_an_py39.py!}
- ```
+```Python hl_lines="26-30"
+{!> ../../docs_src/security/tutorial007_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="26-30"
- {!> ../../../docs_src/security/tutorial007_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ nicht annotiert"
+```Python hl_lines="26-30"
+{!> ../../docs_src/security/tutorial007_an.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="23-27"
- {!> ../../../docs_src/security/tutorial007.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="23-27"
+{!> ../../docs_src/security/tutorial007.py!}
+```
+
+////
diff --git a/docs/de/docs/advanced/security/index.md b/docs/de/docs/advanced/security/index.md
index a3c975bed..380e48bbf 100644
--- a/docs/de/docs/advanced/security/index.md
+++ b/docs/de/docs/advanced/security/index.md
@@ -4,10 +4,13 @@
Neben den in [Tutorial – Benutzerhandbuch: Sicherheit](../../tutorial/security/index.md){.internal-link target=_blank} behandelten Funktionen gibt es noch einige zusätzliche Funktionen zur Handhabung der Sicherheit.
-!!! tip "Tipp"
- Die nächsten Abschnitte sind **nicht unbedingt „fortgeschritten“**.
+/// tip | "Tipp"
- Und es ist möglich, dass für Ihren Anwendungsfall die Lösung in einem davon liegt.
+Die nächsten Abschnitte sind **nicht unbedingt „fortgeschritten“**.
+
+Und es ist möglich, dass für Ihren Anwendungsfall die Lösung in einem davon liegt.
+
+///
## Lesen Sie zuerst das Tutorial
diff --git a/docs/de/docs/advanced/security/oauth2-scopes.md b/docs/de/docs/advanced/security/oauth2-scopes.md
index ffd34d65f..c0af2560a 100644
--- a/docs/de/docs/advanced/security/oauth2-scopes.md
+++ b/docs/de/docs/advanced/security/oauth2-scopes.md
@@ -10,18 +10,21 @@ Jedes Mal, wenn Sie sich mit Facebook, Google, GitHub, Microsoft oder Twitter an
In diesem Abschnitt erfahren Sie, wie Sie Authentifizierung und Autorisierung mit demselben OAuth2, mit Scopes in Ihrer **FastAPI**-Anwendung verwalten.
-!!! warning "Achtung"
- Dies ist ein mehr oder weniger fortgeschrittener Abschnitt. Wenn Sie gerade erst anfangen, können Sie ihn überspringen.
+/// warning | "Achtung"
- Sie benötigen nicht unbedingt OAuth2-Scopes, und Sie können die Authentifizierung und Autorisierung handhaben wie Sie möchten.
+Dies ist ein mehr oder weniger fortgeschrittener Abschnitt. Wenn Sie gerade erst anfangen, können Sie ihn überspringen.
- Aber OAuth2 mit Scopes kann bequem in Ihre API (mit OpenAPI) und deren API-Dokumentation integriert werden.
+Sie benötigen nicht unbedingt OAuth2-Scopes, und Sie können die Authentifizierung und Autorisierung handhaben wie Sie möchten.
- Dennoch, verwenden Sie solche Scopes oder andere Sicherheits-/Autorisierungsanforderungen in Ihrem Code so wie Sie es möchten.
+Aber OAuth2 mit Scopes kann bequem in Ihre API (mit OpenAPI) und deren API-Dokumentation integriert werden.
- In vielen Fällen kann OAuth2 mit Scopes ein Overkill sein.
+Dennoch, verwenden Sie solche Scopes oder andere Sicherheits-/Autorisierungsanforderungen in Ihrem Code so wie Sie es möchten.
- Aber wenn Sie wissen, dass Sie es brauchen oder neugierig sind, lesen Sie weiter.
+In vielen Fällen kann OAuth2 mit Scopes ein Overkill sein.
+
+Aber wenn Sie wissen, dass Sie es brauchen oder neugierig sind, lesen Sie weiter.
+
+///
## OAuth2-Scopes und OpenAPI
@@ -43,63 +46,87 @@ Er wird normalerweise verwendet, um bestimmte Sicherheitsberechtigungen zu dekla
* `instagram_basic` wird von Facebook / Instagram verwendet.
* `https://www.googleapis.com/auth/drive` wird von Google verwendet.
-!!! info
- In OAuth2 ist ein „Scope“ nur ein String, der eine bestimmte erforderliche Berechtigung deklariert.
+/// info
- Es spielt keine Rolle, ob er andere Zeichen wie `:` enthält oder ob es eine URL ist.
+In OAuth2 ist ein „Scope“ nur ein String, der eine bestimmte erforderliche Berechtigung deklariert.
- Diese Details sind implementierungsspezifisch.
+Es spielt keine Rolle, ob er andere Zeichen wie `:` enthält oder ob es eine URL ist.
- Für OAuth2 sind es einfach nur Strings.
+Diese Details sind implementierungsspezifisch.
+
+Für OAuth2 sind es einfach nur Strings.
+
+///
## Gesamtübersicht
Sehen wir uns zunächst kurz die Teile an, die sich gegenüber den Beispielen im Haupt-**Tutorial – Benutzerhandbuch** für [OAuth2 mit Password (und Hashing), Bearer mit JWT-Tokens](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank} ändern. Diesmal verwenden wir OAuth2-Scopes:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="4 8 12 46 64 105 107-115 121-124 128-134 139 155"
- {!> ../../../docs_src/security/tutorial005_an_py310.py!}
- ```
+```Python hl_lines="4 8 12 46 64 105 107-115 121-124 128-134 139 155"
+{!> ../../docs_src/security/tutorial005_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155"
- {!> ../../../docs_src/security/tutorial005_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155"
+{!> ../../docs_src/security/tutorial005_an_py39.py!}
+```
- ```Python hl_lines="2 4 8 12 47 65 106 108-116 122-125 129-135 140 156"
- {!> ../../../docs_src/security/tutorial005_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="2 4 8 12 47 65 106 108-116 122-125 129-135 140 156"
+{!> ../../docs_src/security/tutorial005_an.py!}
+```
- ```Python hl_lines="3 7 11 45 63 104 106-114 120-123 127-133 138 154"
- {!> ../../../docs_src/security/tutorial005_py310.py!}
- ```
+////
-=== "Python 3.9+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155"
- {!> ../../../docs_src/security/tutorial005_py39.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.8+ nicht annotiert"
+///
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="3 7 11 45 63 104 106-114 120-123 127-133 138 154"
+{!> ../../docs_src/security/tutorial005_py310.py!}
+```
- ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155"
- {!> ../../../docs_src/security/tutorial005.py!}
- ```
+////
+
+//// tab | Python 3.9+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155"
+{!> ../../docs_src/security/tutorial005_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155"
+{!> ../../docs_src/security/tutorial005.py!}
+```
+
+////
Sehen wir uns diese Änderungen nun Schritt für Schritt an.
@@ -109,51 +136,71 @@ Die erste Änderung ist, dass wir jetzt das OAuth2-Sicherheitsschema mit zwei ve
Der `scopes`-Parameter erhält ein `dict` mit jedem Scope als Schlüssel und dessen Beschreibung als Wert:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="62-65"
- {!> ../../../docs_src/security/tutorial005_an_py310.py!}
- ```
+```Python hl_lines="62-65"
+{!> ../../docs_src/security/tutorial005_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="62-65"
- {!> ../../../docs_src/security/tutorial005_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="62-65"
+{!> ../../docs_src/security/tutorial005_an_py39.py!}
+```
- ```Python hl_lines="63-66"
- {!> ../../../docs_src/security/tutorial005_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="63-66"
+{!> ../../docs_src/security/tutorial005_an.py!}
+```
- ```Python hl_lines="61-64"
- {!> ../../../docs_src/security/tutorial005_py310.py!}
- ```
+////
+//// tab | Python 3.10+ nicht annotiert
-=== "Python 3.9+ nicht annotiert"
+/// tip | "Tipp"
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- ```Python hl_lines="62-65"
- {!> ../../../docs_src/security/tutorial005_py39.py!}
- ```
+///
-=== "Python 3.8+ nicht annotiert"
+```Python hl_lines="61-64"
+{!> ../../docs_src/security/tutorial005_py310.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="62-65"
- {!> ../../../docs_src/security/tutorial005.py!}
- ```
+//// tab | Python 3.9+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="62-65"
+{!> ../../docs_src/security/tutorial005_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="62-65"
+{!> ../../docs_src/security/tutorial005.py!}
+```
+
+////
Da wir diese Scopes jetzt deklarieren, werden sie in der API-Dokumentation angezeigt, wenn Sie sich einloggen/autorisieren.
@@ -171,55 +218,79 @@ Wir verwenden immer noch dasselbe `OAuth2PasswordRequestForm`. Es enthält eine
Und wir geben die Scopes als Teil des JWT-Tokens zurück.
-!!! danger "Gefahr"
- Der Einfachheit halber fügen wir hier die empfangenen Scopes direkt zum Token hinzu.
+/// danger | "Gefahr"
- Aus Sicherheitsgründen sollten Sie jedoch sicherstellen, dass Sie in Ihrer Anwendung nur die Scopes hinzufügen, die der Benutzer tatsächlich haben kann, oder die Sie vordefiniert haben.
+Der Einfachheit halber fügen wir hier die empfangenen Scopes direkt zum Token hinzu.
-=== "Python 3.10+"
+Aus Sicherheitsgründen sollten Sie jedoch sicherstellen, dass Sie in Ihrer Anwendung nur die Scopes hinzufügen, die der Benutzer tatsächlich haben kann, oder die Sie vordefiniert haben.
- ```Python hl_lines="155"
- {!> ../../../docs_src/security/tutorial005_an_py310.py!}
- ```
+///
-=== "Python 3.9+"
+//// tab | Python 3.10+
- ```Python hl_lines="155"
- {!> ../../../docs_src/security/tutorial005_an_py39.py!}
- ```
+```Python hl_lines="155"
+{!> ../../docs_src/security/tutorial005_an_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="156"
- {!> ../../../docs_src/security/tutorial005_an.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.10+ nicht annotiert"
+```Python hl_lines="155"
+{!> ../../docs_src/security/tutorial005_an_py39.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="154"
- {!> ../../../docs_src/security/tutorial005_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.9+ nicht annotiert"
+```Python hl_lines="156"
+{!> ../../docs_src/security/tutorial005_an.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="155"
- {!> ../../../docs_src/security/tutorial005_py39.py!}
- ```
+//// tab | Python 3.10+ nicht annotiert
-=== "Python 3.8+ nicht annotiert"
+/// tip | "Tipp"
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- ```Python hl_lines="155"
- {!> ../../../docs_src/security/tutorial005.py!}
- ```
+///
+
+```Python hl_lines="154"
+{!> ../../docs_src/security/tutorial005_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="155"
+{!> ../../docs_src/security/tutorial005_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="155"
+{!> ../../docs_src/security/tutorial005.py!}
+```
+
+////
## Scopes in *Pfadoperationen* und Abhängigkeiten deklarieren
@@ -237,62 +308,89 @@ Und die Abhängigkeitsfunktion `get_current_active_user` kann auch Unterabhängi
In diesem Fall erfordert sie den Scope `me` (sie könnte mehr als einen Scope erfordern).
-!!! note "Hinweis"
- Sie müssen nicht unbedingt an verschiedenen Stellen verschiedene Scopes hinzufügen.
+/// note | "Hinweis"
- Wir tun dies hier, um zu demonstrieren, wie **FastAPI** auf verschiedenen Ebenen deklarierte Scopes verarbeitet.
+Sie müssen nicht unbedingt an verschiedenen Stellen verschiedene Scopes hinzufügen.
-=== "Python 3.10+"
+Wir tun dies hier, um zu demonstrieren, wie **FastAPI** auf verschiedenen Ebenen deklarierte Scopes verarbeitet.
- ```Python hl_lines="4 139 170"
- {!> ../../../docs_src/security/tutorial005_an_py310.py!}
- ```
+///
-=== "Python 3.9+"
+//// tab | Python 3.10+
- ```Python hl_lines="4 139 170"
- {!> ../../../docs_src/security/tutorial005_an_py39.py!}
- ```
+```Python hl_lines="4 139 170"
+{!> ../../docs_src/security/tutorial005_an_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="4 140 171"
- {!> ../../../docs_src/security/tutorial005_an.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.10+ nicht annotiert"
+```Python hl_lines="4 139 170"
+{!> ../../docs_src/security/tutorial005_an_py39.py!}
+```
- !!! 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.8+
-=== "Python 3.9+ nicht annotiert"
+```Python hl_lines="4 140 171"
+{!> ../../docs_src/security/tutorial005_an.py!}
+```
- !!! 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.10+ nicht annotiert
-=== "Python 3.8+ nicht annotiert"
+/// tip | "Tipp"
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- ```Python hl_lines="4 139 168"
- {!> ../../../docs_src/security/tutorial005.py!}
- ```
+///
-!!! info "Technische Details"
- `Security` ist tatsächlich eine Unterklasse von `Depends` und hat nur noch einen zusätzlichen Parameter, den wir später kennenlernen werden.
+```Python hl_lines="3 138 167"
+{!> ../../docs_src/security/tutorial005_py310.py!}
+```
- Durch die Verwendung von `Security` anstelle von `Depends` weiß **FastAPI** jedoch, dass es Sicherheits-Scopes deklarieren, intern verwenden und die API mit OpenAPI dokumentieren kann.
+////
- Wenn Sie jedoch `Query`, `Path`, `Depends`, `Security` und andere von `fastapi` importieren, handelt es sich tatsächlich um Funktionen, die spezielle Klassen zurückgeben.
+//// tab | Python 3.9+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="4 139 168"
+{!> ../../docs_src/security/tutorial005_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="4 139 168"
+{!> ../../docs_src/security/tutorial005.py!}
+```
+
+////
+
+/// info | "Technische Details"
+
+`Security` ist tatsächlich eine Unterklasse von `Depends` und hat nur noch einen zusätzlichen Parameter, den wir später kennenlernen werden.
+
+Durch die Verwendung von `Security` anstelle von `Depends` weiß **FastAPI** jedoch, dass es Sicherheits-Scopes deklarieren, intern verwenden und die API mit OpenAPI dokumentieren kann.
+
+Wenn Sie jedoch `Query`, `Path`, `Depends`, `Security` und andere von `fastapi` importieren, handelt es sich tatsächlich um Funktionen, die spezielle Klassen zurückgeben.
+
+///
## `SecurityScopes` verwenden
@@ -308,50 +406,71 @@ Wir deklarieren auch einen speziellen Parameter vom Typ `SecurityScopes`, der au
Diese `SecurityScopes`-Klasse ähnelt `Request` (`Request` wurde verwendet, um das Request-Objekt direkt zu erhalten).
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="8 105"
- {!> ../../../docs_src/security/tutorial005_an_py310.py!}
- ```
+```Python hl_lines="8 105"
+{!> ../../docs_src/security/tutorial005_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="8 105"
- {!> ../../../docs_src/security/tutorial005_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="8 105"
+{!> ../../docs_src/security/tutorial005_an_py39.py!}
+```
- ```Python hl_lines="8 106"
- {!> ../../../docs_src/security/tutorial005_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="8 106"
+{!> ../../docs_src/security/tutorial005_an.py!}
+```
- ```Python hl_lines="7 104"
- {!> ../../../docs_src/security/tutorial005_py310.py!}
- ```
+////
-=== "Python 3.9+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="8 105"
- {!> ../../../docs_src/security/tutorial005_py39.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.8+ nicht annotiert"
+///
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="7 104"
+{!> ../../docs_src/security/tutorial005_py310.py!}
+```
- ```Python hl_lines="8 105"
- {!> ../../../docs_src/security/tutorial005.py!}
- ```
+////
+
+//// tab | Python 3.9+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="8 105"
+{!> ../../docs_src/security/tutorial005_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="8 105"
+{!> ../../docs_src/security/tutorial005.py!}
+```
+
+////
## Die `scopes` verwenden
@@ -365,50 +484,71 @@ Wir erstellen eine `HTTPException`, die wir später an mehreren Stellen wiederve
In diese Exception fügen wir (falls vorhanden) die erforderlichen Scopes als durch Leerzeichen getrennten String ein (unter Verwendung von `scope_str`). Wir fügen diesen String mit den Scopes in den Header `WWW-Authenticate` ein (das ist Teil der Spezifikation).
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="105 107-115"
- {!> ../../../docs_src/security/tutorial005_an_py310.py!}
- ```
+```Python hl_lines="105 107-115"
+{!> ../../docs_src/security/tutorial005_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="105 107-115"
- {!> ../../../docs_src/security/tutorial005_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="105 107-115"
+{!> ../../docs_src/security/tutorial005_an_py39.py!}
+```
- ```Python hl_lines="106 108-116"
- {!> ../../../docs_src/security/tutorial005_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="106 108-116"
+{!> ../../docs_src/security/tutorial005_an.py!}
+```
- ```Python hl_lines="104 106-114"
- {!> ../../../docs_src/security/tutorial005_py310.py!}
- ```
+////
-=== "Python 3.9+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="105 107-115"
- {!> ../../../docs_src/security/tutorial005_py39.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.8+ nicht annotiert"
+///
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="104 106-114"
+{!> ../../docs_src/security/tutorial005_py310.py!}
+```
- ```Python hl_lines="105 107-115"
- {!> ../../../docs_src/security/tutorial005.py!}
- ```
+////
+
+//// tab | Python 3.9+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="105 107-115"
+{!> ../../docs_src/security/tutorial005_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="105 107-115"
+{!> ../../docs_src/security/tutorial005.py!}
+```
+
+////
## Den `username` und das Format der Daten überprüfen
@@ -424,50 +564,71 @@ Anstelle beispielsweise eines `dict`s oder etwas anderem, was später in der Anw
Wir verifizieren auch, dass wir einen Benutzer mit diesem Benutzernamen haben, und wenn nicht, lösen wir dieselbe Exception aus, die wir zuvor erstellt haben.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="46 116-127"
- {!> ../../../docs_src/security/tutorial005_an_py310.py!}
- ```
+```Python hl_lines="46 116-127"
+{!> ../../docs_src/security/tutorial005_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="46 116-127"
- {!> ../../../docs_src/security/tutorial005_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="46 116-127"
+{!> ../../docs_src/security/tutorial005_an_py39.py!}
+```
- ```Python hl_lines="47 117-128"
- {!> ../../../docs_src/security/tutorial005_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="47 117-128"
+{!> ../../docs_src/security/tutorial005_an.py!}
+```
- ```Python hl_lines="45 115-126"
- {!> ../../../docs_src/security/tutorial005_py310.py!}
- ```
+////
-=== "Python 3.9+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="46 116-127"
- {!> ../../../docs_src/security/tutorial005_py39.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.8+ nicht annotiert"
+///
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="45 115-126"
+{!> ../../docs_src/security/tutorial005_py310.py!}
+```
- ```Python hl_lines="46 116-127"
- {!> ../../../docs_src/security/tutorial005.py!}
- ```
+////
+
+//// tab | Python 3.9+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="46 116-127"
+{!> ../../docs_src/security/tutorial005_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="46 116-127"
+{!> ../../docs_src/security/tutorial005.py!}
+```
+
+////
## Die `scopes` verifizieren
@@ -475,50 +636,71 @@ Wir überprüfen nun, ob das empfangenen Token alle Scopes enthält, die von die
Hierzu verwenden wir `security_scopes.scopes`, das eine `list`e mit allen diesen Scopes als `str` enthält.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="128-134"
- {!> ../../../docs_src/security/tutorial005_an_py310.py!}
- ```
+```Python hl_lines="128-134"
+{!> ../../docs_src/security/tutorial005_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="128-134"
- {!> ../../../docs_src/security/tutorial005_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="128-134"
+{!> ../../docs_src/security/tutorial005_an_py39.py!}
+```
- ```Python hl_lines="129-135"
- {!> ../../../docs_src/security/tutorial005_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="129-135"
+{!> ../../docs_src/security/tutorial005_an.py!}
+```
- ```Python hl_lines="127-133"
- {!> ../../../docs_src/security/tutorial005_py310.py!}
- ```
+////
-=== "Python 3.9+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="128-134"
- {!> ../../../docs_src/security/tutorial005_py39.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.8+ nicht annotiert"
+///
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="127-133"
+{!> ../../docs_src/security/tutorial005_py310.py!}
+```
- ```Python hl_lines="128-134"
- {!> ../../../docs_src/security/tutorial005.py!}
- ```
+////
+
+//// tab | Python 3.9+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="128-134"
+{!> ../../docs_src/security/tutorial005_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="128-134"
+{!> ../../docs_src/security/tutorial005.py!}
+```
+
+////
## Abhängigkeitsbaum und Scopes
@@ -545,10 +727,13 @@ So sieht die Hierarchie der Abhängigkeiten und Scopes aus:
* `security_scopes.scopes` enthält `["me"]` für die *Pfadoperation* `read_users_me`, da das in der Abhängigkeit `get_current_active_user` deklariert ist.
* `security_scopes.scopes` wird `[]` (nichts) für die *Pfadoperation* `read_system_status` enthalten, da diese keine `Security` mit `scopes` deklariert hat, und deren Abhängigkeit `get_current_user` ebenfalls keinerlei `scopes` deklariert.
-!!! tip "Tipp"
- Das Wichtige und „Magische“ hier ist, dass `get_current_user` für jede *Pfadoperation* eine andere Liste von `scopes` hat, die überprüft werden.
+/// tip | "Tipp"
- Alles hängt von den „Scopes“ ab, die in jeder *Pfadoperation* und jeder Abhängigkeit im Abhängigkeitsbaum für diese bestimmte *Pfadoperation* deklariert wurden.
+Das Wichtige und „Magische“ hier ist, dass `get_current_user` für jede *Pfadoperation* eine andere Liste von `scopes` hat, die überprüft werden.
+
+Alles hängt von den „Scopes“ ab, die in jeder *Pfadoperation* und jeder Abhängigkeit im Abhängigkeitsbaum für diese bestimmte *Pfadoperation* deklariert wurden.
+
+///
## Weitere Details zu `SecurityScopes`.
@@ -586,10 +771,13 @@ Am häufigsten ist der „Implicit“-Flow.
Am sichersten ist der „Code“-Flow, die Implementierung ist jedoch komplexer, da mehr Schritte erforderlich sind. Da er komplexer ist, schlagen viele Anbieter letztendlich den „Implicit“-Flow vor.
-!!! note "Hinweis"
- Es ist üblich, dass jeder Authentifizierungsanbieter seine Flows anders benennt, um sie zu einem Teil seiner Marke zu machen.
+/// note | "Hinweis"
- Aber am Ende implementieren sie denselben OAuth2-Standard.
+Es ist üblich, dass jeder Authentifizierungsanbieter seine Flows anders benennt, um sie zu einem Teil seiner Marke zu machen.
+
+Aber am Ende implementieren sie denselben OAuth2-Standard.
+
+///
**FastAPI** enthält Werkzeuge für alle diese OAuth2-Authentifizierungs-Flows in `fastapi.security.oauth2`.
diff --git a/docs/de/docs/advanced/settings.md b/docs/de/docs/advanced/settings.md
index fe01d8e1f..8b9ba2f48 100644
--- a/docs/de/docs/advanced/settings.md
+++ b/docs/de/docs/advanced/settings.md
@@ -8,44 +8,51 @@ Aus diesem Grund werden diese üblicherweise in Umgebungsvariablen bereitgestell
## Umgebungsvariablen
-!!! tip "Tipp"
- Wenn Sie bereits wissen, was „Umgebungsvariablen“ sind und wie man sie verwendet, können Sie gerne mit dem nächsten Abschnitt weiter unten fortfahren.
+/// tip | "Tipp"
+
+Wenn Sie bereits wissen, was „Umgebungsvariablen“ sind und wie man sie verwendet, können Sie gerne mit dem nächsten Abschnitt weiter unten fortfahren.
+
+///
Eine Umgebungsvariable (auch bekannt als „env var“) ist eine Variable, die sich außerhalb des Python-Codes im Betriebssystem befindet und von Ihrem Python-Code (oder auch von anderen Programmen) gelesen werden kann.
Sie können Umgebungsvariablen in der Shell erstellen und verwenden, ohne Python zu benötigen:
-=== "Linux, macOS, Windows Bash"
+//// tab | Linux, macOS, Windows Bash
-
-!!! info
- Die wunderschönen Illustrationen stammen von Ketrina Thompson. 🎨
+/// info
+
+Die wunderschönen Illustrationen stammen von Ketrina Thompson. 🎨
+
+///
---
@@ -199,8 +205,11 @@ Sie essen sie und sind fertig. ⏹
Es wurde nicht viel geredet oder geflirtet, da die meiste Zeit mit Warten 🕙 vor der Theke verbracht wurde. 😞
-!!! info
- Die wunderschönen Illustrationen stammen von Ketrina Thompson. 🎨
+/// info
+
+Die wunderschönen Illustrationen stammen von Ketrina Thompson. 🎨
+
+///
---
@@ -392,12 +401,15 @@ All das ist es, was FastAPI (via Starlette) befeuert und es eine so beeindrucken
## Sehr technische Details
-!!! warning "Achtung"
- Das folgende können Sie wahrscheinlich überspringen.
+/// warning | "Achtung"
- Dies sind sehr technische Details darüber, wie **FastAPI** unter der Haube funktioniert.
+Das folgende können Sie wahrscheinlich überspringen.
- Wenn Sie über gute technische Kenntnisse verfügen (Coroutinen, Threads, Blocking, usw.) und neugierig sind, wie FastAPI mit `async def`s im Vergleich zu normalen `def`s umgeht, fahren Sie fort.
+Dies sind sehr technische Details darüber, wie **FastAPI** unter der Haube funktioniert.
+
+Wenn Sie über gute technische Kenntnisse verfügen (Coroutinen, Threads, Blocking, usw.) und neugierig sind, wie FastAPI mit `async def`s im Vergleich zu normalen `def`s umgeht, fahren Sie fort.
+
+///
### Pfadoperation-Funktionen
diff --git a/docs/de/docs/contributing.md b/docs/de/docs/contributing.md
index b1bd62496..58567ad7f 100644
--- a/docs/de/docs/contributing.md
+++ b/docs/de/docs/contributing.md
@@ -24,63 +24,73 @@ Das erstellt ein Verzeichnis `./env/` mit den Python-Binärdateien und Sie könn
Aktivieren Sie die neue Umgebung mit:
-=== "Linux, macOS"
+//// tab | Linux, macOS
- email_validator - für E-Mail-Validierung.
+* email-validator - für E-Mail-Validierung.
* pydantic-settings - für die Verwaltung von Einstellungen.
* pydantic-extra-types - für zusätzliche Typen, mit Pydantic zu verwenden.
diff --git a/docs/de/docs/newsletter.md b/docs/de/docs/newsletter.md
deleted file mode 100644
index 31995b164..000000000
--- a/docs/de/docs/newsletter.md
+++ /dev/null
@@ -1,5 +0,0 @@
-# FastAPI und Freunde Newsletter
-
-
-
-
diff --git a/docs/de/docs/python-types.md b/docs/de/docs/python-types.md
index d11a193dd..a43bf5ffe 100644
--- a/docs/de/docs/python-types.md
+++ b/docs/de/docs/python-types.md
@@ -12,15 +12,18 @@ Dies ist lediglich eine **schnelle Anleitung / Auffrischung** über Pythons Typh
Aber selbst wenn Sie **FastAPI** nie verwenden, wird es für Sie nützlich sein, ein wenig darüber zu lernen.
-!!! note "Hinweis"
- Wenn Sie ein Python-Experte sind und bereits alles über Typhinweise wissen, überspringen Sie dieses Kapitel und fahren Sie mit dem nächsten fort.
+/// note | "Hinweis"
+
+Wenn Sie ein Python-Experte sind und bereits alles über Typhinweise wissen, überspringen Sie dieses Kapitel und fahren Sie mit dem nächsten fort.
+
+///
## Motivation
Fangen wir mit einem einfachen Beispiel an:
```Python
-{!../../../docs_src/python_types/tutorial001.py!}
+{!../../docs_src/python_types/tutorial001.py!}
```
Dieses Programm gibt aus:
@@ -36,7 +39,7 @@ Die Funktion macht Folgendes:
* Verkettet sie mit einem Leerzeichen in der Mitte.
```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial001.py!}
+{!../../docs_src/python_types/tutorial001.py!}
```
### Bearbeiten Sie es
@@ -80,7 +83,7 @@ Das war's.
Das sind die „Typhinweise“:
```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial002.py!}
+{!../../docs_src/python_types/tutorial002.py!}
```
Das ist nicht das gleiche wie das Deklarieren von Defaultwerten, wie es hier der Fall ist:
@@ -110,7 +113,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!}
```
Da der Editor die Typen der Variablen kennt, erhalten Sie nicht nur Code-Vervollständigung, sondern auch eine Fehlerprüfung:
@@ -120,7 +123,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!}
```
## Deklarieren von Typen
@@ -141,7 +144,7 @@ Zum Beispiel diese:
* `bytes`
```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial005.py!}
+{!../../docs_src/python_types/tutorial005.py!}
```
### Generische Typen mit Typ-Parametern
@@ -170,45 +173,55 @@ Wenn Sie über die **neueste Version von Python** verfügen, verwenden Sie die B
Definieren wir zum Beispiel eine Variable, die eine `list` von `str` – eine Liste von Strings – sein soll.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- Deklarieren Sie die Variable mit der gleichen Doppelpunkt-Syntax (`:`).
+Deklarieren Sie die Variable mit der gleichen Doppelpunkt-Syntax (`:`).
- Als Typ nehmen Sie `list`.
+Als Typ nehmen Sie `list`.
- Da die Liste ein Typ ist, welcher innere Typen enthält, werden diese von eckigen Klammern umfasst:
+Da die Liste ein Typ ist, welcher innere Typen enthält, werden diese von eckigen Klammern umfasst:
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial006_py39.py!}
- ```
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial006_py39.py!}
+```
-=== "Python 3.8+"
+////
- Von `typing` importieren Sie `List` (mit Großbuchstaben `L`):
+//// tab | Python 3.8+
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial006.py!}
- ```
+Von `typing` importieren Sie `List` (mit Großbuchstaben `L`):
- Deklarieren Sie die Variable mit der gleichen Doppelpunkt-Syntax (`:`).
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial006.py!}
+```
- Als Typ nehmen Sie das `List`, das Sie von `typing` importiert haben.
+Deklarieren Sie die Variable mit der gleichen Doppelpunkt-Syntax (`:`).
- Da die Liste ein Typ ist, welcher innere Typen enthält, werden diese von eckigen Klammern umfasst:
+Als Typ nehmen Sie das `List`, das Sie von `typing` importiert haben.
- ```Python hl_lines="4"
- {!> ../../../docs_src/python_types/tutorial006.py!}
- ```
+Da die Liste ein Typ ist, welcher innere Typen enthält, werden diese von eckigen Klammern umfasst:
-!!! tip "Tipp"
- Die inneren Typen in den eckigen Klammern werden als „Typ-Parameter“ bezeichnet.
+```Python hl_lines="4"
+{!> ../../docs_src/python_types/tutorial006.py!}
+```
- In diesem Fall ist `str` der Typ-Parameter, der an `List` übergeben wird (oder `list` in Python 3.9 und darüber).
+////
+
+/// tip | "Tipp"
+
+Die inneren Typen in den eckigen Klammern werden als „Typ-Parameter“ bezeichnet.
+
+In diesem Fall ist `str` der Typ-Parameter, der an `List` übergeben wird (oder `list` in Python 3.9 und darüber).
+
+///
Das bedeutet: Die Variable `items` ist eine Liste – `list` – und jedes der Elemente in dieser Liste ist ein String – `str`.
-!!! tip "Tipp"
- Wenn Sie Python 3.9 oder höher verwenden, müssen Sie `List` nicht von `typing` importieren, Sie können stattdessen den regulären `list`-Typ verwenden.
+/// tip | "Tipp"
+
+Wenn Sie Python 3.9 oder höher verwenden, müssen Sie `List` nicht von `typing` importieren, Sie können stattdessen den regulären `list`-Typ verwenden.
+
+///
Auf diese Weise kann Ihr Editor Sie auch bei der Bearbeitung von Einträgen aus der Liste unterstützen:
@@ -224,17 +237,21 @@ Und trotzdem weiß der Editor, dass es sich um ein `str` handelt, und bietet ent
Das Gleiche gilt für die Deklaration eines Tupels – `tuple` – und einer Menge – `set`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial007_py39.py!}
- ```
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial007_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial007.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial007.py!}
+```
+
+////
Das bedeutet:
@@ -249,17 +266,21 @@ Der erste Typ-Parameter ist für die Schlüssel des `dict`.
Der zweite Typ-Parameter ist für die Werte des `dict`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial008_py39.py!}
- ```
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial008_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial008.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial008.py!}
+```
+
+////
Das bedeutet:
@@ -275,17 +296,21 @@ In Python 3.6 und höher (inklusive Python 3.10) können Sie den `Union`-Typ von
In Python 3.10 gibt es zusätzlich eine **neue Syntax**, die es erlaubt, die möglichen Typen getrennt von einem vertikalen Balken (`|`) aufzulisten.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial008b_py310.py!}
- ```
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial008b_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial008b.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial008b.py!}
+```
+
+////
In beiden Fällen bedeutet das, dass `item` ein `int` oder ein `str` sein kann.
@@ -296,7 +321,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!}
```
Wenn Sie `Optional[str]` anstelle von nur `str` verwenden, wird Ihr Editor Ihnen dabei helfen, Fehler zu erkennen, bei denen Sie annehmen könnten, dass ein Wert immer eine String (`str`) ist, obwohl er auch `None` sein könnte.
@@ -305,23 +330,29 @@ Wenn Sie `Optional[str]` anstelle von nur `str` verwenden, wird Ihr Editor Ihnen
Das bedeutet auch, dass Sie in Python 3.10 `Something | None` verwenden können:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial009_py310.py!}
- ```
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial009_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial009.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ Alternative"
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial009.py!}
+```
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial009b.py!}
- ```
+////
+
+//// tab | Python 3.8+ Alternative
+
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial009b.py!}
+```
+
+////
#### `Union` oder `Optional` verwenden?
@@ -339,7 +370,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!}
```
Der Parameter `name` ist definiert als `Optional[str]`, aber er ist **nicht optional**, Sie können die Funktion nicht ohne diesen Parameter aufrufen:
@@ -357,7 +388,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!}
```
Und dann müssen Sie sich nicht mehr um Namen wie `Optional` und `Union` kümmern. 😎
@@ -366,47 +397,53 @@ Und dann müssen Sie sich nicht mehr um Namen wie `Optional` und `Union` kümmer
Diese Typen, die Typ-Parameter in eckigen Klammern akzeptieren, werden **generische Typen** oder **Generics** genannt.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- Sie können die eingebauten Typen als Generics verwenden (mit eckigen Klammern und Typen darin):
+Sie können die eingebauten Typen als Generics verwenden (mit eckigen Klammern und Typen darin):
- * `list`
- * `tuple`
- * `set`
- * `dict`
+* `list`
+* `tuple`
+* `set`
+* `dict`
- Verwenden Sie für den Rest, wie unter Python 3.8, das `typing`-Modul:
+Verwenden Sie für den Rest, wie unter Python 3.8, das `typing`-Modul:
- * `Union`
- * `Optional` (so wie unter Python 3.8)
- * ... und andere.
+* `Union`
+* `Optional` (so wie unter Python 3.8)
+* ... und andere.
- In Python 3.10 können Sie als Alternative zu den Generics `Union` und `Optional` den vertikalen Balken (`|`) verwenden, um Vereinigungen von Typen zu deklarieren, das ist besser und einfacher.
+In Python 3.10 können Sie als Alternative zu den Generics `Union` und `Optional` den vertikalen Balken (`|`) verwenden, um Vereinigungen von Typen zu deklarieren, das ist besser und einfacher.
-=== "Python 3.9+"
+////
- Sie können die eingebauten Typen als Generics verwenden (mit eckigen Klammern und Typen darin):
+//// tab | Python 3.9+
- * `list`
- * `tuple`
- * `set`
- * `dict`
+Sie können die eingebauten Typen als Generics verwenden (mit eckigen Klammern und Typen darin):
- Verwenden Sie für den Rest, wie unter Python 3.8, das `typing`-Modul:
+* `list`
+* `tuple`
+* `set`
+* `dict`
- * `Union`
- * `Optional`
- * ... und andere.
+Verwenden Sie für den Rest, wie unter Python 3.8, das `typing`-Modul:
-=== "Python 3.8+"
+* `Union`
+* `Optional`
+* ... und andere.
- * `List`
- * `Tuple`
- * `Set`
- * `Dict`
- * `Union`
- * `Optional`
- * ... und andere.
+////
+
+//// tab | Python 3.8+
+
+* `List`
+* `Tuple`
+* `Set`
+* `Dict`
+* `Union`
+* `Optional`
+* ... und andere.
+
+////
### Klassen als Typen
@@ -415,13 +452,13 @@ 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!}
```
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!}
```
Und wiederum bekommen Sie die volle Editor-Unterstützung:
@@ -446,55 +483,71 @@ Und Sie erhalten volle Editor-Unterstützung für dieses Objekt.
Ein Beispiel aus der offiziellen Pydantic Dokumentation:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python
- {!> ../../../docs_src/python_types/tutorial011_py310.py!}
- ```
+```Python
+{!> ../../docs_src/python_types/tutorial011_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python
- {!> ../../../docs_src/python_types/tutorial011_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python
+{!> ../../docs_src/python_types/tutorial011_py39.py!}
+```
- ```Python
- {!> ../../../docs_src/python_types/tutorial011.py!}
- ```
+////
-!!! info
- Um mehr über Pydantic zu erfahren, schauen Sie sich dessen Dokumentation an.
+//// tab | Python 3.8+
+
+```Python
+{!> ../../docs_src/python_types/tutorial011.py!}
+```
+
+////
+
+/// info
+
+Um mehr über Pydantic zu erfahren, schauen Sie sich dessen Dokumentation an.
+
+///
**FastAPI** basiert vollständig auf Pydantic.
Viel mehr von all dem werden Sie in praktischer Anwendung im [Tutorial - Benutzerhandbuch](tutorial/index.md){.internal-link target=_blank} sehen.
-!!! tip "Tipp"
- Pydantic verhält sich speziell, wenn Sie `Optional` oder `Union[Etwas, None]` ohne einen Default-Wert verwenden. Sie können darüber in der Pydantic Dokumentation unter Required fields mehr erfahren.
+/// tip | "Tipp"
+
+Pydantic verhält sich speziell, wenn Sie `Optional` oder `Union[Etwas, None]` ohne einen Default-Wert verwenden. Sie können darüber in der Pydantic Dokumentation unter Required fields mehr erfahren.
+
+///
## Typhinweise mit Metadaten-Annotationen
Python bietet auch die Möglichkeit, **zusätzliche Metadaten** in Typhinweisen unterzubringen, mittels `Annotated`.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- In Python 3.9 ist `Annotated` ein Teil der Standardbibliothek, Sie können es von `typing` importieren.
+In Python 3.9 ist `Annotated` ein Teil der Standardbibliothek, Sie können es von `typing` importieren.
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial013_py39.py!}
- ```
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial013_py39.py!}
+```
-=== "Python 3.8+"
+////
- In Versionen niedriger als Python 3.9 importieren Sie `Annotated` von `typing_extensions`.
+//// tab | Python 3.8+
- Es wird bereits mit **FastAPI** installiert sein.
+In Versionen niedriger als Python 3.9 importieren Sie `Annotated` von `typing_extensions`.
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial013.py!}
- ```
+Es wird bereits mit **FastAPI** installiert sein.
+
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial013.py!}
+```
+
+////
Python selbst macht nichts mit `Annotated`. Für Editoren und andere Tools ist der Typ immer noch `str`.
@@ -506,10 +559,13 @@ Im Moment müssen Sie nur wissen, dass `Annotated` existiert, und dass es Standa
Später werden Sie sehen, wie **mächtig** es sein kann.
-!!! tip "Tipp"
- Der Umstand, dass es **Standard-Python** ist, bedeutet, dass Sie immer noch die **bestmögliche Entwickler-Erfahrung** in ihrem Editor haben, sowie mit den Tools, die Sie nutzen, um ihren Code zu analysieren, zu refaktorisieren, usw. ✨
+/// tip | "Tipp"
- Und ebenfalls, dass Ihr Code sehr kompatibel mit vielen anderen Python-Tools und -Bibliotheken sein wird. 🚀
+Der Umstand, dass es **Standard-Python** ist, bedeutet, dass Sie immer noch die **bestmögliche Entwickler-Erfahrung** in ihrem Editor haben, sowie mit den Tools, die Sie nutzen, um ihren Code zu analysieren, zu refaktorisieren, usw. ✨
+
+Und ebenfalls, dass Ihr Code sehr kompatibel mit vielen anderen Python-Tools und -Bibliotheken sein wird. 🚀
+
+///
## Typhinweise in **FastAPI**
@@ -533,5 +589,8 @@ Das mag alles abstrakt klingen. Machen Sie sich keine Sorgen. Sie werden all das
Das Wichtigste ist, dass **FastAPI** durch die Verwendung von Standard-Python-Typen an einer einzigen Stelle (anstatt weitere Klassen, Dekoratoren usw. hinzuzufügen) einen Großteil der Arbeit für Sie erledigt.
-!!! info
- Wenn Sie bereits das ganze Tutorial durchgearbeitet haben und mehr über Typen erfahren wollen, dann ist eine gute Ressource der „Cheat Sheet“ von `mypy`.
+/// info
+
+Wenn Sie bereits das ganze Tutorial durchgearbeitet haben und mehr über Typen erfahren wollen, dann ist eine gute Ressource der „Cheat Sheet“ von `mypy`.
+
+///
diff --git a/docs/de/docs/reference/apirouter.md b/docs/de/docs/reference/apirouter.md
deleted file mode 100644
index b0728b7df..000000000
--- a/docs/de/docs/reference/apirouter.md
+++ /dev/null
@@ -1,24 +0,0 @@
-# `APIRouter`-Klasse
-
-Hier sind die Referenzinformationen für die Klasse `APIRouter` mit all ihren Parametern, Attributen und Methoden.
-
-Sie können die `APIRouter`-Klasse direkt von `fastapi` importieren:
-
-```python
-from fastapi import APIRouter
-```
-
-::: fastapi.APIRouter
- options:
- members:
- - websocket
- - include_router
- - get
- - put
- - post
- - delete
- - options
- - head
- - patch
- - trace
- - on_event
diff --git a/docs/de/docs/reference/background.md b/docs/de/docs/reference/background.md
deleted file mode 100644
index 0fd389325..000000000
--- a/docs/de/docs/reference/background.md
+++ /dev/null
@@ -1,11 +0,0 @@
-# Hintergrundtasks – `BackgroundTasks`
-
-Sie können einen Parameter in einer *Pfadoperation-Funktion* oder einer Abhängigkeitsfunktion mit dem Typ `BackgroundTasks` deklarieren und diesen danach verwenden, um die Ausführung von Hintergrundtasks nach dem Senden der Response zu definieren.
-
-Sie können `BackgroundTasks` direkt von `fastapi` importieren:
-
-```python
-from fastapi import BackgroundTasks
-```
-
-::: fastapi.BackgroundTasks
diff --git a/docs/de/docs/reference/dependencies.md b/docs/de/docs/reference/dependencies.md
deleted file mode 100644
index 2ed5b5050..000000000
--- a/docs/de/docs/reference/dependencies.md
+++ /dev/null
@@ -1,29 +0,0 @@
-# Abhängigkeiten – `Depends()` und `Security()`
-
-## `Depends()`
-
-Abhängigkeiten werden hauptsächlich mit der speziellen Funktion `Depends()` behandelt, die ein Callable entgegennimmt.
-
-Hier finden Sie deren Referenz und Parameter.
-
-Sie können sie direkt von `fastapi` importieren:
-
-```python
-from fastapi import Depends
-```
-
-::: fastapi.Depends
-
-## `Security()`
-
-In vielen Szenarien können Sie die Sicherheit (Autorisierung, Authentifizierung usw.) mit Abhängigkeiten handhaben, indem Sie `Depends()` verwenden.
-
-Wenn Sie jedoch auch OAuth2-Scopes deklarieren möchten, können Sie `Security()` anstelle von `Depends()` verwenden.
-
-Sie können `Security()` direkt von `fastapi` importieren:
-
-```python
-from fastapi import Security
-```
-
-::: fastapi.Security
diff --git a/docs/de/docs/reference/encoders.md b/docs/de/docs/reference/encoders.md
deleted file mode 100644
index 2489b8c60..000000000
--- a/docs/de/docs/reference/encoders.md
+++ /dev/null
@@ -1,3 +0,0 @@
-# Encoder – `jsonable_encoder`
-
-::: fastapi.encoders.jsonable_encoder
diff --git a/docs/de/docs/reference/exceptions.md b/docs/de/docs/reference/exceptions.md
deleted file mode 100644
index 230f902a9..000000000
--- a/docs/de/docs/reference/exceptions.md
+++ /dev/null
@@ -1,20 +0,0 @@
-# Exceptions – `HTTPException` und `WebSocketException`
-
-Dies sind die Exceptions, die Sie auslösen können, um dem Client Fehler zu berichten.
-
-Wenn Sie eine Exception auslösen, wird, wie es bei normalem Python der Fall wäre, der Rest der Ausführung abgebrochen. Auf diese Weise können Sie diese Exceptions von überall im Code werfen, um einen Request abzubrechen und den Fehler dem Client anzuzeigen.
-
-Sie können Folgendes verwenden:
-
-* `HTTPException`
-* `WebSocketException`
-
-Diese Exceptions können direkt von `fastapi` importiert werden:
-
-```python
-from fastapi import HTTPException, WebSocketException
-```
-
-::: fastapi.HTTPException
-
-::: fastapi.WebSocketException
diff --git a/docs/de/docs/reference/fastapi.md b/docs/de/docs/reference/fastapi.md
deleted file mode 100644
index 4e6a56971..000000000
--- a/docs/de/docs/reference/fastapi.md
+++ /dev/null
@@ -1,31 +0,0 @@
-# `FastAPI`-Klasse
-
-Hier sind die Referenzinformationen für die Klasse `FastAPI` mit all ihren Parametern, Attributen und Methoden.
-
-Sie können die `FastAPI`-Klasse direkt von `fastapi` importieren:
-
-```python
-from fastapi import FastAPI
-```
-
-::: fastapi.FastAPI
- options:
- members:
- - openapi_version
- - webhooks
- - state
- - dependency_overrides
- - openapi
- - websocket
- - include_router
- - get
- - put
- - post
- - delete
- - options
- - head
- - patch
- - trace
- - on_event
- - middleware
- - exception_handler
diff --git a/docs/de/docs/reference/httpconnection.md b/docs/de/docs/reference/httpconnection.md
deleted file mode 100644
index 32a9696fa..000000000
--- a/docs/de/docs/reference/httpconnection.md
+++ /dev/null
@@ -1,11 +0,0 @@
-# `HTTPConnection`-Klasse
-
-Wenn Sie Abhängigkeiten definieren möchten, die sowohl mit HTTP als auch mit WebSockets kompatibel sein sollen, können Sie einen Parameter definieren, der eine `HTTPConnection` anstelle eines `Request` oder eines `WebSocket` akzeptiert.
-
-Sie können diese von `fastapi.requests` importieren:
-
-```python
-from fastapi.requests import HTTPConnection
-```
-
-::: fastapi.requests.HTTPConnection
diff --git a/docs/de/docs/reference/index.md b/docs/de/docs/reference/index.md
deleted file mode 100644
index e9362b962..000000000
--- a/docs/de/docs/reference/index.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# Referenz – Code-API
-
-Hier ist die Referenz oder Code-API, die Klassen, Funktionen, Parameter, Attribute und alle FastAPI-Teile, die Sie in Ihren Anwendungen verwenden können.
-
-Wenn Sie **FastAPI** lernen möchten, ist es viel besser, das [FastAPI-Tutorial](https://fastapi.tiangolo.com/tutorial/) zu lesen.
-
-!!! note "Hinweis Deutsche Übersetzung"
- Die nachfolgende API wird aus der Quelltext-Dokumentation erstellt, daher sind nur die Einleitungen auf Deutsch.
diff --git a/docs/de/docs/reference/middleware.md b/docs/de/docs/reference/middleware.md
deleted file mode 100644
index d8d2d50fc..000000000
--- a/docs/de/docs/reference/middleware.md
+++ /dev/null
@@ -1,45 +0,0 @@
-# Middleware
-
-Es gibt mehrere Middlewares, die direkt von Starlette bereitgestellt werden.
-
-Lesen Sie mehr darüber in der [FastAPI-Dokumentation über Middleware](../advanced/middleware.md).
-
-::: fastapi.middleware.cors.CORSMiddleware
-
-Kann von `fastapi` importiert werden:
-
-```python
-from fastapi.middleware.cors import CORSMiddleware
-```
-
-::: fastapi.middleware.gzip.GZipMiddleware
-
-Kann von `fastapi` importiert werden:
-
-```python
-from fastapi.middleware.gzip import GZipMiddleware
-```
-
-::: fastapi.middleware.httpsredirect.HTTPSRedirectMiddleware
-
-Kann von `fastapi` importiert werden:
-
-```python
-from fastapi.middleware.httpsredirect import HTTPSRedirectMiddleware
-```
-
-::: fastapi.middleware.trustedhost.TrustedHostMiddleware
-
-Kann von `fastapi` importiert werden:
-
-```python
-from fastapi.middleware.trustedhost import TrustedHostMiddleware
-```
-
-::: fastapi.middleware.wsgi.WSGIMiddleware
-
-Kann von `fastapi` importiert werden:
-
-```python
-from fastapi.middleware.wsgi import WSGIMiddleware
-```
diff --git a/docs/de/docs/reference/openapi/docs.md b/docs/de/docs/reference/openapi/docs.md
deleted file mode 100644
index 3c19ba917..000000000
--- a/docs/de/docs/reference/openapi/docs.md
+++ /dev/null
@@ -1,11 +0,0 @@
-# OpenAPI `docs`
-
-Werkzeuge zur Verwaltung der automatischen OpenAPI-UI-Dokumentation, einschließlich Swagger UI (standardmäßig unter `/docs`) und ReDoc (standardmäßig unter `/redoc`).
-
-::: fastapi.openapi.docs.get_swagger_ui_html
-
-::: fastapi.openapi.docs.get_redoc_html
-
-::: fastapi.openapi.docs.get_swagger_ui_oauth2_redirect_html
-
-::: fastapi.openapi.docs.swagger_ui_default_parameters
diff --git a/docs/de/docs/reference/openapi/index.md b/docs/de/docs/reference/openapi/index.md
deleted file mode 100644
index 0ae3d67c6..000000000
--- a/docs/de/docs/reference/openapi/index.md
+++ /dev/null
@@ -1,5 +0,0 @@
-# OpenAPI
-
-Es gibt mehrere Werkzeuge zur Handhabung von OpenAPI.
-
-Normalerweise müssen Sie diese nicht verwenden, es sei denn, Sie haben einen bestimmten fortgeschrittenen Anwendungsfall, welcher das erfordert.
diff --git a/docs/de/docs/reference/openapi/models.md b/docs/de/docs/reference/openapi/models.md
deleted file mode 100644
index 64306b15f..000000000
--- a/docs/de/docs/reference/openapi/models.md
+++ /dev/null
@@ -1,5 +0,0 @@
-# OpenAPI-`models`
-
-OpenAPI Pydantic-Modelle, werden zum Generieren und Validieren der generierten OpenAPI verwendet.
-
-::: fastapi.openapi.models
diff --git a/docs/de/docs/reference/parameters.md b/docs/de/docs/reference/parameters.md
deleted file mode 100644
index 2638eaf48..000000000
--- a/docs/de/docs/reference/parameters.md
+++ /dev/null
@@ -1,35 +0,0 @@
-# Request-Parameter
-
-Hier die Referenzinformationen für die Request-Parameter.
-
-Dies sind die Sonderfunktionen, die Sie mittels `Annotated` in *Pfadoperation-Funktion*-Parameter oder Abhängigkeitsfunktionen einfügen können, um Daten aus dem Request abzurufen.
-
-Dies beinhaltet:
-
-* `Query()`
-* `Path()`
-* `Body()`
-* `Cookie()`
-* `Header()`
-* `Form()`
-* `File()`
-
-Sie können diese alle direkt von `fastapi` importieren:
-
-```python
-from fastapi import Body, Cookie, File, Form, Header, Path, Query
-```
-
-::: fastapi.Query
-
-::: fastapi.Path
-
-::: fastapi.Body
-
-::: fastapi.Cookie
-
-::: fastapi.Header
-
-::: fastapi.Form
-
-::: fastapi.File
diff --git a/docs/de/docs/reference/request.md b/docs/de/docs/reference/request.md
deleted file mode 100644
index b170c1e40..000000000
--- a/docs/de/docs/reference/request.md
+++ /dev/null
@@ -1,14 +0,0 @@
-# `Request`-Klasse
-
-Sie können einen Parameter in einer *Pfadoperation-Funktion* oder einer Abhängigkeit als vom Typ `Request` deklarieren und dann direkt auf das Requestobjekt zugreifen, ohne jegliche Validierung, usw.
-
-Sie können es direkt von `fastapi` importieren:
-
-```python
-from fastapi import Request
-```
-
-!!! tip "Tipp"
- Wenn Sie Abhängigkeiten definieren möchten, die sowohl mit HTTP als auch mit WebSockets kompatibel sein sollen, können Sie einen Parameter definieren, der eine `HTTPConnection` anstelle eines `Request` oder eines `WebSocket` akzeptiert.
-
-::: fastapi.Request
diff --git a/docs/de/docs/reference/response.md b/docs/de/docs/reference/response.md
deleted file mode 100644
index 215918931..000000000
--- a/docs/de/docs/reference/response.md
+++ /dev/null
@@ -1,13 +0,0 @@
-# `Response`-Klasse
-
-Sie können einen Parameter in einer *Pfadoperation-Funktion* oder einer Abhängigkeit als `Response` deklarieren und dann Daten für die Response wie Header oder Cookies festlegen.
-
-Diese können Sie auch direkt verwenden, um eine Instanz davon zu erstellen und diese von Ihren *Pfadoperationen* zurückzugeben.
-
-Sie können sie direkt von `fastapi` importieren:
-
-```python
-from fastapi import Response
-```
-
-::: fastapi.Response
diff --git a/docs/de/docs/reference/responses.md b/docs/de/docs/reference/responses.md
deleted file mode 100644
index c0e9f07e7..000000000
--- a/docs/de/docs/reference/responses.md
+++ /dev/null
@@ -1,164 +0,0 @@
-# Benutzerdefinierte Responseklassen – File, HTML, Redirect, Streaming, usw.
-
-Es gibt mehrere benutzerdefinierte Responseklassen, von denen Sie eine Instanz erstellen und diese direkt von Ihren *Pfadoperationen* zurückgeben können.
-
-Lesen Sie mehr darüber in der [FastAPI-Dokumentation zu benutzerdefinierten Responses – HTML, Stream, Datei, andere](../advanced/custom-response.md).
-
-Sie können diese direkt von `fastapi.responses` importieren:
-
-```python
-from fastapi.responses import (
- FileResponse,
- HTMLResponse,
- JSONResponse,
- ORJSONResponse,
- PlainTextResponse,
- RedirectResponse,
- Response,
- StreamingResponse,
- UJSONResponse,
-)
-```
-
-## FastAPI-Responses
-
-Es gibt einige benutzerdefinierte FastAPI-Responseklassen, welche Sie verwenden können, um die JSON-Performanz zu optimieren.
-
-::: fastapi.responses.UJSONResponse
- options:
- members:
- - charset
- - status_code
- - media_type
- - body
- - background
- - raw_headers
- - render
- - init_headers
- - headers
- - set_cookie
- - delete_cookie
-
-::: fastapi.responses.ORJSONResponse
- options:
- members:
- - charset
- - status_code
- - media_type
- - body
- - background
- - raw_headers
- - render
- - init_headers
- - headers
- - set_cookie
- - delete_cookie
-
-## Starlette-Responses
-
-::: fastapi.responses.FileResponse
- options:
- members:
- - chunk_size
- - charset
- - status_code
- - media_type
- - body
- - background
- - raw_headers
- - render
- - init_headers
- - headers
- - set_cookie
- - delete_cookie
-
-::: fastapi.responses.HTMLResponse
- options:
- members:
- - charset
- - status_code
- - media_type
- - body
- - background
- - raw_headers
- - render
- - init_headers
- - headers
- - set_cookie
- - delete_cookie
-
-::: fastapi.responses.JSONResponse
- options:
- members:
- - charset
- - status_code
- - media_type
- - body
- - background
- - raw_headers
- - render
- - init_headers
- - headers
- - set_cookie
- - delete_cookie
-
-::: fastapi.responses.PlainTextResponse
- options:
- members:
- - charset
- - status_code
- - media_type
- - body
- - background
- - raw_headers
- - render
- - init_headers
- - headers
- - set_cookie
- - delete_cookie
-
-::: fastapi.responses.RedirectResponse
- options:
- members:
- - charset
- - status_code
- - media_type
- - body
- - background
- - raw_headers
- - render
- - init_headers
- - headers
- - set_cookie
- - delete_cookie
-
-::: fastapi.responses.Response
- options:
- members:
- - charset
- - status_code
- - media_type
- - body
- - background
- - raw_headers
- - render
- - init_headers
- - headers
- - set_cookie
- - delete_cookie
-
-::: fastapi.responses.StreamingResponse
- options:
- members:
- - body_iterator
- - charset
- - status_code
- - media_type
- - body
- - background
- - raw_headers
- - render
- - init_headers
- - headers
- - set_cookie
- - delete_cookie
diff --git a/docs/de/docs/reference/security/index.md b/docs/de/docs/reference/security/index.md
deleted file mode 100644
index 4c2375f2f..000000000
--- a/docs/de/docs/reference/security/index.md
+++ /dev/null
@@ -1,73 +0,0 @@
-# Sicherheitstools
-
-Wenn Sie Abhängigkeiten mit OAuth2-Scopes deklarieren müssen, verwenden Sie `Security()`.
-
-Aber Sie müssen immer noch definieren, was das Dependable, das Callable ist, welches Sie als Parameter an `Depends()` oder `Security()` übergeben.
-
-Es gibt mehrere Tools, mit denen Sie diese Dependables erstellen können, und sie werden in OpenAPI integriert, sodass sie in der Oberfläche der automatischen Dokumentation angezeigt werden und von automatisch generierten Clients und SDKs, usw., verwendet werden können.
-
-Sie können sie von `fastapi.security` importieren:
-
-```python
-from fastapi.security import (
- APIKeyCookie,
- APIKeyHeader,
- APIKeyQuery,
- HTTPAuthorizationCredentials,
- HTTPBasic,
- HTTPBasicCredentials,
- HTTPBearer,
- HTTPDigest,
- OAuth2,
- OAuth2AuthorizationCodeBearer,
- OAuth2PasswordBearer,
- OAuth2PasswordRequestForm,
- OAuth2PasswordRequestFormStrict,
- OpenIdConnect,
- SecurityScopes,
-)
-```
-
-## API-Schlüssel-Sicherheitsschemas
-
-::: fastapi.security.APIKeyCookie
-
-::: fastapi.security.APIKeyHeader
-
-::: fastapi.security.APIKeyQuery
-
-## HTTP-Authentifizierungsschemas
-
-::: fastapi.security.HTTPBasic
-
-::: fastapi.security.HTTPBearer
-
-::: fastapi.security.HTTPDigest
-
-## HTTP-Anmeldeinformationen
-
-::: fastapi.security.HTTPAuthorizationCredentials
-
-::: fastapi.security.HTTPBasicCredentials
-
-## OAuth2-Authentifizierung
-
-::: fastapi.security.OAuth2
-
-::: fastapi.security.OAuth2AuthorizationCodeBearer
-
-::: fastapi.security.OAuth2PasswordBearer
-
-## OAuth2-Passwortformulare
-
-::: fastapi.security.OAuth2PasswordRequestForm
-
-::: fastapi.security.OAuth2PasswordRequestFormStrict
-
-## OAuth2-Sicherheitsscopes in Abhängigkeiten
-
-::: fastapi.security.SecurityScopes
-
-## OpenID Connect
-
-::: fastapi.security.OpenIdConnect
diff --git a/docs/de/docs/reference/staticfiles.md b/docs/de/docs/reference/staticfiles.md
deleted file mode 100644
index 5629854c6..000000000
--- a/docs/de/docs/reference/staticfiles.md
+++ /dev/null
@@ -1,13 +0,0 @@
-# Statische Dateien – `StaticFiles`
-
-Sie können die `StaticFiles`-Klasse verwenden, um statische Dateien wie JavaScript, CSS, Bilder, usw. bereitzustellen.
-
-Lesen Sie mehr darüber in der [FastAPI-Dokumentation zu statischen Dateien](../tutorial/static-files.md).
-
-Sie können sie direkt von `fastapi.staticfiles` importieren:
-
-```python
-from fastapi.staticfiles import StaticFiles
-```
-
-::: fastapi.staticfiles.StaticFiles
diff --git a/docs/de/docs/reference/status.md b/docs/de/docs/reference/status.md
deleted file mode 100644
index 1d9458ee9..000000000
--- a/docs/de/docs/reference/status.md
+++ /dev/null
@@ -1,36 +0,0 @@
-# Statuscodes
-
-Sie können das Modul `status` von `fastapi` importieren:
-
-```python
-from fastapi import status
-```
-
-`status` wird direkt von Starlette bereitgestellt.
-
-Es enthält eine Gruppe benannter Konstanten (Variablen) mit ganzzahligen Statuscodes.
-
-Zum Beispiel:
-
-* 200: `status.HTTP_200_OK`
-* 403: `status.HTTP_403_FORBIDDEN`
-* usw.
-
-Es kann praktisch sein, schnell auf HTTP- (und WebSocket-)Statuscodes in Ihrer Anwendung zuzugreifen, indem Sie die automatische Vervollständigung für den Namen verwenden, ohne sich die Zahlen für die Statuscodes merken zu müssen.
-
-Lesen Sie mehr darüber in der [FastAPI-Dokumentation zu Response-Statuscodes](../tutorial/response-status-code.md).
-
-## Beispiel
-
-```python
-from fastapi import FastAPI, status
-
-app = FastAPI()
-
-
-@app.get("/items/", status_code=status.HTTP_418_IM_A_TEAPOT)
-def read_items():
- return [{"name": "Plumbus"}, {"name": "Portal Gun"}]
-```
-
-::: fastapi.status
diff --git a/docs/de/docs/reference/templating.md b/docs/de/docs/reference/templating.md
deleted file mode 100644
index c367a0179..000000000
--- a/docs/de/docs/reference/templating.md
+++ /dev/null
@@ -1,13 +0,0 @@
-# Templating – `Jinja2Templates`
-
-Sie können die `Jinja2Templates`-Klasse verwenden, um Jinja-Templates zu rendern.
-
-Lesen Sie mehr darüber in der [FastAPI-Dokumentation zu Templates](../advanced/templates.md).
-
-Sie können die Klasse direkt von `fastapi.templating` importieren:
-
-```python
-from fastapi.templating import Jinja2Templates
-```
-
-::: fastapi.templating.Jinja2Templates
diff --git a/docs/de/docs/reference/testclient.md b/docs/de/docs/reference/testclient.md
deleted file mode 100644
index 5bc089c05..000000000
--- a/docs/de/docs/reference/testclient.md
+++ /dev/null
@@ -1,13 +0,0 @@
-# Testclient – `TestClient`
-
-Sie können die `TestClient`-Klasse verwenden, um FastAPI-Anwendungen zu testen, ohne eine tatsächliche HTTP- und Socket-Verbindung zu erstellen, Sie kommunizieren einfach direkt mit dem FastAPI-Code.
-
-Lesen Sie mehr darüber in der [FastAPI-Dokumentation über Testen](../tutorial/testing.md).
-
-Sie können sie direkt von `fastapi.testclient` importieren:
-
-```python
-from fastapi.testclient import TestClient
-```
-
-::: fastapi.testclient.TestClient
diff --git a/docs/de/docs/reference/uploadfile.md b/docs/de/docs/reference/uploadfile.md
deleted file mode 100644
index 8556edf82..000000000
--- a/docs/de/docs/reference/uploadfile.md
+++ /dev/null
@@ -1,22 +0,0 @@
-# `UploadFile`-Klasse
-
-Sie können *Pfadoperation-Funktionsparameter* als Parameter vom Typ `UploadFile` definieren, um Dateien aus dem Request zu erhalten.
-
-Sie können es direkt von `fastapi` importieren:
-
-```python
-from fastapi import UploadFile
-```
-
-::: fastapi.UploadFile
- options:
- members:
- - file
- - filename
- - size
- - headers
- - content_type
- - read
- - write
- - seek
- - close
diff --git a/docs/de/docs/reference/websockets.md b/docs/de/docs/reference/websockets.md
deleted file mode 100644
index 35657172c..000000000
--- a/docs/de/docs/reference/websockets.md
+++ /dev/null
@@ -1,64 +0,0 @@
-# WebSockets
-
-Bei der Definition von WebSockets deklarieren Sie normalerweise einen Parameter vom Typ `WebSocket` und können damit Daten vom Client lesen und an ihn senden. Er wird direkt von Starlette bereitgestellt, Sie können ihn aber von `fastapi` importieren:
-
-```python
-from fastapi import WebSocket
-```
-
-!!! tip "Tipp"
- Wenn Sie Abhängigkeiten definieren möchten, die sowohl mit HTTP als auch mit WebSockets kompatibel sein sollen, können Sie einen Parameter definieren, der eine `HTTPConnection` anstelle eines `Request` oder eines `WebSocket` akzeptiert.
-
-::: fastapi.WebSocket
- options:
- members:
- - scope
- - app
- - url
- - base_url
- - headers
- - query_params
- - path_params
- - cookies
- - client
- - state
- - url_for
- - client_state
- - application_state
- - receive
- - send
- - accept
- - receive_text
- - receive_bytes
- - receive_json
- - iter_text
- - iter_bytes
- - iter_json
- - send_text
- - send_bytes
- - send_json
- - close
-
-Wenn ein Client die Verbindung trennt, wird eine `WebSocketDisconnect`-Exception ausgelöst, die Sie abfangen können.
-
-Sie können diese direkt von `fastapi` importieren:
-
-```python
-from fastapi import WebSocketDisconnect
-```
-
-::: fastapi.WebSocketDisconnect
-
-## WebSockets – zusätzliche Klassen
-
-Zusätzliche Klassen für die Handhabung von WebSockets.
-
-Werden direkt von Starlette bereitgestellt, Sie können sie jedoch von `fastapi` importieren:
-
-```python
-from fastapi.websockets import WebSocketDisconnect, WebSocketState
-```
-
-::: fastapi.websockets.WebSocketDisconnect
-
-::: fastapi.websockets.WebSocketState
diff --git a/docs/de/docs/tutorial/background-tasks.md b/docs/de/docs/tutorial/background-tasks.md
index a7bfd55a7..cd857f5e7 100644
--- a/docs/de/docs/tutorial/background-tasks.md
+++ b/docs/de/docs/tutorial/background-tasks.md
@@ -16,7 +16,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!}
```
**FastAPI** erstellt für Sie das Objekt vom Typ `BackgroundTasks` und übergibt es als diesen Parameter.
@@ -34,7 +34,7 @@ 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!}
```
## Den Hintergrundtask hinzufügen
@@ -42,7 +42,7 @@ Und da der Schreibvorgang nicht `async` und `await` verwendet, definieren wir di
Ü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!}
```
`.add_task()` erhält als Argumente:
@@ -57,41 +57,57 @@ Die Verwendung von `BackgroundTasks` funktioniert auch mit dem ../../../docs_src/background_tasks/tutorial002_an_py310.py!}
- ```
+```Python hl_lines="13 15 22 25"
+{!> ../../docs_src/background_tasks/tutorial002_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="13 15 22 25"
- {!> ../../../docs_src/background_tasks/tutorial002_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="13 15 22 25"
+{!> ../../docs_src/background_tasks/tutorial002_an_py39.py!}
+```
- ```Python hl_lines="14 16 23 26"
- {!> ../../../docs_src/background_tasks/tutorial002_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="14 16 23 26"
+{!> ../../docs_src/background_tasks/tutorial002_an.py!}
+```
- ```Python hl_lines="11 13 20 23"
- {!> ../../../docs_src/background_tasks/tutorial002_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="13 15 22 25"
- {!> ../../../docs_src/background_tasks/tutorial002.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="11 13 20 23"
+{!> ../../docs_src/background_tasks/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="13 15 22 25"
+{!> ../../docs_src/background_tasks/tutorial002.py!}
+```
+
+////
In obigem Beispiel werden die Nachrichten, *nachdem* die Response gesendet wurde, in die Datei `log.txt` geschrieben.
diff --git a/docs/de/docs/tutorial/bigger-applications.md b/docs/de/docs/tutorial/bigger-applications.md
index 66dee0a9a..000fa1f43 100644
--- a/docs/de/docs/tutorial/bigger-applications.md
+++ b/docs/de/docs/tutorial/bigger-applications.md
@@ -4,8 +4,11 @@ Wenn Sie eine Anwendung oder eine Web-API erstellen, ist es selten der Fall, das
**FastAPI** bietet ein praktisches Werkzeug zur Strukturierung Ihrer Anwendung bei gleichzeitiger Wahrung der Flexibilität.
-!!! info
- Wenn Sie von Flask kommen, wäre dies das Äquivalent zu Flasks Blueprints.
+/// info
+
+Wenn Sie von Flask kommen, wäre dies das Äquivalent zu Flasks Blueprints.
+
+///
## Eine Beispiel-Dateistruktur
@@ -26,16 +29,19 @@ Nehmen wir an, Sie haben eine Dateistruktur wie diese:
│ └── admin.py
```
-!!! tip "Tipp"
- Es gibt mehrere `__init__.py`-Dateien: eine in jedem Verzeichnis oder Unterverzeichnis.
+/// tip | "Tipp"
- Das ermöglicht den Import von Code aus einer Datei in eine andere.
+Es gibt mehrere `__init__.py`-Dateien: eine in jedem Verzeichnis oder Unterverzeichnis.
- In `app/main.py` könnten Sie beispielsweise eine Zeile wie diese haben:
+Das ermöglicht den Import von Code aus einer Datei in eine andere.
- ```
- from app.routers import items
- ```
+In `app/main.py` könnten Sie beispielsweise eine Zeile wie diese haben:
+
+```
+from app.routers import items
+```
+
+///
* Das Verzeichnis `app` enthält alles. Und es hat eine leere Datei `app/__init__.py`, es handelt sich also um ein „Python-Package“ (eine Sammlung von „Python-Modulen“): `app`.
* Es enthält eine Datei `app/main.py`. Da sie sich in einem Python-Package (einem Verzeichnis mit einer Datei `__init__.py`) befindet, ist sie ein „Modul“ dieses Packages: `app.main`.
@@ -80,7 +86,7 @@ Sie können die *Pfadoperationen* für dieses Modul mit `APIRouter` erstellen.
Sie importieren ihn und erstellen eine „Instanz“ auf die gleiche Weise wie mit der Klasse `FastAPI`:
```Python hl_lines="1 3" title="app/routers/users.py"
-{!../../../docs_src/bigger_applications/app/routers/users.py!}
+{!../../docs_src/bigger_applications/app/routers/users.py!}
```
### *Pfadoperationen* mit `APIRouter`
@@ -90,7 +96,7 @@ Und dann verwenden Sie ihn, um Ihre *Pfadoperationen* zu deklarieren.
Verwenden Sie ihn auf die gleiche Weise wie die Klasse `FastAPI`:
```Python hl_lines="6 11 16" title="app/routers/users.py"
-{!../../../docs_src/bigger_applications/app/routers/users.py!}
+{!../../docs_src/bigger_applications/app/routers/users.py!}
```
Sie können sich `APIRouter` als eine „Mini-`FastAPI`“-Klasse vorstellen.
@@ -99,8 +105,11 @@ Alle die gleichen Optionen werden unterstützt.
Alle die gleichen `parameters`, `responses`, `dependencies`, `tags`, usw.
-!!! tip "Tipp"
- In diesem Beispiel heißt die Variable `router`, aber Sie können ihr einen beliebigen Namen geben.
+/// tip | "Tipp"
+
+In diesem Beispiel heißt die Variable `router`, aber Sie können ihr einen beliebigen Namen geben.
+
+///
Wir werden diesen `APIRouter` in die Hauptanwendung `FastAPI` einbinden, aber zuerst kümmern wir uns um die Abhängigkeiten und einen anderen `APIRouter`.
@@ -112,31 +121,43 @@ Also fügen wir sie in ihr eigenes `dependencies`-Modul (`app/dependencies.py`)
Wir werden nun eine einfache Abhängigkeit verwenden, um einen benutzerdefinierten `X-Token`-Header zu lesen:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="3 6-8" title="app/dependencies.py"
- {!> ../../../docs_src/bigger_applications/app_an_py39/dependencies.py!}
- ```
+```Python hl_lines="3 6-8" title="app/dependencies.py"
+{!> ../../docs_src/bigger_applications/app_an_py39/dependencies.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1 5-7" title="app/dependencies.py"
- {!> ../../../docs_src/bigger_applications/app_an/dependencies.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ nicht annotiert"
+```Python hl_lines="1 5-7" title="app/dependencies.py"
+{!> ../../docs_src/bigger_applications/app_an/dependencies.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="1 4-6" title="app/dependencies.py"
- {!> ../../../docs_src/bigger_applications/app/dependencies.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
-!!! tip "Tipp"
- Um dieses Beispiel zu vereinfachen, verwenden wir einen erfundenen Header.
+/// tip | "Tipp"
- Aber in der Praxis werden Sie mit den integrierten [Sicherheits-Werkzeugen](security/index.md){.internal-link target=_blank} bessere Ergebnisse erzielen.
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="1 4-6" title="app/dependencies.py"
+{!> ../../docs_src/bigger_applications/app/dependencies.py!}
+```
+
+////
+
+/// tip | "Tipp"
+
+Um dieses Beispiel zu vereinfachen, verwenden wir einen erfundenen Header.
+
+Aber in der Praxis werden Sie mit den integrierten [Sicherheits-Werkzeugen](security/index.md){.internal-link target=_blank} bessere Ergebnisse erzielen.
+
+///
## Ein weiteres Modul mit `APIRouter`.
@@ -161,7 +182,7 @@ Wir wissen, dass alle *Pfadoperationen* in diesem Modul folgendes haben:
Anstatt also alles zu jeder *Pfadoperation* hinzuzufügen, können wir es dem `APIRouter` hinzufügen.
```Python hl_lines="5-10 16 21" title="app/routers/items.py"
-{!../../../docs_src/bigger_applications/app/routers/items.py!}
+{!../../docs_src/bigger_applications/app/routers/items.py!}
```
Da der Pfad jeder *Pfadoperation* mit `/` beginnen muss, wie in:
@@ -180,8 +201,11 @@ Wir können auch eine Liste von `tags` und zusätzliche `responses` hinzufügen,
Und wir können eine Liste von `dependencies` hinzufügen, die allen *Pfadoperationen* im Router hinzugefügt und für jeden an sie gerichteten Request ausgeführt/aufgelöst werden.
-!!! tip "Tipp"
- Beachten Sie, dass ähnlich wie bei [Abhängigkeiten in *Pfadoperation-Dekoratoren*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank} kein Wert an Ihre *Pfadoperation-Funktion* übergeben wird.
+/// tip | "Tipp"
+
+Beachten Sie, dass ähnlich wie bei [Abhängigkeiten in *Pfadoperation-Dekoratoren*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank} kein Wert an Ihre *Pfadoperation-Funktion* übergeben wird.
+
+///
Das Endergebnis ist, dass die Pfade für diese Artikel jetzt wie folgt lauten:
@@ -198,11 +222,17 @@ Das Endergebnis ist, dass die Pfade für diese Artikel jetzt wie folgt lauten:
* Zuerst werden die Router-Abhängigkeiten ausgeführt, dann die [`dependencies` im Dekorator](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank} und dann die normalen Parameterabhängigkeiten.
* Sie können auch [`Security`-Abhängigkeiten mit `scopes`](../advanced/security/oauth2-scopes.md){.internal-link target=_blank} hinzufügen.
-!!! tip "Tipp"
- `dependencies` im `APIRouter` können beispielsweise verwendet werden, um eine Authentifizierung für eine ganze Gruppe von *Pfadoperationen* zu erfordern. Selbst wenn die Abhängigkeiten nicht jeder einzeln hinzugefügt werden.
+/// tip | "Tipp"
-!!! check
- Die Parameter `prefix`, `tags`, `responses` und `dependencies` sind (wie in vielen anderen Fällen) nur ein Feature von **FastAPI**, um Ihnen dabei zu helfen, Codeverdoppelung zu vermeiden.
+`dependencies` im `APIRouter` können beispielsweise verwendet werden, um eine Authentifizierung für eine ganze Gruppe von *Pfadoperationen* zu erfordern. Selbst wenn die Abhängigkeiten nicht jeder einzeln hinzugefügt werden.
+
+///
+
+/// check
+
+Die Parameter `prefix`, `tags`, `responses` und `dependencies` sind (wie in vielen anderen Fällen) nur ein Feature von **FastAPI**, um Ihnen dabei zu helfen, Codeverdoppelung zu vermeiden.
+
+///
### Die Abhängigkeiten importieren
@@ -213,13 +243,16 @@ Und wir müssen die Abhängigkeitsfunktion aus dem Modul `app.dependencies` impo
Daher verwenden wir einen relativen Import mit `..` für die Abhängigkeiten:
```Python hl_lines="3" title="app/routers/items.py"
-{!../../../docs_src/bigger_applications/app/routers/items.py!}
+{!../../docs_src/bigger_applications/app/routers/items.py!}
```
#### Wie relative Importe funktionieren
-!!! tip "Tipp"
- Wenn Sie genau wissen, wie Importe funktionieren, fahren Sie mit dem nächsten Abschnitt unten fort.
+/// tip | "Tipp"
+
+Wenn Sie genau wissen, wie Importe funktionieren, fahren Sie mit dem nächsten Abschnitt unten fort.
+
+///
Ein einzelner Punkt `.`, wie in:
@@ -283,13 +316,16 @@ Wir fügen weder das Präfix `/items` noch `tags=["items"]` zu jeder *Pfadoperat
Aber wir können immer noch _mehr_ `tags` hinzufügen, die auf eine bestimmte *Pfadoperation* angewendet werden, sowie einige zusätzliche `responses`, die speziell für diese *Pfadoperation* gelten:
```Python hl_lines="30-31" title="app/routers/items.py"
-{!../../../docs_src/bigger_applications/app/routers/items.py!}
+{!../../docs_src/bigger_applications/app/routers/items.py!}
```
-!!! tip "Tipp"
- Diese letzte Pfadoperation wird eine Kombination von Tags haben: `["items", "custom"]`.
+/// tip | "Tipp"
- Und sie wird auch beide Responses in der Dokumentation haben, eine für `404` und eine für `403`.
+Diese letzte Pfadoperation wird eine Kombination von Tags haben: `["items", "custom"]`.
+
+Und sie wird auch beide Responses in der Dokumentation haben, eine für `404` und eine für `403`.
+
+///
## Das Haupt-`FastAPI`.
@@ -308,7 +344,7 @@ Sie importieren und erstellen wie gewohnt eine `FastAPI`-Klasse.
Und wir können sogar [globale Abhängigkeiten](dependencies/global-dependencies.md){.internal-link target=_blank} deklarieren, die mit den Abhängigkeiten für jeden `APIRouter` kombiniert werden:
```Python hl_lines="1 3 7" title="app/main.py"
-{!../../../docs_src/bigger_applications/app/main.py!}
+{!../../docs_src/bigger_applications/app/main.py!}
```
### Den `APIRouter` importieren
@@ -316,7 +352,7 @@ Und wir können sogar [globale Abhängigkeiten](dependencies/global-dependencies
Jetzt importieren wir die anderen Submodule, die `APIRouter` haben:
```Python hl_lines="4-5" title="app/main.py"
-{!../../../docs_src/bigger_applications/app/main.py!}
+{!../../docs_src/bigger_applications/app/main.py!}
```
Da es sich bei den Dateien `app/routers/users.py` und `app/routers/items.py` um Submodule handelt, die Teil desselben Python-Packages `app` sind, können wir einen einzelnen Punkt `.` verwenden, um sie mit „relativen Imports“ zu importieren.
@@ -345,20 +381,23 @@ Wir könnten sie auch wie folgt importieren:
from app.routers import items, users
```
-!!! info
- Die erste Version ist ein „relativer Import“:
+/// info
- ```Python
- from .routers import items, users
- ```
+Die erste Version ist ein „relativer Import“:
- Die zweite Version ist ein „absoluter Import“:
+```Python
+from .routers import items, users
+```
- ```Python
- from app.routers import items, users
- ```
+Die zweite Version ist ein „absoluter Import“:
- Um mehr über Python-Packages und -Module zu erfahren, lesen Sie die offizielle Python-Dokumentation über Module.
+```Python
+from app.routers import items, users
+```
+
+Um mehr über Python-Packages und -Module zu erfahren, lesen Sie die offizielle Python-Dokumentation über Module.
+
+///
### Namenskollisionen vermeiden
@@ -378,7 +417,7 @@ würde der `router` von `users` den von `items` überschreiben und wir könnten
Um also beide in derselben Datei verwenden zu können, importieren wir die Submodule direkt:
```Python hl_lines="5" title="app/main.py"
-{!../../../docs_src/bigger_applications/app/main.py!}
+{!../../docs_src/bigger_applications/app/main.py!}
```
@@ -387,29 +426,38 @@ Um also beide in derselben Datei verwenden zu können, importieren wir die Submo
Inkludieren wir nun die `router` aus diesen Submodulen `users` und `items`:
```Python hl_lines="10-11" title="app/main.py"
-{!../../../docs_src/bigger_applications/app/main.py!}
+{!../../docs_src/bigger_applications/app/main.py!}
```
-!!! info
- `users.router` enthält den `APIRouter` in der Datei `app/routers/users.py`.
+/// info
- Und `items.router` enthält den `APIRouter` in der Datei `app/routers/items.py`.
+`users.router` enthält den `APIRouter` in der Datei `app/routers/users.py`.
+
+Und `items.router` enthält den `APIRouter` in der Datei `app/routers/items.py`.
+
+///
Mit `app.include_router()` können wir jeden `APIRouter` zur Hauptanwendung `FastAPI` hinzufügen.
Es wird alle Routen von diesem Router als Teil von dieser inkludieren.
-!!! note "Technische Details"
- Tatsächlich wird intern eine *Pfadoperation* für jede *Pfadoperation* erstellt, die im `APIRouter` deklariert wurde.
+/// note | "Technische Details"
- Hinter den Kulissen wird es also tatsächlich so funktionieren, als ob alles dieselbe einzige Anwendung wäre.
+Tatsächlich wird intern eine *Pfadoperation* für jede *Pfadoperation* erstellt, die im `APIRouter` deklariert wurde.
-!!! check
- Bei der Einbindung von Routern müssen Sie sich keine Gedanken über die Performanz machen.
+Hinter den Kulissen wird es also tatsächlich so funktionieren, als ob alles dieselbe einzige Anwendung wäre.
- Dies dauert Mikrosekunden und geschieht nur beim Start.
+///
- Es hat also keinen Einfluss auf die Leistung. ⚡
+/// check
+
+Bei der Einbindung von Routern müssen Sie sich keine Gedanken über die Performanz machen.
+
+Dies dauert Mikrosekunden und geschieht nur beim Start.
+
+Es hat also keinen Einfluss auf die Leistung. ⚡
+
+///
### Einen `APIRouter` mit benutzerdefinierten `prefix`, `tags`, `responses` und `dependencies` einfügen
@@ -420,7 +468,7 @@ Sie enthält einen `APIRouter` mit einigen administrativen *Pfadoperationen*, di
In diesem Beispiel wird es ganz einfach sein. Nehmen wir jedoch an, dass wir, da sie mit anderen Projekten in der Organisation geteilt wird, sie nicht ändern und kein `prefix`, `dependencies`, `tags`, usw. direkt zum `APIRouter` hinzufügen können:
```Python hl_lines="3" title="app/internal/admin.py"
-{!../../../docs_src/bigger_applications/app/internal/admin.py!}
+{!../../docs_src/bigger_applications/app/internal/admin.py!}
```
Aber wir möchten immer noch ein benutzerdefiniertes `prefix` festlegen, wenn wir den `APIRouter` einbinden, sodass alle seine *Pfadoperationen* mit `/admin` beginnen, wir möchten es mit den `dependencies` sichern, die wir bereits für dieses Projekt haben, und wir möchten `tags` und `responses` hinzufügen.
@@ -428,7 +476,7 @@ Aber wir möchten immer noch ein benutzerdefiniertes `prefix` festlegen, wenn wi
Wir können das alles deklarieren, ohne den ursprünglichen `APIRouter` ändern zu müssen, indem wir diese Parameter an `app.include_router()` übergeben:
```Python hl_lines="14-17" title="app/main.py"
-{!../../../docs_src/bigger_applications/app/main.py!}
+{!../../docs_src/bigger_applications/app/main.py!}
```
Auf diese Weise bleibt der ursprüngliche `APIRouter` unverändert, sodass wir dieselbe `app/internal/admin.py`-Datei weiterhin mit anderen Projekten in der Organisation teilen können.
@@ -451,21 +499,24 @@ Wir können *Pfadoperationen* auch direkt zur `FastAPI`-App hinzufügen.
Hier machen wir es ... nur um zu zeigen, dass wir es können 🤷:
```Python hl_lines="21-23" title="app/main.py"
-{!../../../docs_src/bigger_applications/app/main.py!}
+{!../../docs_src/bigger_applications/app/main.py!}
```
und es wird korrekt funktionieren, zusammen mit allen anderen *Pfadoperationen*, die mit `app.include_router()` hinzugefügt wurden.
-!!! info "Sehr technische Details"
- **Hinweis**: Dies ist ein sehr technisches Detail, das Sie wahrscheinlich **einfach überspringen** können.
+/// info | "Sehr technische Details"
- ---
+**Hinweis**: Dies ist ein sehr technisches Detail, das Sie wahrscheinlich **einfach überspringen** können.
- Die `APIRouter` sind nicht „gemountet“, sie sind nicht vom Rest der Anwendung isoliert.
+---
- Das liegt daran, dass wir deren *Pfadoperationen* in das OpenAPI-Schema und die Benutzeroberflächen einbinden möchten.
+Die `APIRouter` sind nicht „gemountet“, sie sind nicht vom Rest der Anwendung isoliert.
- Da wir sie nicht einfach isolieren und unabhängig vom Rest „mounten“ können, werden die *Pfadoperationen* „geklont“ (neu erstellt) und nicht direkt einbezogen.
+Das liegt daran, dass wir deren *Pfadoperationen* in das OpenAPI-Schema und die Benutzeroberflächen einbinden möchten.
+
+Da wir sie nicht einfach isolieren und unabhängig vom Rest „mounten“ können, werden die *Pfadoperationen* „geklont“ (neu erstellt) und nicht direkt einbezogen.
+
+///
## Es in der automatischen API-Dokumentation ansehen
diff --git a/docs/de/docs/tutorial/body-fields.md b/docs/de/docs/tutorial/body-fields.md
index 643be7489..d22524c67 100644
--- a/docs/de/docs/tutorial/body-fields.md
+++ b/docs/de/docs/tutorial/body-fields.md
@@ -6,98 +6,139 @@ So wie Sie zusätzliche Validation und Metadaten in Parametern der **Pfadoperati
Importieren Sie es zuerst:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="4"
+{!> ../../docs_src/body_fields/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="4"
+{!> ../../docs_src/body_fields/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="4"
+{!> ../../docs_src/body_fields/tutorial001_an.py!}
+```
- ```Python hl_lines="2"
- {!> ../../../docs_src/body_fields/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-!!! warning "Achtung"
- Beachten Sie, dass `Field` direkt von `pydantic` importiert wird, nicht von `fastapi`, wie die anderen (`Query`, `Path`, `Body`, usw.)
+///
+
+```Python hl_lines="2"
+{!> ../../docs_src/body_fields/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="4"
+{!> ../../docs_src/body_fields/tutorial001.py!}
+```
+
+////
+
+/// warning | "Achtung"
+
+Beachten Sie, dass `Field` direkt von `pydantic` importiert wird, nicht von `fastapi`, wie die anderen (`Query`, `Path`, `Body`, usw.)
+
+///
## Modellattribute deklarieren
Dann können Sie `Field` mit Modellattributen deklarieren:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="11-14"
+{!> ../../docs_src/body_fields/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="11-14"
+{!> ../../docs_src/body_fields/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="12-15"
- {!> ../../../docs_src/body_fields/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="12-15"
+{!> ../../docs_src/body_fields/tutorial001_an.py!}
+```
- ```Python hl_lines="9-12"
- {!> ../../../docs_src/body_fields/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="9-12"
+{!> ../../docs_src/body_fields/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="11-14"
+{!> ../../docs_src/body_fields/tutorial001.py!}
+```
+
+////
`Field` funktioniert genauso wie `Query`, `Path` und `Body`, es hat die gleichen Parameter, usw.
-!!! note "Technische Details"
- Tatsächlich erstellen `Query`, `Path` und andere, die sie kennenlernen werden, Instanzen von Unterklassen einer allgemeinen Klasse `Param`, die ihrerseits eine Unterklasse von Pydantics `FieldInfo`-Klasse ist.
+/// note | "Technische Details"
- Und Pydantics `Field` gibt ebenfalls eine Instanz von `FieldInfo` zurück.
+Tatsächlich erstellen `Query`, `Path` und andere, die sie kennenlernen werden, Instanzen von Unterklassen einer allgemeinen Klasse `Param`, die ihrerseits eine Unterklasse von Pydantics `FieldInfo`-Klasse ist.
- `Body` gibt auch Instanzen einer Unterklasse von `FieldInfo` zurück. Und später werden Sie andere sehen, die Unterklassen der `Body`-Klasse sind.
+Und Pydantics `Field` gibt ebenfalls eine Instanz von `FieldInfo` zurück.
- Denken Sie daran, dass `Query`, `Path` und andere von `fastapi` tatsächlich Funktionen sind, die spezielle Klassen zurückgeben.
+`Body` gibt auch Instanzen einer Unterklasse von `FieldInfo` zurück. Und später werden Sie andere sehen, die Unterklassen der `Body`-Klasse sind.
-!!! tip "Tipp"
- Beachten Sie, dass jedes Modellattribut mit einem Typ, Defaultwert und `Field` die gleiche Struktur hat wie ein Parameter einer Pfadoperation-Funktion, nur mit `Field` statt `Path`, `Query`, `Body`.
+Denken Sie daran, dass `Query`, `Path` und andere von `fastapi` tatsächlich Funktionen sind, die spezielle Klassen zurückgeben.
+
+///
+
+/// tip | "Tipp"
+
+Beachten Sie, dass jedes Modellattribut mit einem Typ, Defaultwert und `Field` die gleiche Struktur hat wie ein Parameter einer Pfadoperation-Funktion, nur mit `Field` statt `Path`, `Query`, `Body`.
+
+///
## Zusätzliche Information hinzufügen
@@ -105,8 +146,11 @@ Sie können zusätzliche Information in `Field`, `Query`, `Body`, usw. deklarier
Sie werden später mehr darüber lernen, wie man zusätzliche Information unterbringt, wenn Sie lernen, Beispiele zu deklarieren.
-!!! warning "Achtung"
- Extra-Schlüssel, die `Field` überreicht werden, werden auch im resultierenden OpenAPI-Schema Ihrer Anwendung gelistet. Da diese Schlüssel nicht notwendigerweise Teil der OpenAPI-Spezifikation sind, könnten einige OpenAPI-Tools, wie etwa [der OpenAPI-Validator](https://validator.swagger.io/), nicht mit Ihrem generierten Schema funktionieren.
+/// warning | "Achtung"
+
+Extra-Schlüssel, die `Field` überreicht werden, werden auch im resultierenden OpenAPI-Schema Ihrer Anwendung gelistet. Da diese Schlüssel nicht notwendigerweise Teil der OpenAPI-Spezifikation sind, könnten einige OpenAPI-Tools, wie etwa [der OpenAPI-Validator](https://validator.swagger.io/), nicht mit Ihrem generierten Schema funktionieren.
+
+///
## Zusammenfassung
diff --git a/docs/de/docs/tutorial/body-multiple-params.md b/docs/de/docs/tutorial/body-multiple-params.md
index 6a237243e..26ae73ebc 100644
--- a/docs/de/docs/tutorial/body-multiple-params.md
+++ b/docs/de/docs/tutorial/body-multiple-params.md
@@ -8,44 +8,63 @@ Zuerst einmal, Sie können `Path`-, `Query`- und Requestbody-Parameter-Deklarati
Und Sie können auch Body-Parameter als optional kennzeichnen, indem Sie den Defaultwert auf `None` setzen:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="18-20"
- {!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="18-20"
+{!> ../../docs_src/body_multiple_params/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="18-20"
- {!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="18-20"
+{!> ../../docs_src/body_multiple_params/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="19-21"
- {!> ../../../docs_src/body_multiple_params/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="19-21"
+{!> ../../docs_src/body_multiple_params/tutorial001_an.py!}
+```
- ```Python hl_lines="17-19"
- {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="19-21"
- {!> ../../../docs_src/body_multiple_params/tutorial001.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-!!! note "Hinweis"
- Beachten Sie, dass in diesem Fall das `item`, welches vom Body genommen wird, optional ist. Da es `None` als Defaultwert hat.
+///
+
+```Python hl_lines="17-19"
+{!> ../../docs_src/body_multiple_params/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="19-21"
+{!> ../../docs_src/body_multiple_params/tutorial001.py!}
+```
+
+////
+
+/// note | "Hinweis"
+
+Beachten Sie, dass in diesem Fall das `item`, welches vom Body genommen wird, optional ist. Da es `None` als Defaultwert hat.
+
+///
## Mehrere Body-Parameter
@@ -62,17 +81,21 @@ Im vorherigen Beispiel erwartete die *Pfadoperation* einen JSON-Body mit den Att
Aber Sie können auch mehrere Body-Parameter deklarieren, z. B. `item` und `user`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!}
- ```
+```Python hl_lines="20"
+{!> ../../docs_src/body_multiple_params/tutorial002_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="22"
- {!> ../../../docs_src/body_multiple_params/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="22"
+{!> ../../docs_src/body_multiple_params/tutorial002.py!}
+```
+
+////
In diesem Fall wird **FastAPI** bemerken, dass es mehr als einen Body-Parameter in der Funktion gibt (zwei Parameter, die Pydantic-Modelle sind).
@@ -93,8 +116,11 @@ Es wird deshalb die Parameternamen als Schlüssel (Feldnamen) im Body verwenden,
}
```
-!!! note "Hinweis"
- Beachten Sie, dass, obwohl `item` wie zuvor deklariert wurde, es nun unter einem Schlüssel `item` im Body erwartet wird.
+/// note | "Hinweis"
+
+Beachten Sie, dass, obwohl `item` wie zuvor deklariert wurde, es nun unter einem Schlüssel `item` im Body erwartet wird.
+
+///
**FastAPI** wird die automatische Konvertierung des Requests übernehmen, sodass der Parameter `item` seinen spezifischen Inhalt bekommt, genau so wie der Parameter `user`.
@@ -110,41 +136,57 @@ Wenn Sie diesen Parameter einfach so hinzufügen, wird **FastAPI** annehmen, das
Aber Sie können **FastAPI** instruieren, ihn als weiteren Body-Schlüssel zu erkennen, indem Sie `Body` verwenden:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="23"
- {!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!}
- ```
+```Python hl_lines="23"
+{!> ../../docs_src/body_multiple_params/tutorial003_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="23"
- {!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="23"
+{!> ../../docs_src/body_multiple_params/tutorial003_an_py39.py!}
+```
- ```Python hl_lines="24"
- {!> ../../../docs_src/body_multiple_params/tutorial003_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="24"
+{!> ../../docs_src/body_multiple_params/tutorial003_an.py!}
+```
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="22"
- {!> ../../../docs_src/body_multiple_params/tutorial003.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="20"
+{!> ../../docs_src/body_multiple_params/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="22"
+{!> ../../docs_src/body_multiple_params/tutorial003.py!}
+```
+
+////
In diesem Fall erwartet **FastAPI** einen Body wie:
@@ -184,44 +226,63 @@ q: str | None = None
Zum Beispiel:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!}
- ```
+```Python hl_lines="27"
+{!> ../../docs_src/body_multiple_params/tutorial004_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="27"
+{!> ../../docs_src/body_multiple_params/tutorial004_an_py39.py!}
+```
- ```Python hl_lines="28"
- {!> ../../../docs_src/body_multiple_params/tutorial004_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="28"
+{!> ../../docs_src/body_multiple_params/tutorial004_an.py!}
+```
- ```Python hl_lines="25"
- {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-!!! info
- `Body` hat die gleichen zusätzlichen Validierungs- und Metadaten-Parameter wie `Query` und `Path` und andere, die Sie später kennenlernen.
+///
+
+```Python hl_lines="25"
+{!> ../../docs_src/body_multiple_params/tutorial004_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="27"
+{!> ../../docs_src/body_multiple_params/tutorial004.py!}
+```
+
+////
+
+/// info
+
+`Body` hat die gleichen zusätzlichen Validierungs- und Metadaten-Parameter wie `Query` und `Path` und andere, die Sie später kennenlernen.
+
+///
## Einen einzelnen Body-Parameter einbetten
@@ -237,41 +298,57 @@ item: Item = Body(embed=True)
so wie in:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="17"
- {!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!}
- ```
+```Python hl_lines="17"
+{!> ../../docs_src/body_multiple_params/tutorial005_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="17"
- {!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="17"
+{!> ../../docs_src/body_multiple_params/tutorial005_an_py39.py!}
+```
- ```Python hl_lines="18"
- {!> ../../../docs_src/body_multiple_params/tutorial005_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="18"
+{!> ../../docs_src/body_multiple_params/tutorial005_an.py!}
+```
- ```Python hl_lines="15"
- {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="17"
- {!> ../../../docs_src/body_multiple_params/tutorial005.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="15"
+{!> ../../docs_src/body_multiple_params/tutorial005_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="17"
+{!> ../../docs_src/body_multiple_params/tutorial005.py!}
+```
+
+////
In diesem Fall erwartet **FastAPI** einen Body wie:
diff --git a/docs/de/docs/tutorial/body-nested-models.md b/docs/de/docs/tutorial/body-nested-models.md
index a7a15a6c2..13153aa68 100644
--- a/docs/de/docs/tutorial/body-nested-models.md
+++ b/docs/de/docs/tutorial/body-nested-models.md
@@ -6,17 +6,21 @@ Mit **FastAPI** können Sie (dank Pydantic) beliebig tief verschachtelte Modelle
Sie können ein Attribut als Kindtyp definieren, zum Beispiel eine Python-`list`e.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="12"
- {!> ../../../docs_src/body_nested_models/tutorial001_py310.py!}
- ```
+```Python hl_lines="12"
+{!> ../../docs_src/body_nested_models/tutorial001_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="14"
+{!> ../../docs_src/body_nested_models/tutorial001.py!}
+```
+
+////
Das bewirkt, dass `tags` eine Liste ist, wenngleich es nichts über den Typ der Elemente der Liste aussagt.
@@ -31,7 +35,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!}
```
### Eine `list`e mit einem Typ-Parameter deklarieren
@@ -61,23 +65,29 @@ Verwenden Sie dieselbe Standardsyntax für Modellattribute mit inneren Typen.
In unserem Beispiel können wir also bewirken, dass `tags` spezifisch eine „Liste von Strings“ ist:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="12"
- {!> ../../../docs_src/body_nested_models/tutorial002_py310.py!}
- ```
+```Python hl_lines="12"
+{!> ../../docs_src/body_nested_models/tutorial002_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial002_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="14"
+{!> ../../docs_src/body_nested_models/tutorial002_py39.py!}
+```
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial002.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="14"
+{!> ../../docs_src/body_nested_models/tutorial002.py!}
+```
+
+////
## Set-Typen
@@ -87,23 +97,29 @@ Python hat einen Datentyp speziell für Mengen eindeutiger Dinge: das ../../../docs_src/body_nested_models/tutorial003_py310.py!}
- ```
+```Python hl_lines="12"
+{!> ../../docs_src/body_nested_models/tutorial003_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial003_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="14"
+{!> ../../docs_src/body_nested_models/tutorial003_py39.py!}
+```
- ```Python hl_lines="1 14"
- {!> ../../../docs_src/body_nested_models/tutorial003.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="1 14"
+{!> ../../docs_src/body_nested_models/tutorial003.py!}
+```
+
+////
Jetzt, selbst wenn Sie einen Request mit duplizierten Daten erhalten, werden diese zu einem Set eindeutiger Dinge konvertiert.
@@ -125,45 +141,57 @@ Alles das beliebig tief verschachtelt.
Wir können zum Beispiel ein `Image`-Modell definieren.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7-9"
- {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!}
- ```
+```Python hl_lines="7-9"
+{!> ../../docs_src/body_nested_models/tutorial004_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="9-11"
- {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="9-11"
+{!> ../../docs_src/body_nested_models/tutorial004_py39.py!}
+```
- ```Python hl_lines="9-11"
- {!> ../../../docs_src/body_nested_models/tutorial004.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9-11"
+{!> ../../docs_src/body_nested_models/tutorial004.py!}
+```
+
+////
### Das Kindmodell als Typ verwenden
Und dann können wir es als Typ eines Attributes verwenden.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="18"
- {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!}
- ```
+```Python hl_lines="18"
+{!> ../../docs_src/body_nested_models/tutorial004_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="20"
+{!> ../../docs_src/body_nested_models/tutorial004_py39.py!}
+```
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial004.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="20"
+{!> ../../docs_src/body_nested_models/tutorial004.py!}
+```
+
+////
Das würde bedeuten, dass **FastAPI** einen Body erwartet wie:
@@ -196,23 +224,29 @@ Um alle Optionen kennenzulernen, die Sie haben, schauen Sie sich ../../../docs_src/body_nested_models/tutorial005_py310.py!}
- ```
+```Python hl_lines="2 8"
+{!> ../../docs_src/body_nested_models/tutorial005_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="4 10"
- {!> ../../../docs_src/body_nested_models/tutorial005_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="4 10"
+{!> ../../docs_src/body_nested_models/tutorial005_py39.py!}
+```
- ```Python hl_lines="4 10"
- {!> ../../../docs_src/body_nested_models/tutorial005.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="4 10"
+{!> ../../docs_src/body_nested_models/tutorial005.py!}
+```
+
+////
Es wird getestet, ob der String eine gültige URL ist, und als solche wird er in JSON Schema / OpenAPI dokumentiert.
@@ -220,23 +254,29 @@ Es wird getestet, ob der String eine gültige URL ist, und als solche wird er in
Sie können Pydantic-Modelle auch als Typen innerhalb von `list`, `set`, usw. verwenden:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="18"
- {!> ../../../docs_src/body_nested_models/tutorial006_py310.py!}
- ```
+```Python hl_lines="18"
+{!> ../../docs_src/body_nested_models/tutorial006_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial006_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="20"
+{!> ../../docs_src/body_nested_models/tutorial006_py39.py!}
+```
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial006.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="20"
+{!> ../../docs_src/body_nested_models/tutorial006.py!}
+```
+
+////
Das wird einen JSON-Body erwarten (konvertieren, validieren, dokumentieren), wie:
@@ -264,33 +304,45 @@ Das wird einen JSON-Body erwarten (konvertieren, validieren, dokumentieren), wie
}
```
-!!! info
- Beachten Sie, dass der `images`-Schlüssel jetzt eine Liste von Bild-Objekten hat.
+/// info
+
+Beachten Sie, dass der `images`-Schlüssel jetzt eine Liste von Bild-Objekten hat.
+
+///
## Tief verschachtelte Modelle
Sie können beliebig tief verschachtelte Modelle definieren:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7 12 18 21 25"
- {!> ../../../docs_src/body_nested_models/tutorial007_py310.py!}
- ```
+```Python hl_lines="7 12 18 21 25"
+{!> ../../docs_src/body_nested_models/tutorial007_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="9 14 20 23 27"
- {!> ../../../docs_src/body_nested_models/tutorial007_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="9 14 20 23 27"
+{!> ../../docs_src/body_nested_models/tutorial007_py39.py!}
+```
- ```Python hl_lines="9 14 20 23 27"
- {!> ../../../docs_src/body_nested_models/tutorial007.py!}
- ```
+////
-!!! info
- Beachten Sie, wie `Offer` eine Liste von `Item`s hat, von denen jedes seinerseits eine optionale Liste von `Image`s hat.
+//// tab | Python 3.8+
+
+```Python hl_lines="9 14 20 23 27"
+{!> ../../docs_src/body_nested_models/tutorial007.py!}
+```
+
+////
+
+/// info
+
+Beachten Sie, wie `Offer` eine Liste von `Item`s hat, von denen jedes seinerseits eine optionale Liste von `Image`s hat.
+
+///
## Bodys aus reinen Listen
@@ -308,17 +360,21 @@ images: list[Image]
so wie in:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="13"
- {!> ../../../docs_src/body_nested_models/tutorial008_py39.py!}
- ```
+```Python hl_lines="13"
+{!> ../../docs_src/body_nested_models/tutorial008_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="15"
- {!> ../../../docs_src/body_nested_models/tutorial008.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="15"
+{!> ../../docs_src/body_nested_models/tutorial008.py!}
+```
+
+////
## Editor-Unterstützung überall
@@ -348,26 +404,33 @@ Das schauen wir uns mal an.
Im folgenden Beispiel akzeptieren Sie irgendein `dict`, solange es `int`-Schlüssel und `float`-Werte hat.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="7"
- {!> ../../../docs_src/body_nested_models/tutorial009_py39.py!}
- ```
+```Python hl_lines="7"
+{!> ../../docs_src/body_nested_models/tutorial009_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/body_nested_models/tutorial009.py!}
- ```
+//// tab | Python 3.8+
-!!! tip "Tipp"
- Bedenken Sie, dass JSON nur `str` als Schlüssel unterstützt.
+```Python hl_lines="9"
+{!> ../../docs_src/body_nested_models/tutorial009.py!}
+```
- Aber Pydantic hat automatische Datenkonvertierung.
+////
- Das bedeutet, dass Ihre API-Clients nur Strings senden können, aber solange diese Strings nur Zahlen enthalten, wird Pydantic sie konvertieren und validieren.
+/// tip | "Tipp"
- Und das `dict` welches Sie als `weights` erhalten, wird `int`-Schlüssel und `float`-Werte haben.
+Bedenken Sie, dass JSON nur `str` als Schlüssel unterstützt.
+
+Aber Pydantic hat automatische Datenkonvertierung.
+
+Das bedeutet, dass Ihre API-Clients nur Strings senden können, aber solange diese Strings nur Zahlen enthalten, wird Pydantic sie konvertieren und validieren.
+
+Und das `dict` welches Sie als `weights` erhalten, wird `int`-Schlüssel und `float`-Werte haben.
+
+///
## Zusammenfassung
diff --git a/docs/de/docs/tutorial/body-updates.md b/docs/de/docs/tutorial/body-updates.md
index 2b3716d6f..ed5c1890f 100644
--- a/docs/de/docs/tutorial/body-updates.md
+++ b/docs/de/docs/tutorial/body-updates.md
@@ -6,23 +6,29 @@ Um einen Artikel zu aktualisieren, können Sie die ../../../docs_src/body_updates/tutorial001_py310.py!}
- ```
+```Python hl_lines="28-33"
+{!> ../../docs_src/body_updates/tutorial001_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="30-35"
- {!> ../../../docs_src/body_updates/tutorial001_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="30-35"
+{!> ../../docs_src/body_updates/tutorial001_py39.py!}
+```
- ```Python hl_lines="30-35"
- {!> ../../../docs_src/body_updates/tutorial001.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="30-35"
+{!> ../../docs_src/body_updates/tutorial001.py!}
+```
+
+////
`PUT` wird verwendet, um Daten zu empfangen, die die existierenden Daten ersetzen sollen.
@@ -48,14 +54,17 @@ Sie können auch die ../../../docs_src/body_updates/tutorial002_py310.py!}
- ```
+```Python hl_lines="32"
+{!> ../../docs_src/body_updates/tutorial002_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="34"
- {!> ../../../docs_src/body_updates/tutorial002_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="34"
+{!> ../../docs_src/body_updates/tutorial002_py39.py!}
+```
- ```Python hl_lines="34"
- {!> ../../../docs_src/body_updates/tutorial002.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="34"
+{!> ../../docs_src/body_updates/tutorial002.py!}
+```
+
+////
### Pydantics `update`-Parameter verwenden
Jetzt können Sie eine Kopie des existierenden Modells mittels `.model_copy()` erstellen, wobei Sie dem `update`-Parameter ein `dict` mit den zu ändernden Daten übergeben.
-!!! info
- In Pydantic v1 hieß diese Methode `.copy()`, in Pydantic v2 wurde sie deprecated (aber immer noch unterstützt) und in `.model_copy()` umbenannt.
+/// info
- Die Beispiele hier verwenden `.copy()` für die Kompatibilität mit Pydantic v1, Sie sollten jedoch stattdessen `.model_copy()` verwenden, wenn Sie Pydantic v2 verwenden können.
+In Pydantic v1 hieß diese Methode `.copy()`, in Pydantic v2 wurde sie deprecated (aber immer noch unterstützt) und in `.model_copy()` umbenannt.
+
+Die Beispiele hier verwenden `.copy()` für die Kompatibilität mit Pydantic v1, Sie sollten jedoch stattdessen `.model_copy()` verwenden, wenn Sie Pydantic v2 verwenden können.
+
+///
Wie in `stored_item_model.model_copy(update=update_data)`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="33"
- {!> ../../../docs_src/body_updates/tutorial002_py310.py!}
- ```
+```Python hl_lines="33"
+{!> ../../docs_src/body_updates/tutorial002_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="35"
- {!> ../../../docs_src/body_updates/tutorial002_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="35"
+{!> ../../docs_src/body_updates/tutorial002_py39.py!}
+```
- ```Python hl_lines="35"
- {!> ../../../docs_src/body_updates/tutorial002.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="35"
+{!> ../../docs_src/body_updates/tutorial002.py!}
+```
+
+////
### Rekapitulation zum teilweisen Ersetzen
@@ -134,32 +161,44 @@ Zusammengefasst, um Teil-Ersetzungen vorzunehmen:
* Speichern Sie die Daten in Ihrer Datenbank.
* Geben Sie das aktualisierte Modell zurück.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="28-35"
- {!> ../../../docs_src/body_updates/tutorial002_py310.py!}
- ```
+```Python hl_lines="28-35"
+{!> ../../docs_src/body_updates/tutorial002_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="30-37"
- {!> ../../../docs_src/body_updates/tutorial002_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="30-37"
+{!> ../../docs_src/body_updates/tutorial002_py39.py!}
+```
- ```Python hl_lines="30-37"
- {!> ../../../docs_src/body_updates/tutorial002.py!}
- ```
+////
-!!! tip "Tipp"
- Sie können tatsächlich die gleiche Technik mit einer HTTP `PUT` Operation verwenden.
+//// tab | Python 3.8+
- Aber dieses Beispiel verwendet `PATCH`, da dieses für solche Anwendungsfälle geschaffen wurde.
+```Python hl_lines="30-37"
+{!> ../../docs_src/body_updates/tutorial002.py!}
+```
-!!! note "Hinweis"
- Beachten Sie, dass das hereinkommende Modell immer noch validiert wird.
+////
- Wenn Sie also Teil-Aktualisierungen empfangen wollen, die alle Attribute auslassen können, müssen Sie ein Modell haben, dessen Attribute alle als optional gekennzeichnet sind (mit Defaultwerten oder `None`).
+/// tip | "Tipp"
- Um zu unterscheiden zwischen Modellen für **Aktualisierungen**, mit lauter optionalen Werten, und solchen für die **Erzeugung**, mit benötigten Werten, können Sie die Techniken verwenden, die in [Extramodelle](extra-models.md){.internal-link target=_blank} beschrieben wurden.
+Sie können tatsächlich die gleiche Technik mit einer HTTP `PUT` Operation verwenden.
+
+Aber dieses Beispiel verwendet `PATCH`, da dieses für solche Anwendungsfälle geschaffen wurde.
+
+///
+
+/// note | "Hinweis"
+
+Beachten Sie, dass das hereinkommende Modell immer noch validiert wird.
+
+Wenn Sie also Teil-Aktualisierungen empfangen wollen, die alle Attribute auslassen können, müssen Sie ein Modell haben, dessen Attribute alle als optional gekennzeichnet sind (mit Defaultwerten oder `None`).
+
+Um zu unterscheiden zwischen Modellen für **Aktualisierungen**, mit lauter optionalen Werten, und solchen für die **Erzeugung**, mit benötigten Werten, können Sie die Techniken verwenden, die in [Extramodelle](extra-models.md){.internal-link target=_blank} beschrieben wurden.
+
+///
diff --git a/docs/de/docs/tutorial/body.md b/docs/de/docs/tutorial/body.md
index 6611cb51a..3a64e747e 100644
--- a/docs/de/docs/tutorial/body.md
+++ b/docs/de/docs/tutorial/body.md
@@ -8,28 +8,35 @@ Ihre API sendet fast immer einen **Response**body. Aber Clients senden nicht unb
Um einen **Request**body zu deklarieren, verwenden Sie Pydantic-Modelle mit allen deren Fähigkeiten und Vorzügen.
-!!! info
- Um Daten zu versenden, sollten Sie eines von: `POST` (meistverwendet), `PUT`, `DELETE` oder `PATCH` verwenden.
+/// info
- Senden Sie einen Body mit einem `GET`-Request, dann führt das laut Spezifikation zu undefiniertem Verhalten. Trotzdem wird es von FastAPI unterstützt, für sehr komplexe/extreme Anwendungsfälle.
+Um Daten zu versenden, sollten Sie eines von: `POST` (meistverwendet), `PUT`, `DELETE` oder `PATCH` verwenden.
- Da aber davon abgeraten wird, zeigt die interaktive Dokumentation mit Swagger-Benutzeroberfläche die Dokumentation für den Body auch nicht an, wenn `GET` verwendet wird. Dazwischengeschaltete Proxys unterstützen es möglicherweise auch nicht.
+Senden Sie einen Body mit einem `GET`-Request, dann führt das laut Spezifikation zu undefiniertem Verhalten. Trotzdem wird es von FastAPI unterstützt, für sehr komplexe/extreme Anwendungsfälle.
+
+Da aber davon abgeraten wird, zeigt die interaktive Dokumentation mit Swagger-Benutzeroberfläche die Dokumentation für den Body auch nicht an, wenn `GET` verwendet wird. Dazwischengeschaltete Proxys unterstützen es möglicherweise auch nicht.
+
+///
## Importieren Sie Pydantics `BaseModel`
Zuerst müssen Sie `BaseModel` von `pydantic` importieren:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="2"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
+```Python hl_lines="2"
+{!> ../../docs_src/body/tutorial001_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="4"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="4"
+{!> ../../docs_src/body/tutorial001.py!}
+```
+
+////
## Erstellen Sie Ihr Datenmodell
@@ -37,17 +44,21 @@ Dann deklarieren Sie Ihr Datenmodell als eine Klasse, die von `BaseModel` erbt.
Verwenden Sie Standard-Python-Typen für die Klassenattribute:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="5-9"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
+```Python hl_lines="5-9"
+{!> ../../docs_src/body/tutorial001_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="7-11"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="7-11"
+{!> ../../docs_src/body/tutorial001.py!}
+```
+
+////
Wie auch bei Query-Parametern gilt, wenn ein Modellattribut einen Defaultwert hat, ist das Attribut nicht erforderlich. Ansonsten ist es erforderlich. Verwenden Sie `None`, um es als optional zu kennzeichnen.
@@ -75,17 +86,21 @@ Da `description` und `tax` optional sind (mit `None` als Defaultwert), wäre fol
Um es zu Ihrer *Pfadoperation* hinzuzufügen, deklarieren Sie es auf die gleiche Weise, wie Sie Pfad- und Query-Parameter deklariert haben:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="16"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
+```Python hl_lines="16"
+{!> ../../docs_src/body/tutorial001_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="18"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="18"
+{!> ../../docs_src/body/tutorial001.py!}
+```
+
+////
... und deklarieren Sie seinen Typ als das Modell, welches Sie erstellt haben, `Item`.
@@ -134,32 +149,39 @@ Aber Sie bekommen die gleiche Editor-Unterstützung in
-!!! tip "Tipp"
- Wenn Sie PyCharm als Ihren Editor verwenden, probieren Sie das Pydantic PyCharm Plugin aus.
+/// tip | "Tipp"
- Es verbessert die Editor-Unterstützung für Pydantic-Modelle, mit:
+Wenn Sie PyCharm als Ihren Editor verwenden, probieren Sie das Pydantic PyCharm Plugin aus.
- * Code-Vervollständigung
- * Typüberprüfungen
- * Refaktorisierung
- * Suchen
- * Inspektionen
+Es verbessert die Editor-Unterstützung für Pydantic-Modelle, mit:
+
+* Code-Vervollständigung
+* Typüberprüfungen
+* Refaktorisierung
+* Suchen
+* Inspektionen
+
+///
## Das Modell verwenden
Innerhalb der Funktion können Sie alle Attribute des Modells direkt verwenden:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="19"
- {!> ../../../docs_src/body/tutorial002_py310.py!}
- ```
+```Python hl_lines="19"
+{!> ../../docs_src/body/tutorial002_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="21"
- {!> ../../../docs_src/body/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="21"
+{!> ../../docs_src/body/tutorial002.py!}
+```
+
+////
## Requestbody- + Pfad-Parameter
@@ -167,17 +189,21 @@ Sie können Pfad- und Requestbody-Parameter gleichzeitig deklarieren.
**FastAPI** erkennt, dass Funktionsparameter, die mit Pfad-Parametern übereinstimmen, **vom Pfad genommen** werden sollen, und dass Funktionsparameter, welche Pydantic-Modelle sind, **vom Requestbody genommen** werden sollen.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="15-16"
- {!> ../../../docs_src/body/tutorial003_py310.py!}
- ```
+```Python hl_lines="15-16"
+{!> ../../docs_src/body/tutorial003_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="17-18"
- {!> ../../../docs_src/body/tutorial003.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="17-18"
+{!> ../../docs_src/body/tutorial003.py!}
+```
+
+////
## Requestbody- + Pfad- + Query-Parameter
@@ -185,17 +211,21 @@ Sie können auch zur gleichen Zeit **Body-**, **Pfad-** und **Query-Parameter**
**FastAPI** wird jeden Parameter korrekt erkennen und die Daten vom richtigen Ort holen.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="16"
- {!> ../../../docs_src/body/tutorial004_py310.py!}
- ```
+```Python hl_lines="16"
+{!> ../../docs_src/body/tutorial004_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="18"
- {!> ../../../docs_src/body/tutorial004.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="18"
+{!> ../../docs_src/body/tutorial004.py!}
+```
+
+////
Die Funktionsparameter werden wie folgt erkannt:
@@ -203,10 +233,13 @@ Die Funktionsparameter werden wie folgt erkannt:
* Wenn der Parameter ein **einfacher Typ** ist (wie `int`, `float`, `str`, `bool`, usw.), wird er als **Query**-Parameter interpretiert.
* Wenn der Parameter vom Typ eines **Pydantic-Modells** ist, wird er als Request**body** interpretiert.
-!!! note "Hinweis"
- FastAPI weiß, dass der Wert von `q` nicht erforderlich ist, wegen des definierten Defaultwertes `= None`
+/// note | "Hinweis"
- Das `Union` in `Union[str, None]` wird von FastAPI nicht verwendet, aber es erlaubt Ihrem Editor, Sie besser zu unterstützen und Fehler zu erkennen.
+FastAPI weiß, dass der Wert von `q` nicht erforderlich ist, wegen des definierten Defaultwertes `= None`
+
+Das `Union` in `Union[str, None]` wird von FastAPI nicht verwendet, aber es erlaubt Ihrem Editor, Sie besser zu unterstützen und Fehler zu erkennen.
+
+///
## Ohne Pydantic
diff --git a/docs/de/docs/tutorial/cookie-params.md b/docs/de/docs/tutorial/cookie-params.md
index c95e28c7d..4714a59ae 100644
--- a/docs/de/docs/tutorial/cookie-params.md
+++ b/docs/de/docs/tutorial/cookie-params.md
@@ -6,41 +6,57 @@ So wie `Query`- und `Path`-Parameter können Sie auch ../../../docs_src/dependencies/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="3"
+{!> ../../docs_src/dependencies/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="3"
- {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="3"
+{!> ../../docs_src/dependencies/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="3"
- {!> ../../../docs_src/dependencies/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="3"
+{!> ../../docs_src/dependencies/tutorial001_an.py!}
+```
- ```Python hl_lines="1"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="3"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="1"
+{!> ../../docs_src/dependencies/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="3"
+{!> ../../docs_src/dependencies/tutorial001.py!}
+```
+
+////
### Deklarieren der Abhängigkeit im „Dependant“
So wie auch `Body`, `Query`, usw., verwenden Sie `Depends` mit den Parametern Ihrer *Pfadoperation-Funktion*:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="13 18"
- {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="13 18"
+{!> ../../docs_src/dependencies/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="15 20"
- {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="15 20"
+{!> ../../docs_src/dependencies/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="16 21"
- {!> ../../../docs_src/dependencies/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="16 21"
+{!> ../../docs_src/dependencies/tutorial001_an.py!}
+```
- ```Python hl_lines="11 16"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="15 20"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="11 16"
+{!> ../../docs_src/dependencies/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="15 20"
+{!> ../../docs_src/dependencies/tutorial001.py!}
+```
+
+////
Obwohl Sie `Depends` in den Parametern Ihrer Funktion genauso verwenden wie `Body`, `Query`, usw., funktioniert `Depends` etwas anders.
@@ -179,8 +230,11 @@ Sie **rufen diese nicht direkt auf** (fügen Sie am Ende keine Klammern hinzu),
Und diese Funktion akzeptiert Parameter auf die gleiche Weise wie *Pfadoperation-Funktionen*.
-!!! tip "Tipp"
- Im nächsten Kapitel erfahren Sie, welche anderen „Dinge“, außer Funktionen, Sie als Abhängigkeiten verwenden können.
+/// tip | "Tipp"
+
+Im nächsten Kapitel erfahren Sie, welche anderen „Dinge“, außer Funktionen, Sie als Abhängigkeiten verwenden können.
+
+///
Immer wenn ein neuer Request eintrifft, kümmert sich **FastAPI** darum:
@@ -201,10 +255,13 @@ common_parameters --> read_users
Auf diese Weise schreiben Sie gemeinsam genutzten Code nur einmal, und **FastAPI** kümmert sich darum, ihn für Ihre *Pfadoperationen* aufzurufen.
-!!! check
- Beachten Sie, dass Sie keine spezielle Klasse erstellen und diese irgendwo an **FastAPI** übergeben müssen, um sie zu „registrieren“ oder so ähnlich.
+/// check
- Sie übergeben es einfach an `Depends` und **FastAPI** weiß, wie der Rest erledigt wird.
+Beachten Sie, dass Sie keine spezielle Klasse erstellen und diese irgendwo an **FastAPI** übergeben müssen, um sie zu „registrieren“ oder so ähnlich.
+
+Sie übergeben es einfach an `Depends` und **FastAPI** weiß, wie der Rest erledigt wird.
+
+///
## `Annotated`-Abhängigkeiten wiederverwenden
@@ -218,28 +275,37 @@ commons: Annotated[dict, Depends(common_parameters)]
Da wir jedoch `Annotated` verwenden, können wir diesen `Annotated`-Wert in einer Variablen speichern und an mehreren Stellen verwenden:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="12 16 21"
- {!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!}
- ```
+```Python hl_lines="12 16 21"
+{!> ../../docs_src/dependencies/tutorial001_02_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="14 18 23"
- {!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="14 18 23"
+{!> ../../docs_src/dependencies/tutorial001_02_an_py39.py!}
+```
- ```Python hl_lines="15 19 24"
- {!> ../../../docs_src/dependencies/tutorial001_02_an.py!}
- ```
+////
-!!! tip "Tipp"
- Das ist schlicht Standard-Python, es wird als „Typalias“ bezeichnet und ist eigentlich nicht **FastAPI**-spezifisch.
+//// tab | Python 3.8+
- Da **FastAPI** jedoch auf Standard-Python, einschließlich `Annotated`, basiert, können Sie diesen Trick in Ihrem Code verwenden. 😎
+```Python hl_lines="15 19 24"
+{!> ../../docs_src/dependencies/tutorial001_02_an.py!}
+```
+
+////
+
+/// tip | "Tipp"
+
+Das ist schlicht Standard-Python, es wird als „Typalias“ bezeichnet und ist eigentlich nicht **FastAPI**-spezifisch.
+
+Da **FastAPI** jedoch auf Standard-Python, einschließlich `Annotated`, basiert, können Sie diesen Trick in Ihrem Code verwenden. 😎
+
+///
Die Abhängigkeiten funktionieren weiterhin wie erwartet, und das **Beste daran** ist, dass die **Typinformationen erhalten bleiben**, was bedeutet, dass Ihr Editor Ihnen weiterhin **automatische Vervollständigung**, **Inline-Fehler**, usw. bieten kann. Das Gleiche gilt für andere Tools wie `mypy`.
@@ -255,8 +321,11 @@ Und Sie können Abhängigkeiten mit `async def` innerhalb normaler `def`-*Pfadop
Es spielt keine Rolle. **FastAPI** weiß, was zu tun ist.
-!!! note "Hinweis"
- Wenn Ihnen das nichts sagt, lesen Sie den [Async: *„In Eile?“*](../../async.md#in-eile){.internal-link target=_blank}-Abschnitt über `async` und `await` in der Dokumentation.
+/// note | "Hinweis"
+
+Wenn Ihnen das nichts sagt, lesen Sie den [Async: *„In Eile?“*](../../async.md#in-eile){.internal-link target=_blank}-Abschnitt über `async` und `await` in der Dokumentation.
+
+///
## Integriert in OpenAPI
diff --git a/docs/de/docs/tutorial/dependencies/sub-dependencies.md b/docs/de/docs/tutorial/dependencies/sub-dependencies.md
index 0fa2af839..a20aed63b 100644
--- a/docs/de/docs/tutorial/dependencies/sub-dependencies.md
+++ b/docs/de/docs/tutorial/dependencies/sub-dependencies.md
@@ -10,41 +10,57 @@ Diese können so **tief** verschachtelt sein, wie nötig.
Sie könnten eine erste Abhängigkeit („Dependable“) wie folgt erstellen:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="8-9"
- {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!}
- ```
+```Python hl_lines="8-9"
+{!> ../../docs_src/dependencies/tutorial005_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="8-9"
- {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="8-9"
+{!> ../../docs_src/dependencies/tutorial005_an_py39.py!}
+```
- ```Python hl_lines="9-10"
- {!> ../../../docs_src/dependencies/tutorial005_an.py!}
- ```
+////
-=== "Python 3.10 nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="9-10"
+{!> ../../docs_src/dependencies/tutorial005_an.py!}
+```
- ```Python hl_lines="6-7"
- {!> ../../../docs_src/dependencies/tutorial005_py310.py!}
- ```
+////
-=== "Python 3.8 nicht annotiert"
+//// tab | Python 3.10 nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="8-9"
- {!> ../../../docs_src/dependencies/tutorial005.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="6-7"
+{!> ../../docs_src/dependencies/tutorial005_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8 nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="8-9"
+{!> ../../docs_src/dependencies/tutorial005.py!}
+```
+
+////
Diese deklariert einen optionalen Abfrageparameter `q` vom Typ `str` und gibt ihn dann einfach zurück.
@@ -54,41 +70,57 @@ Das ist recht einfach (nicht sehr nützlich), hilft uns aber dabei, uns auf die
Dann können Sie eine weitere Abhängigkeitsfunktion (ein „Dependable“) erstellen, die gleichzeitig eine eigene Abhängigkeit deklariert (also auch ein „Dependant“ ist):
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="13"
- {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!}
- ```
+```Python hl_lines="13"
+{!> ../../docs_src/dependencies/tutorial005_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="13"
- {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="13"
+{!> ../../docs_src/dependencies/tutorial005_an_py39.py!}
+```
- ```Python hl_lines="14"
- {!> ../../../docs_src/dependencies/tutorial005_an.py!}
- ```
+////
-=== "Python 3.10 nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="14"
+{!> ../../docs_src/dependencies/tutorial005_an.py!}
+```
- ```Python hl_lines="11"
- {!> ../../../docs_src/dependencies/tutorial005_py310.py!}
- ```
+////
-=== "Python 3.8 nicht annotiert"
+//// tab | Python 3.10 nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="13"
- {!> ../../../docs_src/dependencies/tutorial005.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="11"
+{!> ../../docs_src/dependencies/tutorial005_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8 nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="13"
+{!> ../../docs_src/dependencies/tutorial005.py!}
+```
+
+////
Betrachten wir die deklarierten Parameter:
@@ -101,46 +133,65 @@ Betrachten wir die deklarierten Parameter:
Diese Abhängigkeit verwenden wir nun wie folgt:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="23"
- {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!}
- ```
+```Python hl_lines="23"
+{!> ../../docs_src/dependencies/tutorial005_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="23"
- {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="23"
+{!> ../../docs_src/dependencies/tutorial005_an_py39.py!}
+```
- ```Python hl_lines="24"
- {!> ../../../docs_src/dependencies/tutorial005_an.py!}
- ```
+////
-=== "Python 3.10 nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="24"
+{!> ../../docs_src/dependencies/tutorial005_an.py!}
+```
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial005_py310.py!}
- ```
+////
-=== "Python 3.8 nicht annotiert"
+//// tab | Python 3.10 nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="22"
- {!> ../../../docs_src/dependencies/tutorial005.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-!!! info
- Beachten Sie, dass wir in der *Pfadoperation-Funktion* nur eine einzige Abhängigkeit deklarieren, den `query_or_cookie_extractor`.
+///
- Aber **FastAPI** wird wissen, dass es zuerst `query_extractor` auflösen muss, um dessen Resultat `query_or_cookie_extractor` zu übergeben, wenn dieses aufgerufen wird.
+```Python hl_lines="19"
+{!> ../../docs_src/dependencies/tutorial005_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8 nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="22"
+{!> ../../docs_src/dependencies/tutorial005.py!}
+```
+
+////
+
+/// info
+
+Beachten Sie, dass wir in der *Pfadoperation-Funktion* nur eine einzige Abhängigkeit deklarieren, den `query_or_cookie_extractor`.
+
+Aber **FastAPI** wird wissen, dass es zuerst `query_extractor` auflösen muss, um dessen Resultat `query_or_cookie_extractor` zu übergeben, wenn dieses aufgerufen wird.
+
+///
```mermaid
graph TB
@@ -161,22 +212,29 @@ Und es speichert den zurückgegebenen Wert in einem ../../../docs_src/encoder/tutorial001_py310.py!}
- ```
+```Python hl_lines="4 21"
+{!> ../../docs_src/encoder/tutorial001_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="5 22"
- {!> ../../../docs_src/encoder/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="5 22"
+{!> ../../docs_src/encoder/tutorial001.py!}
+```
+
+////
In diesem Beispiel wird das Pydantic-Modell in ein `dict`, und das `datetime`-Objekt in ein `str` konvertiert.
@@ -38,5 +42,8 @@ Das Resultat dieses Aufrufs ist etwas, das mit Pythons Standard- ../../../docs_src/extra_data_types/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="1 3 12-16"
+{!> ../../docs_src/extra_data_types/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="1 3 12-16"
- {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="1 3 12-16"
+{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="1 3 13-17"
- {!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="1 3 13-17"
+{!> ../../docs_src/extra_data_types/tutorial001_an.py!}
+```
- ```Python hl_lines="1 2 11-15"
- {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip
- ```Python hl_lines="1 2 12-16"
- {!> ../../../docs_src/extra_data_types/tutorial001.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="1 2 11-15"
+{!> ../../docs_src/extra_data_types/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="1 2 12-16"
+{!> ../../docs_src/extra_data_types/tutorial001.py!}
+```
+
+////
Beachten Sie, dass die Parameter innerhalb der Funktion ihren natürlichen Datentyp haben und Sie beispielsweise normale Datumsmanipulationen durchführen können, wie zum Beispiel:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="18-19"
+{!> ../../docs_src/extra_data_types/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="18-19"
+{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="19-20"
- {!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="19-20"
+{!> ../../docs_src/extra_data_types/tutorial001_an.py!}
+```
- ```Python hl_lines="17-18"
- {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/extra_data_types/tutorial001.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="17-18"
+{!> ../../docs_src/extra_data_types/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="18-19"
+{!> ../../docs_src/extra_data_types/tutorial001.py!}
+```
+
+////
diff --git a/docs/de/docs/tutorial/extra-models.md b/docs/de/docs/tutorial/extra-models.md
index cdf16c4ba..14e842065 100644
--- a/docs/de/docs/tutorial/extra-models.md
+++ b/docs/de/docs/tutorial/extra-models.md
@@ -8,31 +8,41 @@ Insbesondere Benutzermodelle, denn:
* Das **herausgehende Modell** sollte kein Passwort haben.
* Das **Datenbankmodell** sollte wahrscheinlich ein gehashtes Passwort haben.
-!!! danger "Gefahr"
- Speichern Sie niemals das Klartext-Passwort eines Benutzers. Speichern Sie immer den „sicheren Hash“, den Sie verifizieren können.
+/// danger | "Gefahr"
- Falls Ihnen das nichts sagt, in den [Sicherheits-Kapiteln](security/simple-oauth2.md#passwort-hashing){.internal-link target=_blank} werden Sie lernen, was ein „Passwort-Hash“ ist.
+Speichern Sie niemals das Klartext-Passwort eines Benutzers. Speichern Sie immer den „sicheren Hash“, den Sie verifizieren können.
+
+Falls Ihnen das nichts sagt, in den [Sicherheits-Kapiteln](security/simple-oauth2.md#passwort-hashing){.internal-link target=_blank} werden Sie lernen, was ein „Passwort-Hash“ ist.
+
+///
## Mehrere Modelle
Hier der generelle Weg, wie die Modelle mit ihren Passwort-Feldern aussehen könnten, und an welchen Orten sie verwendet werden würden.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39"
- {!> ../../../docs_src/extra_models/tutorial001_py310.py!}
- ```
+```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39"
+{!> ../../docs_src/extra_models/tutorial001_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41"
- {!> ../../../docs_src/extra_models/tutorial001.py!}
- ```
+//// tab | Python 3.8+
-!!! info
- In Pydantic v1 hieß diese Methode `.dict()`, in Pydantic v2 wurde sie deprecated (aber immer noch unterstützt) und in `.model_dump()` umbenannt.
+```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41"
+{!> ../../docs_src/extra_models/tutorial001.py!}
+```
- Die Beispiele hier verwenden `.dict()` für die Kompatibilität mit Pydantic v1, Sie sollten jedoch stattdessen `.model_dump()` verwenden, wenn Sie Pydantic v2 verwenden können.
+////
+
+/// info
+
+In Pydantic v1 hieß diese Methode `.dict()`, in Pydantic v2 wurde sie deprecated (aber immer noch unterstützt) und in `.model_dump()` umbenannt.
+
+Die Beispiele hier verwenden `.dict()` für die Kompatibilität mit Pydantic v1, Sie sollten jedoch stattdessen `.model_dump()` verwenden, wenn Sie Pydantic v2 verwenden können.
+
+///
### Über `**user_in.dict()`
@@ -144,8 +154,11 @@ UserInDB(
)
```
-!!! warning "Achtung"
- Die Hilfsfunktionen `fake_password_hasher` und `fake_save_user` demonstrieren nur den möglichen Fluss der Daten und bieten natürlich keine echte Sicherheit.
+/// warning | "Achtung"
+
+Die Hilfsfunktionen `fake_password_hasher` und `fake_save_user` demonstrieren nur den möglichen Fluss der Daten und bieten natürlich keine echte Sicherheit.
+
+///
## Verdopplung vermeiden
@@ -163,17 +176,21 @@ Die ganze Datenkonvertierung, -validierung, -dokumentation, usw. wird immer noch
Auf diese Weise beschreiben wir nur noch die Unterschiede zwischen den Modellen (mit Klartext-`password`, mit `hashed_password`, und ohne Passwort):
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7 13-14 17-18 21-22"
- {!> ../../../docs_src/extra_models/tutorial002_py310.py!}
- ```
+```Python hl_lines="7 13-14 17-18 21-22"
+{!> ../../docs_src/extra_models/tutorial002_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9 15-16 19-20 23-24"
- {!> ../../../docs_src/extra_models/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="9 15-16 19-20 23-24"
+{!> ../../docs_src/extra_models/tutorial002.py!}
+```
+
+////
## `Union`, oder `anyOf`
@@ -183,20 +200,27 @@ Das wird in OpenAPI mit `anyOf` angezeigt.
Um das zu tun, verwenden Sie Pythons Standard-Typhinweis `typing.Union`:
-!!! note "Hinweis"
- Listen Sie, wenn Sie eine `Union` definieren, denjenigen Typ zuerst, der am spezifischsten ist, gefolgt von den weniger spezifischen Typen. Im Beispiel oben, in `Union[PlaneItem, CarItem]` also den spezifischeren `PlaneItem` vor dem weniger spezifischen `CarItem`.
+/// note | "Hinweis"
-=== "Python 3.10+"
+Listen Sie, wenn Sie eine `Union` definieren, denjenigen Typ zuerst, der am spezifischsten ist, gefolgt von den weniger spezifischen Typen. Im Beispiel oben, in `Union[PlaneItem, CarItem]` also den spezifischeren `PlaneItem` vor dem weniger spezifischen `CarItem`.
- ```Python hl_lines="1 14-15 18-20 33"
- {!> ../../../docs_src/extra_models/tutorial003_py310.py!}
- ```
+///
-=== "Python 3.8+"
+//// tab | Python 3.10+
- ```Python hl_lines="1 14-15 18-20 33"
- {!> ../../../docs_src/extra_models/tutorial003.py!}
- ```
+```Python hl_lines="1 14-15 18-20 33"
+{!> ../../docs_src/extra_models/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="1 14-15 18-20 33"
+{!> ../../docs_src/extra_models/tutorial003.py!}
+```
+
+////
### `Union` in Python 3.10
@@ -218,17 +242,21 @@ Genauso können Sie eine Response deklarieren, die eine Liste von Objekten ist.
Verwenden Sie dafür Pythons Standard `typing.List` (oder nur `list` in Python 3.9 und darüber):
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="18"
- {!> ../../../docs_src/extra_models/tutorial004_py39.py!}
- ```
+```Python hl_lines="18"
+{!> ../../docs_src/extra_models/tutorial004_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1 20"
- {!> ../../../docs_src/extra_models/tutorial004.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="1 20"
+{!> ../../docs_src/extra_models/tutorial004.py!}
+```
+
+////
## Response mit beliebigem `dict`
@@ -238,17 +266,21 @@ Das ist nützlich, wenn Sie die gültigen Feld-/Attribut-Namen von vorneherein n
In diesem Fall können Sie `typing.Dict` verwenden (oder nur `dict` in Python 3.9 und darüber):
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="6"
- {!> ../../../docs_src/extra_models/tutorial005_py39.py!}
- ```
+```Python hl_lines="6"
+{!> ../../docs_src/extra_models/tutorial005_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1 8"
- {!> ../../../docs_src/extra_models/tutorial005.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="1 8"
+{!> ../../docs_src/extra_models/tutorial005.py!}
+```
+
+////
## Zusammenfassung
diff --git a/docs/de/docs/tutorial/first-steps.md b/docs/de/docs/tutorial/first-steps.md
index 27ba3ec16..fe3886b70 100644
--- a/docs/de/docs/tutorial/first-steps.md
+++ b/docs/de/docs/tutorial/first-steps.md
@@ -3,7 +3,7 @@
Die einfachste FastAPI-Datei könnte wie folgt aussehen:
```Python
-{!../../../docs_src/first_steps/tutorial001.py!}
+{!../../docs_src/first_steps/tutorial001.py!}
```
Kopieren Sie dies in eine Datei `main.py`.
@@ -24,12 +24,15 @@ $ uvicorn main:app --reload
-!!! note "Hinweis"
- Der Befehl `uvicorn main:app` bezieht sich auf:
+/// note | "Hinweis"
- * `main`: die Datei `main.py` (das sogenannte Python-„Modul“).
- * `app`: das Objekt, welches in der Datei `main.py` mit der Zeile `app = FastAPI()` erzeugt wurde.
- * `--reload`: lässt den Server nach Codeänderungen neu starten. Verwenden Sie das nur während der Entwicklung.
+Der Befehl `uvicorn main:app` bezieht sich auf:
+
+* `main`: die Datei `main.py` (das sogenannte Python-„Modul“).
+* `app`: das Objekt, welches in der Datei `main.py` mit der Zeile `app = FastAPI()` erzeugt wurde.
+* `--reload`: lässt den Server nach Codeänderungen neu starten. Verwenden Sie das nur während der Entwicklung.
+
+///
In der Konsolenausgabe sollte es eine Zeile geben, die ungefähr so aussieht:
@@ -131,20 +134,23 @@ 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!}
```
`FastAPI` ist eine Python-Klasse, die die gesamte Funktionalität für Ihre API bereitstellt.
-!!! note "Technische Details"
- `FastAPI` ist eine Klasse, die direkt von `Starlette` erbt.
+/// note | "Technische Details"
- Sie können alle Starlette-Funktionalitäten auch mit `FastAPI` nutzen.
+`FastAPI` ist eine Klasse, die direkt von `Starlette` erbt.
+
+Sie können alle Starlette-Funktionalitäten auch mit `FastAPI` nutzen.
+
+///
### Schritt 2: Erzeugen einer `FastAPI`-„Instanz“
```Python hl_lines="3"
-{!../../../docs_src/first_steps/tutorial001.py!}
+{!../../docs_src/first_steps/tutorial001.py!}
```
In diesem Beispiel ist die Variable `app` eine „Instanz“ der Klasse `FastAPI`.
@@ -166,7 +172,7 @@ $ uvicorn main:app --reload
Wenn Sie Ihre Anwendung wie folgt erstellen:
```Python hl_lines="3"
-{!../../../docs_src/first_steps/tutorial002.py!}
+{!../../docs_src/first_steps/tutorial002.py!}
```
Und in eine Datei `main.py` einfügen, dann würden Sie `uvicorn` wie folgt aufrufen:
@@ -199,8 +205,11 @@ https://example.com/items/foo
/items/foo
```
-!!! info
- Ein „Pfad“ wird häufig auch als „Endpunkt“ oder „Route“ bezeichnet.
+/// info
+
+Ein „Pfad“ wird häufig auch als „Endpunkt“ oder „Route“ bezeichnet.
+
+///
Bei der Erstellung einer API ist der „Pfad“ die wichtigste Möglichkeit zur Trennung von „Anliegen“ und „Ressourcen“.
@@ -242,7 +251,7 @@ Wir werden sie auch „**Operationen**“ nennen.
#### Definieren eines *Pfadoperation-Dekorators*
```Python hl_lines="6"
-{!../../../docs_src/first_steps/tutorial001.py!}
+{!../../docs_src/first_steps/tutorial001.py!}
```
Das `@app.get("/")` sagt **FastAPI**, dass die Funktion direkt darunter für die Bearbeitung von Anfragen zuständig ist, die an:
@@ -250,16 +259,19 @@ Das `@app.get("/")` sagt **FastAPI**, dass die Funktion direkt darunter für die
* den Pfad `/`
* unter der Verwendung der get-Operation gehen
-!!! info "`@decorator` Information"
- Diese `@something`-Syntax wird in Python „Dekorator“ genannt.
+/// info | "`@decorator` Information"
- Sie platzieren ihn über einer Funktion. Wie ein hübscher, dekorativer Hut (daher kommt wohl der Begriff).
+Diese `@something`-Syntax wird in Python „Dekorator“ genannt.
- Ein „Dekorator“ nimmt die darunter stehende Funktion und macht etwas damit.
+Sie platzieren ihn über einer Funktion. Wie ein hübscher, dekorativer Hut (daher kommt wohl der Begriff).
- In unserem Fall teilt dieser Dekorator **FastAPI** mit, dass die folgende Funktion mit dem **Pfad** `/` und der **Operation** `get` zusammenhängt.
+Ein „Dekorator“ nimmt die darunter stehende Funktion und macht etwas damit.
- Dies ist der „**Pfadoperation-Dekorator**“.
+In unserem Fall teilt dieser Dekorator **FastAPI** mit, dass die folgende Funktion mit dem **Pfad** `/` und der **Operation** `get` zusammenhängt.
+
+Dies ist der „**Pfadoperation-Dekorator**“.
+
+///
Sie können auch die anderen Operationen verwenden:
@@ -274,14 +286,17 @@ Oder die exotischeren:
* `@app.patch()`
* `@app.trace()`
-!!! tip "Tipp"
- Es steht Ihnen frei, jede Operation (HTTP-Methode) so zu verwenden, wie Sie es möchten.
+/// tip | "Tipp"
- **FastAPI** erzwingt keine bestimmte Bedeutung.
+Es steht Ihnen frei, jede Operation (HTTP-Methode) so zu verwenden, wie Sie es möchten.
- Die hier aufgeführten Informationen dienen als Leitfaden und sind nicht verbindlich.
+**FastAPI** erzwingt keine bestimmte Bedeutung.
- Wenn Sie beispielsweise GraphQL verwenden, führen Sie normalerweise alle Aktionen nur mit „POST“-Operationen durch.
+Die hier aufgeführten Informationen dienen als Leitfaden und sind nicht verbindlich.
+
+Wenn Sie beispielsweise GraphQL verwenden, führen Sie normalerweise alle Aktionen nur mit „POST“-Operationen durch.
+
+///
### Schritt 4: Definieren der **Pfadoperation-Funktion**
@@ -292,7 +307,7 @@ Das ist unsere „**Pfadoperation-Funktion**“:
* **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!}
```
Dies ist eine Python-Funktion.
@@ -306,16 +321,19 @@ 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!}
```
-!!! note "Hinweis"
- Wenn Sie den Unterschied nicht kennen, lesen Sie [Async: *„In Eile?“*](../async.md#in-eile){.internal-link target=_blank}.
+/// note | "Hinweis"
+
+Wenn Sie den Unterschied nicht kennen, lesen Sie [Async: *„In Eile?“*](../async.md#in-eile){.internal-link target=_blank}.
+
+///
### Schritt 5: den Inhalt zurückgeben
```Python hl_lines="8"
-{!../../../docs_src/first_steps/tutorial001.py!}
+{!../../docs_src/first_steps/tutorial001.py!}
```
Sie können ein `dict`, eine `list`, einzelne Werte wie `str`, `int`, usw. zurückgeben.
diff --git a/docs/de/docs/tutorial/handling-errors.md b/docs/de/docs/tutorial/handling-errors.md
index af658b971..70dc0c523 100644
--- a/docs/de/docs/tutorial/handling-errors.md
+++ b/docs/de/docs/tutorial/handling-errors.md
@@ -26,7 +26,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!}
```
### Eine `HTTPException` in Ihrem Code auslösen
@@ -42,7 +42,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!}
```
### Die resultierende Response
@@ -63,12 +63,15 @@ Aber wenn der Client `http://example.com/items/bar` anfragt (ein nicht-existiere
}
```
-!!! tip "Tipp"
- Wenn Sie eine `HTTPException` auslösen, können Sie dem Parameter `detail` jeden Wert übergeben, der nach JSON konvertiert werden kann, nicht nur `str`.
+/// tip | "Tipp"
- Zum Beispiel ein `dict`, eine `list`, usw.
+Wenn Sie eine `HTTPException` auslösen, können Sie dem Parameter `detail` jeden Wert übergeben, der nach JSON konvertiert werden kann, nicht nur `str`.
- Das wird automatisch von **FastAPI** gehandhabt und der Wert nach JSON konvertiert.
+Zum Beispiel ein `dict`, eine `list`, usw.
+
+Das wird automatisch von **FastAPI** gehandhabt und der Wert nach JSON konvertiert.
+
+///
## Benutzerdefinierte Header hinzufügen
@@ -79,7 +82,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!}
```
## Benutzerdefinierte Exceptionhandler definieren
@@ -93,7 +96,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!}
```
Wenn Sie nun `/unicorns/yolo` anfragen, `raise`d die *Pfadoperation* eine `UnicornException`.
@@ -106,10 +109,13 @@ Sie erhalten also einen sauberen Error mit einem Statuscode `418` und dem JSON-I
{"message": "Oops! yolo did something. There goes a rainbow..."}
```
-!!! note "Technische Details"
- Sie können auch `from starlette.requests import Request` und `from starlette.responses import JSONResponse` verwenden.
+/// note | "Technische Details"
- **FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. Das Gleiche gilt für `Request`.
+Sie können auch `from starlette.requests import Request` und `from starlette.responses import JSONResponse` verwenden.
+
+**FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. Das Gleiche gilt für `Request`.
+
+///
## Die Default-Exceptionhandler überschreiben
@@ -130,7 +136,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!}
```
Wenn Sie nun `/items/foo` besuchen, erhalten Sie statt des Default-JSON-Errors:
@@ -160,8 +166,11 @@ path -> item_id
#### `RequestValidationError` vs. `ValidationError`
-!!! warning "Achtung"
- Das folgende sind technische Details, die Sie überspringen können, wenn sie für Sie nicht wichtig sind.
+/// warning | "Achtung"
+
+Das folgende sind technische Details, die Sie überspringen können, wenn sie für Sie nicht wichtig sind.
+
+///
`RequestValidationError` ist eine Unterklasse von Pydantics `ValidationError`.
@@ -180,13 +189,16 @@ 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!}
```
-!!! note "Technische Details"
- Sie können auch `from starlette.responses import PlainTextResponse` verwenden.
+/// note | "Technische Details"
- **FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette.
+Sie können auch `from starlette.responses import PlainTextResponse` verwenden.
+
+**FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette.
+
+///
### Den `RequestValidationError`-Body verwenden
@@ -195,7 +207,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!}
```
Jetzt versuchen Sie, einen ungültigen Artikel zu senden:
@@ -253,7 +265,7 @@ 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!}
```
In diesem Beispiel `print`en Sie nur den Fehler mit einer sehr ausdrucksstarken Nachricht, aber Sie sehen, worauf wir hinauswollen. Sie können mit der Exception etwas machen und dann einfach die Default-Exceptionhandler wiederverwenden.
diff --git a/docs/de/docs/tutorial/header-params.md b/docs/de/docs/tutorial/header-params.md
index 3c9807f47..c4901c2ee 100644
--- a/docs/de/docs/tutorial/header-params.md
+++ b/docs/de/docs/tutorial/header-params.md
@@ -6,41 +6,57 @@ So wie `Query`-, `Path`-, und `Cookie`-Parameter können Sie auch .
+/// tip | "Tipp"
- Wenn Sie jedoch benutzerdefinierte Header haben, die ein Client in einem Browser sehen soll, müssen Sie sie zu Ihrer CORS-Konfigurationen ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) hinzufügen, indem Sie den Parameter `expose_headers` verwenden, der in der Starlette-CORS-Dokumentation dokumentiert ist.
+Beachten Sie, dass benutzerdefinierte proprietäre Header hinzugefügt werden können. Verwenden Sie dafür das Präfix 'X-'.
-!!! note "Technische Details"
- Sie könnten auch `from starlette.requests import Request` verwenden.
+Wenn Sie jedoch benutzerdefinierte Header haben, die ein Client in einem Browser sehen soll, müssen Sie sie zu Ihrer CORS-Konfigurationen ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) hinzufügen, indem Sie den Parameter `expose_headers` verwenden, der in der Starlette-CORS-Dokumentation dokumentiert ist.
- **FastAPI** bietet es als Komfort für Sie, den Entwickler, an. Aber es stammt direkt von Starlette.
+///
+
+/// note | "Technische Details"
+
+Sie könnten auch `from starlette.requests import Request` verwenden.
+
+**FastAPI** bietet es als Komfort für Sie, den Entwickler, an. Aber es stammt direkt von Starlette.
+
+///
### Vor und nach der `response`
@@ -51,7 +60,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!}
```
## Andere Middlewares
diff --git a/docs/de/docs/tutorial/path-operation-configuration.md b/docs/de/docs/tutorial/path-operation-configuration.md
index 80a4fadc9..411916e9c 100644
--- a/docs/de/docs/tutorial/path-operation-configuration.md
+++ b/docs/de/docs/tutorial/path-operation-configuration.md
@@ -2,8 +2,11 @@
Es gibt mehrere Konfigurations-Parameter, die Sie Ihrem *Pfadoperation-Dekorator* übergeben können.
-!!! warning "Achtung"
- Beachten Sie, dass diese Parameter direkt dem *Pfadoperation-Dekorator* übergeben werden, nicht der *Pfadoperation-Funktion*.
+/// warning | "Achtung"
+
+Beachten Sie, dass diese Parameter direkt dem *Pfadoperation-Dekorator* übergeben werden, nicht der *Pfadoperation-Funktion*.
+
+///
## Response-Statuscode
@@ -13,52 +16,67 @@ Sie können direkt den `int`-Code übergeben, etwa `404`.
Aber falls Sie sich nicht mehr erinnern, wofür jede Nummer steht, können Sie die Abkürzungs-Konstanten in `status` verwenden:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="1 15"
- {!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!}
- ```
+```Python hl_lines="1 15"
+{!> ../../docs_src/path_operation_configuration/tutorial001_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="3 17"
- {!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="3 17"
+{!> ../../docs_src/path_operation_configuration/tutorial001_py39.py!}
+```
- ```Python hl_lines="3 17"
- {!> ../../../docs_src/path_operation_configuration/tutorial001.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="3 17"
+{!> ../../docs_src/path_operation_configuration/tutorial001.py!}
+```
+
+////
Dieser Statuscode wird in der Response verwendet und zum OpenAPI-Schema hinzugefügt.
-!!! note "Technische Details"
- Sie können auch `from starlette import status` verwenden.
+/// note | "Technische Details"
- **FastAPI** bietet dieselben `starlette.status`-Codes auch via `fastapi.status` an, als Annehmlichkeit für Sie, den Entwickler. Sie kommen aber direkt von Starlette.
+Sie können auch `from starlette import status` verwenden.
+
+**FastAPI** bietet dieselben `starlette.status`-Codes auch via `fastapi.status` an, als Annehmlichkeit für Sie, den Entwickler. Sie kommen aber direkt von Starlette.
+
+///
## Tags
Sie können Ihrer *Pfadoperation* Tags hinzufügen, mittels des Parameters `tags`, dem eine `list`e von `str`s übergeben wird (in der Regel nur ein `str`):
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="15 20 25"
- {!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!}
- ```
+```Python hl_lines="15 20 25"
+{!> ../../docs_src/path_operation_configuration/tutorial002_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="17 22 27"
- {!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="17 22 27"
+{!> ../../docs_src/path_operation_configuration/tutorial002_py39.py!}
+```
- ```Python hl_lines="17 22 27"
- {!> ../../../docs_src/path_operation_configuration/tutorial002.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="17 22 27"
+{!> ../../docs_src/path_operation_configuration/tutorial002.py!}
+```
+
+////
Diese werden zum OpenAPI-Schema hinzugefügt und von den automatischen Dokumentations-Benutzeroberflächen verwendet:
@@ -73,30 +91,36 @@ 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!}
```
## Zusammenfassung und Beschreibung
Sie können eine Zusammenfassung (`summary`) und eine Beschreibung (`description`) hinzufügen:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!}
- ```
+```Python hl_lines="18-19"
+{!> ../../docs_src/path_operation_configuration/tutorial003_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="20-21"
- {!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="20-21"
+{!> ../../docs_src/path_operation_configuration/tutorial003_py39.py!}
+```
- ```Python hl_lines="20-21"
- {!> ../../../docs_src/path_operation_configuration/tutorial003.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="20-21"
+{!> ../../docs_src/path_operation_configuration/tutorial003.py!}
+```
+
+////
## Beschreibung mittels Docstring
@@ -104,23 +128,29 @@ Da Beschreibungen oft mehrere Zeilen lang sind, können Sie die Beschreibung der
Sie können im Docstring Markdown schreiben, es wird korrekt interpretiert und angezeigt (die Einrückung des Docstring beachtend).
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="17-25"
- {!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!}
- ```
+```Python hl_lines="17-25"
+{!> ../../docs_src/path_operation_configuration/tutorial004_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="19-27"
- {!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="19-27"
+{!> ../../docs_src/path_operation_configuration/tutorial004_py39.py!}
+```
- ```Python hl_lines="19-27"
- {!> ../../../docs_src/path_operation_configuration/tutorial004.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="19-27"
+{!> ../../docs_src/path_operation_configuration/tutorial004.py!}
+```
+
+////
In der interaktiven Dokumentation sieht das dann so aus:
@@ -130,31 +160,43 @@ In der interaktiven Dokumentation sieht das dann so aus:
Die Response können Sie mit dem Parameter `response_description` beschreiben:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="19"
- {!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!}
- ```
+```Python hl_lines="19"
+{!> ../../docs_src/path_operation_configuration/tutorial005_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="21"
- {!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="21"
+{!> ../../docs_src/path_operation_configuration/tutorial005_py39.py!}
+```
- ```Python hl_lines="21"
- {!> ../../../docs_src/path_operation_configuration/tutorial005.py!}
- ```
+////
-!!! info
- beachten Sie, dass sich `response_description` speziell auf die Response bezieht, während `description` sich generell auf die *Pfadoperation* bezieht.
+//// tab | Python 3.8+
-!!! check
- OpenAPI verlangt, dass jede *Pfadoperation* über eine Beschreibung der Response verfügt.
+```Python hl_lines="21"
+{!> ../../docs_src/path_operation_configuration/tutorial005.py!}
+```
- Daher, wenn Sie keine vergeben, wird **FastAPI** automatisch eine für „Erfolgreiche Response“ erstellen.
+////
+
+/// info
+
+beachten Sie, dass sich `response_description` speziell auf die Response bezieht, während `description` sich generell auf die *Pfadoperation* bezieht.
+
+///
+
+/// check
+
+OpenAPI verlangt, dass jede *Pfadoperation* über eine Beschreibung der Response verfügt.
+
+Daher, wenn Sie keine vergeben, wird **FastAPI** automatisch eine für „Erfolgreiche Response“ erstellen.
+
+///
@@ -163,7 +205,7 @@ Die Response können Sie mit dem Parameter `response_description` beschreiben:
Wenn Sie eine *Pfadoperation* als deprecated kennzeichnen möchten, ohne sie zu entfernen, fügen Sie den Parameter `deprecated` hinzu:
```Python hl_lines="16"
-{!../../../docs_src/path_operation_configuration/tutorial006.py!}
+{!../../docs_src/path_operation_configuration/tutorial006.py!}
```
Sie wird in der interaktiven Dokumentation gut sichtbar als deprecated markiert werden:
diff --git a/docs/de/docs/tutorial/path-params-numeric-validations.md b/docs/de/docs/tutorial/path-params-numeric-validations.md
index aa3b59b8b..fc2d5dff1 100644
--- a/docs/de/docs/tutorial/path-params-numeric-validations.md
+++ b/docs/de/docs/tutorial/path-params-numeric-validations.md
@@ -6,48 +6,67 @@ So wie Sie mit `Query` für Query-Parameter zusätzliche Validierungen und Metad
Importieren Sie zuerst `Path` von `fastapi`, und importieren Sie `Annotated`.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="1 3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="1 3"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="1 3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="1 3"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="3-4"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="3-4"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
+```
- ```Python hl_lines="1"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-!!! info
- FastAPI unterstützt (und empfiehlt die Verwendung von) `Annotated` seit Version 0.95.0.
+///
- Wenn Sie eine ältere Version haben, werden Sie Fehler angezeigt bekommen, wenn Sie versuchen, `Annotated` zu verwenden.
+```Python hl_lines="1"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
+```
- Bitte [aktualisieren Sie FastAPI](../deployment/versions.md#upgrade-der-fastapi-versionen){.internal-link target=_blank} daher mindestens zu Version 0.95.1, bevor Sie `Annotated` verwenden.
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="3"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!}
+```
+
+////
+
+/// info
+
+FastAPI unterstützt (und empfiehlt die Verwendung von) `Annotated` seit Version 0.95.0.
+
+Wenn Sie eine ältere Version haben, werden Sie Fehler angezeigt bekommen, wenn Sie versuchen, `Annotated` zu verwenden.
+
+Bitte [aktualisieren Sie FastAPI](../deployment/versions.md#upgrade-der-fastapi-versionen){.internal-link target=_blank} daher mindestens zu Version 0.95.1, bevor Sie `Annotated` verwenden.
+
+///
## Metadaten deklarieren
@@ -55,53 +74,75 @@ Sie können die gleichen Parameter deklarieren wie für `Query`.
Um zum Beispiel einen `title`-Metadaten-Wert für den Pfad-Parameter `item_id` zu deklarieren, schreiben Sie:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="10"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="10"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="11"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="11"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
+```
- ```Python hl_lines="8"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-!!! note "Hinweis"
- Ein Pfad-Parameter ist immer erforderlich, weil er Teil des Pfads sein muss.
+///
- Sie sollten ihn daher mit `...` deklarieren, um ihn als erforderlich auszuzeichnen.
+```Python hl_lines="8"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
+```
- Doch selbst wenn Sie ihn mit `None` deklarieren, oder einen Defaultwert setzen, bewirkt das nichts, er bleibt immer erforderlich.
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="10"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!}
+```
+
+////
+
+/// note | "Hinweis"
+
+Ein Pfad-Parameter ist immer erforderlich, weil er Teil des Pfads sein muss.
+
+Sie sollten ihn daher mit `...` deklarieren, um ihn als erforderlich auszuzeichnen.
+
+Doch selbst wenn Sie ihn mit `None` deklarieren, oder einen Defaultwert setzen, bewirkt das nichts, er bleibt immer erforderlich.
+
+///
## Sortieren Sie die Parameter, wie Sie möchten
-!!! tip "Tipp"
- Wenn Sie `Annotated` verwenden, ist das folgende nicht so wichtig / nicht notwendig.
+/// tip | "Tipp"
+
+Wenn Sie `Annotated` verwenden, ist das folgende nicht so wichtig / nicht notwendig.
+
+///
Nehmen wir an, Sie möchten den Query-Parameter `q` als erforderlichen `str` deklarieren.
@@ -117,33 +158,45 @@ Für **FastAPI** ist es nicht wichtig. Es erkennt die Parameter anhand ihres Nam
Sie können Ihre Funktion also so deklarieren:
-=== "Python 3.8 nicht annotiert"
+//// tab | Python 3.8 nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="7"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="7"
+{!> ../../docs_src/path_params_numeric_validations/tutorial002.py!}
+```
+
+////
Aber bedenken Sie, dass Sie dieses Problem nicht haben, wenn Sie `Annotated` verwenden, da Sie nicht die Funktions-Parameter-Defaultwerte für `Query()` oder `Path()` verwenden.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!}
- ```
+```Python hl_lines="10"
+{!> ../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../docs_src/path_params_numeric_validations/tutorial002_an.py!}
+```
+
+////
## Sortieren Sie die Parameter wie Sie möchten: Tricks
-!!! tip "Tipp"
- Wenn Sie `Annotated` verwenden, ist das folgende nicht so wichtig / nicht notwendig.
+/// tip | "Tipp"
+
+Wenn Sie `Annotated` verwenden, ist das folgende nicht so wichtig / nicht notwendig.
+
+///
Hier ein **kleiner Trick**, der nützlich sein kann, aber Sie werden ihn nicht oft brauchen.
@@ -161,50 +214,63 @@ 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!}
```
### Besser mit `Annotated`
Bedenken Sie, dass Sie, wenn Sie `Annotated` verwenden, dieses Problem nicht haben, weil Sie keine Defaultwerte für Ihre Funktionsparameter haben. Sie müssen daher wahrscheinlich auch nicht `*` verwenden.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!}
- ```
+```Python hl_lines="10"
+{!> ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../docs_src/path_params_numeric_validations/tutorial003_an.py!}
+```
+
+////
## Validierung von Zahlen: Größer oder gleich
Mit `Query` und `Path` (und anderen, die Sie später kennenlernen), können Sie Zahlenbeschränkungen deklarieren.
Hier, mit `ge=1`, wird festgelegt, dass `item_id` eine Ganzzahl benötigt, die größer oder gleich `1` ist (`g`reater than or `e`qual).
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!}
- ```
+```Python hl_lines="10"
+{!> ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ nicht annotiert"
+```Python hl_lines="9"
+{!> ../../docs_src/path_params_numeric_validations/tutorial004_an.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="8"
+{!> ../../docs_src/path_params_numeric_validations/tutorial004.py!}
+```
+
+////
## Validierung von Zahlen: Größer und kleiner oder gleich
@@ -213,26 +279,35 @@ Das Gleiche trifft zu auf:
* `gt`: `g`reater `t`han – größer als
* `le`: `l`ess than or `e`qual – kleiner oder gleich
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!}
- ```
+```Python hl_lines="10"
+{!> ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ nicht annotiert"
+```Python hl_lines="9"
+{!> ../../docs_src/path_params_numeric_validations/tutorial005_an.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="9"
+{!> ../../docs_src/path_params_numeric_validations/tutorial005.py!}
+```
+
+////
## Validierung von Zahlen: Floats, größer und kleiner
@@ -244,26 +319,35 @@ Hier wird es wichtig, in der Lage zu sein, lt.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="13"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!}
- ```
+```Python hl_lines="13"
+{!> ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="12"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ nicht annotiert"
+```Python hl_lines="12"
+{!> ../../docs_src/path_params_numeric_validations/tutorial006_an.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="11"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="11"
+{!> ../../docs_src/path_params_numeric_validations/tutorial006.py!}
+```
+
+////
## Zusammenfassung
@@ -276,18 +360,24 @@ Und Sie können auch Validierungen für Zahlen deklarieren:
* `lt`: `l`ess `t`han – kleiner als
* `le`: `l`ess than or `e`qual – kleiner oder gleich
-!!! info
- `Query`, `Path`, und andere Klassen, die Sie später kennenlernen, sind Unterklassen einer allgemeinen `Param`-Klasse.
+/// info
- Sie alle teilen die gleichen Parameter für zusätzliche Validierung und Metadaten, die Sie gesehen haben.
+`Query`, `Path`, und andere Klassen, die Sie später kennenlernen, sind Unterklassen einer allgemeinen `Param`-Klasse.
-!!! note "Technische Details"
- `Query`, `Path` und andere, die Sie von `fastapi` importieren, sind tatsächlich Funktionen.
+Sie alle teilen die gleichen Parameter für zusätzliche Validierung und Metadaten, die Sie gesehen haben.
- Die, wenn sie aufgerufen werden, Instanzen der Klassen mit demselben Namen zurückgeben.
+///
- Sie importieren also `Query`, welches eine Funktion ist. Aber wenn Sie es aufrufen, gibt es eine Instanz der Klasse zurück, die auch `Query` genannt wird.
+/// note | "Technische Details"
- Diese Funktionen existieren (statt die Klassen direkt zu verwenden), damit Ihr Editor keine Fehlermeldungen über ihre Typen ausgibt.
+`Query`, `Path` und andere, die Sie von `fastapi` importieren, sind tatsächlich Funktionen.
- Auf diese Weise können Sie Ihren Editor und Ihre Programmier-Tools verwenden, ohne besondere Einstellungen vornehmen zu müssen, um diese Fehlermeldungen stummzuschalten.
+Die, wenn sie aufgerufen werden, Instanzen der Klassen mit demselben Namen zurückgeben.
+
+Sie importieren also `Query`, welches eine Funktion ist. Aber wenn Sie es aufrufen, gibt es eine Instanz der Klasse zurück, die auch `Query` genannt wird.
+
+Diese Funktionen existieren (statt die Klassen direkt zu verwenden), damit Ihr Editor keine Fehlermeldungen über ihre Typen ausgibt.
+
+Auf diese Weise können Sie Ihren Editor und Ihre Programmier-Tools verwenden, ohne besondere Einstellungen vornehmen zu müssen, um diese Fehlermeldungen stummzuschalten.
+
+///
diff --git a/docs/de/docs/tutorial/path-params.md b/docs/de/docs/tutorial/path-params.md
index 8c8f2e008..9cb172c94 100644
--- a/docs/de/docs/tutorial/path-params.md
+++ b/docs/de/docs/tutorial/path-params.md
@@ -3,7 +3,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!}
```
Der Wert des Pfad-Parameters `item_id` wird Ihrer Funktion als das Argument `item_id` übergeben.
@@ -19,13 +19,16 @@ Wenn Sie dieses Beispiel ausführen und auf Konversion
@@ -35,10 +38,13 @@ Wenn Sie dieses Beispiel ausführen und Ihren Browser unter „parsen“.
+Beachten Sie, dass der Wert, den Ihre Funktion erhält und zurückgibt, die Zahl `3` ist, also ein `int`. Nicht der String `"3"`, also ein `str`.
+
+Sprich, mit dieser Typdeklaration wird **FastAPI** die Anfrage automatisch „parsen“.
+
+///
## Datenvalidierung
@@ -65,12 +71,15 @@ Der Pfad-Parameter `item_id` hatte den Wert `"foo"`, was kein `int` ist.
Die gleiche Fehlermeldung würde angezeigt werden, wenn Sie ein `float` (also eine Kommazahl) statt eines `int`s übergeben würden, wie etwa in: http://127.0.0.1:8000/items/4.2
-!!! check
- Sprich, mit der gleichen Python-Typdeklaration gibt Ihnen **FastAPI** Datenvalidierung.
+/// check
- Beachten Sie, dass die Fehlermeldung auch direkt die Stelle anzeigt, wo die Validierung nicht erfolgreich war.
+Sprich, mit der gleichen Python-Typdeklaration gibt Ihnen **FastAPI** Datenvalidierung.
- Das ist unglaublich hilfreich, wenn Sie Code entwickeln und debuggen, welcher mit ihrer API interagiert.
+Beachten Sie, dass die Fehlermeldung auch direkt die Stelle anzeigt, wo die Validierung nicht erfolgreich war.
+
+Das ist unglaublich hilfreich, wenn Sie Code entwickeln und debuggen, welcher mit ihrer API interagiert.
+
+///
## Dokumentation
@@ -78,10 +87,13 @@ Wenn Sie die Seite
-!!! check
- Wiederum, mit dieser gleichen Python-Typdeklaration gibt Ihnen **FastAPI** eine automatische, interaktive Dokumentation (verwendet die Swagger-Benutzeroberfläche).
+/// check
- Beachten Sie, dass der Pfad-Parameter dort als Ganzzahl deklariert ist.
+Wiederum, mit dieser gleichen Python-Typdeklaration gibt Ihnen **FastAPI** eine automatische, interaktive Dokumentation (verwendet die Swagger-Benutzeroberfläche).
+
+Beachten Sie, dass der Pfad-Parameter dort als Ganzzahl deklariert ist.
+
+///
## Nützliche Standards. Alternative Dokumentation
@@ -112,7 +124,7 @@ Und Sie haben auch einen Pfad `/users/{user_id}`, um Daten über einen spezifisc
Weil *Pfadoperationen* in ihrer Reihenfolge ausgewertet werden, müssen Sie sicherstellen, dass der Pfad `/users/me` vor `/users/{user_id}` deklariert wurde:
```Python hl_lines="6 11"
-{!../../../docs_src/path_params/tutorial003.py!}
+{!../../docs_src/path_params/tutorial003.py!}
```
Ansonsten würde der Pfad für `/users/{user_id}` auch `/users/me` auswerten, und annehmen, dass ein Parameter `user_id` mit dem Wert `"me"` übergeben wurde.
@@ -120,7 +132,7 @@ Ansonsten würde der Pfad für `/users/{user_id}` auch `/users/me` auswerten, un
Sie können eine Pfadoperation auch nicht erneut definieren:
```Python hl_lines="6 11"
-{!../../../docs_src/path_params/tutorial003b.py!}
+{!../../docs_src/path_params/tutorial003b.py!}
```
Die erste Definition wird immer verwendet werden, da ihr Pfad zuerst übereinstimmt.
@@ -138,21 +150,27 @@ Indem Sie von `str` erben, weiß die API Dokumentation, dass die Werte des Enums
Erstellen Sie dann Klassen-Attribute mit festgelegten Werten, welches die erlaubten Werte sein werden:
```Python hl_lines="1 6-9"
-{!../../../docs_src/path_params/tutorial005.py!}
+{!../../docs_src/path_params/tutorial005.py!}
```
-!!! info
- Enumerationen (oder kurz Enums) gibt es in Python seit Version 3.4.
+/// info
-!!! tip "Tipp"
- Falls Sie sich fragen, was „AlexNet“, „ResNet“ und „LeNet“ ist, das sind Namen von Modellen für maschinelles Lernen.
+Enumerationen (oder kurz Enums) gibt es in Python seit Version 3.4.
+
+///
+
+/// tip | "Tipp"
+
+Falls Sie sich fragen, was „AlexNet“, „ResNet“ und „LeNet“ ist, das sind Namen von Modellen für maschinelles Lernen.
+
+///
### Deklarieren Sie einen *Pfad-Parameter*
Dann erstellen Sie einen *Pfad-Parameter*, der als Typ die gerade erstellte Enum-Klasse hat (`ModelName`):
```Python hl_lines="16"
-{!../../../docs_src/path_params/tutorial005.py!}
+{!../../docs_src/path_params/tutorial005.py!}
```
### Testen Sie es in der API-Dokumentation
@@ -170,7 +188,7 @@ Der *Pfad-Parameter* wird ein * ../../../docs_src/query_params_str_validations/tutorial001_py310.py!}
- ```
+```Python hl_lines="7"
+{!> ../../docs_src/query_params_str_validations/tutorial001_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../docs_src/query_params_str_validations/tutorial001.py!}
+```
+
+////
Der Query-Parameter `q` hat den Typ `Union[str, None]` (oder `str | None` in Python 3.10), was bedeutet, er ist entweder ein `str` oder `None`. Der Defaultwert ist `None`, also weiß FastAPI, der Parameter ist nicht erforderlich.
-!!! note "Hinweis"
- FastAPI weiß nur dank des definierten Defaultwertes `=None`, dass der Wert von `q` nicht erforderlich ist
+/// note | "Hinweis"
- `Union[str, None]` hingegen erlaubt ihren Editor, Sie besser zu unterstützen und Fehler zu erkennen.
+FastAPI weiß nur dank des definierten Defaultwertes `=None`, dass der Wert von `q` nicht erforderlich ist
+
+`Union[str, None]` hingegen erlaubt ihren Editor, Sie besser zu unterstützen und Fehler zu erkennen.
+
+///
## Zusätzliche Validierung
@@ -34,30 +41,37 @@ Importieren Sie zuerst:
* `Query` von `fastapi`
* `Annotated` von `typing` (oder von `typing_extensions` in Python unter 3.9)
-=== "Python 3.10+"
+//// tab | Python 3.10+
- In Python 3.9 oder darüber, ist `Annotated` Teil der Standardbibliothek, also können Sie es von `typing` importieren.
+In Python 3.9 oder darüber, ist `Annotated` Teil der Standardbibliothek, also können Sie es von `typing` importieren.
- ```Python hl_lines="1 3"
- {!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!}
- ```
+```Python hl_lines="1 3"
+{!> ../../docs_src/query_params_str_validations/tutorial002_an_py310.py!}
+```
-=== "Python 3.8+"
+////
- In Versionen unter Python 3.9 importieren Sie `Annotated` von `typing_extensions`.
+//// tab | Python 3.8+
- Es wird bereits mit FastAPI installiert sein.
+In Versionen unter Python 3.9 importieren Sie `Annotated` von `typing_extensions`.
- ```Python hl_lines="3-4"
- {!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!}
- ```
+Es wird bereits mit FastAPI installiert sein.
-!!! info
- FastAPI unterstützt (und empfiehlt die Verwendung von) `Annotated` seit Version 0.95.0.
+```Python hl_lines="3-4"
+{!> ../../docs_src/query_params_str_validations/tutorial002_an.py!}
+```
- Wenn Sie eine ältere Version haben, werden Sie Fehler angezeigt bekommen, wenn Sie versuchen, `Annotated` zu verwenden.
+////
- Bitte [aktualisieren Sie FastAPI](../deployment/versions.md#upgrade-der-fastapi-versionen){.internal-link target=_blank} daher mindestens zu Version 0.95.1, bevor Sie `Annotated` verwenden.
+/// info
+
+FastAPI unterstützt (und empfiehlt die Verwendung von) `Annotated` seit Version 0.95.0.
+
+Wenn Sie eine ältere Version haben, werden Sie Fehler angezeigt bekommen, wenn Sie versuchen, `Annotated` zu verwenden.
+
+Bitte [aktualisieren Sie FastAPI](../deployment/versions.md#upgrade-der-fastapi-versionen){.internal-link target=_blank} daher mindestens zu Version 0.95.1, bevor Sie `Annotated` verwenden.
+
+///
## `Annotated` im Typ des `q`-Parameters verwenden
@@ -67,31 +81,39 @@ Jetzt ist es an der Zeit, das mit FastAPI auszuprobieren. 🚀
Wir hatten diese Typannotation:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python
- q: str | None = None
- ```
+```Python
+q: str | None = None
+```
-=== "Python 3.8+"
+////
- ```Python
- q: Union[str, None] = None
- ```
+//// tab | Python 3.8+
+
+```Python
+q: Union[str, None] = None
+```
+
+////
Wir wrappen das nun in `Annotated`, sodass daraus wird:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python
- q: Annotated[str | None] = None
- ```
+```Python
+q: Annotated[str | None] = None
+```
-=== "Python 3.8+"
+////
- ```Python
- q: Annotated[Union[str, None]] = None
- ```
+//// tab | Python 3.8+
+
+```Python
+q: Annotated[Union[str, None]] = None
+```
+
+////
Beide Versionen bedeuten dasselbe: `q` ist ein Parameter, der `str` oder `None` sein kann. Standardmäßig ist er `None`.
@@ -101,17 +123,21 @@ Wenden wir uns jetzt den spannenden Dingen zu. 🎉
Jetzt, da wir `Annotated` für unsere Metadaten deklariert haben, fügen Sie `Query` hinzu, und setzen Sie den Parameter `max_length` auf `50`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/query_params_str_validations/tutorial002_an_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="10"
+{!> ../../docs_src/query_params_str_validations/tutorial002_an.py!}
+```
+
+////
Beachten Sie, dass der Defaultwert immer noch `None` ist, sodass der Parameter immer noch optional ist.
@@ -127,22 +153,29 @@ FastAPI wird nun:
Frühere Versionen von FastAPI (vor 0.95.0) benötigten `Query` als Defaultwert des Parameters, statt es innerhalb von `Annotated` unterzubringen. Die Chance ist groß, dass Sie Quellcode sehen, der das immer noch so macht, darum erkläre ich es Ihnen.
-!!! tip "Tipp"
- Verwenden Sie für neuen Code, und wann immer möglich, `Annotated`, wie oben erklärt. Es gibt mehrere Vorteile (unten erläutert) und keine Nachteile. 🍰
+/// tip | "Tipp"
+
+Verwenden Sie für neuen Code, und wann immer möglich, `Annotated`, wie oben erklärt. Es gibt mehrere Vorteile (unten erläutert) und keine Nachteile. 🍰
+
+///
So würden Sie `Query()` als Defaultwert Ihres Funktionsparameters verwenden, den Parameter `max_length` auf 50 gesetzt:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!}
- ```
+```Python hl_lines="7"
+{!> ../../docs_src/query_params_str_validations/tutorial002_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../docs_src/query_params_str_validations/tutorial002.py!}
+```
+
+////
Da wir in diesem Fall (ohne die Verwendung von `Annotated`) den Parameter-Defaultwert `None` mit `Query()` ersetzen, müssen wir nun dessen Defaultwert mit dem Parameter `Query(default=None)` deklarieren. Das dient demselben Zweck, `None` als Defaultwert für den Funktionsparameter zu setzen (zumindest für FastAPI).
@@ -172,22 +205,25 @@ q: str | None = None
Nur, dass die `Query`-Versionen den Parameter explizit als Query-Parameter deklarieren.
-!!! info
- Bedenken Sie, dass:
+/// info
- ```Python
- = None
- ```
+Bedenken Sie, dass:
- oder:
+```Python
+= None
+```
- ```Python
- = Query(default=None)
- ```
+oder:
- der wichtigste Teil ist, um einen Parameter optional zu machen, da dieses `None` der Defaultwert ist, und das ist es, was diesen Parameter **nicht erforderlich** macht.
+```Python
+= Query(default=None)
+```
- Der Teil mit `Union[str, None]` erlaubt es Ihrem Editor, Sie besser zu unterstützen, aber er sagt FastAPI nicht, dass dieser Parameter optional ist.
+der wichtigste Teil ist, um einen Parameter optional zu machen, da dieses `None` der Defaultwert ist, und das ist es, was diesen Parameter **nicht erforderlich** macht.
+
+Der Teil mit `Union[str, None]` erlaubt es Ihrem Editor, Sie besser zu unterstützen, aber er sagt FastAPI nicht, dass dieser Parameter optional ist.
+
+///
Jetzt können wir `Query` weitere Parameter übergeben. Fangen wir mit dem `max_length` Parameter an, der auf Strings angewendet wird:
@@ -239,81 +275,113 @@ Da `Annotated` mehrere Metadaten haben kann, können Sie dieselbe Funktion auch
Sie können auch einen Parameter `min_length` hinzufügen:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial003_an_py310.py!}
- ```
+```Python hl_lines="10"
+{!> ../../docs_src/query_params_str_validations/tutorial003_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial003_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="10"
+{!> ../../docs_src/query_params_str_validations/tutorial003_an_py39.py!}
+```
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial003_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="11"
+{!> ../../docs_src/query_params_str_validations/tutorial003_an.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial003.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="7"
+{!> ../../docs_src/query_params_str_validations/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="10"
+{!> ../../docs_src/query_params_str_validations/tutorial003.py!}
+```
+
+////
## Reguläre Ausdrücke hinzufügen
Sie können einen Regulären Ausdruck `pattern` definieren, mit dem der Parameter übereinstimmen muss:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial004_an_py310.py!}
- ```
+```Python hl_lines="11"
+{!> ../../docs_src/query_params_str_validations/tutorial004_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial004_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="11"
+{!> ../../docs_src/query_params_str_validations/tutorial004_an_py39.py!}
+```
- ```Python hl_lines="12"
- {!> ../../../docs_src/query_params_str_validations/tutorial004_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="12"
+{!> ../../docs_src/query_params_str_validations/tutorial004_an.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial004.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="9"
+{!> ../../docs_src/query_params_str_validations/tutorial004_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="11"
+{!> ../../docs_src/query_params_str_validations/tutorial004.py!}
+```
+
+////
Dieses bestimmte reguläre Suchmuster prüft, ob der erhaltene Parameter-Wert:
@@ -331,11 +399,13 @@ Vor Pydantic Version 2 und vor FastAPI Version 0.100.0, war der Name des Paramet
Sie könnten immer noch Code sehen, der den alten Namen verwendet:
-=== "Python 3.10+ Pydantic v1"
+//// tab | Python 3.10+ Pydantic v1
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial004_an_py310_regex.py!}
- ```
+```Python hl_lines="11"
+{!> ../../docs_src/query_params_str_validations/tutorial004_an_py310_regex.py!}
+```
+
+////
Beachten Sie aber, dass das deprecated ist, und zum neuen Namen `pattern` geändert werden sollte. 🤓
@@ -345,29 +415,41 @@ Sie können natürlich andere Defaultwerte als `None` verwenden.
Beispielsweise könnten Sie den `q` Query-Parameter so deklarieren, dass er eine `min_length` von `3` hat, und den Defaultwert `"fixedquery"`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial005_an_py39.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/query_params_str_validations/tutorial005_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial005_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ nicht annotiert"
+```Python hl_lines="8"
+{!> ../../docs_src/query_params_str_validations/tutorial005_an.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial005.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
-!!! note "Hinweis"
- Ein Parameter ist optional (nicht erforderlich), wenn er irgendeinen Defaultwert, auch `None`, hat.
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="7"
+{!> ../../docs_src/query_params_str_validations/tutorial005.py!}
+```
+
+////
+
+/// note | "Hinweis"
+
+Ein Parameter ist optional (nicht erforderlich), wenn er irgendeinen Defaultwert, auch `None`, hat.
+
+///
## Erforderliche Parameter
@@ -385,75 +467,103 @@ q: Union[str, None] = None
Aber jetzt deklarieren wir den Parameter mit `Query`, wie in:
-=== "Annotiert"
+//// tab | Annotiert
- ```Python
- q: Annotated[Union[str, None], Query(min_length=3)] = None
- ```
+```Python
+q: Annotated[Union[str, None], Query(min_length=3)] = None
+```
-=== "Nicht annotiert"
+////
- ```Python
- q: Union[str, None] = Query(default=None, min_length=3)
- ```
+//// tab | Nicht annotiert
+
+```Python
+q: Union[str, None] = Query(default=None, min_length=3)
+```
+
+////
Wenn Sie einen Parameter erforderlich machen wollen, während Sie `Query` verwenden, deklarieren Sie ebenfalls einfach keinen Defaultwert:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial006_an_py39.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/query_params_str_validations/tutorial006_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial006_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ nicht annotiert"
+```Python hl_lines="8"
+{!> ../../docs_src/query_params_str_validations/tutorial006_an.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial006.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
- !!! tip "Tipp"
- Beachten Sie, dass, obwohl in diesem Fall `Query()` der Funktionsparameter-Defaultwert ist, wir nicht `default=None` zu `Query()` hinzufügen.
+/// tip | "Tipp"
- Verwenden Sie bitte trotzdem die `Annotated`-Version. 😉
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="7"
+{!> ../../docs_src/query_params_str_validations/tutorial006.py!}
+```
+
+/// tip | "Tipp"
+
+Beachten Sie, dass, obwohl in diesem Fall `Query()` der Funktionsparameter-Defaultwert ist, wir nicht `default=None` zu `Query()` hinzufügen.
+
+Verwenden Sie bitte trotzdem die `Annotated`-Version. 😉
+
+///
+
+////
### Erforderlich mit Ellipse (`...`)
Es gibt eine Alternative, die explizit deklariert, dass ein Wert erforderlich ist. Sie können als Default das Literal `...` setzen:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial006b_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ nicht annotiert"
+```Python hl_lines="8"
+{!> ../../docs_src/query_params_str_validations/tutorial006b_an.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial006b.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
-!!! info
- Falls Sie das `...` bisher noch nicht gesehen haben: Es ist ein spezieller einzelner Wert, Teil von Python und wird „Ellipsis“ genannt (Deutsch: Ellipse).
+/// tip | "Tipp"
- Es wird von Pydantic und FastAPI verwendet, um explizit zu deklarieren, dass ein Wert erforderlich ist.
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="7"
+{!> ../../docs_src/query_params_str_validations/tutorial006b.py!}
+```
+
+////
+
+/// info
+
+Falls Sie das `...` bisher noch nicht gesehen haben: Es ist ein spezieller einzelner Wert, Teil von Python und wird „Ellipsis“ genannt (Deutsch: Ellipse).
+
+Es wird von Pydantic und FastAPI verwendet, um explizit zu deklarieren, dass ein Wert erforderlich ist.
+
+///
Dies wird **FastAPI** wissen lassen, dass dieser Parameter erforderlich ist.
@@ -463,47 +573,69 @@ Sie können deklarieren, dass ein Parameter `None` akzeptiert, aber dennoch erfo
Um das zu machen, deklarieren Sie, dass `None` ein gültiger Typ ist, aber verwenden Sie dennoch `...` als Default:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py310.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/query_params_str_validations/tutorial006c_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="9"
+{!> ../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial006c_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="10"
+{!> ../../docs_src/query_params_str_validations/tutorial006c_an.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial006c.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-!!! tip "Tipp"
- Pydantic, welches die gesamte Datenvalidierung und Serialisierung in FastAPI antreibt, hat ein spezielles Verhalten, wenn Sie `Optional` oder `Union[Something, None]` ohne Defaultwert verwenden, Sie können mehr darüber in der Pydantic-Dokumentation unter Required fields erfahren.
+///
-!!! tip "Tipp"
- Denken Sie daran, dass Sie in den meisten Fällen, wenn etwas erforderlich ist, einfach den Defaultwert weglassen können. Sie müssen also normalerweise `...` nicht verwenden.
+```Python hl_lines="7"
+{!> ../../docs_src/query_params_str_validations/tutorial006c_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="9"
+{!> ../../docs_src/query_params_str_validations/tutorial006c.py!}
+```
+
+////
+
+/// tip | "Tipp"
+
+Pydantic, welches die gesamte Datenvalidierung und Serialisierung in FastAPI antreibt, hat ein spezielles Verhalten, wenn Sie `Optional` oder `Union[Something, None]` ohne Defaultwert verwenden, Sie können mehr darüber in der Pydantic-Dokumentation unter Required fields erfahren.
+
+///
+
+/// tip | "Tipp"
+
+Denken Sie daran, dass Sie in den meisten Fällen, wenn etwas erforderlich ist, einfach den Defaultwert weglassen können. Sie müssen also normalerweise `...` nicht verwenden.
+
+///
## Query-Parameter-Liste / Mehrere Werte
@@ -511,50 +643,71 @@ Wenn Sie einen Query-Parameter explizit mit `Query` auszeichnen, können Sie ihn
Um zum Beispiel einen Query-Parameter `q` zu deklarieren, der mehrere Male in der URL vorkommen kann, schreiben Sie:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial011_an_py310.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/query_params_str_validations/tutorial011_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial011_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="9"
+{!> ../../docs_src/query_params_str_validations/tutorial011_an_py39.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial011_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="10"
+{!> ../../docs_src/query_params_str_validations/tutorial011_an.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial011_py310.py!}
- ```
+////
-=== "Python 3.9+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-=== "Python 3.8+ nicht annotiert"
+///
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="7"
+{!> ../../docs_src/query_params_str_validations/tutorial011_py310.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial011.py!}
- ```
+////
+
+//// tab | Python 3.9+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="9"
+{!> ../../docs_src/query_params_str_validations/tutorial011_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="9"
+{!> ../../docs_src/query_params_str_validations/tutorial011.py!}
+```
+
+////
Dann, mit einer URL wie:
@@ -575,8 +728,11 @@ Die Response für diese URL wäre also:
}
```
-!!! tip "Tipp"
- Um einen Query-Parameter vom Typ `list` zu deklarieren, wie im Beispiel oben, müssen Sie explizit `Query` verwenden, sonst würde der Parameter als Requestbody interpretiert werden.
+/// tip | "Tipp"
+
+Um einen Query-Parameter vom Typ `list` zu deklarieren, wie im Beispiel oben, müssen Sie explizit `Query` verwenden, sonst würde der Parameter als Requestbody interpretiert werden.
+
+///
Die interaktive API-Dokumentation wird entsprechend aktualisiert und erlaubt jetzt mehrere Werte.
@@ -586,35 +742,49 @@ Die interaktive API-Dokumentation wird entsprechend aktualisiert und erlaubt jet
Und Sie können auch eine Default-`list`e von Werten definieren, wenn keine übergeben werden:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial012_an_py39.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/query_params_str_validations/tutorial012_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial012_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.9+ nicht annotiert"
+```Python hl_lines="10"
+{!> ../../docs_src/query_params_str_validations/tutorial012_an.py!}
+```
- !!! 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.9+ nicht annotiert
-=== "Python 3.8+ nicht annotiert"
+/// tip | "Tipp"
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial012.py!}
- ```
+///
+
+```Python hl_lines="7"
+{!> ../../docs_src/query_params_str_validations/tutorial012_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="9"
+{!> ../../docs_src/query_params_str_validations/tutorial012.py!}
+```
+
+////
Wenn Sie auf:
@@ -637,31 +807,43 @@ gehen, wird der Default für `q` verwendet: `["foo", "bar"]`, und als Response e
Sie können auch `list` direkt verwenden, anstelle von `List[str]` (oder `list[str]` in Python 3.9+):
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial013_an_py39.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/query_params_str_validations/tutorial013_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial013_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ nicht annotiert"
+```Python hl_lines="8"
+{!> ../../docs_src/query_params_str_validations/tutorial013_an.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial013.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
-!!! note "Hinweis"
- Beachten Sie, dass FastAPI in diesem Fall den Inhalt der Liste nicht überprüft.
+/// tip | "Tipp"
- Zum Beispiel würde `List[int]` überprüfen (und dokumentieren) dass die Liste Ganzzahlen enthält. `list` alleine macht das nicht.
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="7"
+{!> ../../docs_src/query_params_str_validations/tutorial013.py!}
+```
+
+////
+
+/// note | "Hinweis"
+
+Beachten Sie, dass FastAPI in diesem Fall den Inhalt der Liste nicht überprüft.
+
+Zum Beispiel würde `List[int]` überprüfen (und dokumentieren) dass die Liste Ganzzahlen enthält. `list` alleine macht das nicht.
+
+///
## Deklarieren von mehr Metadaten
@@ -669,86 +851,121 @@ Sie können mehr Informationen zum Parameter hinzufügen.
Diese Informationen werden zur generierten OpenAPI hinzugefügt, und von den Dokumentations-Oberflächen und von externen Tools verwendet.
-!!! note "Hinweis"
- Beachten Sie, dass verschiedene Tools OpenAPI möglicherweise unterschiedlich gut unterstützen.
+/// note | "Hinweis"
- Einige könnten noch nicht alle zusätzlichen Informationen anzeigen, die Sie deklariert haben, obwohl in den meisten Fällen geplant ist, das fehlende Feature zu implementieren.
+Beachten Sie, dass verschiedene Tools OpenAPI möglicherweise unterschiedlich gut unterstützen.
+
+Einige könnten noch nicht alle zusätzlichen Informationen anzeigen, die Sie deklariert haben, obwohl in den meisten Fällen geplant ist, das fehlende Feature zu implementieren.
+
+///
Sie können einen Titel hinzufügen – `title`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial007_an_py310.py!}
- ```
+```Python hl_lines="10"
+{!> ../../docs_src/query_params_str_validations/tutorial007_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial007_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="10"
+{!> ../../docs_src/query_params_str_validations/tutorial007_an_py39.py!}
+```
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial007_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="11"
+{!> ../../docs_src/query_params_str_validations/tutorial007_an.py!}
+```
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial007.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="8"
+{!> ../../docs_src/query_params_str_validations/tutorial007_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="10"
+{!> ../../docs_src/query_params_str_validations/tutorial007.py!}
+```
+
+////
Und eine Beschreibung – `description`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="14"
- {!> ../../../docs_src/query_params_str_validations/tutorial008_an_py310.py!}
- ```
+```Python hl_lines="14"
+{!> ../../docs_src/query_params_str_validations/tutorial008_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="14"
- {!> ../../../docs_src/query_params_str_validations/tutorial008_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="14"
+{!> ../../docs_src/query_params_str_validations/tutorial008_an_py39.py!}
+```
- ```Python hl_lines="15"
- {!> ../../../docs_src/query_params_str_validations/tutorial008_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="15"
+{!> ../../docs_src/query_params_str_validations/tutorial008_an.py!}
+```
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="13"
- {!> ../../../docs_src/query_params_str_validations/tutorial008.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="11"
+{!> ../../docs_src/query_params_str_validations/tutorial008_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="13"
+{!> ../../docs_src/query_params_str_validations/tutorial008.py!}
+```
+
+////
## Alias-Parameter
@@ -768,41 +985,57 @@ Aber Sie möchten dennoch exakt `item-query` verwenden.
Dann können Sie einen `alias` deklarieren, und dieser Alias wird verwendet, um den Parameter-Wert zu finden:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial009_an_py310.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/query_params_str_validations/tutorial009_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial009_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="9"
+{!> ../../docs_src/query_params_str_validations/tutorial009_an_py39.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial009_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="10"
+{!> ../../docs_src/query_params_str_validations/tutorial009_an.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial009.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="7"
+{!> ../../docs_src/query_params_str_validations/tutorial009_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="9"
+{!> ../../docs_src/query_params_str_validations/tutorial009.py!}
+```
+
+////
## Parameter als deprecated ausweisen
@@ -812,41 +1045,57 @@ Sie müssen ihn eine Weile dort belassen, weil Clients ihn benutzen, aber Sie m
In diesem Fall fügen Sie den Parameter `deprecated=True` zu `Query` hinzu.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="19"
- {!> ../../../docs_src/query_params_str_validations/tutorial010_an_py310.py!}
- ```
+```Python hl_lines="19"
+{!> ../../docs_src/query_params_str_validations/tutorial010_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="19"
- {!> ../../../docs_src/query_params_str_validations/tutorial010_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="19"
+{!> ../../docs_src/query_params_str_validations/tutorial010_an_py39.py!}
+```
- ```Python hl_lines="20"
- {!> ../../../docs_src/query_params_str_validations/tutorial010_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="20"
+{!> ../../docs_src/query_params_str_validations/tutorial010_an.py!}
+```
- ```Python hl_lines="16"
- {!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="18"
- {!> ../../../docs_src/query_params_str_validations/tutorial010.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="16"
+{!> ../../docs_src/query_params_str_validations/tutorial010_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="18"
+{!> ../../docs_src/query_params_str_validations/tutorial010.py!}
+```
+
+////
Die Dokumentation wird das so anzeigen:
@@ -856,41 +1105,57 @@ Die Dokumentation wird das so anzeigen:
Um einen Query-Parameter vom generierten OpenAPI-Schema auszuschließen (und daher von automatischen Dokumentations-Systemen), setzen Sie den Parameter `include_in_schema` in `Query` auf `False`.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial014_an_py310.py!}
- ```
+```Python hl_lines="10"
+{!> ../../docs_src/query_params_str_validations/tutorial014_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial014_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="10"
+{!> ../../docs_src/query_params_str_validations/tutorial014_an_py39.py!}
+```
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial014_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="11"
+{!> ../../docs_src/query_params_str_validations/tutorial014_an.py!}
+```
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial014.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="8"
+{!> ../../docs_src/query_params_str_validations/tutorial014_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="10"
+{!> ../../docs_src/query_params_str_validations/tutorial014.py!}
+```
+
+////
## Zusammenfassung
diff --git a/docs/de/docs/tutorial/query-params.md b/docs/de/docs/tutorial/query-params.md
index 1b9b56bea..bb1dbdf9c 100644
--- a/docs/de/docs/tutorial/query-params.md
+++ b/docs/de/docs/tutorial/query-params.md
@@ -3,7 +3,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!}
```
Query-Parameter (Deutsch: Abfrage-Parameter) sind die Schlüssel-Wert-Paare, die nach dem `?` in einer URL aufgelistet sind, getrennt durch `&`-Zeichen.
@@ -63,38 +63,49 @@ gehen, werden die Parameter-Werte Ihrer Funktion sein:
Auf die gleiche Weise können Sie optionale Query-Parameter deklarieren, indem Sie deren Defaultwert auf `None` setzen:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params/tutorial002_py310.py!}
- ```
+```Python hl_lines="7"
+{!> ../../docs_src/query_params/tutorial002_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../docs_src/query_params/tutorial002.py!}
+```
+
+////
In diesem Fall wird der Funktionsparameter `q` optional, und standardmäßig `None` sein.
-!!! check
- Beachten Sie auch, dass **FastAPI** intelligent genug ist, um zu erkennen, dass `item_id` ein Pfad-Parameter ist und `q` keiner, daher muss letzteres ein Query-Parameter sein.
+/// check
+
+Beachten Sie auch, dass **FastAPI** intelligent genug ist, um zu erkennen, dass `item_id` ein Pfad-Parameter ist und `q` keiner, daher muss letzteres ein Query-Parameter sein.
+
+///
## Query-Parameter Typkonvertierung
Sie können auch `bool`-Typen deklarieren und sie werden konvertiert:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params/tutorial003_py310.py!}
- ```
+```Python hl_lines="7"
+{!> ../../docs_src/query_params/tutorial003_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params/tutorial003.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../docs_src/query_params/tutorial003.py!}
+```
+
+////
Wenn Sie nun zu:
@@ -136,17 +147,21 @@ Und Sie müssen sie auch nicht in einer spezifischen Reihenfolge deklarieren.
Parameter werden anhand ihres Namens erkannt:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="6 8"
- {!> ../../../docs_src/query_params/tutorial004_py310.py!}
- ```
+```Python hl_lines="6 8"
+{!> ../../docs_src/query_params/tutorial004_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="8 10"
- {!> ../../../docs_src/query_params/tutorial004.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="8 10"
+{!> ../../docs_src/query_params/tutorial004.py!}
+```
+
+////
## Erforderliche Query-Parameter
@@ -157,7 +172,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!}
```
Hier ist `needy` ein erforderlicher Query-Parameter vom Typ `str`.
@@ -204,17 +219,21 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
Und natürlich können Sie einige Parameter als erforderlich, einige mit Defaultwert, und einige als vollständig optional definieren:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params/tutorial006_py310.py!}
- ```
+```Python hl_lines="8"
+{!> ../../docs_src/query_params/tutorial006_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params/tutorial006.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="10"
+{!> ../../docs_src/query_params/tutorial006.py!}
+```
+
+////
In diesem Fall gibt es drei Query-Parameter:
@@ -222,5 +241,8 @@ In diesem Fall gibt es drei Query-Parameter:
* `skip`, ein `int` mit einem Defaultwert `0`.
* `limit`, ein optionales `int`.
-!!! tip "Tipp"
- Sie können auch `Enum`s verwenden, auf die gleiche Weise wie mit [Pfad-Parametern](path-params.md#vordefinierte-parameterwerte){.internal-link target=_blank}.
+/// tip | "Tipp"
+
+Sie können auch `Enum`s verwenden, auf die gleiche Weise wie mit [Pfad-Parametern](path-params.md#vordefinierte-parameterwerte){.internal-link target=_blank}.
+
+///
diff --git a/docs/de/docs/tutorial/request-files.md b/docs/de/docs/tutorial/request-files.md
index 67b5e3a87..c0d0ef3f2 100644
--- a/docs/de/docs/tutorial/request-files.md
+++ b/docs/de/docs/tutorial/request-files.md
@@ -2,70 +2,97 @@
Mit `File` können sie vom Client hochzuladende Dateien definieren.
-!!! info
- Um hochgeladene Dateien zu empfangen, installieren Sie zuerst `python-multipart`.
+/// info
- Z. B. `pip install python-multipart`.
+Um hochgeladene Dateien zu empfangen, installieren Sie zuerst `python-multipart`.
- Das, weil hochgeladene Dateien als „Formulardaten“ gesendet werden.
+Z. B. `pip install python-multipart`.
+
+Das, weil hochgeladene Dateien als „Formulardaten“ gesendet werden.
+
+///
## `File` importieren
Importieren Sie `File` und `UploadFile` von `fastapi`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="3"
- {!> ../../../docs_src/request_files/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="3"
+{!> ../../docs_src/request_files/tutorial001_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/request_files/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ nicht annotiert"
+```Python hl_lines="1"
+{!> ../../docs_src/request_files/tutorial001_an.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/request_files/tutorial001.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="1"
+{!> ../../docs_src/request_files/tutorial001.py!}
+```
+
+////
## `File`-Parameter definieren
Erstellen Sie Datei-Parameter, so wie Sie es auch mit `Body` und `Form` machen würden:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="9"
- {!> ../../../docs_src/request_files/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/request_files/tutorial001_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/request_files/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ nicht annotiert"
+```Python hl_lines="8"
+{!> ../../docs_src/request_files/tutorial001_an.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/request_files/tutorial001.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
-!!! info
- `File` ist eine Klasse, die direkt von `Form` erbt.
+/// tip | "Tipp"
- Aber erinnern Sie sich, dass, wenn Sie `Query`, `Path`, `File` und andere von `fastapi` importieren, diese tatsächlich Funktionen sind, welche spezielle Klassen zurückgeben
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-!!! 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.
+///
+
+```Python hl_lines="7"
+{!> ../../docs_src/request_files/tutorial001.py!}
+```
+
+////
+
+/// info
+
+`File` ist eine Klasse, die direkt von `Form` erbt.
+
+Aber erinnern Sie sich, dass, wenn Sie `Query`, `Path`, `File` und andere von `fastapi` importieren, diese tatsächlich Funktionen sind, welche spezielle Klassen zurückgeben
+
+///
+
+/// tip | "Tipp"
+
+Um Dateibodys zu deklarieren, müssen Sie `File` verwenden, da diese Parameter sonst als Query-Parameter oder Body(-JSON)-Parameter interpretiert werden würden.
+
+///
Die Dateien werden als „Formulardaten“ hochgeladen.
@@ -79,26 +106,35 @@ Aber es gibt viele Fälle, in denen Sie davon profitieren, `UploadFile` zu verwe
Definieren Sie einen Datei-Parameter mit dem Typ `UploadFile`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="14"
- {!> ../../../docs_src/request_files/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="14"
+{!> ../../docs_src/request_files/tutorial001_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="13"
- {!> ../../../docs_src/request_files/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ nicht annotiert"
+```Python hl_lines="13"
+{!> ../../docs_src/request_files/tutorial001_an.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="12"
- {!> ../../../docs_src/request_files/tutorial001.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="12"
+{!> ../../docs_src/request_files/tutorial001.py!}
+```
+
+////
`UploadFile` zu verwenden, hat mehrere Vorzüge gegenüber `bytes`:
@@ -141,11 +177,17 @@ Wenn Sie sich innerhalb einer normalen `def`-*Pfadoperation-Funktion* befinden,
contents = myfile.file.read()
```
-!!! note "Technische Details zu `async`"
- Wenn Sie die `async`-Methoden verwenden, führt **FastAPI** die Datei-Methoden in einem Threadpool aus und erwartet sie.
+/// note | "Technische Details zu `async`"
-!!! note "Technische Details zu Starlette"
- **FastAPI**s `UploadFile` erbt direkt von **Starlette**s `UploadFile`, fügt aber ein paar notwendige Teile hinzu, um es kompatibel mit **Pydantic** und anderen Teilen von FastAPI zu machen.
+Wenn Sie die `async`-Methoden verwenden, führt **FastAPI** die Datei-Methoden in einem Threadpool aus und erwartet sie.
+
+///
+
+/// note | "Technische Details zu Starlette"
+
+**FastAPI**s `UploadFile` erbt direkt von **Starlette**s `UploadFile`, fügt aber ein paar notwendige Teile hinzu, um es kompatibel mit **Pydantic** und anderen Teilen von FastAPI zu machen.
+
+///
## Was sind „Formulardaten“
@@ -153,82 +195,113 @@ HTML-Formulare (``) senden die Daten in einer „speziellen“ Kodi
**FastAPI** stellt sicher, dass diese Daten korrekt ausgelesen werden, statt JSON zu erwarten.
-!!! note "Technische Details"
- Daten aus Formularen werden, wenn es keine Dateien sind, normalerweise mit dem „media type“ `application/x-www-form-urlencoded` kodiert.
+/// note | "Technische Details"
- Sollte das Formular aber Dateien enthalten, dann werden diese mit `multipart/form-data` kodiert. Wenn Sie `File` verwenden, wird **FastAPI** wissen, dass es die Dateien vom korrekten Teil des Bodys holen muss.
+Daten aus Formularen werden, wenn es keine Dateien sind, normalerweise mit dem „media type“ `application/x-www-form-urlencoded` kodiert.
- Wenn Sie mehr über Formularfelder und ihre Kodierungen lesen möchten, besuchen Sie die MDN-Webdokumentation für POST.
+Sollte das Formular aber Dateien enthalten, dann werden diese mit `multipart/form-data` kodiert. Wenn Sie `File` verwenden, wird **FastAPI** wissen, dass es die Dateien vom korrekten Teil des Bodys holen muss.
-!!! warning "Achtung"
- 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.
+Wenn Sie mehr über Formularfelder und ihre Kodierungen lesen möchten, besuchen Sie die MDN-Webdokumentation für POST.
- Das ist keine Limitation von **FastAPI**, sondern Teil des HTTP-Protokolls.
+///
+
+/// warning | "Achtung"
+
+Sie können mehrere `File`- und `Form`-Parameter in einer *Pfadoperation* deklarieren, aber Sie können nicht gleichzeitig auch `Body`-Felder deklarieren, welche Sie als JSON erwarten, da der Request den Body mittels `multipart/form-data` statt `application/json` kodiert.
+
+Das ist keine Limitation von **FastAPI**, sondern Teil des HTTP-Protokolls.
+
+///
## Optionaler Datei-Upload
Sie können eine Datei optional machen, indem Sie Standard-Typannotationen verwenden und den Defaultwert auf `None` setzen:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9 17"
- {!> ../../../docs_src/request_files/tutorial001_02_an_py310.py!}
- ```
+```Python hl_lines="9 17"
+{!> ../../docs_src/request_files/tutorial001_02_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="9 17"
- {!> ../../../docs_src/request_files/tutorial001_02_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="9 17"
+{!> ../../docs_src/request_files/tutorial001_02_an_py39.py!}
+```
- ```Python hl_lines="10 18"
- {!> ../../../docs_src/request_files/tutorial001_02_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="10 18"
+{!> ../../docs_src/request_files/tutorial001_02_an.py!}
+```
- ```Python hl_lines="7 15"
- {!> ../../../docs_src/request_files/tutorial001_02_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="9 17"
- {!> ../../../docs_src/request_files/tutorial001_02.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="7 15"
+{!> ../../docs_src/request_files/tutorial001_02_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="9 17"
+{!> ../../docs_src/request_files/tutorial001_02.py!}
+```
+
+////
## `UploadFile` mit zusätzlichen Metadaten
Sie können auch `File()` zusammen mit `UploadFile` verwenden, um zum Beispiel zusätzliche Metadaten zu setzen:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="9 15"
- {!> ../../../docs_src/request_files/tutorial001_03_an_py39.py!}
- ```
+```Python hl_lines="9 15"
+{!> ../../docs_src/request_files/tutorial001_03_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="8 14"
- {!> ../../../docs_src/request_files/tutorial001_03_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ nicht annotiert"
+```Python hl_lines="8 14"
+{!> ../../docs_src/request_files/tutorial001_03_an.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="7 13"
- {!> ../../../docs_src/request_files/tutorial001_03.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="7 13"
+{!> ../../docs_src/request_files/tutorial001_03.py!}
+```
+
+////
## Mehrere Datei-Uploads
@@ -238,76 +311,107 @@ Diese werden demselben Formularfeld zugeordnet, welches mit den Formulardaten ge
Um das zu machen, deklarieren Sie eine Liste von `bytes` oder `UploadFile`s:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="10 15"
- {!> ../../../docs_src/request_files/tutorial002_an_py39.py!}
- ```
+```Python hl_lines="10 15"
+{!> ../../docs_src/request_files/tutorial002_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="11 16"
- {!> ../../../docs_src/request_files/tutorial002_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.9+ nicht annotiert"
+```Python hl_lines="11 16"
+{!> ../../docs_src/request_files/tutorial002_an.py!}
+```
- !!! 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.9+ nicht annotiert
-=== "Python 3.8+ nicht annotiert"
+/// tip | "Tipp"
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- ```Python hl_lines="10 15"
- {!> ../../../docs_src/request_files/tutorial002.py!}
- ```
+///
+
+```Python hl_lines="8 13"
+{!> ../../docs_src/request_files/tutorial002_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="10 15"
+{!> ../../docs_src/request_files/tutorial002.py!}
+```
+
+////
Sie erhalten, wie deklariert, eine `list`e von `bytes` oder `UploadFile`s.
-!!! note "Technische Details"
- Sie können auch `from starlette.responses import HTMLResponse` verwenden.
+/// note | "Technische Details"
- **FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette.
+Sie können auch `from starlette.responses import HTMLResponse` verwenden.
+
+**FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette.
+
+///
### Mehrere Datei-Uploads mit zusätzlichen Metadaten
Und so wie zuvor können Sie `File()` verwenden, um zusätzliche Parameter zu setzen, sogar für `UploadFile`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="11 18-20"
- {!> ../../../docs_src/request_files/tutorial003_an_py39.py!}
- ```
+```Python hl_lines="11 18-20"
+{!> ../../docs_src/request_files/tutorial003_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="12 19-21"
- {!> ../../../docs_src/request_files/tutorial003_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.9+ nicht annotiert"
+```Python hl_lines="12 19-21"
+{!> ../../docs_src/request_files/tutorial003_an.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="9 16"
- {!> ../../../docs_src/request_files/tutorial003_py39.py!}
- ```
+//// tab | Python 3.9+ nicht annotiert
-=== "Python 3.8+ nicht annotiert"
+/// tip | "Tipp"
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- ```Python hl_lines="11 18"
- {!> ../../../docs_src/request_files/tutorial003.py!}
- ```
+///
+
+```Python hl_lines="9 16"
+{!> ../../docs_src/request_files/tutorial003_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="11 18"
+{!> ../../docs_src/request_files/tutorial003.py!}
+```
+
+////
## Zusammenfassung
diff --git a/docs/de/docs/tutorial/request-forms-and-files.md b/docs/de/docs/tutorial/request-forms-and-files.md
index 86b1406e6..2b89edbb4 100644
--- a/docs/de/docs/tutorial/request-forms-and-files.md
+++ b/docs/de/docs/tutorial/request-forms-and-files.md
@@ -2,67 +2,91 @@
Sie können gleichzeitig Dateien und Formulardaten mit `File` und `Form` definieren.
-!!! info
- Um hochgeladene Dateien und/oder Formulardaten zu empfangen, installieren Sie zuerst `python-multipart`.
+/// info
- Z. B. `pip install python-multipart`.
+Um hochgeladene Dateien und/oder Formulardaten zu empfangen, installieren Sie zuerst `python-multipart`.
+
+Z. B. `pip install python-multipart`.
+
+///
## `File` und `Form` importieren
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="3"
- {!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="3"
+{!> ../../docs_src/request_forms_and_files/tutorial001_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ nicht annotiert"
+```Python hl_lines="1"
+{!> ../../docs_src/request_forms_and_files/tutorial001_an.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/request_forms_and_files/tutorial001.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="1"
+{!> ../../docs_src/request_forms_and_files/tutorial001.py!}
+```
+
+////
## `File` und `Form`-Parameter definieren
Erstellen Sie Datei- und Formularparameter, so wie Sie es auch mit `Body` und `Query` machen würden:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="10-12"
- {!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="10-12"
+{!> ../../docs_src/request_forms_and_files/tutorial001_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9-11"
- {!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ nicht annotiert"
+```Python hl_lines="9-11"
+{!> ../../docs_src/request_forms_and_files/tutorial001_an.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/request_forms_and_files/tutorial001.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="8"
+{!> ../../docs_src/request_forms_and_files/tutorial001.py!}
+```
+
+////
Die Datei- und Formularfelder werden als Formulardaten hochgeladen, und Sie erhalten diese Dateien und Formularfelder.
Und Sie können einige der Dateien als `bytes` und einige als `UploadFile` deklarieren.
-!!! warning "Achtung"
- Sie können mehrere `File`- und `Form`-Parameter in einer *Pfadoperation* deklarieren, aber Sie können nicht gleichzeitig auch `Body`-Felder deklarieren, welche Sie als JSON erwarten, da der Request den Body mittels `multipart/form-data` statt `application/json` kodiert.
+/// warning | "Achtung"
- Das ist keine Limitation von **FastAPI**, sondern Teil des HTTP-Protokolls.
+Sie können mehrere `File`- und `Form`-Parameter in einer *Pfadoperation* deklarieren, aber Sie können nicht gleichzeitig auch `Body`-Felder deklarieren, welche Sie als JSON erwarten, da der Request den Body mittels `multipart/form-data` statt `application/json` kodiert.
+
+Das ist keine Limitation von **FastAPI**, sondern Teil des HTTP-Protokolls.
+
+///
## Zusammenfassung
diff --git a/docs/de/docs/tutorial/request-forms.md b/docs/de/docs/tutorial/request-forms.md
index 6c029b5fe..0784aa8c0 100644
--- a/docs/de/docs/tutorial/request-forms.md
+++ b/docs/de/docs/tutorial/request-forms.md
@@ -2,60 +2,81 @@
Wenn Sie Felder aus Formularen statt JSON empfangen müssen, können Sie `Form` verwenden.
-!!! info
- Um Formulare zu verwenden, installieren Sie zuerst `python-multipart`.
+/// info
- Z. B. `pip install python-multipart`.
+Um Formulare zu verwenden, installieren Sie zuerst `python-multipart`.
+
+Z. B. `pip install python-multipart`.
+
+///
## `Form` importieren
Importieren Sie `Form` von `fastapi`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="3"
- {!> ../../../docs_src/request_forms/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="3"
+{!> ../../docs_src/request_forms/tutorial001_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/request_forms/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ nicht annotiert"
+```Python hl_lines="1"
+{!> ../../docs_src/request_forms/tutorial001_an.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/request_forms/tutorial001.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="1"
+{!> ../../docs_src/request_forms/tutorial001.py!}
+```
+
+////
## `Form`-Parameter definieren
Erstellen Sie Formular-Parameter, so wie Sie es auch mit `Body` und `Query` machen würden:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="9"
- {!> ../../../docs_src/request_forms/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/request_forms/tutorial001_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/request_forms/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ nicht annotiert"
+```Python hl_lines="8"
+{!> ../../docs_src/request_forms/tutorial001_an.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/request_forms/tutorial001.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="7"
+{!> ../../docs_src/request_forms/tutorial001.py!}
+```
+
+////
Zum Beispiel stellt eine der Möglichkeiten, die OAuth2 Spezifikation zu verwenden (genannt „password flow“), die Bedingung, einen `username` und ein `password` als Formularfelder zu senden.
@@ -63,11 +84,17 @@ Die Spec erfordert, dass di
Mit `Form` haben Sie die gleichen Konfigurationsmöglichkeiten wie mit `Body` (und `Query`, `Path`, `Cookie`), inklusive Validierung, Beispielen, einem Alias (z. B. `user-name` statt `username`), usw.
-!!! info
- `Form` ist eine Klasse, die direkt von `Body` erbt.
+/// info
-!!! 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.
+`Form` ist eine Klasse, die direkt von `Body` erbt.
+
+///
+
+/// tip | "Tipp"
+
+Um Formularbodys zu deklarieren, verwenden Sie explizit `Form`, da diese Parameter sonst als Query-Parameter oder Body(-JSON)-Parameter interpretiert werden würden.
+
+///
## Über „Formularfelder“
@@ -75,17 +102,23 @@ HTML-Formulare (``) senden die Daten in einer „speziellen“ Kodi
**FastAPI** stellt sicher, dass diese Daten korrekt ausgelesen werden, statt JSON zu erwarten.
-!!! note "Technische Details"
- Daten aus Formularen werden normalerweise mit dem „media type“ `application/x-www-form-urlencoded` kodiert.
+/// note | "Technische Details"
- Wenn das Formular stattdessen Dateien enthält, werden diese mit `multipart/form-data` kodiert. Im nächsten Kapitel erfahren Sie mehr über die Handhabung von Dateien.
+Daten aus Formularen werden normalerweise mit dem „media type“ `application/x-www-form-urlencoded` kodiert.
- Wenn Sie mehr über Formularfelder und ihre Kodierungen lesen möchten, besuchen Sie die MDN-Webdokumentation für POST.
+Wenn das Formular stattdessen Dateien enthält, werden diese mit `multipart/form-data` kodiert. Im nächsten Kapitel erfahren Sie mehr über die Handhabung von Dateien.
-!!! warning "Achtung"
- 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.
+Wenn Sie mehr über Formularfelder und ihre Kodierungen lesen möchten, besuchen Sie die MDN-Webdokumentation für POST.
- Das ist keine Limitation von **FastAPI**, sondern Teil des HTTP-Protokolls.
+///
+
+/// warning | "Achtung"
+
+Sie können mehrere `Form`-Parameter in einer *Pfadoperation* deklarieren, aber Sie können nicht gleichzeitig auch `Body`-Felder deklarieren, welche Sie als JSON erwarten, da der Request den Body mittels `application/x-www-form-urlencoded` statt `application/json` kodiert.
+
+Das ist keine Limitation von **FastAPI**, sondern Teil des HTTP-Protokolls.
+
+///
## Zusammenfassung
diff --git a/docs/de/docs/tutorial/response-model.md b/docs/de/docs/tutorial/response-model.md
index d5b92e0f9..31ad73c77 100644
--- a/docs/de/docs/tutorial/response-model.md
+++ b/docs/de/docs/tutorial/response-model.md
@@ -4,23 +4,29 @@ Sie können den Typ der ../../../docs_src/response_model/tutorial001_01_py310.py!}
- ```
+```Python hl_lines="16 21"
+{!> ../../docs_src/response_model/tutorial001_01_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="18 23"
- {!> ../../../docs_src/response_model/tutorial001_01_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="18 23"
+{!> ../../docs_src/response_model/tutorial001_01_py39.py!}
+```
- ```Python hl_lines="18 23"
- {!> ../../../docs_src/response_model/tutorial001_01.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="18 23"
+{!> ../../docs_src/response_model/tutorial001_01.py!}
+```
+
+////
FastAPI wird diesen Rückgabetyp verwenden, um:
@@ -53,35 +59,47 @@ Sie können `response_model` in jeder möglichen *Pfadoperation* verwenden:
* `@app.delete()`
* usw.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001_py310.py!}
- ```
+```Python hl_lines="17 22 24-27"
+{!> ../../docs_src/response_model/tutorial001_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="17 22 24-27"
+{!> ../../docs_src/response_model/tutorial001_py39.py!}
+```
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001.py!}
- ```
+////
-!!! note "Hinweis"
- Beachten Sie, dass `response_model` ein Parameter der „Dekorator“-Methode ist (`get`, `post`, usw.). Nicht der *Pfadoperation-Funktion*, so wie die anderen Parameter.
+//// tab | Python 3.8+
+
+```Python hl_lines="17 22 24-27"
+{!> ../../docs_src/response_model/tutorial001.py!}
+```
+
+////
+
+/// note | "Hinweis"
+
+Beachten Sie, dass `response_model` ein Parameter der „Dekorator“-Methode ist (`get`, `post`, usw.). Nicht der *Pfadoperation-Funktion*, so wie die anderen Parameter.
+
+///
`response_model` nimmt denselben Typ entgegen, den Sie auch für ein Pydantic-Modellfeld deklarieren würden, also etwa ein Pydantic-Modell, aber es kann auch z. B. eine `list`e von Pydantic-Modellen sein, wie etwa `List[Item]`.
FastAPI wird dieses `response_model` nehmen, um die Daten zu dokumentieren, validieren, usw. und auch, um **die Ausgabedaten** entsprechend der Typdeklaration **zu konvertieren und filtern**.
-!!! tip "Tipp"
- Wenn Sie in Ihrem Editor strikte Typchecks haben, mypy, usw., können Sie den Funktions-Rückgabetyp als `Any` deklarieren.
+/// tip | "Tipp"
- So sagen Sie dem Editor, dass Sie absichtlich *irgendetwas* zurückgeben. Aber FastAPI wird trotzdem die Dokumentation, Validierung, Filterung, usw. der Daten übernehmen, via `response_model`.
+Wenn Sie in Ihrem Editor strikte Typchecks haben, mypy, usw., können Sie den Funktions-Rückgabetyp als `Any` deklarieren.
+
+So sagen Sie dem Editor, dass Sie absichtlich *irgendetwas* zurückgeben. Aber FastAPI wird trotzdem die Dokumentation, Validierung, Filterung, usw. der Daten übernehmen, via `response_model`.
+
+///
### `response_model`-Priorität
@@ -95,37 +113,48 @@ Sie können auch `response_model=None` verwenden, um das Erstellen eines Respons
Im Folgenden deklarieren wir ein `UserIn`-Modell; es enthält ein Klartext-Passwort:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7 9"
- {!> ../../../docs_src/response_model/tutorial002_py310.py!}
- ```
+```Python hl_lines="7 9"
+{!> ../../docs_src/response_model/tutorial002_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9 11"
- {!> ../../../docs_src/response_model/tutorial002.py!}
- ```
+//// tab | Python 3.8+
-!!! info
- Um `EmailStr` zu verwenden, installieren Sie zuerst `email_validator`.
+```Python hl_lines="9 11"
+{!> ../../docs_src/response_model/tutorial002.py!}
+```
- Z. B. `pip install email-validator`
- oder `pip install pydantic[email]`.
+////
+
+/// info
+
+Um `EmailStr` zu verwenden, installieren Sie zuerst `email-validator`.
+
+Z. B. `pip install email-validator`
+oder `pip install pydantic[email]`.
+
+///
Wir verwenden dieses Modell, um sowohl unsere Eingabe- als auch Ausgabedaten zu deklarieren:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="16"
- {!> ../../../docs_src/response_model/tutorial002_py310.py!}
- ```
+```Python hl_lines="16"
+{!> ../../docs_src/response_model/tutorial002_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="18"
- {!> ../../../docs_src/response_model/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="18"
+{!> ../../docs_src/response_model/tutorial002.py!}
+```
+
+////
Immer wenn jetzt ein Browser einen Benutzer mit Passwort erzeugt, gibt die API dasselbe Passwort in der Response zurück.
@@ -133,52 +162,67 @@ Hier ist das möglicherweise kein Problem, da es derselbe Benutzer ist, der das
Aber wenn wir dasselbe Modell für eine andere *Pfadoperation* verwenden, könnten wir das Passwort dieses Benutzers zu jedem Client schicken.
-!!! danger "Gefahr"
- Speichern Sie niemals das Klartext-Passwort eines Benutzers, oder versenden Sie es in einer Response wie dieser, wenn Sie sich nicht der resultierenden Gefahren bewusst sind und nicht wissen, was Sie tun.
+/// danger | "Gefahr"
+
+Speichern Sie niemals das Klartext-Passwort eines Benutzers, oder versenden Sie es in einer Response wie dieser, wenn Sie sich nicht der resultierenden Gefahren bewusst sind und nicht wissen, was Sie tun.
+
+///
## Ausgabemodell hinzufügen
Wir können stattdessen ein Eingabemodell mit dem Klartext-Passwort, und ein Ausgabemodell ohne das Passwort erstellen:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9 11 16"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
+```Python hl_lines="9 11 16"
+{!> ../../docs_src/response_model/tutorial003_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9 11 16"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="9 11 16"
+{!> ../../docs_src/response_model/tutorial003.py!}
+```
+
+////
Obwohl unsere *Pfadoperation-Funktion* hier denselben `user` von der Eingabe zurückgibt, der das Passwort enthält:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
+```Python hl_lines="24"
+{!> ../../docs_src/response_model/tutorial003_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="24"
+{!> ../../docs_src/response_model/tutorial003.py!}
+```
+
+////
... haben wir deklariert, dass `response_model` das Modell `UserOut` ist, welches das Passwort nicht enthält:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
+```Python hl_lines="22"
+{!> ../../docs_src/response_model/tutorial003_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="22"
+{!> ../../docs_src/response_model/tutorial003.py!}
+```
+
+////
Darum wird **FastAPI** sich darum kümmern, dass alle Daten, die nicht im Ausgabemodell deklariert sind, herausgefiltert werden (mittels Pydantic).
@@ -202,17 +246,21 @@ Aber in den meisten Fällen, wenn wir so etwas machen, wollen wir nur, dass das
Und in solchen Fällen können wir Klassen und Vererbung verwenden, um Vorteil aus den Typannotationen in der Funktion zu ziehen, was vom Editor und von Tools besser unterstützt wird, während wir gleichzeitig FastAPIs **Datenfilterung** behalten.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7-10 13-14 18"
- {!> ../../../docs_src/response_model/tutorial003_01_py310.py!}
- ```
+```Python hl_lines="7-10 13-14 18"
+{!> ../../docs_src/response_model/tutorial003_01_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9-13 15-16 20"
- {!> ../../../docs_src/response_model/tutorial003_01.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="9-13 15-16 20"
+{!> ../../docs_src/response_model/tutorial003_01.py!}
+```
+
+////
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.
@@ -255,7 +303,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!}
```
Dieser einfache Anwendungsfall wird automatisch von FastAPI gehandhabt, weil die Annotation des Rückgabetyps die Klasse (oder eine Unterklasse von) `Response` ist.
@@ -267,7 +315,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!}
```
Das wird ebenfalls funktionieren, weil `RedirectResponse` eine Unterklasse von `Response` ist, und FastAPI sich um diesen einfachen Anwendungsfall automatisch kümmert.
@@ -278,17 +326,21 @@ Aber wenn Sie ein beliebiges anderes Objekt zurückgeben, das kein gültiger Pyd
Das gleiche wird passieren, wenn Sie eine Union mehrerer Typen haben, und einer oder mehrere sind nicht gültige Pydantic-Typen. Zum Beispiel funktioniert folgendes nicht 💥:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="8"
- {!> ../../../docs_src/response_model/tutorial003_04_py310.py!}
- ```
+```Python hl_lines="8"
+{!> ../../docs_src/response_model/tutorial003_04_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/response_model/tutorial003_04.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="10"
+{!> ../../docs_src/response_model/tutorial003_04.py!}
+```
+
+////
... das scheitert, da die Typannotation kein Pydantic-Typ ist, und auch keine einzelne `Response`-Klasse, oder -Unterklasse, es ist eine Union (eines von beiden) von `Response` und `dict`.
@@ -300,17 +352,21 @@ Aber Sie möchten dennoch den Rückgabetyp in der Funktion annotieren, um Unters
In diesem Fall können Sie die Generierung des Responsemodells abschalten, indem Sie `response_model=None` setzen:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7"
- {!> ../../../docs_src/response_model/tutorial003_05_py310.py!}
- ```
+```Python hl_lines="7"
+{!> ../../docs_src/response_model/tutorial003_05_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/response_model/tutorial003_05.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../docs_src/response_model/tutorial003_05.py!}
+```
+
+////
Das bewirkt, dass FastAPI die Generierung des Responsemodells unterlässt, und damit können Sie jede gewünschte Rückgabetyp-Annotation haben, ohne dass es Ihre FastAPI-Anwendung beeinflusst. 🤓
@@ -318,23 +374,29 @@ Das bewirkt, dass FastAPI die Generierung des Responsemodells unterlässt, und d
Ihr Responsemodell könnte Defaultwerte haben, wie:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9 11-12"
- {!> ../../../docs_src/response_model/tutorial004_py310.py!}
- ```
+```Python hl_lines="9 11-12"
+{!> ../../docs_src/response_model/tutorial004_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="11 13-14"
- {!> ../../../docs_src/response_model/tutorial004_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="11 13-14"
+{!> ../../docs_src/response_model/tutorial004_py39.py!}
+```
- ```Python hl_lines="11 13-14"
- {!> ../../../docs_src/response_model/tutorial004.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="11 13-14"
+{!> ../../docs_src/response_model/tutorial004.py!}
+```
+
+////
* `description: Union[str, None] = None` (oder `str | None = None` in Python 3.10) hat einen Defaultwert `None`.
* `tax: float = 10.5` hat einen Defaultwert `10.5`.
@@ -348,23 +410,29 @@ Wenn Sie zum Beispiel Modelle mit vielen optionalen Attributen in einer NoSQL-Da
Sie können den *Pfadoperation-Dekorator*-Parameter `response_model_exclude_unset=True` setzen:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial004_py310.py!}
- ```
+```Python hl_lines="22"
+{!> ../../docs_src/response_model/tutorial004_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial004_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="24"
+{!> ../../docs_src/response_model/tutorial004_py39.py!}
+```
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial004.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="24"
+{!> ../../docs_src/response_model/tutorial004.py!}
+```
+
+////
Die Defaultwerte werden dann nicht in der Response enthalten sein, sondern nur die tatsächlich gesetzten Werte.
@@ -377,21 +445,30 @@ Wenn Sie also den Artikel mit der ID `foo` bei der *Pfadoperation* anfragen, wir
}
```
-!!! info
- In Pydantic v1 hieß diese Methode `.dict()`, in Pydantic v2 wurde sie deprecated (aber immer noch unterstützt) und in `.model_dump()` umbenannt.
+/// info
- Die Beispiele hier verwenden `.dict()` für die Kompatibilität mit Pydantic v1, Sie sollten jedoch stattdessen `.model_dump()` verwenden, wenn Sie Pydantic v2 verwenden können.
+In Pydantic v1 hieß diese Methode `.dict()`, in Pydantic v2 wurde sie deprecated (aber immer noch unterstützt) und in `.model_dump()` umbenannt.
-!!! info
- FastAPI verwendet `.dict()` von Pydantic Modellen, mit dessen `exclude_unset`-Parameter, um das zu erreichen.
+Die Beispiele hier verwenden `.dict()` für die Kompatibilität mit Pydantic v1, Sie sollten jedoch stattdessen `.model_dump()` verwenden, wenn Sie Pydantic v2 verwenden können.
-!!! info
- Sie können auch:
+///
- * `response_model_exclude_defaults=True`
- * `response_model_exclude_none=True`
+/// info
- verwenden, wie in der Pydantic Dokumentation für `exclude_defaults` und `exclude_none` beschrieben.
+FastAPI verwendet `.dict()` von Pydantic Modellen, mit dessen `exclude_unset`-Parameter, um das zu erreichen.
+
+///
+
+/// info
+
+Sie können auch:
+
+* `response_model_exclude_defaults=True`
+* `response_model_exclude_none=True`
+
+verwenden, wie in der Pydantic Dokumentation für `exclude_defaults` und `exclude_none` beschrieben.
+
+///
#### Daten mit Werten für Felder mit Defaultwerten
@@ -426,10 +503,13 @@ dann ist FastAPI klug genug (tatsächlich ist Pydantic klug genug) zu erkennen,
Diese Felder werden also in der JSON-Response enthalten sein.
-!!! tip "Tipp"
- Beachten Sie, dass Defaultwerte alles Mögliche sein können, nicht nur `None`.
+/// tip | "Tipp"
- Sie können eine Liste (`[]`), ein `float` `10.5`, usw. sein.
+Beachten Sie, dass Defaultwerte alles Mögliche sein können, nicht nur `None`.
+
+Sie können eine Liste (`[]`), ein `float` `10.5`, usw. sein.
+
+///
### `response_model_include` und `response_model_exclude`
@@ -439,45 +519,59 @@ Diese nehmen ein `set` von `str`s entgegen, welches Namen von Attributen sind, d
Das kann als schnelle Abkürzung verwendet werden, wenn Sie nur ein Pydantic-Modell haben und ein paar Daten von der Ausgabe ausschließen wollen.
-!!! tip "Tipp"
- Es wird dennoch empfohlen, dass Sie die Ideen von oben verwenden, also mehrere Klassen statt dieser Parameter.
+/// tip | "Tipp"
- Der Grund ist, dass das das generierte JSON-Schema in der OpenAPI ihrer Anwendung (und deren Dokumentation) dennoch das komplette Modell abbildet, selbst wenn Sie `response_model_include` oder `response_model_exclude` verwenden, um einige Attribute auszuschließen.
+Es wird dennoch empfohlen, dass Sie die Ideen von oben verwenden, also mehrere Klassen statt dieser Parameter.
- Das trifft auch auf `response_model_by_alias` zu, welches ähnlich funktioniert.
+Der Grund ist, dass das das generierte JSON-Schema in der OpenAPI ihrer Anwendung (und deren Dokumentation) dennoch das komplette Modell abbildet, selbst wenn Sie `response_model_include` oder `response_model_exclude` verwenden, um einige Attribute auszuschließen.
-=== "Python 3.10+"
+Das trifft auch auf `response_model_by_alias` zu, welches ähnlich funktioniert.
- ```Python hl_lines="29 35"
- {!> ../../../docs_src/response_model/tutorial005_py310.py!}
- ```
+///
-=== "Python 3.8+"
+//// tab | Python 3.10+
- ```Python hl_lines="31 37"
- {!> ../../../docs_src/response_model/tutorial005.py!}
- ```
+```Python hl_lines="29 35"
+{!> ../../docs_src/response_model/tutorial005_py310.py!}
+```
-!!! tip "Tipp"
- Die Syntax `{"name", "description"}` erzeugt ein `set` mit diesen zwei Werten.
+////
- Äquivalent zu `set(["name", "description"])`.
+//// tab | Python 3.8+
+
+```Python hl_lines="31 37"
+{!> ../../docs_src/response_model/tutorial005.py!}
+```
+
+////
+
+/// tip | "Tipp"
+
+Die Syntax `{"name", "description"}` erzeugt ein `set` mit diesen zwei Werten.
+
+Äquivalent zu `set(["name", "description"])`.
+
+///
#### `list`en statt `set`s verwenden
Wenn Sie vergessen, ein `set` zu verwenden, und stattdessen eine `list`e oder ein `tuple` übergeben, wird FastAPI die dennoch in ein `set` konvertieren, und es wird korrekt funktionieren:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="29 35"
- {!> ../../../docs_src/response_model/tutorial006_py310.py!}
- ```
+```Python hl_lines="29 35"
+{!> ../../docs_src/response_model/tutorial006_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="31 37"
- {!> ../../../docs_src/response_model/tutorial006.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="31 37"
+{!> ../../docs_src/response_model/tutorial006.py!}
+```
+
+////
## Zusammenfassung
diff --git a/docs/de/docs/tutorial/response-status-code.md b/docs/de/docs/tutorial/response-status-code.md
index a9cc238f8..872007a12 100644
--- a/docs/de/docs/tutorial/response-status-code.md
+++ b/docs/de/docs/tutorial/response-status-code.md
@@ -9,16 +9,22 @@ So wie ein Responsemodell, können Sie auch einen HTTP-Statuscode für die Respo
* usw.
```Python hl_lines="6"
-{!../../../docs_src/response_status_code/tutorial001.py!}
+{!../../docs_src/response_status_code/tutorial001.py!}
```
-!!! note "Hinweis"
- Beachten Sie, dass `status_code` ein Parameter der „Dekorator“-Methode ist (`get`, `post`, usw.). Nicht der *Pfadoperation-Funktion*, so wie die anderen Parameter und der Body.
+/// note | "Hinweis"
+
+Beachten Sie, dass `status_code` ein Parameter der „Dekorator“-Methode ist (`get`, `post`, usw.). Nicht der *Pfadoperation-Funktion*, so wie die anderen Parameter und der Body.
+
+///
Dem `status_code`-Parameter wird eine Zahl mit dem HTTP-Statuscode übergeben.
-!!! info
- Alternativ kann `status_code` auch ein `IntEnum` erhalten, so wie Pythons `http.HTTPStatus`.
+/// info
+
+Alternativ kann `status_code` auch ein `IntEnum` erhalten, so wie Pythons `http.HTTPStatus`.
+
+///
Das wird:
@@ -27,15 +33,21 @@ Das wird:
-!!! note "Hinweis"
- Einige Responsecodes (siehe nächster Abschnitt) kennzeichnen, dass die Response keinen Body hat.
+/// note | "Hinweis"
- FastAPI versteht das und wird in der OpenAPI-Dokumentation anzeigen, dass es keinen Responsebody gibt.
+Einige Responsecodes (siehe nächster Abschnitt) kennzeichnen, dass die Response keinen Body hat.
+
+FastAPI versteht das und wird in der OpenAPI-Dokumentation anzeigen, dass es keinen Responsebody gibt.
+
+///
## Über HTTP-Statuscodes
-!!! note "Hinweis"
- Wenn Sie bereits wissen, was HTTP-Statuscodes sind, überspringen Sie dieses Kapitel und fahren Sie mit dem nächsten fort.
+/// note | "Hinweis"
+
+Wenn Sie bereits wissen, was HTTP-Statuscodes sind, überspringen Sie dieses Kapitel und fahren Sie mit dem nächsten fort.
+
+///
In HTTP senden Sie als Teil der Response einen aus drei Ziffern bestehenden numerischen Statuscode.
@@ -54,15 +66,18 @@ Kurz:
* Für allgemeine Fehler beim Client können Sie einfach `400` verwenden.
* `500` und darüber stehen für Server-Fehler. Diese verwenden Sie fast nie direkt. Wenn etwas an irgendeiner Stelle in Ihrem Anwendungscode oder im Server schiefläuft, wird automatisch einer dieser Fehler-Statuscodes zurückgegeben.
-!!! tip "Tipp"
- Um mehr über Statuscodes zu lernen, und welcher wofür verwendet wird, lesen Sie die MDN Dokumentation über HTTP-Statuscodes.
+/// tip | "Tipp"
+
+Um mehr über Statuscodes zu lernen, und welcher wofür verwendet wird, lesen Sie die MDN Dokumentation über HTTP-Statuscodes.
+
+///
## Abkürzung, um die Namen zu erinnern
Schauen wir uns das vorherige Beispiel noch einmal an:
```Python hl_lines="6"
-{!../../../docs_src/response_status_code/tutorial001.py!}
+{!../../docs_src/response_status_code/tutorial001.py!}
```
`201` ist der Statuscode für „Created“ („Erzeugt“).
@@ -72,17 +87,20 @@ Aber Sie müssen sich nicht daran erinnern, welcher dieser Codes was bedeutet.
Sie können die Hilfsvariablen von `fastapi.status` verwenden.
```Python hl_lines="1 6"
-{!../../../docs_src/response_status_code/tutorial002.py!}
+{!../../docs_src/response_status_code/tutorial002.py!}
```
Diese sind nur eine Annehmlichkeit und enthalten dieselbe Nummer, aber auf diese Weise können Sie die Autovervollständigung Ihres Editors verwenden, um sie zu finden:
-!!! note "Technische Details"
- Sie können auch `from starlette import status` verwenden.
+/// note | "Technische Details"
- **FastAPI** bietet dieselben `starlette.status`-Codes auch via `fastapi.status` an, als Annehmlichkeit für Sie, den Entwickler. Sie kommen aber direkt von Starlette.
+Sie können auch `from starlette import status` verwenden.
+
+**FastAPI** bietet dieselben `starlette.status`-Codes auch via `fastapi.status` an, als Annehmlichkeit für Sie, den Entwickler. Sie kommen aber direkt von Starlette.
+
+///
## Den Defaultwert ändern
diff --git a/docs/de/docs/tutorial/schema-extra-example.md b/docs/de/docs/tutorial/schema-extra-example.md
index e8bfc9876..0da1a4ea4 100644
--- a/docs/de/docs/tutorial/schema-extra-example.md
+++ b/docs/de/docs/tutorial/schema-extra-example.md
@@ -8,71 +8,93 @@ Hier sind mehrere Möglichkeiten, das zu tun.
Sie können `examples` („Beispiele“) für ein Pydantic-Modell deklarieren, welche dem generierten JSON-Schema hinzugefügt werden.
-=== "Python 3.10+ Pydantic v2"
+//// tab | Python 3.10+ Pydantic v2
- ```Python hl_lines="13-24"
- {!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!}
- ```
+```Python hl_lines="13-24"
+{!> ../../docs_src/schema_extra_example/tutorial001_py310.py!}
+```
-=== "Python 3.10+ Pydantic v1"
+////
- ```Python hl_lines="13-23"
- {!> ../../../docs_src/schema_extra_example/tutorial001_py310_pv1.py!}
- ```
+//// tab | Python 3.10+ Pydantic v1
-=== "Python 3.8+ Pydantic v2"
+```Python hl_lines="13-23"
+{!> ../../docs_src/schema_extra_example/tutorial001_py310_pv1.py!}
+```
- ```Python hl_lines="15-26"
- {!> ../../../docs_src/schema_extra_example/tutorial001.py!}
- ```
+////
-=== "Python 3.8+ Pydantic v1"
+//// tab | Python 3.8+ Pydantic v2
- ```Python hl_lines="15-25"
- {!> ../../../docs_src/schema_extra_example/tutorial001_pv1.py!}
- ```
+```Python hl_lines="15-26"
+{!> ../../docs_src/schema_extra_example/tutorial001.py!}
+```
+
+////
+
+//// tab | Python 3.8+ Pydantic v1
+
+```Python hl_lines="15-25"
+{!> ../../docs_src/schema_extra_example/tutorial001_pv1.py!}
+```
+
+////
Diese zusätzlichen Informationen werden unverändert zum für dieses Modell ausgegebenen **JSON-Schema** hinzugefügt und in der API-Dokumentation verwendet.
-=== "Pydantic v2"
+//// tab | Pydantic v2
- In Pydantic Version 2 würden Sie das Attribut `model_config` verwenden, das ein `dict` akzeptiert, wie beschrieben in Pydantic-Dokumentation: Configuration.
+In Pydantic Version 2 würden Sie das Attribut `model_config` verwenden, das ein `dict` akzeptiert, wie beschrieben in Pydantic-Dokumentation: Configuration.
- Sie können `json_schema_extra` setzen, mit einem `dict`, das alle zusätzlichen Daten enthält, die im generierten JSON-Schema angezeigt werden sollen, einschließlich `examples`.
+Sie können `json_schema_extra` setzen, mit einem `dict`, das alle zusätzlichen Daten enthält, die im generierten JSON-Schema angezeigt werden sollen, einschließlich `examples`.
-=== "Pydantic v1"
+////
- In Pydantic Version 1 würden Sie eine interne Klasse `Config` und `schema_extra` verwenden, wie beschrieben in Pydantic-Dokumentation: Schema customization.
+//// tab | Pydantic v1
- Sie können `schema_extra` setzen, mit einem `dict`, das alle zusätzlichen Daten enthält, die im generierten JSON-Schema angezeigt werden sollen, einschließlich `examples`.
+In Pydantic Version 1 würden Sie eine interne Klasse `Config` und `schema_extra` verwenden, wie beschrieben in Pydantic-Dokumentation: Schema customization.
-!!! tip "Tipp"
- Mit derselben Technik können Sie das JSON-Schema erweitern und Ihre eigenen benutzerdefinierten Zusatzinformationen hinzufügen.
+Sie können `schema_extra` setzen, mit einem `dict`, das alle zusätzlichen Daten enthält, die im generierten JSON-Schema angezeigt werden sollen, einschließlich `examples`.
- Sie könnten das beispielsweise verwenden, um Metadaten für eine Frontend-Benutzeroberfläche usw. hinzuzufügen.
+////
-!!! info
- OpenAPI 3.1.0 (verwendet seit FastAPI 0.99.0) hat Unterstützung für `examples` hinzugefügt, was Teil des **JSON Schema** Standards ist.
+/// tip | "Tipp"
- Zuvor unterstützte es nur das Schlüsselwort `example` mit einem einzigen Beispiel. Dieses wird weiterhin von OpenAPI 3.1.0 unterstützt, ist jedoch deprecated und nicht Teil des JSON Schema Standards. Wir empfehlen Ihnen daher, von `example` nach `examples` zu migrieren. 🤓
+Mit derselben Technik können Sie das JSON-Schema erweitern und Ihre eigenen benutzerdefinierten Zusatzinformationen hinzufügen.
- Mehr erfahren Sie am Ende dieser Seite.
+Sie könnten das beispielsweise verwenden, um Metadaten für eine Frontend-Benutzeroberfläche usw. hinzuzufügen.
+
+///
+
+/// info
+
+OpenAPI 3.1.0 (verwendet seit FastAPI 0.99.0) hat Unterstützung für `examples` hinzugefügt, was Teil des **JSON Schema** Standards ist.
+
+Zuvor unterstützte es nur das Schlüsselwort `example` mit einem einzigen Beispiel. Dieses wird weiterhin von OpenAPI 3.1.0 unterstützt, ist jedoch deprecated und nicht Teil des JSON Schema Standards. Wir empfehlen Ihnen daher, von `example` nach `examples` zu migrieren. 🤓
+
+Mehr erfahren Sie am Ende dieser Seite.
+
+///
## Zusätzliche Argumente für `Field`
Wenn Sie `Field()` mit Pydantic-Modellen verwenden, können Sie ebenfalls zusätzliche `examples` deklarieren:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="2 8-11"
- {!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!}
- ```
+```Python hl_lines="2 8-11"
+{!> ../../docs_src/schema_extra_example/tutorial002_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="4 10-13"
- {!> ../../../docs_src/schema_extra_example/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="4 10-13"
+{!> ../../docs_src/schema_extra_example/tutorial002.py!}
+```
+
+////
## `examples` im JSON-Schema – OpenAPI
@@ -92,41 +114,57 @@ können Sie auch eine Gruppe von `examples` mit zusätzlichen Informationen dekl
Hier übergeben wir `examples`, welches ein einzelnes Beispiel für die in `Body()` erwarteten Daten enthält:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="22-29"
- {!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!}
- ```
+```Python hl_lines="22-29"
+{!> ../../docs_src/schema_extra_example/tutorial003_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="22-29"
- {!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="22-29"
+{!> ../../docs_src/schema_extra_example/tutorial003_an_py39.py!}
+```
- ```Python hl_lines="23-30"
- {!> ../../../docs_src/schema_extra_example/tutorial003_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="23-30"
+{!> ../../docs_src/schema_extra_example/tutorial003_an.py!}
+```
- ```Python hl_lines="18-25"
- {!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="20-27"
- {!> ../../../docs_src/schema_extra_example/tutorial003.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="18-25"
+{!> ../../docs_src/schema_extra_example/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="20-27"
+{!> ../../docs_src/schema_extra_example/tutorial003.py!}
+```
+
+////
### Beispiel in der Dokumentations-Benutzeroberfläche
@@ -138,41 +176,57 @@ Mit jeder der oben genannten Methoden würde es in `/docs` so aussehen:
Sie können natürlich auch mehrere `examples` übergeben:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="23-38"
- {!> ../../../docs_src/schema_extra_example/tutorial004_an_py310.py!}
- ```
+```Python hl_lines="23-38"
+{!> ../../docs_src/schema_extra_example/tutorial004_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="23-38"
- {!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="23-38"
+{!> ../../docs_src/schema_extra_example/tutorial004_an_py39.py!}
+```
- ```Python hl_lines="24-39"
- {!> ../../../docs_src/schema_extra_example/tutorial004_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="24-39"
+{!> ../../docs_src/schema_extra_example/tutorial004_an.py!}
+```
- ```Python hl_lines="19-34"
- {!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="21-36"
- {!> ../../../docs_src/schema_extra_example/tutorial004.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="19-34"
+{!> ../../docs_src/schema_extra_example/tutorial004_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="21-36"
+{!> ../../docs_src/schema_extra_example/tutorial004.py!}
+```
+
+////
Wenn Sie das tun, werden die Beispiele Teil des internen **JSON-Schemas** für diese Body-Daten.
@@ -213,41 +267,57 @@ Jedes spezifische Beispiel-`dict` in den `examples` kann Folgendes enthalten:
Sie können es so verwenden:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="23-49"
- {!> ../../../docs_src/schema_extra_example/tutorial005_an_py310.py!}
- ```
+```Python hl_lines="23-49"
+{!> ../../docs_src/schema_extra_example/tutorial005_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="23-49"
- {!> ../../../docs_src/schema_extra_example/tutorial005_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="23-49"
+{!> ../../docs_src/schema_extra_example/tutorial005_an_py39.py!}
+```
- ```Python hl_lines="24-50"
- {!> ../../../docs_src/schema_extra_example/tutorial005_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="24-50"
+{!> ../../docs_src/schema_extra_example/tutorial005_an.py!}
+```
- ```Python hl_lines="19-45"
- {!> ../../../docs_src/schema_extra_example/tutorial005_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="21-47"
- {!> ../../../docs_src/schema_extra_example/tutorial005.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="19-45"
+{!> ../../docs_src/schema_extra_example/tutorial005_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="21-47"
+{!> ../../docs_src/schema_extra_example/tutorial005.py!}
+```
+
+////
### OpenAPI-Beispiele in der Dokumentations-Benutzeroberfläche
@@ -257,17 +327,23 @@ Wenn `openapi_examples` zu `Body()` hinzugefügt wird, würde `/docs` so aussehe
## Technische Details
-!!! tip "Tipp"
- Wenn Sie bereits **FastAPI** Version **0.99.0 oder höher** verwenden, können Sie diese Details wahrscheinlich **überspringen**.
+/// tip | "Tipp"
- Sie sind für ältere Versionen relevanter, bevor OpenAPI 3.1.0 verfügbar war.
+Wenn Sie bereits **FastAPI** Version **0.99.0 oder höher** verwenden, können Sie diese Details wahrscheinlich **überspringen**.
- Sie können dies als eine kurze **Geschichtsstunde** zu OpenAPI und JSON Schema betrachten. 🤓
+Sie sind für ältere Versionen relevanter, bevor OpenAPI 3.1.0 verfügbar war.
-!!! warning "Achtung"
- Dies sind sehr technische Details zu den Standards **JSON Schema** und **OpenAPI**.
+Sie können dies als eine kurze **Geschichtsstunde** zu OpenAPI und JSON Schema betrachten. 🤓
- Wenn die oben genannten Ideen bereits für Sie funktionieren, reicht das möglicherweise aus und Sie benötigen diese Details wahrscheinlich nicht, überspringen Sie sie gerne.
+///
+
+/// warning | "Achtung"
+
+Dies sind sehr technische Details zu den Standards **JSON Schema** und **OpenAPI**.
+
+Wenn die oben genannten Ideen bereits für Sie funktionieren, reicht das möglicherweise aus und Sie benötigen diese Details wahrscheinlich nicht, überspringen Sie sie gerne.
+
+///
Vor OpenAPI 3.1.0 verwendete OpenAPI eine ältere und modifizierte Version von **JSON Schema**.
@@ -285,8 +361,11 @@ OpenAPI fügte auch die Felder `example` und `examples` zu anderen Teilen der Sp
* `File()`
* `Form()`
-!!! info
- Dieser alte, OpenAPI-spezifische `examples`-Parameter heißt seit FastAPI `0.103.0` jetzt `openapi_examples`.
+/// info
+
+Dieser alte, OpenAPI-spezifische `examples`-Parameter heißt seit FastAPI `0.103.0` jetzt `openapi_examples`.
+
+///
### JSON Schemas Feld `examples`
@@ -298,10 +377,13 @@ Und jetzt hat dieses neue `examples`-Feld Vorrang vor dem alten (und benutzerdef
Dieses neue `examples`-Feld in JSON Schema ist **nur eine `list`e** von Beispielen, kein Dict mit zusätzlichen Metadaten wie an den anderen Stellen in OpenAPI (oben beschrieben).
-!!! info
- Selbst, nachdem OpenAPI 3.1.0 veröffentlicht wurde, mit dieser neuen, einfacheren Integration mit JSON Schema, unterstützte Swagger UI, das Tool, das die automatische Dokumentation bereitstellt, eine Zeit lang OpenAPI 3.1.0 nicht (das tut es seit Version 5.0.0 🎉).
+/// info
- Aus diesem Grund verwendeten Versionen von FastAPI vor 0.99.0 immer noch Versionen von OpenAPI vor 3.1.0.
+Selbst, nachdem OpenAPI 3.1.0 veröffentlicht wurde, mit dieser neuen, einfacheren Integration mit JSON Schema, unterstützte Swagger UI, das Tool, das die automatische Dokumentation bereitstellt, eine Zeit lang OpenAPI 3.1.0 nicht (das tut es seit Version 5.0.0 🎉).
+
+Aus diesem Grund verwendeten Versionen von FastAPI vor 0.99.0 immer noch Versionen von OpenAPI vor 3.1.0.
+
+///
### Pydantic- und FastAPI-`examples`
diff --git a/docs/de/docs/tutorial/security/first-steps.md b/docs/de/docs/tutorial/security/first-steps.md
index 1e75fa8d9..c552a681b 100644
--- a/docs/de/docs/tutorial/security/first-steps.md
+++ b/docs/de/docs/tutorial/security/first-steps.md
@@ -20,35 +20,47 @@ Lassen Sie uns zunächst einfach den Code verwenden und sehen, wie er funktionie
Kopieren Sie das Beispiel in eine Datei `main.py`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python
- {!> ../../../docs_src/security/tutorial001_an_py39.py!}
- ```
+```Python
+{!> ../../docs_src/security/tutorial001_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python
- {!> ../../../docs_src/security/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ nicht annotiert"
+```Python
+{!> ../../docs_src/security/tutorial001_an.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python
- {!> ../../../docs_src/security/tutorial001.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python
+{!> ../../docs_src/security/tutorial001.py!}
+```
+
+////
## Ausführen
-!!! info
- Um hochgeladene Dateien zu empfangen, installieren Sie zuerst `python-multipart`.
+/// info
- Z. B. `pip install python-multipart`.
+Um hochgeladene Dateien zu empfangen, installieren Sie zuerst `python-multipart`.
- Das, weil **OAuth2** „Formulardaten“ zum Senden von `username` und `password` verwendet.
+Z. B. `pip install python-multipart`.
+
+Das, weil **OAuth2** „Formulardaten“ zum Senden von `username` und `password` verwendet.
+
+///
Führen Sie das Beispiel aus mit:
@@ -70,17 +82,23 @@ Sie werden etwa Folgendes sehen:
-!!! check "Authorize-Button!"
- Sie haben bereits einen glänzenden, neuen „Authorize“-Button.
+/// check | "Authorize-Button!"
- Und Ihre *Pfadoperation* hat in der oberen rechten Ecke ein kleines Schloss, auf das Sie klicken können.
+Sie haben bereits einen glänzenden, neuen „Authorize“-Button.
+
+Und Ihre *Pfadoperation* hat in der oberen rechten Ecke ein kleines Schloss, auf das Sie klicken können.
+
+///
Und wenn Sie darauf klicken, erhalten Sie ein kleines Anmeldeformular zur Eingabe eines `username` und `password` (und anderer optionaler Felder):
-!!! note "Hinweis"
- Es spielt keine Rolle, was Sie in das Formular eingeben, es wird noch nicht funktionieren. Wir kommen dahin.
+/// note | "Hinweis"
+
+Es spielt keine Rolle, was Sie in das Formular eingeben, es wird noch nicht funktionieren. Wir kommen dahin.
+
+///
Dies ist natürlich nicht das Frontend für die Endbenutzer, aber es ist ein großartiges automatisches Tool, um Ihre gesamte API interaktiv zu dokumentieren.
@@ -122,53 +140,71 @@ Betrachten wir es also aus dieser vereinfachten Sicht:
In diesem Beispiel verwenden wir **OAuth2** mit dem **Password**-Flow und einem **Bearer**-Token. Wir machen das mit der Klasse `OAuth2PasswordBearer`.
-!!! info
- Ein „Bearer“-Token ist nicht die einzige Option.
+/// info
- Aber es ist die beste für unseren Anwendungsfall.
+Ein „Bearer“-Token ist nicht die einzige Option.
- Und es ist wahrscheinlich auch für die meisten anderen Anwendungsfälle die beste, es sei denn, Sie sind ein OAuth2-Experte und wissen genau, warum es eine andere Option gibt, die Ihren Anforderungen besser entspricht.
+Aber es ist die beste für unseren Anwendungsfall.
- In dem Fall gibt Ihnen **FastAPI** ebenfalls die Tools, die Sie zum Erstellen brauchen.
+Und es ist wahrscheinlich auch für die meisten anderen Anwendungsfälle die beste, es sei denn, Sie sind ein OAuth2-Experte und wissen genau, warum es eine andere Option gibt, die Ihren Anforderungen besser entspricht.
+
+In dem Fall gibt Ihnen **FastAPI** ebenfalls die Tools, die Sie zum Erstellen brauchen.
+
+///
Wenn wir eine Instanz der Klasse `OAuth2PasswordBearer` erstellen, übergeben wir den Parameter `tokenUrl`. Dieser Parameter enthält die URL, die der Client (das Frontend, das im Browser des Benutzers ausgeführt wird) verwendet, wenn er den `username` und das `password` sendet, um einen Token zu erhalten.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="8"
- {!> ../../../docs_src/security/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="8"
+{!> ../../docs_src/security/tutorial001_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/security/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ nicht annotiert"
+```Python hl_lines="7"
+{!> ../../docs_src/security/tutorial001_an.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="6"
- {!> ../../../docs_src/security/tutorial001.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
-!!! tip "Tipp"
- Hier bezieht sich `tokenUrl="token"` auf eine relative URL `token`, die wir noch nicht erstellt haben. Da es sich um eine relative URL handelt, entspricht sie `./token`.
+/// tip | "Tipp"
- Da wir eine relative URL verwenden, würde sich das, wenn sich Ihre API unter `https://example.com/` befindet, auf `https://example.com/token` beziehen. Wenn sich Ihre API jedoch unter `https://example.com/api/v1/` befände, würde es sich auf `https://example.com/api/v1/token` beziehen.
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- Die Verwendung einer relativen URL ist wichtig, um sicherzustellen, dass Ihre Anwendung auch in einem fortgeschrittenen Anwendungsfall, wie [hinter einem Proxy](../../advanced/behind-a-proxy.md){.internal-link target=_blank}, weiterhin funktioniert.
+///
+
+```Python hl_lines="6"
+{!> ../../docs_src/security/tutorial001.py!}
+```
+
+////
+
+/// tip | "Tipp"
+
+Hier bezieht sich `tokenUrl="token"` auf eine relative URL `token`, die wir noch nicht erstellt haben. Da es sich um eine relative URL handelt, entspricht sie `./token`.
+
+Da wir eine relative URL verwenden, würde sich das, wenn sich Ihre API unter `https://example.com/` befindet, auf `https://example.com/token` beziehen. Wenn sich Ihre API jedoch unter `https://example.com/api/v1/` befände, würde es sich auf `https://example.com/api/v1/token` beziehen.
+
+Die Verwendung einer relativen URL ist wichtig, um sicherzustellen, dass Ihre Anwendung auch in einem fortgeschrittenen Anwendungsfall, wie [hinter einem Proxy](../../advanced/behind-a-proxy.md){.internal-link target=_blank}, weiterhin funktioniert.
+
+///
Dieser Parameter erstellt nicht diesen Endpunkt / diese *Pfadoperation*, sondern deklariert, dass die URL `/token` diejenige sein wird, die der Client verwenden soll, um den Token abzurufen. Diese Information wird in OpenAPI und dann in den interaktiven API-Dokumentationssystemen verwendet.
Wir werden demnächst auch die eigentliche Pfadoperation erstellen.
-!!! info
- Wenn Sie ein sehr strenger „Pythonista“ sind, missfällt Ihnen möglicherweise die Schreibweise des Parameternamens `tokenUrl` anstelle von `token_url`.
+/// info
- Das liegt daran, dass FastAPI denselben Namen wie in der OpenAPI-Spezifikation verwendet. Sodass Sie, wenn Sie mehr über eines dieser Sicherheitsschemas herausfinden möchten, den Namen einfach kopieren und einfügen können, um weitere Informationen darüber zu erhalten.
+Wenn Sie ein sehr strenger „Pythonista“ sind, missfällt Ihnen möglicherweise die Schreibweise des Parameternamens `tokenUrl` anstelle von `token_url`.
+
+Das liegt daran, dass FastAPI denselben Namen wie in der OpenAPI-Spezifikation verwendet. Sodass Sie, wenn Sie mehr über eines dieser Sicherheitsschemas herausfinden möchten, den Namen einfach kopieren und einfügen können, um weitere Informationen darüber zu erhalten.
+
+///
Die Variable `oauth2_scheme` ist eine Instanz von `OAuth2PasswordBearer`, aber auch ein „Callable“.
@@ -184,35 +220,47 @@ Es kann also mit `Depends` verwendet werden.
Jetzt können Sie dieses `oauth2_scheme` als Abhängigkeit `Depends` übergeben.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="12"
- {!> ../../../docs_src/security/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="12"
+{!> ../../docs_src/security/tutorial001_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="11"
- {!> ../../../docs_src/security/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ nicht annotiert"
+```Python hl_lines="11"
+{!> ../../docs_src/security/tutorial001_an.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/security/tutorial001.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="10"
+{!> ../../docs_src/security/tutorial001.py!}
+```
+
+////
Diese Abhängigkeit stellt einen `str` bereit, der dem Parameter `token` der *Pfadoperation-Funktion* zugewiesen wird.
**FastAPI** weiß, dass es diese Abhängigkeit verwenden kann, um ein „Sicherheitsschema“ im OpenAPI-Schema (und der automatischen API-Dokumentation) zu definieren.
-!!! info "Technische Details"
- **FastAPI** weiß, dass es die Klasse `OAuth2PasswordBearer` (deklariert in einer Abhängigkeit) verwenden kann, um das Sicherheitsschema in OpenAPI zu definieren, da es von `fastapi.security.oauth2.OAuth2` erbt, das wiederum von `fastapi.security.base.SecurityBase` erbt.
+/// info | "Technische Details"
- Alle Sicherheits-Werkzeuge, die in OpenAPI integriert sind (und die automatische API-Dokumentation), erben von `SecurityBase`, so weiß **FastAPI**, wie es sie in OpenAPI integrieren muss.
+**FastAPI** weiß, dass es die Klasse `OAuth2PasswordBearer` (deklariert in einer Abhängigkeit) verwenden kann, um das Sicherheitsschema in OpenAPI zu definieren, da es von `fastapi.security.oauth2.OAuth2` erbt, das wiederum von `fastapi.security.base.SecurityBase` erbt.
+
+Alle Sicherheits-Werkzeuge, die in OpenAPI integriert sind (und die automatische API-Dokumentation), erben von `SecurityBase`, so weiß **FastAPI**, wie es sie in OpenAPI integrieren muss.
+
+///
## Was es macht
diff --git a/docs/de/docs/tutorial/security/get-current-user.md b/docs/de/docs/tutorial/security/get-current-user.md
index 09b55a20e..a9478a36e 100644
--- a/docs/de/docs/tutorial/security/get-current-user.md
+++ b/docs/de/docs/tutorial/security/get-current-user.md
@@ -2,26 +2,35 @@
Im vorherigen Kapitel hat das Sicherheitssystem (das auf dem Dependency Injection System basiert) der *Pfadoperation-Funktion* einen `token` vom Typ `str` überreicht:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="12"
- {!> ../../../docs_src/security/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="12"
+{!> ../../docs_src/security/tutorial001_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="11"
- {!> ../../../docs_src/security/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ nicht annotiert"
+```Python hl_lines="11"
+{!> ../../docs_src/security/tutorial001_an.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/security/tutorial001.py!}
- ```
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="10"
+{!> ../../docs_src/security/tutorial001.py!}
+```
+
+////
Aber das ist immer noch nicht so nützlich.
@@ -33,41 +42,57 @@ Erstellen wir zunächst ein Pydantic-Benutzermodell.
So wie wir Pydantic zum Deklarieren von Bodys verwenden, können wir es auch überall sonst verwenden:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="5 12-16"
- {!> ../../../docs_src/security/tutorial002_an_py310.py!}
- ```
+```Python hl_lines="5 12-16"
+{!> ../../docs_src/security/tutorial002_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="5 12-16"
- {!> ../../../docs_src/security/tutorial002_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="5 12-16"
+{!> ../../docs_src/security/tutorial002_an_py39.py!}
+```
- ```Python hl_lines="5 13-17"
- {!> ../../../docs_src/security/tutorial002_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="5 13-17"
+{!> ../../docs_src/security/tutorial002_an.py!}
+```
- ```Python hl_lines="3 10-14"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="5 12-16"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="3 10-14"
+{!> ../../docs_src/security/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="5 12-16"
+{!> ../../docs_src/security/tutorial002.py!}
+```
+
+////
## Eine `get_current_user`-Abhängigkeit erstellen
@@ -79,135 +104,189 @@ Erinnern Sie sich, dass Abhängigkeiten Unterabhängigkeiten haben können?
So wie wir es zuvor in der *Pfadoperation* direkt gemacht haben, erhält unsere neue Abhängigkeit `get_current_user` von der Unterabhängigkeit `oauth2_scheme` einen `token` vom Typ `str`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="25"
- {!> ../../../docs_src/security/tutorial002_an_py310.py!}
- ```
+```Python hl_lines="25"
+{!> ../../docs_src/security/tutorial002_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="25"
- {!> ../../../docs_src/security/tutorial002_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="25"
+{!> ../../docs_src/security/tutorial002_an_py39.py!}
+```
- ```Python hl_lines="26"
- {!> ../../../docs_src/security/tutorial002_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="26"
+{!> ../../docs_src/security/tutorial002_an.py!}
+```
- ```Python hl_lines="23"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="25"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="23"
+{!> ../../docs_src/security/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="25"
+{!> ../../docs_src/security/tutorial002.py!}
+```
+
+////
## Den Benutzer holen
`get_current_user` wird eine von uns erstellte (gefakte) Hilfsfunktion verwenden, welche einen Token vom Typ `str` entgegennimmt und unser Pydantic-`User`-Modell zurückgibt:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="19-22 26-27"
- {!> ../../../docs_src/security/tutorial002_an_py310.py!}
- ```
+```Python hl_lines="19-22 26-27"
+{!> ../../docs_src/security/tutorial002_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="19-22 26-27"
- {!> ../../../docs_src/security/tutorial002_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="19-22 26-27"
+{!> ../../docs_src/security/tutorial002_an_py39.py!}
+```
- ```Python hl_lines="20-23 27-28"
- {!> ../../../docs_src/security/tutorial002_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="20-23 27-28"
+{!> ../../docs_src/security/tutorial002_an.py!}
+```
- ```Python hl_lines="17-20 24-25"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="19-22 26-27"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="17-20 24-25"
+{!> ../../docs_src/security/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="19-22 26-27"
+{!> ../../docs_src/security/tutorial002.py!}
+```
+
+////
## Den aktuellen Benutzer einfügen
Und jetzt können wir wiederum `Depends` mit unserem `get_current_user` in der *Pfadoperation* verwenden:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="31"
- {!> ../../../docs_src/security/tutorial002_an_py310.py!}
- ```
+```Python hl_lines="31"
+{!> ../../docs_src/security/tutorial002_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="31"
- {!> ../../../docs_src/security/tutorial002_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="31"
+{!> ../../docs_src/security/tutorial002_an_py39.py!}
+```
- ```Python hl_lines="32"
- {!> ../../../docs_src/security/tutorial002_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="32"
+{!> ../../docs_src/security/tutorial002_an.py!}
+```
- ```Python hl_lines="29"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="31"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="29"
+{!> ../../docs_src/security/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="31"
+{!> ../../docs_src/security/tutorial002.py!}
+```
+
+////
Beachten Sie, dass wir als Typ von `current_user` das Pydantic-Modell `User` deklarieren.
Das wird uns innerhalb der Funktion bei Codevervollständigung und Typprüfungen helfen.
-!!! tip "Tipp"
- Sie erinnern sich vielleicht, dass Requestbodys ebenfalls mit Pydantic-Modellen deklariert werden.
+/// tip | "Tipp"
- Weil Sie `Depends` verwenden, wird **FastAPI** hier aber nicht verwirrt.
+Sie erinnern sich vielleicht, dass Requestbodys ebenfalls mit Pydantic-Modellen deklariert werden.
-!!! check
- Die Art und Weise, wie dieses System von Abhängigkeiten konzipiert ist, ermöglicht es uns, verschiedene Abhängigkeiten (verschiedene „Dependables“) zu haben, die alle ein `User`-Modell zurückgeben.
+Weil Sie `Depends` verwenden, wird **FastAPI** hier aber nicht verwirrt.
- Wir sind nicht darauf beschränkt, nur eine Abhängigkeit zu haben, die diesen Typ von Daten zurückgeben kann.
+///
+
+/// check
+
+Die Art und Weise, wie dieses System von Abhängigkeiten konzipiert ist, ermöglicht es uns, verschiedene Abhängigkeiten (verschiedene „Dependables“) zu haben, die alle ein `User`-Modell zurückgeben.
+
+Wir sind nicht darauf beschränkt, nur eine Abhängigkeit zu haben, die diesen Typ von Daten zurückgeben kann.
+
+///
## Andere Modelle
@@ -241,41 +320,57 @@ Und alle (oder beliebige Teile davon) können Vorteil ziehen aus der Wiederverwe
Und alle diese Tausenden von *Pfadoperationen* können nur drei Zeilen lang sein:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="30-32"
- {!> ../../../docs_src/security/tutorial002_an_py310.py!}
- ```
+```Python hl_lines="30-32"
+{!> ../../docs_src/security/tutorial002_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="30-32"
- {!> ../../../docs_src/security/tutorial002_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="30-32"
+{!> ../../docs_src/security/tutorial002_an_py39.py!}
+```
- ```Python hl_lines="31-33"
- {!> ../../../docs_src/security/tutorial002_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="31-33"
+{!> ../../docs_src/security/tutorial002_an.py!}
+```
- ```Python hl_lines="28-30"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="30-32"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="28-30"
+{!> ../../docs_src/security/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="30-32"
+{!> ../../docs_src/security/tutorial002.py!}
+```
+
+////
## Zusammenfassung
diff --git a/docs/de/docs/tutorial/security/index.md b/docs/de/docs/tutorial/security/index.md
index 7a11e704d..ad0927361 100644
--- a/docs/de/docs/tutorial/security/index.md
+++ b/docs/de/docs/tutorial/security/index.md
@@ -32,9 +32,11 @@ Heutzutage ist es nicht sehr populär und wird kaum verwendet.
OAuth2 spezifiziert nicht, wie die Kommunikation verschlüsselt werden soll, sondern erwartet, dass Ihre Anwendung mit HTTPS bereitgestellt wird.
-!!! tip "Tipp"
- Im Abschnitt über **Deployment** erfahren Sie, wie Sie HTTPS mithilfe von Traefik und Let's Encrypt kostenlos einrichten.
+/// tip | "Tipp"
+Im Abschnitt über **Deployment** erfahren Sie, wie Sie HTTPS mithilfe von Traefik und Let's Encrypt kostenlos einrichten.
+
+///
## OpenID Connect
@@ -87,10 +89,13 @@ OpenAPI definiert die folgenden Sicherheitsschemas:
* Diese automatische Erkennung ist es, die in der OpenID Connect Spezifikation definiert ist.
-!!! tip "Tipp"
- Auch die Integration anderer Authentifizierungs-/Autorisierungsanbieter wie Google, Facebook, Twitter, GitHub, usw. ist möglich und relativ einfach.
+/// tip | "Tipp"
- Das komplexeste Problem besteht darin, einen Authentifizierungs-/Autorisierungsanbieter wie solche aufzubauen, aber **FastAPI** reicht Ihnen die Tools, das einfach zu erledigen, während Ihnen die schwere Arbeit abgenommen wird.
+Auch die Integration anderer Authentifizierungs-/Autorisierungsanbieter wie Google, Facebook, Twitter, GitHub, usw. ist möglich und relativ einfach.
+
+Das komplexeste Problem besteht darin, einen Authentifizierungs-/Autorisierungsanbieter wie solche aufzubauen, aber **FastAPI** reicht Ihnen die Tools, das einfach zu erledigen, während Ihnen die schwere Arbeit abgenommen wird.
+
+///
## **FastAPI** Tools
diff --git a/docs/de/docs/tutorial/security/oauth2-jwt.md b/docs/de/docs/tutorial/security/oauth2-jwt.md
index 9f43cccc9..79e817840 100644
--- a/docs/de/docs/tutorial/security/oauth2-jwt.md
+++ b/docs/de/docs/tutorial/security/oauth2-jwt.md
@@ -44,10 +44,13 @@ $ pip install "python-jose[cryptography]"
Hier verwenden wir das empfohlene: pyca/cryptography.
-!!! tip "Tipp"
- Dieses Tutorial verwendete zuvor PyJWT.
+/// tip | "Tipp"
- Es wurde jedoch aktualisiert, stattdessen python-jose zu verwenden, da dieses alle Funktionen von PyJWT sowie einige Extras bietet, die Sie später möglicherweise benötigen, wenn Sie Integrationen mit anderen Tools erstellen.
+Dieses Tutorial verwendete zuvor PyJWT.
+
+Es wurde jedoch aktualisiert, stattdessen python-jose zu verwenden, da dieses alle Funktionen von PyJWT sowie einige Extras bietet, die Sie später möglicherweise benötigen, wenn Sie Integrationen mit anderen Tools erstellen.
+
+///
## Passwort-Hashing
@@ -83,12 +86,15 @@ $ pip install "passlib[bcrypt]"
-!!! tip "Tipp"
- Mit `passlib` können Sie sogar konfigurieren, Passwörter zu lesen, die von **Django**, einem **Flask**-Sicherheit-Plugin, oder vielen anderen erstellt wurden.
+/// tip | "Tipp"
- So könnten Sie beispielsweise die gleichen Daten aus einer Django-Anwendung in einer Datenbank mit einer FastAPI-Anwendung teilen. Oder schrittweise eine Django-Anwendung migrieren, während Sie dieselbe Datenbank verwenden.
+Mit `passlib` können Sie sogar konfigurieren, Passwörter zu lesen, die von **Django**, einem **Flask**-Sicherheit-Plugin, oder vielen anderen erstellt wurden.
- Und Ihre Benutzer könnten sich gleichzeitig über Ihre Django-Anwendung oder Ihre **FastAPI**-Anwendung anmelden.
+So könnten Sie beispielsweise die gleichen Daten aus einer Django-Anwendung in einer Datenbank mit einer FastAPI-Anwendung teilen. Oder schrittweise eine Django-Anwendung migrieren, während Sie dieselbe Datenbank verwenden.
+
+Und Ihre Benutzer könnten sich gleichzeitig über Ihre Django-Anwendung oder Ihre **FastAPI**-Anwendung anmelden.
+
+///
## Die Passwörter hashen und überprüfen
@@ -96,12 +102,15 @@ Importieren Sie die benötigten Tools aus `passlib`.
Erstellen Sie einen PassLib-„Kontext“. Der wird für das Hashen und Verifizieren von Passwörtern verwendet.
-!!! tip "Tipp"
- Der PassLib-Kontext kann auch andere Hashing-Algorithmen verwenden, einschließlich deprecateter Alter, um etwa nur eine Verifizierung usw. zu ermöglichen.
+/// tip | "Tipp"
- Sie könnten ihn beispielsweise verwenden, um von einem anderen System (wie Django) generierte Passwörter zu lesen und zu verifizieren, aber alle neuen Passwörter mit einem anderen Algorithmus wie Bcrypt zu hashen.
+Der PassLib-Kontext kann auch andere Hashing-Algorithmen verwenden, einschließlich deprecateter Alter, um etwa nur eine Verifizierung usw. zu ermöglichen.
- Und mit allen gleichzeitig kompatibel sein.
+Sie könnten ihn beispielsweise verwenden, um von einem anderen System (wie Django) generierte Passwörter zu lesen und zu verifizieren, aber alle neuen Passwörter mit einem anderen Algorithmus wie Bcrypt zu hashen.
+
+Und mit allen gleichzeitig kompatibel sein.
+
+///
Erstellen Sie eine Hilfsfunktion, um ein vom Benutzer stammendes Passwort zu hashen.
@@ -109,44 +118,63 @@ Und eine weitere, um zu überprüfen, ob ein empfangenes Passwort mit dem gespei
Und noch eine, um einen Benutzer zu authentifizieren und zurückzugeben.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7 48 55-56 59-60 69-75"
- {!> ../../../docs_src/security/tutorial004_an_py310.py!}
- ```
+```Python hl_lines="7 48 55-56 59-60 69-75"
+{!> ../../docs_src/security/tutorial004_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="7 48 55-56 59-60 69-75"
- {!> ../../../docs_src/security/tutorial004_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="7 48 55-56 59-60 69-75"
+{!> ../../docs_src/security/tutorial004_an_py39.py!}
+```
- ```Python hl_lines="7 49 56-57 60-61 70-76"
- {!> ../../../docs_src/security/tutorial004_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="7 49 56-57 60-61 70-76"
+{!> ../../docs_src/security/tutorial004_an.py!}
+```
- ```Python hl_lines="6 47 54-55 58-59 68-74"
- {!> ../../../docs_src/security/tutorial004_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="7 48 55-56 59-60 69-75"
- {!> ../../../docs_src/security/tutorial004.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-!!! note "Hinweis"
- Wenn Sie sich die neue (gefakte) Datenbank `fake_users_db` anschauen, sehen Sie, wie das gehashte Passwort jetzt aussieht: `"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`.
+///
+
+```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"
+
+Wenn Sie sich die neue (gefakte) Datenbank `fake_users_db` anschauen, sehen Sie, wie das gehashte Passwort jetzt aussieht: `"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`.
+
+///
## JWT-Token verarbeiten
@@ -176,41 +204,57 @@ Definieren Sie ein Pydantic-Modell, das im Token-Endpunkt für die Response verw
Erstellen Sie eine Hilfsfunktion, um einen neuen Zugriffstoken zu generieren.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="6 12-14 28-30 78-86"
- {!> ../../../docs_src/security/tutorial004_an_py310.py!}
- ```
+```Python hl_lines="6 12-14 28-30 78-86"
+{!> ../../docs_src/security/tutorial004_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="6 12-14 28-30 78-86"
- {!> ../../../docs_src/security/tutorial004_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="6 12-14 28-30 78-86"
+{!> ../../docs_src/security/tutorial004_an_py39.py!}
+```
- ```Python hl_lines="6 13-15 29-31 79-87"
- {!> ../../../docs_src/security/tutorial004_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="6 13-15 29-31 79-87"
+{!> ../../docs_src/security/tutorial004_an.py!}
+```
- ```Python hl_lines="5 11-13 27-29 77-85"
- {!> ../../../docs_src/security/tutorial004_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="6 12-14 28-30 78-86"
- {!> ../../../docs_src/security/tutorial004.py!}
- ```
+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!}
+```
+
+////
## Die Abhängigkeiten aktualisieren
@@ -220,41 +264,57 @@ Dekodieren Sie den empfangenen Token, validieren Sie ihn und geben Sie den aktue
Wenn der Token ungültig ist, geben Sie sofort einen HTTP-Fehler zurück.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="89-106"
- {!> ../../../docs_src/security/tutorial004_an_py310.py!}
- ```
+```Python hl_lines="89-106"
+{!> ../../docs_src/security/tutorial004_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="89-106"
- {!> ../../../docs_src/security/tutorial004_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="89-106"
+{!> ../../docs_src/security/tutorial004_an_py39.py!}
+```
- ```Python hl_lines="90-107"
- {!> ../../../docs_src/security/tutorial004_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="90-107"
+{!> ../../docs_src/security/tutorial004_an.py!}
+```
- ```Python hl_lines="88-105"
- {!> ../../../docs_src/security/tutorial004_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="89-106"
- {!> ../../../docs_src/security/tutorial004.py!}
- ```
+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!}
+```
+
+////
## Die *Pfadoperation* `/token` aktualisieren
@@ -262,41 +322,57 @@ Erstellen Sie ein `timedelta` mit der Ablaufz
Erstellen Sie einen echten JWT-Zugriffstoken und geben Sie ihn zurück.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="117-132"
- {!> ../../../docs_src/security/tutorial004_an_py310.py!}
- ```
+```Python hl_lines="117-132"
+{!> ../../docs_src/security/tutorial004_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="117-132"
- {!> ../../../docs_src/security/tutorial004_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="117-132"
+{!> ../../docs_src/security/tutorial004_an_py39.py!}
+```
- ```Python hl_lines="118-133"
- {!> ../../../docs_src/security/tutorial004_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="118-133"
+{!> ../../docs_src/security/tutorial004_an.py!}
+```
- ```Python hl_lines="114-129"
- {!> ../../../docs_src/security/tutorial004_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="115-130"
- {!> ../../../docs_src/security/tutorial004.py!}
- ```
+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!}
+```
+
+////
### Technische Details zum JWT-„Subjekt“ `sub`
@@ -335,8 +411,11 @@ Verwenden Sie die Anmeldeinformationen:
Benutzername: `johndoe`
Passwort: `secret`.
-!!! check
- Beachten Sie, dass im Code nirgendwo das Klartext-Passwort "`secret`" steht, wir haben nur die gehashte Version.
+/// check
+
+Beachten Sie, dass im Code nirgendwo das Klartext-Passwort "`secret`" steht, wir haben nur die gehashte Version.
+
+///
@@ -357,8 +436,11 @@ Wenn Sie die Developer Tools öffnen, können Sie sehen, dass die gesendeten Dat
-!!! note "Hinweis"
- Beachten Sie den Header `Authorization` mit einem Wert, der mit `Bearer` beginnt.
+/// note | "Hinweis"
+
+Beachten Sie den Header `Authorization` mit einem Wert, der mit `Bearer` beginnt.
+
+///
## Fortgeschrittene Verwendung mit `scopes`
diff --git a/docs/de/docs/tutorial/security/simple-oauth2.md b/docs/de/docs/tutorial/security/simple-oauth2.md
index ed280d486..4c20fae55 100644
--- a/docs/de/docs/tutorial/security/simple-oauth2.md
+++ b/docs/de/docs/tutorial/security/simple-oauth2.md
@@ -32,14 +32,17 @@ Diese werden normalerweise verwendet, um bestimmte Sicherheitsberechtigungen zu
* `instagram_basic` wird von Facebook / Instagram verwendet.
* `https://www.googleapis.com/auth/drive` wird von Google verwendet.
-!!! info
- In OAuth2 ist ein „Scope“ nur ein String, der eine bestimmte erforderliche Berechtigung deklariert.
+/// info
- Es spielt keine Rolle, ob er andere Zeichen wie `:` enthält oder ob es eine URL ist.
+In OAuth2 ist ein „Scope“ nur ein String, der eine bestimmte erforderliche Berechtigung deklariert.
- Diese Details sind implementierungsspezifisch.
+Es spielt keine Rolle, ob er andere Zeichen wie `:` enthält oder ob es eine URL ist.
- Für OAuth2 sind es einfach nur Strings.
+Diese Details sind implementierungsspezifisch.
+
+Für OAuth2 sind es einfach nur Strings.
+
+///
## Code, um `username` und `password` entgegenzunehmen.
@@ -49,41 +52,57 @@ Lassen Sie uns nun die von **FastAPI** bereitgestellten Werkzeuge verwenden, um
Importieren Sie zunächst `OAuth2PasswordRequestForm` und verwenden Sie es als Abhängigkeit mit `Depends` in der *Pfadoperation* für `/token`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="4 78"
- {!> ../../../docs_src/security/tutorial003_an_py310.py!}
- ```
+```Python hl_lines="4 78"
+{!> ../../docs_src/security/tutorial003_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="4 78"
- {!> ../../../docs_src/security/tutorial003_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="4 78"
+{!> ../../docs_src/security/tutorial003_an_py39.py!}
+```
- ```Python hl_lines="4 79"
- {!> ../../../docs_src/security/tutorial003_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="4 79"
+{!> ../../docs_src/security/tutorial003_an.py!}
+```
- ```Python hl_lines="2 74"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="4 76"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="2 74"
+{!> ../../docs_src/security/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="4 76"
+{!> ../../docs_src/security/tutorial003.py!}
+```
+
+////
`OAuth2PasswordRequestForm` ist eine Klassenabhängigkeit, die einen Formularbody deklariert mit:
@@ -92,29 +111,38 @@ Importieren Sie zunächst `OAuth2PasswordRequestForm` und verwenden Sie es als A
* Einem optionalen `scope`-Feld als langem String, bestehend aus durch Leerzeichen getrennten Strings.
* Einem optionalen `grant_type` („Art der Anmeldung“).
-!!! tip "Tipp"
- Die OAuth2-Spezifikation *erfordert* tatsächlich ein Feld `grant_type` mit dem festen Wert `password`, aber `OAuth2PasswordRequestForm` erzwingt dies nicht.
+/// tip | "Tipp"
- Wenn Sie es erzwingen müssen, verwenden Sie `OAuth2PasswordRequestFormStrict` anstelle von `OAuth2PasswordRequestForm`.
+Die OAuth2-Spezifikation *erfordert* tatsächlich ein Feld `grant_type` mit dem festen Wert `password`, aber `OAuth2PasswordRequestForm` erzwingt dies nicht.
+
+Wenn Sie es erzwingen müssen, verwenden Sie `OAuth2PasswordRequestFormStrict` anstelle von `OAuth2PasswordRequestForm`.
+
+///
* Eine optionale `client_id` (benötigen wir für unser Beispiel nicht).
* Ein optionales `client_secret` (benötigen wir für unser Beispiel nicht).
-!!! info
- `OAuth2PasswordRequestForm` ist keine spezielle Klasse für **FastAPI**, so wie `OAuth2PasswordBearer`.
+/// info
- `OAuth2PasswordBearer` lässt **FastAPI** wissen, dass es sich um ein Sicherheitsschema handelt. Daher wird es auf diese Weise zu OpenAPI hinzugefügt.
+`OAuth2PasswordRequestForm` ist keine spezielle Klasse für **FastAPI**, so wie `OAuth2PasswordBearer`.
- Aber `OAuth2PasswordRequestForm` ist nur eine Klassenabhängigkeit, die Sie selbst hätten schreiben können, oder Sie hätten `Form`ular-Parameter direkt deklarieren können.
+`OAuth2PasswordBearer` lässt **FastAPI** wissen, dass es sich um ein Sicherheitsschema handelt. Daher wird es auf diese Weise zu OpenAPI hinzugefügt.
- Da es sich jedoch um einen häufigen Anwendungsfall handelt, wird er zur Vereinfachung direkt von **FastAPI** bereitgestellt.
+Aber `OAuth2PasswordRequestForm` ist nur eine Klassenabhängigkeit, die Sie selbst hätten schreiben können, oder Sie hätten `Form`ular-Parameter direkt deklarieren können.
+
+Da es sich jedoch um einen häufigen Anwendungsfall handelt, wird er zur Vereinfachung direkt von **FastAPI** bereitgestellt.
+
+///
### Die Formulardaten verwenden
-!!! tip "Tipp"
- Die Instanz der Klassenabhängigkeit `OAuth2PasswordRequestForm` verfügt, statt eines Attributs `scope` mit dem durch Leerzeichen getrennten langen String, über das Attribut `scopes` mit einer tatsächlichen Liste von Strings, einem für jeden gesendeten Scope.
+/// tip | "Tipp"
- In diesem Beispiel verwenden wir keine `scopes`, aber die Funktionalität ist vorhanden, wenn Sie sie benötigen.
+Die Instanz der Klassenabhängigkeit `OAuth2PasswordRequestForm` verfügt, statt eines Attributs `scope` mit dem durch Leerzeichen getrennten langen String, über das Attribut `scopes` mit einer tatsächlichen Liste von Strings, einem für jeden gesendeten Scope.
+
+In diesem Beispiel verwenden wir keine `scopes`, aber die Funktionalität ist vorhanden, wenn Sie sie benötigen.
+
+///
Rufen Sie nun die Benutzerdaten aus der (gefakten) Datenbank ab, für diesen `username` aus dem Formularfeld.
@@ -122,41 +150,57 @@ Wenn es keinen solchen Benutzer gibt, geben wir die Fehlermeldung „Incorrect u
Für den Fehler verwenden wir die Exception `HTTPException`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="3 79-81"
- {!> ../../../docs_src/security/tutorial003_an_py310.py!}
- ```
+```Python hl_lines="3 79-81"
+{!> ../../docs_src/security/tutorial003_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="3 79-81"
- {!> ../../../docs_src/security/tutorial003_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="3 79-81"
+{!> ../../docs_src/security/tutorial003_an_py39.py!}
+```
- ```Python hl_lines="3 80-82"
- {!> ../../../docs_src/security/tutorial003_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="3 80-82"
+{!> ../../docs_src/security/tutorial003_an.py!}
+```
- ```Python hl_lines="1 75-77"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="3 77-79"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="1 75-77"
+{!> ../../docs_src/security/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="3 77-79"
+{!> ../../docs_src/security/tutorial003.py!}
+```
+
+////
### Das Passwort überprüfen
@@ -182,41 +226,57 @@ Wenn Ihre Datenbank gestohlen wird, hat der Dieb nicht die Klartext-Passwörter
Der Dieb kann also nicht versuchen, die gleichen Passwörter in einem anderen System zu verwenden (da viele Benutzer überall das gleiche Passwort verwenden, wäre dies gefährlich).
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="82-85"
- {!> ../../../docs_src/security/tutorial003_an_py310.py!}
- ```
+```Python hl_lines="82-85"
+{!> ../../docs_src/security/tutorial003_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="82-85"
- {!> ../../../docs_src/security/tutorial003_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="82-85"
+{!> ../../docs_src/security/tutorial003_an_py39.py!}
+```
- ```Python hl_lines="83-86"
- {!> ../../../docs_src/security/tutorial003_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="83-86"
+{!> ../../docs_src/security/tutorial003_an.py!}
+```
- ```Python hl_lines="78-81"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="80-83"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="78-81"
+{!> ../../docs_src/security/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="80-83"
+{!> ../../docs_src/security/tutorial003.py!}
+```
+
+////
#### Über `**user_dict`
@@ -234,8 +294,11 @@ UserInDB(
)
```
-!!! info
- Eine ausführlichere Erklärung von `**user_dict` finden Sie in [der Dokumentation für **Extra Modelle**](../extra-models.md#uber-user_indict){.internal-link target=_blank}.
+/// info
+
+Eine ausführlichere Erklärung von `**user_dict` finden Sie in [der Dokumentation für **Extra Modelle**](../extra-models.md#uber-user_indict){.internal-link target=_blank}.
+
+///
## Den Token zurückgeben
@@ -247,55 +310,77 @@ Und es sollte einen `access_token` haben, mit einem String, der unseren Zugriffs
In diesem einfachen Beispiel gehen wir einfach völlig unsicher vor und geben denselben `username` wie der Token zurück.
-!!! tip "Tipp"
- Im nächsten Kapitel sehen Sie eine wirklich sichere Implementierung mit Passwort-Hashing und JWT-Tokens.
+/// tip | "Tipp"
- Aber konzentrieren wir uns zunächst auf die spezifischen Details, die wir benötigen.
+Im nächsten Kapitel sehen Sie eine wirklich sichere Implementierung mit Passwort-Hashing und JWT-Tokens.
-=== "Python 3.10+"
+Aber konzentrieren wir uns zunächst auf die spezifischen Details, die wir benötigen.
- ```Python hl_lines="87"
- {!> ../../../docs_src/security/tutorial003_an_py310.py!}
- ```
+///
-=== "Python 3.9+"
+//// tab | Python 3.10+
- ```Python hl_lines="87"
- {!> ../../../docs_src/security/tutorial003_an_py39.py!}
- ```
+```Python hl_lines="87"
+{!> ../../docs_src/security/tutorial003_an_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="88"
- {!> ../../../docs_src/security/tutorial003_an.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.10+ nicht annotiert"
+```Python hl_lines="87"
+{!> ../../docs_src/security/tutorial003_an_py39.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="83"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ nicht annotiert"
+```Python hl_lines="88"
+{!> ../../docs_src/security/tutorial003_an.py!}
+```
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+////
- ```Python hl_lines="85"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+//// tab | Python 3.10+ nicht annotiert
-!!! tip "Tipp"
- Gemäß der Spezifikation sollten Sie ein JSON mit einem `access_token` und einem `token_type` zurückgeben, genau wie in diesem Beispiel.
+/// tip | "Tipp"
- Das müssen Sie selbst in Ihrem Code tun und sicherstellen, dass Sie diese JSON-Schlüssel verwenden.
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- Es ist fast das Einzige, woran Sie denken müssen, es selbst richtigzumachen und die Spezifikationen einzuhalten.
+///
- Den Rest erledigt **FastAPI** für Sie.
+```Python hl_lines="83"
+{!> ../../docs_src/security/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="85"
+{!> ../../docs_src/security/tutorial003.py!}
+```
+
+////
+
+/// tip | "Tipp"
+
+Gemäß der Spezifikation sollten Sie ein JSON mit einem `access_token` und einem `token_type` zurückgeben, genau wie in diesem Beispiel.
+
+Das müssen Sie selbst in Ihrem Code tun und sicherstellen, dass Sie diese JSON-Schlüssel verwenden.
+
+Es ist fast das Einzige, woran Sie denken müssen, es selbst richtigzumachen und die Spezifikationen einzuhalten.
+
+Den Rest erledigt **FastAPI** für Sie.
+
+///
## Die Abhängigkeiten aktualisieren
@@ -309,56 +394,75 @@ Beide Abhängigkeiten geben nur dann einen HTTP-Error zurück, wenn der Benutzer
In unserem Endpunkt erhalten wir also nur dann einen Benutzer, wenn der Benutzer existiert, korrekt authentifiziert wurde und aktiv ist:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="58-66 69-74 94"
- {!> ../../../docs_src/security/tutorial003_an_py310.py!}
- ```
+```Python hl_lines="58-66 69-74 94"
+{!> ../../docs_src/security/tutorial003_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="58-66 69-74 94"
- {!> ../../../docs_src/security/tutorial003_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="58-66 69-74 94"
+{!> ../../docs_src/security/tutorial003_an_py39.py!}
+```
- ```Python hl_lines="59-67 70-75 95"
- {!> ../../../docs_src/security/tutorial003_an.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python hl_lines="59-67 70-75 95"
+{!> ../../docs_src/security/tutorial003_an.py!}
+```
- ```Python hl_lines="56-64 67-70 88"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python hl_lines="58-66 69-72 90"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
-!!! info
- Der zusätzliche Header `WWW-Authenticate` mit dem Wert `Bearer`, den wir hier zurückgeben, ist ebenfalls Teil der Spezifikation.
+///
- Jeder HTTP-(Fehler-)Statuscode 401 „UNAUTHORIZED“ soll auch einen `WWW-Authenticate`-Header zurückgeben.
+```Python hl_lines="56-64 67-70 88"
+{!> ../../docs_src/security/tutorial003_py310.py!}
+```
- Im Fall von Bearer-Tokens (in unserem Fall) sollte der Wert dieses Headers `Bearer` lauten.
+////
- Sie können diesen zusätzlichen Header tatsächlich weglassen und es würde trotzdem funktionieren.
+//// tab | Python 3.8+ nicht annotiert
- Aber er wird hier bereitgestellt, um den Spezifikationen zu entsprechen.
+/// tip | "Tipp"
- Außerdem gibt es möglicherweise Tools, die ihn erwarten und verwenden (jetzt oder in der Zukunft) und das könnte für Sie oder Ihre Benutzer jetzt oder in der Zukunft nützlich sein.
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
- Das ist der Vorteil von Standards ...
+///
+
+```Python hl_lines="58-66 69-72 90"
+{!> ../../docs_src/security/tutorial003.py!}
+```
+
+////
+
+/// info
+
+Der zusätzliche Header `WWW-Authenticate` mit dem Wert `Bearer`, den wir hier zurückgeben, ist ebenfalls Teil der Spezifikation.
+
+Jeder HTTP-(Fehler-)Statuscode 401 „UNAUTHORIZED“ soll auch einen `WWW-Authenticate`-Header zurückgeben.
+
+Im Fall von Bearer-Tokens (in unserem Fall) sollte der Wert dieses Headers `Bearer` lauten.
+
+Sie können diesen zusätzlichen Header tatsächlich weglassen und es würde trotzdem funktionieren.
+
+Aber er wird hier bereitgestellt, um den Spezifikationen zu entsprechen.
+
+Außerdem gibt es möglicherweise Tools, die ihn erwarten und verwenden (jetzt oder in der Zukunft) und das könnte für Sie oder Ihre Benutzer jetzt oder in der Zukunft nützlich sein.
+
+Das ist der Vorteil von Standards ...
+
+///
## Es in Aktion sehen
diff --git a/docs/de/docs/tutorial/static-files.md b/docs/de/docs/tutorial/static-files.md
index 1e289e120..4afd251aa 100644
--- a/docs/de/docs/tutorial/static-files.md
+++ b/docs/de/docs/tutorial/static-files.md
@@ -8,13 +8,16 @@ Mit `StaticFiles` können Sie statische Dateien aus einem Verzeichnis automatisc
* „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!}
```
-!!! note "Technische Details"
- Sie könnten auch `from starlette.staticfiles import StaticFiles` verwenden.
+/// note | "Technische Details"
- **FastAPI** stellt dasselbe `starlette.staticfiles` auch via `fastapi.staticfiles` bereit, als Annehmlichkeit für Sie, den Entwickler. Es kommt aber tatsächlich direkt von Starlette.
+Sie könnten auch `from starlette.staticfiles import StaticFiles` verwenden.
+
+**FastAPI** stellt dasselbe `starlette.staticfiles` auch via `fastapi.staticfiles` bereit, als Annehmlichkeit für Sie, den Entwickler. Es kommt aber tatsächlich direkt von Starlette.
+
+///
### Was ist „Mounten“?
diff --git a/docs/de/docs/tutorial/testing.md b/docs/de/docs/tutorial/testing.md
index 541cc1bf0..bda6d7d60 100644
--- a/docs/de/docs/tutorial/testing.md
+++ b/docs/de/docs/tutorial/testing.md
@@ -8,10 +8,13 @@ Damit können Sie `httpx`.
+/// info
- Z. B. `pip install httpx`.
+Um `TestClient` zu verwenden, installieren Sie zunächst `httpx`.
+
+Z. B. `pip install httpx`.
+
+///
Importieren Sie `TestClient`.
@@ -24,23 +27,32 @@ 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!}
```
-!!! tip "Tipp"
- Beachten Sie, dass die Testfunktionen normal `def` und nicht `async def` sind.
+/// tip | "Tipp"
- Und die Anrufe an den Client sind ebenfalls normale Anrufe, die nicht `await` verwenden.
+Beachten Sie, dass die Testfunktionen normal `def` und nicht `async def` sind.
- Dadurch können Sie `pytest` ohne Komplikationen direkt nutzen.
+Und die Anrufe an den Client sind ebenfalls normale Anrufe, die nicht `await` verwenden.
-!!! note "Technische Details"
- Sie könnten auch `from starlette.testclient import TestClient` verwenden.
+Dadurch können Sie `pytest` ohne Komplikationen direkt nutzen.
- **FastAPI** stellt denselben `starlette.testclient` auch via `fastapi.testclient` bereit, als Annehmlichkeit für Sie, den Entwickler. Es kommt aber tatsächlich direkt von Starlette.
+///
-!!! tip "Tipp"
- Wenn Sie in Ihren Tests neben dem Senden von Anfragen an Ihre FastAPI-Anwendung auch `async`-Funktionen aufrufen möchten (z. B. asynchrone Datenbankfunktionen), werfen Sie einen Blick auf die [Async-Tests](../advanced/async-tests.md){.internal-link target=_blank} im Handbuch für fortgeschrittene Benutzer.
+/// note | "Technische Details"
+
+Sie könnten auch `from starlette.testclient import TestClient` verwenden.
+
+**FastAPI** stellt denselben `starlette.testclient` auch via `fastapi.testclient` bereit, als Annehmlichkeit für Sie, den Entwickler. Es kommt aber tatsächlich direkt von Starlette.
+
+///
+
+/// tip | "Tipp"
+
+Wenn Sie in Ihren Tests neben dem Senden von Anfragen an Ihre FastAPI-Anwendung auch `async`-Funktionen aufrufen möchten (z. B. asynchrone Datenbankfunktionen), werfen Sie einen Blick auf die [Async-Tests](../advanced/async-tests.md){.internal-link target=_blank} im Handbuch für fortgeschrittene Benutzer.
+
+///
## Tests separieren
@@ -63,7 +75,7 @@ In der Datei `main.py` haben Sie Ihre **FastAPI**-Anwendung:
```Python
-{!../../../docs_src/app_testing/main.py!}
+{!../../docs_src/app_testing/main.py!}
```
### Testdatei
@@ -81,7 +93,7 @@ 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!}
```
... und haben den Code für die Tests wie zuvor.
@@ -110,48 +122,64 @@ Sie verfügt über eine `POST`-Operation, die mehrere Fehler zurückgeben könnt
Beide *Pfadoperationen* erfordern einen `X-Token`-Header.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python
- {!> ../../../docs_src/app_testing/app_b_an_py310/main.py!}
- ```
+```Python
+{!> ../../docs_src/app_testing/app_b_an_py310/main.py!}
+```
-=== "Python 3.9+"
+////
- ```Python
- {!> ../../../docs_src/app_testing/app_b_an_py39/main.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python
+{!> ../../docs_src/app_testing/app_b_an_py39/main.py!}
+```
- ```Python
- {!> ../../../docs_src/app_testing/app_b_an/main.py!}
- ```
+////
-=== "Python 3.10+ nicht annotiert"
+//// tab | Python 3.8+
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+```Python
+{!> ../../docs_src/app_testing/app_b_an/main.py!}
+```
- ```Python
- {!> ../../../docs_src/app_testing/app_b_py310/main.py!}
- ```
+////
-=== "Python 3.8+ nicht annotiert"
+//// tab | Python 3.10+ nicht annotiert
- !!! tip "Tipp"
- Bevorzugen Sie die `Annotated`-Version, falls möglich.
+/// tip | "Tipp"
- ```Python
- {!> ../../../docs_src/app_testing/app_b/main.py!}
- ```
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python
+{!> ../../docs_src/app_testing/app_b_py310/main.py!}
+```
+
+////
+
+//// tab | Python 3.8+ nicht annotiert
+
+/// tip | "Tipp"
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python
+{!> ../../docs_src/app_testing/app_b/main.py!}
+```
+
+////
### Erweiterte Testdatei
Anschließend könnten Sie `test_main.py` mit den erweiterten Tests aktualisieren:
```Python
-{!> ../../../docs_src/app_testing/app_b/test_main.py!}
+{!> ../../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.
@@ -168,10 +196,13 @@ Z. B.:
Weitere Informationen zum Übergeben von Daten an das Backend (mithilfe von `httpx` oder dem `TestClient`) finden Sie in der HTTPX-Dokumentation.
-!!! info
- Beachten Sie, dass der `TestClient` Daten empfängt, die nach JSON konvertiert werden können, keine Pydantic-Modelle.
+/// info
- Wenn Sie ein Pydantic-Modell in Ihrem Test haben und dessen Daten während des Testens an die Anwendung senden möchten, können Sie den `jsonable_encoder` verwenden, der in [JSON-kompatibler Encoder](encoder.md){.internal-link target=_blank} beschrieben wird.
+Beachten Sie, dass der `TestClient` Daten empfängt, die nach JSON konvertiert werden können, keine Pydantic-Modelle.
+
+Wenn Sie ein Pydantic-Modell in Ihrem Test haben und dessen Daten während des Testens an die Anwendung senden möchten, können Sie den `jsonable_encoder` verwenden, der in [JSON-kompatibler Encoder](encoder.md){.internal-link target=_blank} beschrieben wird.
+
+///
## Tests ausführen
diff --git a/docs/em/docs/advanced/additional-responses.md b/docs/em/docs/advanced/additional-responses.md
index 26963c2e3..e4442135e 100644
--- a/docs/em/docs/advanced/additional-responses.md
+++ b/docs/em/docs/advanced/additional-responses.md
@@ -1,9 +1,12 @@
# 🌖 📨 🗄
-!!! warning
- 👉 👍 🏧 ❔.
+/// warning
- 🚥 👆 ▶️ ⏮️ **FastAPI**, 👆 💪 🚫 💪 👉.
+👉 👍 🏧 ❔.
+
+🚥 👆 ▶️ ⏮️ **FastAPI**, 👆 💪 🚫 💪 👉.
+
+///
👆 💪 📣 🌖 📨, ⏮️ 🌖 👔 📟, 🔉 🆎, 📛, ♒️.
@@ -24,23 +27,29 @@
🖼, 📣 ➕1️⃣ 📨 ⏮️ 👔 📟 `404` & Pydantic 🏷 `Message`, 👆 💪 ✍:
```Python hl_lines="18 22"
-{!../../../docs_src/additional_responses/tutorial001.py!}
+{!../../docs_src/additional_responses/tutorial001.py!}
```
-!!! note
- ✔️ 🤯 👈 👆 ✔️ 📨 `JSONResponse` 🔗.
+/// note
-!!! info
- `model` 🔑 🚫 🍕 🗄.
+✔️ 🤯 👈 👆 ✔️ 📨 `JSONResponse` 🔗.
- **FastAPI** 🔜 ✊ Pydantic 🏷 ⚪️➡️ 📤, 🏗 `JSON Schema`, & 🚮 ⚫️ ☑ 🥉.
+///
- ☑ 🥉:
+/// info
- * 🔑 `content`, 👈 ✔️ 💲 ➕1️⃣ 🎻 🎚 (`dict`) 👈 🔌:
- * 🔑 ⏮️ 📻 🆎, ✅ `application/json`, 👈 🔌 💲 ➕1️⃣ 🎻 🎚, 👈 🔌:
- * 🔑 `schema`, 👈 ✔️ 💲 🎻 🔗 ⚪️➡️ 🏷, 📥 ☑ 🥉.
- * **FastAPI** 🚮 🔗 📥 🌐 🎻 🔗 ➕1️⃣ 🥉 👆 🗄 ↩️ ✅ ⚫️ 🔗. 👉 🌌, 🎏 🈸 & 👩💻 💪 ⚙️ 👈 🎻 🔗 🔗, 🚚 👻 📟 ⚡ 🧰, ♒️.
+`model` 🔑 🚫 🍕 🗄.
+
+**FastAPI** 🔜 ✊ Pydantic 🏷 ⚪️➡️ 📤, 🏗 `JSON Schema`, & 🚮 ⚫️ ☑ 🥉.
+
+☑ 🥉:
+
+* 🔑 `content`, 👈 ✔️ 💲 ➕1️⃣ 🎻 🎚 (`dict`) 👈 🔌:
+ * 🔑 ⏮️ 📻 🆎, ✅ `application/json`, 👈 🔌 💲 ➕1️⃣ 🎻 🎚, 👈 🔌:
+ * 🔑 `schema`, 👈 ✔️ 💲 🎻 🔗 ⚪️➡️ 🏷, 📥 ☑ 🥉.
+ * **FastAPI** 🚮 🔗 📥 🌐 🎻 🔗 ➕1️⃣ 🥉 👆 🗄 ↩️ ✅ ⚫️ 🔗. 👉 🌌, 🎏 🈸 & 👩💻 💪 ⚙️ 👈 🎻 🔗 🔗, 🚚 👻 📟 ⚡ 🧰, ♒️.
+
+///
🏗 📨 🗄 👉 *➡ 🛠️* 🔜:
@@ -169,16 +178,22 @@
🖼, 👆 💪 🚮 🌖 📻 🆎 `image/png`, 📣 👈 👆 *➡ 🛠️* 💪 📨 🎻 🎚 (⏮️ 📻 🆎 `application/json`) ⚖️ 🇩🇴 🖼:
```Python hl_lines="19-24 28"
-{!../../../docs_src/additional_responses/tutorial002.py!}
+{!../../docs_src/additional_responses/tutorial002.py!}
```
-!!! note
- 👀 👈 👆 ✔️ 📨 🖼 ⚙️ `FileResponse` 🔗.
+/// note
-!!! info
- 🚥 👆 ✔ 🎏 📻 🆎 🎯 👆 `responses` 🔢, FastAPI 🔜 🤔 📨 ✔️ 🎏 📻 🆎 👑 📨 🎓 (🔢 `application/json`).
+👀 👈 👆 ✔️ 📨 🖼 ⚙️ `FileResponse` 🔗.
- ✋️ 🚥 👆 ✔️ ✔ 🛃 📨 🎓 ⏮️ `None` 🚮 📻 🆎, FastAPI 🔜 ⚙️ `application/json` 🙆 🌖 📨 👈 ✔️ 👨💼 🏷.
+///
+
+/// info
+
+🚥 👆 ✔ 🎏 📻 🆎 🎯 👆 `responses` 🔢, FastAPI 🔜 🤔 📨 ✔️ 🎏 📻 🆎 👑 📨 🎓 (🔢 `application/json`).
+
+✋️ 🚥 👆 ✔️ ✔ 🛃 📨 🎓 ⏮️ `None` 🚮 📻 🆎, FastAPI 🔜 ⚙️ `application/json` 🙆 🌖 📨 👈 ✔️ 👨💼 🏷.
+
+///
## 🌀 ℹ
@@ -193,7 +208,7 @@
& 📨 ⏮️ 👔 📟 `200` 👈 ⚙️ 👆 `response_model`, ✋️ 🔌 🛃 `example`:
```Python hl_lines="20-31"
-{!../../../docs_src/additional_responses/tutorial003.py!}
+{!../../docs_src/additional_responses/tutorial003.py!}
```
⚫️ 🔜 🌐 🌀 & 🔌 👆 🗄, & 🎦 🛠️ 🩺:
@@ -229,7 +244,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!}
```
## 🌖 ℹ 🔃 🗄 📨
diff --git a/docs/em/docs/advanced/additional-status-codes.md b/docs/em/docs/advanced/additional-status-codes.md
index 392579df6..7a50e1bca 100644
--- a/docs/em/docs/advanced/additional-status-codes.md
+++ b/docs/em/docs/advanced/additional-status-codes.md
@@ -15,20 +15,26 @@
🏆 👈, 🗄 `JSONResponse`, & 📨 👆 🎚 📤 🔗, ⚒ `status_code` 👈 👆 💚:
```Python hl_lines="4 25"
-{!../../../docs_src/additional_status_codes/tutorial001.py!}
+{!../../docs_src/additional_status_codes/tutorial001.py!}
```
-!!! warning
- 🕐❔ 👆 📨 `Response` 🔗, 💖 🖼 🔛, ⚫️ 🔜 📨 🔗.
+/// warning
- ⚫️ 🏆 🚫 🎻 ⏮️ 🏷, ♒️.
+🕐❔ 👆 📨 `Response` 🔗, 💖 🖼 🔛, ⚫️ 🔜 📨 🔗.
- ⚒ 💭 ⚫️ ✔️ 📊 👆 💚 ⚫️ ✔️, & 👈 💲 ☑ 🎻 (🚥 👆 ⚙️ `JSONResponse`).
+⚫️ 🏆 🚫 🎻 ⏮️ 🏷, ♒️.
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette.responses import JSONResponse`.
+⚒ 💭 ⚫️ ✔️ 📊 👆 💚 ⚫️ ✔️, & 👈 💲 ☑ 🎻 (🚥 👆 ⚙️ `JSONResponse`).
- **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. 🎏 ⏮️ `status`.
+///
+
+/// note | "📡 ℹ"
+
+👆 💪 ⚙️ `from starlette.responses import JSONResponse`.
+
+**FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. 🎏 ⏮️ `status`.
+
+///
## 🗄 & 🛠️ 🩺
diff --git a/docs/em/docs/advanced/advanced-dependencies.md b/docs/em/docs/advanced/advanced-dependencies.md
index fa1554734..721428ce4 100644
--- a/docs/em/docs/advanced/advanced-dependencies.md
+++ b/docs/em/docs/advanced/advanced-dependencies.md
@@ -19,7 +19,7 @@
👈, 👥 📣 👩🔬 `__call__`:
```Python hl_lines="10"
-{!../../../docs_src/dependencies/tutorial011.py!}
+{!../../docs_src/dependencies/tutorial011.py!}
```
👉 💼, 👉 `__call__` ⚫️❔ **FastAPI** 🔜 ⚙️ ✅ 🌖 🔢 & 🎧-🔗, & 👉 ⚫️❔ 🔜 🤙 🚶♀️ 💲 🔢 👆 *➡ 🛠️ 🔢* ⏪.
@@ -29,7 +29,7 @@
& 🔜, 👥 💪 ⚙️ `__init__` 📣 🔢 👐 👈 👥 💪 ⚙️ "🔗" 🔗:
```Python hl_lines="7"
-{!../../../docs_src/dependencies/tutorial011.py!}
+{!../../docs_src/dependencies/tutorial011.py!}
```
👉 💼, **FastAPI** 🏆 🚫 ⏱ 👆 ⚖️ 💅 🔃 `__init__`, 👥 🔜 ⚙️ ⚫️ 🔗 👆 📟.
@@ -39,7 +39,7 @@
👥 💪 ✍ 👐 👉 🎓 ⏮️:
```Python hl_lines="16"
-{!../../../docs_src/dependencies/tutorial011.py!}
+{!../../docs_src/dependencies/tutorial011.py!}
```
& 👈 🌌 👥 💪 "🔗" 👆 🔗, 👈 🔜 ✔️ `"bar"` 🔘 ⚫️, 🔢 `checker.fixed_content`.
@@ -57,14 +57,17 @@ checker(q="somequery")
...& 🚶♀️ ⚫️❔ 👈 📨 💲 🔗 👆 *➡ 🛠️ 🔢* 🔢 `fixed_content_included`:
```Python hl_lines="20"
-{!../../../docs_src/dependencies/tutorial011.py!}
+{!../../docs_src/dependencies/tutorial011.py!}
```
-!!! tip
- 🌐 👉 💪 😑 🎭. & ⚫️ 💪 🚫 📶 🆑 ❔ ⚫️ ⚠.
+/// tip
- 👫 🖼 😫 🙅, ✋️ 🎦 ❔ ⚫️ 🌐 👷.
+🌐 👉 💪 😑 🎭. & ⚫️ 💪 🚫 📶 🆑 ❔ ⚫️ ⚠.
- 📃 🔃 💂♂, 📤 🚙 🔢 👈 🛠️ 👉 🎏 🌌.
+👫 🖼 😫 🙅, ✋️ 🎦 ❔ ⚫️ 🌐 👷.
- 🚥 👆 🤔 🌐 👉, 👆 ⏪ 💭 ❔ 👈 🚙 🧰 💂♂ 👷 🔘.
+📃 🔃 💂♂, 📤 🚙 🔢 👈 🛠️ 👉 🎏 🌌.
+
+🚥 👆 🤔 🌐 👉, 👆 ⏪ 💭 ❔ 👈 🚙 🧰 💂♂ 👷 🔘.
+
+///
diff --git a/docs/em/docs/advanced/async-tests.md b/docs/em/docs/advanced/async-tests.md
index df94c6ce7..4d468acd4 100644
--- a/docs/em/docs/advanced/async-tests.md
+++ b/docs/em/docs/advanced/async-tests.md
@@ -33,13 +33,13 @@
📁 `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!}
```
## 🏃 ⚫️
@@ -61,16 +61,19 @@ $ pytest
📑 `@pytest.mark.anyio` 💬 ✳ 👈 👉 💯 🔢 🔜 🤙 🔁:
```Python hl_lines="7"
-{!../../../docs_src/async_tests/test_main.py!}
+{!../../docs_src/async_tests/test_main.py!}
```
-!!! tip
- 🗒 👈 💯 🔢 🔜 `async def` ↩️ `def` ⏭ 🕐❔ ⚙️ `TestClient`.
+/// tip
+
+🗒 👈 💯 🔢 🔜 `async def` ↩️ `def` ⏭ 🕐❔ ⚙️ `TestClient`.
+
+///
⤴️ 👥 💪 ✍ `AsyncClient` ⏮️ 📱, & 📨 🔁 📨 ⚫️, ⚙️ `await`.
-```Python hl_lines="9-10"
-{!../../../docs_src/async_tests/test_main.py!}
+```Python hl_lines="9-12"
+{!../../docs_src/async_tests/test_main.py!}
```
👉 🌓:
@@ -81,12 +84,18 @@ response = client.get('/')
...👈 👥 ⚙️ ⚒ 👆 📨 ⏮️ `TestClient`.
-!!! tip
- 🗒 👈 👥 ⚙️ 🔁/⌛ ⏮️ 🆕 `AsyncClient` - 📨 🔁.
+/// tip
+
+🗒 👈 👥 ⚙️ 🔁/⌛ ⏮️ 🆕 `AsyncClient` - 📨 🔁.
+
+///
## 🎏 🔁 🔢 🤙
🔬 🔢 🔜 🔁, 👆 💪 🔜 🤙 (& `await`) 🎏 `async` 🔢 ↖️ ⚪️➡️ 📨 📨 👆 FastAPI 🈸 👆 💯, ⚫️❔ 👆 🔜 🤙 👫 🙆 🙆 👆 📟.
-!!! tip
- 🚥 👆 ⚔ `RuntimeError: Task attached to a different loop` 🕐❔ 🛠️ 🔁 🔢 🤙 👆 💯 (✅ 🕐❔ ⚙️ ✳ MotorClient) 💭 🔗 🎚 👈 💪 🎉 ➰ 🕴 🏞 🔁 🔢, ✅ `'@app.on_event("startup")` ⏲.
+/// tip
+
+🚥 👆 ⚔ `RuntimeError: Task attached to a different loop` 🕐❔ 🛠️ 🔁 🔢 🤙 👆 💯 (✅ 🕐❔ ⚙️ ✳ MotorClient) 💭 🔗 🎚 👈 💪 🎉 ➰ 🕴 🏞 🔁 🔢, ✅ `'@app.on_event("startup")` ⏲.
+
+///
diff --git a/docs/em/docs/advanced/behind-a-proxy.md b/docs/em/docs/advanced/behind-a-proxy.md
index e3fd26735..e66ddccf7 100644
--- a/docs/em/docs/advanced/behind-a-proxy.md
+++ b/docs/em/docs/advanced/behind-a-proxy.md
@@ -39,8 +39,11 @@ browser --> proxy
proxy --> server
```
-!!! tip
- 📢 `0.0.0.0` 🛎 ⚙️ ⛓ 👈 📋 👂 🔛 🌐 📢 💪 👈 🎰/💽.
+/// tip
+
+📢 `0.0.0.0` 🛎 ⚙️ ⛓ 👈 📋 👂 🔛 🌐 📢 💪 👈 🎰/💽.
+
+///
🩺 🎚 🔜 💪 🗄 🔗 📣 👈 👉 🛠️ `server` 🔎 `/api/v1` (⛅ 🗳). 🖼:
@@ -77,10 +80,13 @@ $ uvicorn main:app --root-path /api/v1
🚥 👆 ⚙️ Hypercorn, ⚫️ ✔️ 🎛 `--root-path`.
-!!! note "📡 ℹ"
- 🔫 🔧 🔬 `root_path` 👉 ⚙️ 💼.
+/// note | "📡 ℹ"
- & `--root-path` 📋 ⏸ 🎛 🚚 👈 `root_path`.
+🔫 🔧 🔬 `root_path` 👉 ⚙️ 💼.
+
+ & `--root-path` 📋 ⏸ 🎛 🚚 👈 `root_path`.
+
+///
### ✅ ⏮️ `root_path`
@@ -89,7 +95,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!}
```
⤴️, 🚥 👆 ▶️ Uvicorn ⏮️:
@@ -118,7 +124,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!}
```
🚶♀️ `root_path` `FastAPI` 🔜 🌓 🚶♀️ `--root-path` 📋 ⏸ 🎛 Uvicorn ⚖️ Hypercorn.
@@ -168,8 +174,11 @@ Uvicorn 🔜 ⌛ 🗳 🔐 Uvicorn `http://127.0.0.1:8000/app`, & ⤴️ ⚫
👉 💬 Traefik 👂 🔛 ⛴ 9️⃣9️⃣9️⃣9️⃣ & ⚙️ ➕1️⃣ 📁 `routes.toml`.
-!!! tip
- 👥 ⚙️ ⛴ 9️⃣9️⃣9️⃣9️⃣ ↩️ 🐩 🇺🇸🔍 ⛴ 8️⃣0️⃣ 👈 👆 🚫 ✔️ 🏃 ⚫️ ⏮️ 📡 (`sudo`) 😌.
+/// tip
+
+👥 ⚙️ ⛴ 9️⃣9️⃣9️⃣9️⃣ ↩️ 🐩 🇺🇸🔍 ⛴ 8️⃣0️⃣ 👈 👆 🚫 ✔️ 🏃 ⚫️ ⏮️ 📡 (`sudo`) 😌.
+
+///
🔜 ✍ 👈 🎏 📁 `routes.toml`:
@@ -235,8 +244,11 @@ $ uvicorn main:app --root-path /api/v1
}
```
-!!! tip
- 👀 👈 ✋️ 👆 🔐 ⚫️ `http://127.0.0.1:8000/app` ⚫️ 🎦 `root_path` `/api/v1`, ✊ ⚪️➡️ 🎛 `--root-path`.
+/// tip
+
+👀 👈 ✋️ 👆 🔐 ⚫️ `http://127.0.0.1:8000/app` ⚫️ 🎦 `root_path` `/api/v1`, ✊ ⚪️➡️ 🎛 `--root-path`.
+
+///
& 🔜 📂 📛 ⏮️ ⛴ Traefik, ✅ ➡ 🔡: http://127.0.0.1:9999/api/v1/app.
@@ -279,8 +291,11 @@ $ uvicorn main:app --root-path /api/v1
## 🌖 💽
-!!! warning
- 👉 🌅 🏧 ⚙️ 💼. 💭 🆓 🚶 ⚫️.
+/// warning
+
+👉 🌅 🏧 ⚙️ 💼. 💭 🆓 🚶 ⚫️.
+
+///
🔢, **FastAPI** 🔜 ✍ `server` 🗄 🔗 ⏮️ 📛 `root_path`.
@@ -291,7 +306,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!}
```
🔜 🏗 🗄 🔗 💖:
@@ -319,22 +334,28 @@ $ uvicorn main:app --root-path /api/v1
}
```
-!!! tip
- 👀 🚘-🏗 💽 ⏮️ `url` 💲 `/api/v1`, ✊ ⚪️➡️ `root_path`.
+/// tip
+
+👀 🚘-🏗 💽 ⏮️ `url` 💲 `/api/v1`, ✊ ⚪️➡️ `root_path`.
+
+///
🩺 🎚 http://127.0.0.1:9999/api/v1/docs ⚫️ 🔜 👀 💖:
-!!! tip
- 🩺 🎚 🔜 🔗 ⏮️ 💽 👈 👆 🖊.
+/// tip
+
+🩺 🎚 🔜 🔗 ⏮️ 💽 👈 👆 🖊.
+
+///
### ❎ 🏧 💽 ⚪️➡️ `root_path`
🚥 👆 🚫 💚 **FastAPI** 🔌 🏧 💽 ⚙️ `root_path`, 👆 💪 ⚙️ 🔢 `root_path_in_servers=False`:
```Python hl_lines="9"
-{!../../../docs_src/behind_a_proxy/tutorial004.py!}
+{!../../docs_src/behind_a_proxy/tutorial004.py!}
```
& ⤴️ ⚫️ 🏆 🚫 🔌 ⚫️ 🗄 🔗.
diff --git a/docs/em/docs/advanced/custom-response.md b/docs/em/docs/advanced/custom-response.md
index cf76c01d0..7147a4536 100644
--- a/docs/em/docs/advanced/custom-response.md
+++ b/docs/em/docs/advanced/custom-response.md
@@ -12,8 +12,11 @@
& 🚥 👈 `Response` ✔️ 🎻 📻 🆎 (`application/json`), 💖 💼 ⏮️ `JSONResponse` & `UJSONResponse`, 💽 👆 📨 🔜 🔁 🗜 (& ⛽) ⏮️ 🙆 Pydantic `response_model` 👈 👆 📣 *➡ 🛠️ 👨🎨*.
-!!! note
- 🚥 👆 ⚙️ 📨 🎓 ⏮️ 🙅♂ 📻 🆎, FastAPI 🔜 ⌛ 👆 📨 ✔️ 🙅♂ 🎚, ⚫️ 🔜 🚫 📄 📨 📁 🚮 🏗 🗄 🩺.
+/// note
+
+🚥 👆 ⚙️ 📨 🎓 ⏮️ 🙅♂ 📻 🆎, FastAPI 🔜 ⌛ 👆 📨 ✔️ 🙅♂ 🎚, ⚫️ 🔜 🚫 📄 📨 📁 🚮 🏗 🗄 🩺.
+
+///
## ⚙️ `ORJSONResponse`
@@ -28,18 +31,24 @@
✋️ 🚥 👆 🎯 👈 🎚 👈 👆 🛬 **🎻 ⏮️ 🎻**, 👆 💪 🚶♀️ ⚫️ 🔗 📨 🎓 & ❎ ➕ 🌥 👈 FastAPI 🔜 ✔️ 🚶♀️ 👆 📨 🎚 🔘 `jsonable_encoder` ⏭ 🚶♀️ ⚫️ 📨 🎓.
```Python hl_lines="2 7"
-{!../../../docs_src/custom_response/tutorial001b.py!}
+{!../../docs_src/custom_response/tutorial001b.py!}
```
-!!! info
- 🔢 `response_class` 🔜 ⚙️ 🔬 "📻 🆎" 📨.
+/// info
- 👉 💼, 🇺🇸🔍 🎚 `Content-Type` 🔜 ⚒ `application/json`.
+🔢 `response_class` 🔜 ⚙️ 🔬 "📻 🆎" 📨.
- & ⚫️ 🔜 📄 ✅ 🗄.
+👉 💼, 🇺🇸🔍 🎚 `Content-Type` 🔜 ⚒ `application/json`.
-!!! tip
- `ORJSONResponse` ⏳ 🕴 💪 FastAPI, 🚫 💃.
+ & ⚫️ 🔜 📄 ✅ 🗄.
+
+///
+
+/// tip
+
+`ORJSONResponse` ⏳ 🕴 💪 FastAPI, 🚫 💃.
+
+///
## 🕸 📨
@@ -49,15 +58,18 @@
* 🚶♀️ `HTMLResponse` 🔢 `response_class` 👆 *➡ 🛠️ 👨🎨*.
```Python hl_lines="2 7"
-{!../../../docs_src/custom_response/tutorial002.py!}
+{!../../docs_src/custom_response/tutorial002.py!}
```
-!!! info
- 🔢 `response_class` 🔜 ⚙️ 🔬 "📻 🆎" 📨.
+/// info
- 👉 💼, 🇺🇸🔍 🎚 `Content-Type` 🔜 ⚒ `text/html`.
+🔢 `response_class` 🔜 ⚙️ 🔬 "📻 🆎" 📨.
- & ⚫️ 🔜 📄 ✅ 🗄.
+👉 💼, 🇺🇸🔍 🎚 `Content-Type` 🔜 ⚒ `text/html`.
+
+ & ⚫️ 🔜 📄 ✅ 🗄.
+
+///
### 📨 `Response`
@@ -66,14 +78,20 @@
🎏 🖼 ⚪️➡️ 🔛, 🛬 `HTMLResponse`, 💪 👀 💖:
```Python hl_lines="2 7 19"
-{!../../../docs_src/custom_response/tutorial003.py!}
+{!../../docs_src/custom_response/tutorial003.py!}
```
-!!! warning
- `Response` 📨 🔗 👆 *➡ 🛠️ 🔢* 🏆 🚫 📄 🗄 (🖼, `Content-Type` 🏆 🚫 📄) & 🏆 🚫 ⭐ 🏧 🎓 🩺.
+/// warning
-!!! info
- ↗️, ☑ `Content-Type` 🎚, 👔 📟, ♒️, 🔜 👟 ⚪️➡️ `Response` 🎚 👆 📨.
+`Response` 📨 🔗 👆 *➡ 🛠️ 🔢* 🏆 🚫 📄 🗄 (🖼, `Content-Type` 🏆 🚫 📄) & 🏆 🚫 ⭐ 🏧 🎓 🩺.
+
+///
+
+/// info
+
+↗️, ☑ `Content-Type` 🎚, 👔 📟, ♒️, 🔜 👟 ⚪️➡️ `Response` 🎚 👆 📨.
+
+///
### 📄 🗄 & 🔐 `Response`
@@ -86,7 +104,7 @@
🖼, ⚫️ 💪 🕳 💖:
```Python hl_lines="7 21 23"
-{!../../../docs_src/custom_response/tutorial004.py!}
+{!../../docs_src/custom_response/tutorial004.py!}
```
👉 🖼, 🔢 `generate_html_response()` ⏪ 🏗 & 📨 `Response` ↩️ 🛬 🕸 `str`.
@@ -103,10 +121,13 @@
✔️ 🤯 👈 👆 💪 ⚙️ `Response` 📨 🕳 🙆, ⚖️ ✍ 🛃 🎧-🎓.
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette.responses import HTMLResponse`.
+/// note | "📡 ℹ"
- **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃.
+👆 💪 ⚙️ `from starlette.responses import HTMLResponse`.
+
+**FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃.
+
+///
### `Response`
@@ -124,7 +145,7 @@
FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 🎚, ⚓️ 🔛 = & 🔁 = ✍ 🆎.
```Python hl_lines="1 18"
-{!../../../docs_src/response_directly/tutorial002.py!}
+{!../../docs_src/response_directly/tutorial002.py!}
```
### `HTMLResponse`
@@ -136,7 +157,7 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎
✊ ✍ ⚖️ 🔢 & 📨 ✅ ✍ 📨.
```Python hl_lines="2 7 9"
-{!../../../docs_src/custom_response/tutorial005.py!}
+{!../../docs_src/custom_response/tutorial005.py!}
```
### `JSONResponse`
@@ -153,15 +174,21 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎
🎛 🎻 📨 ⚙️ `ujson`.
-!!! warning
- `ujson` 🌘 💛 🌘 🐍 🏗-🛠️ ❔ ⚫️ 🍵 📐-💼.
+/// warning
+
+`ujson` 🌘 💛 🌘 🐍 🏗-🛠️ ❔ ⚫️ 🍵 📐-💼.
+
+///
```Python hl_lines="2 7"
-{!../../../docs_src/custom_response/tutorial001.py!}
+{!../../docs_src/custom_response/tutorial001.py!}
```
-!!! tip
- ⚫️ 💪 👈 `ORJSONResponse` 💪 ⏩ 🎛.
+/// tip
+
+⚫️ 💪 👈 `ORJSONResponse` 💪 ⏩ 🎛.
+
+///
### `RedirectResponse`
@@ -170,7 +197,7 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎
👆 💪 📨 `RedirectResponse` 🔗:
```Python hl_lines="2 9"
-{!../../../docs_src/custom_response/tutorial006.py!}
+{!../../docs_src/custom_response/tutorial006.py!}
```
---
@@ -179,7 +206,7 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎
```Python hl_lines="2 7 9"
-{!../../../docs_src/custom_response/tutorial006b.py!}
+{!../../docs_src/custom_response/tutorial006b.py!}
```
🚥 👆 👈, ⤴️ 👆 💪 📨 📛 🔗 ⚪️➡️ 👆 *➡ 🛠️* 🔢.
@@ -191,7 +218,7 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎
👆 💪 ⚙️ `status_code` 🔢 🌀 ⏮️ `response_class` 🔢:
```Python hl_lines="2 7 9"
-{!../../../docs_src/custom_response/tutorial006c.py!}
+{!../../docs_src/custom_response/tutorial006c.py!}
```
### `StreamingResponse`
@@ -199,7 +226,7 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎
✊ 🔁 🚂 ⚖️ 😐 🚂/🎻 & 🎏 📨 💪.
```Python hl_lines="2 14"
-{!../../../docs_src/custom_response/tutorial007.py!}
+{!../../docs_src/custom_response/tutorial007.py!}
```
#### ⚙️ `StreamingResponse` ⏮️ 📁-💖 🎚
@@ -211,7 +238,7 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎
👉 🔌 📚 🗃 🔗 ⏮️ ☁ 💾, 📹 🏭, & 🎏.
```{ .python .annotate hl_lines="2 10-12 14" }
-{!../../../docs_src/custom_response/tutorial008.py!}
+{!../../docs_src/custom_response/tutorial008.py!}
```
1️⃣. 👉 🚂 🔢. ⚫️ "🚂 🔢" ↩️ ⚫️ 🔌 `yield` 📄 🔘.
@@ -222,8 +249,11 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎
🔨 ⚫️ 👉 🌌, 👥 💪 🚮 ⚫️ `with` 🍫, & 👈 🌌, 🚚 👈 ⚫️ 📪 ⏮️ 🏁.
-!!! tip
- 👀 👈 📥 👥 ⚙️ 🐩 `open()` 👈 🚫 🐕🦺 `async` & `await`, 👥 📣 ➡ 🛠️ ⏮️ 😐 `def`.
+/// tip
+
+👀 👈 📥 👥 ⚙️ 🐩 `open()` 👈 🚫 🐕🦺 `async` & `await`, 👥 📣 ➡ 🛠️ ⏮️ 😐 `def`.
+
+///
### `FileResponse`
@@ -239,13 +269,13 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎
📁 📨 🔜 🔌 ☑ `Content-Length`, `Last-Modified` & `ETag` 🎚.
```Python hl_lines="2 10"
-{!../../../docs_src/custom_response/tutorial009.py!}
+{!../../docs_src/custom_response/tutorial009.py!}
```
👆 💪 ⚙️ `response_class` 🔢:
```Python hl_lines="2 8 10"
-{!../../../docs_src/custom_response/tutorial009b.py!}
+{!../../docs_src/custom_response/tutorial009b.py!}
```
👉 💼, 👆 💪 📨 📁 ➡ 🔗 ⚪️➡️ 👆 *➡ 🛠️* 🔢.
@@ -261,7 +291,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!}
```
🔜 ↩️ 🛬:
@@ -289,11 +319,14 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎
🖼 🔛, **FastAPI** 🔜 ⚙️ `ORJSONResponse` 🔢, 🌐 *➡ 🛠️*, ↩️ `JSONResponse`.
```Python hl_lines="2 4"
-{!../../../docs_src/custom_response/tutorial010.py!}
+{!../../docs_src/custom_response/tutorial010.py!}
```
-!!! tip
- 👆 💪 🔐 `response_class` *➡ 🛠️* ⏭.
+/// tip
+
+👆 💪 🔐 `response_class` *➡ 🛠️* ⏭.
+
+///
## 🌖 🧾
diff --git a/docs/em/docs/advanced/dataclasses.md b/docs/em/docs/advanced/dataclasses.md
index e8c4b99a2..ab76e5083 100644
--- a/docs/em/docs/advanced/dataclasses.md
+++ b/docs/em/docs/advanced/dataclasses.md
@@ -5,7 +5,7 @@ FastAPI 🏗 🔛 🔝 **Pydantic**, & 👤 ✔️ 🌏 👆 ❔ ⚙️ Pyda
✋️ FastAPI 🐕🦺 ⚙️ `dataclasses` 🎏 🌌:
```Python hl_lines="1 7-12 19-20"
-{!../../../docs_src/dataclasses/tutorial001.py!}
+{!../../docs_src/dataclasses/tutorial001.py!}
```
👉 🐕🦺 👏 **Pydantic**, ⚫️ ✔️ 🔗 🐕🦺 `dataclasses`.
@@ -20,19 +20,22 @@ FastAPI 🏗 🔛 🔝 **Pydantic**, & 👤 ✔️ 🌏 👆 ❔ ⚙️ Pyda
👉 👷 🎏 🌌 ⏮️ Pydantic 🏷. & ⚫️ 🤙 🏆 🎏 🌌 🔘, ⚙️ Pydantic.
-!!! info
- ✔️ 🤯 👈 🎻 💪 🚫 🌐 Pydantic 🏷 💪.
+/// info
- , 👆 5️⃣📆 💪 ⚙️ Pydantic 🏷.
+✔️ 🤯 👈 🎻 💪 🚫 🌐 Pydantic 🏷 💪.
- ✋️ 🚥 👆 ✔️ 📚 🎻 🤥 🤭, 👉 👌 🎱 ⚙️ 👫 🏋️ 🕸 🛠️ ⚙️ FastAPI. 👶
+, 👆 5️⃣📆 💪 ⚙️ Pydantic 🏷.
+
+✋️ 🚥 👆 ✔️ 📚 🎻 🤥 🤭, 👉 👌 🎱 ⚙️ 👫 🏋️ 🕸 🛠️ ⚙️ FastAPI. 👶
+
+///
## 🎻 `response_model`
👆 💪 ⚙️ `dataclasses` `response_model` 🔢:
```Python hl_lines="1 7-13 19"
-{!../../../docs_src/dataclasses/tutorial002.py!}
+{!../../docs_src/dataclasses/tutorial002.py!}
```
🎻 🔜 🔁 🗜 Pydantic 🎻.
@@ -50,7 +53,7 @@ FastAPI 🏗 🔛 🔝 **Pydantic**, & 👤 ✔️ 🌏 👆 ❔ ⚙️ Pyda
👈 💼, 👆 💪 🎯 💱 🐩 `dataclasses` ⏮️ `pydantic.dataclasses`, ❔ 💧-♻:
```{ .python .annotate hl_lines="1 5 8-11 14-17 23-25 28" }
-{!../../../docs_src/dataclasses/tutorial003.py!}
+{!../../docs_src/dataclasses/tutorial003.py!}
```
1️⃣. 👥 🗄 `field` ⚪️➡️ 🐩 `dataclasses`.
diff --git a/docs/em/docs/advanced/events.md b/docs/em/docs/advanced/events.md
index 19421ff58..2eae2b366 100644
--- a/docs/em/docs/advanced/events.md
+++ b/docs/em/docs/advanced/events.md
@@ -31,24 +31,27 @@
👥 ✍ 🔁 🔢 `lifespan()` ⏮️ `yield` 💖 👉:
```Python hl_lines="16 19"
-{!../../../docs_src/events/tutorial003.py!}
+{!../../docs_src/events/tutorial003.py!}
```
📥 👥 ⚖ 😥 *🕴* 🛠️ 🚚 🏷 🚮 (❌) 🏷 🔢 📖 ⏮️ 🎰 🏫 🏷 ⏭ `yield`. 👉 📟 🔜 🛠️ **⏭** 🈸 **▶️ ✊ 📨**, ⏮️ *🕴*.
& ⤴️, ▶️️ ⏮️ `yield`, 👥 🚚 🏷. 👉 📟 🔜 🛠️ **⏮️** 🈸 **🏁 🚚 📨**, ▶️️ ⏭ *🤫*. 👉 💪, 🖼, 🚀 ℹ 💖 💾 ⚖️ 💻.
-!!! tip
- `shutdown` 🔜 🔨 🕐❔ 👆 **⛔️** 🈸.
+/// tip
- 🎲 👆 💪 ▶️ 🆕 ⏬, ⚖️ 👆 🤚 🎡 🏃 ⚫️. 🤷
+`shutdown` 🔜 🔨 🕐❔ 👆 **⛔️** 🈸.
+
+🎲 👆 💪 ▶️ 🆕 ⏬, ⚖️ 👆 🤚 🎡 🏃 ⚫️. 🤷
+
+///
### 🔆 🔢
🥇 👜 👀, 👈 👥 ⚖ 🔁 🔢 ⏮️ `yield`. 👉 📶 🎏 🔗 ⏮️ `yield`.
```Python hl_lines="14-19"
-{!../../../docs_src/events/tutorial003.py!}
+{!../../docs_src/events/tutorial003.py!}
```
🥇 🍕 🔢, ⏭ `yield`, 🔜 🛠️ **⏭** 🈸 ▶️.
@@ -62,7 +65,7 @@
👈 🗜 🔢 🔘 🕳 🤙 "**🔁 🔑 👨💼**".
```Python hl_lines="1 13"
-{!../../../docs_src/events/tutorial003.py!}
+{!../../docs_src/events/tutorial003.py!}
```
**🔑 👨💼** 🐍 🕳 👈 👆 💪 ⚙️ `with` 📄, 🖼, `open()` 💪 ⚙️ 🔑 👨💼:
@@ -86,15 +89,18 @@ async with lifespan(app):
`lifespan` 🔢 `FastAPI` 📱 ✊ **🔁 🔑 👨💼**, 👥 💪 🚶♀️ 👆 🆕 `lifespan` 🔁 🔑 👨💼 ⚫️.
```Python hl_lines="22"
-{!../../../docs_src/events/tutorial003.py!}
+{!../../docs_src/events/tutorial003.py!}
```
## 🎛 🎉 (😢)
-!!! warning
- 👍 🌌 🍵 *🕴* & *🤫* ⚙️ `lifespan` 🔢 `FastAPI` 📱 🔬 🔛.
+/// warning
- 👆 💪 🎲 🚶 👉 🍕.
+👍 🌌 🍵 *🕴* & *🤫* ⚙️ `lifespan` 🔢 `FastAPI` 📱 🔬 🔛.
+
+👆 💪 🎲 🚶 👉 🍕.
+
+///
📤 🎛 🌌 🔬 👉 ⚛ 🛠️ ⏮️ *🕴* & ⏮️ *🤫*.
@@ -107,7 +113,7 @@ async with lifespan(app):
🚮 🔢 👈 🔜 🏃 ⏭ 🈸 ▶️, 📣 ⚫️ ⏮️ 🎉 `"startup"`:
```Python hl_lines="8"
-{!../../../docs_src/events/tutorial001.py!}
+{!../../docs_src/events/tutorial001.py!}
```
👉 💼, `startup` 🎉 🐕🦺 🔢 🔜 🔢 🏬 "💽" ( `dict`) ⏮️ 💲.
@@ -121,25 +127,34 @@ async with lifespan(app):
🚮 🔢 👈 🔜 🏃 🕐❔ 🈸 🤫 🔽, 📣 ⚫️ ⏮️ 🎉 `"shutdown"`:
```Python hl_lines="6"
-{!../../../docs_src/events/tutorial002.py!}
+{!../../docs_src/events/tutorial002.py!}
```
📥, `shutdown` 🎉 🐕🦺 🔢 🔜 ✍ ✍ ⏸ `"Application shutdown"` 📁 `log.txt`.
-!!! info
- `open()` 🔢, `mode="a"` ⛓ "🎻",, ⏸ 🔜 🚮 ⏮️ ⚫️❔ 🔛 👈 📁, 🍵 📁 ⏮️ 🎚.
+/// info
-!!! tip
- 👀 👈 👉 💼 👥 ⚙️ 🐩 🐍 `open()` 🔢 👈 🔗 ⏮️ 📁.
+`open()` 🔢, `mode="a"` ⛓ "🎻",, ⏸ 🔜 🚮 ⏮️ ⚫️❔ 🔛 👈 📁, 🍵 📁 ⏮️ 🎚.
- , ⚫️ 🔌 👤/🅾 (🔢/🔢), 👈 🚚 "⌛" 👜 ✍ 💾.
+///
- ✋️ `open()` 🚫 ⚙️ `async` & `await`.
+/// tip
- , 👥 📣 🎉 🐕🦺 🔢 ⏮️ 🐩 `def` ↩️ `async def`.
+👀 👈 👉 💼 👥 ⚙️ 🐩 🐍 `open()` 🔢 👈 🔗 ⏮️ 📁.
-!!! info
- 👆 💪 ✍ 🌅 🔃 👫 🎉 🐕🦺 💃 🎉' 🩺.
+, ⚫️ 🔌 👤/🅾 (🔢/🔢), 👈 🚚 "⌛" 👜 ✍ 💾.
+
+✋️ `open()` 🚫 ⚙️ `async` & `await`.
+
+, 👥 📣 🎉 🐕🦺 🔢 ⏮️ 🐩 `def` ↩️ `async def`.
+
+///
+
+/// info
+
+👆 💪 ✍ 🌅 🔃 👫 🎉 🐕🦺 💃 🎉' 🩺.
+
+///
### `startup` & `shutdown` 👯♂️
diff --git a/docs/em/docs/advanced/generate-clients.md b/docs/em/docs/advanced/generate-clients.md
index 261f9fb61..f09d75623 100644
--- a/docs/em/docs/advanced/generate-clients.md
+++ b/docs/em/docs/advanced/generate-clients.md
@@ -16,17 +16,21 @@
➡️ ▶️ ⏮️ 🙅 FastAPI 🈸:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="9-11 14-15 18 19 23"
- {!> ../../../docs_src/generate_clients/tutorial001.py!}
- ```
+```Python hl_lines="9-11 14-15 18 19 23"
+{!> ../../docs_src/generate_clients/tutorial001.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="7-9 12-13 16-17 21"
- {!> ../../../docs_src/generate_clients/tutorial001_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
+
+```Python hl_lines="7-9 12-13 16-17 21"
+{!> ../../docs_src/generate_clients/tutorial001_py39.py!}
+```
+
+////
👀 👈 *➡ 🛠️* 🔬 🏷 👫 ⚙️ 📨 🚀 & 📨 🚀, ⚙️ 🏷 `Item` & `ResponseMessage`.
@@ -111,8 +115,11 @@ frontend-app@1.0.0 generate-client /home/user/code/frontend-app
-!!! tip
- 👀 ✍ `name` & `price`, 👈 🔬 FastAPI 🈸, `Item` 🏷.
+/// tip
+
+👀 ✍ `name` & `price`, 👈 🔬 FastAPI 🈸, `Item` 🏷.
+
+///
👆 🔜 ✔️ ⏸ ❌ 📊 👈 👆 📨:
@@ -129,17 +136,21 @@ frontend-app@1.0.0 generate-client /home/user/code/frontend-app
🖼, 👆 💪 ✔️ 📄 **🏬** & ➕1️⃣ 📄 **👩💻**, & 👫 💪 👽 🔖:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="23 28 36"
- {!> ../../../docs_src/generate_clients/tutorial002.py!}
- ```
+```Python hl_lines="23 28 36"
+{!> ../../docs_src/generate_clients/tutorial002.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="21 26 34"
- {!> ../../../docs_src/generate_clients/tutorial002_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
+
+```Python hl_lines="21 26 34"
+{!> ../../docs_src/generate_clients/tutorial002_py39.py!}
+```
+
+////
### 🏗 📕 👩💻 ⏮️ 🔖
@@ -186,17 +197,21 @@ FastAPI ⚙️ **😍 🆔** 🔠 *➡ 🛠️*, ⚫️ ⚙️ **🛠️ 🆔**
👆 💪 ⤴️ 🚶♀️ 👈 🛃 🔢 **FastAPI** `generate_unique_id_function` 🔢:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="8-9 12"
- {!> ../../../docs_src/generate_clients/tutorial003.py!}
- ```
+```Python hl_lines="8-9 12"
+{!> ../../docs_src/generate_clients/tutorial003.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="6-7 10"
- {!> ../../../docs_src/generate_clients/tutorial003_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
+
+```Python hl_lines="6-7 10"
+{!> ../../docs_src/generate_clients/tutorial003_py39.py!}
+```
+
+////
### 🏗 📕 👩💻 ⏮️ 🛃 🛠️ 🆔
@@ -219,7 +234,7 @@ FastAPI ⚙️ **😍 🆔** 🔠 *➡ 🛠️*, ⚫️ ⚙️ **🛠️ 🆔**
👥 💪 ⏬ 🗄 🎻 📁 `openapi.json` & ⤴️ 👥 💪 **❎ 👈 🔡 🔖** ⏮️ ✍ 💖 👉:
```Python
-{!../../../docs_src/generate_clients/tutorial004.py!}
+{!../../docs_src/generate_clients/tutorial004.py!}
```
⏮️ 👈, 🛠️ 🆔 🔜 📁 ⚪️➡️ 👜 💖 `items-get_items` `get_items`, 👈 🌌 👩💻 🚂 💪 🏗 🙅 👩🔬 📛.
diff --git a/docs/em/docs/advanced/index.md b/docs/em/docs/advanced/index.md
index 43bada6b4..48ef8e46d 100644
--- a/docs/em/docs/advanced/index.md
+++ b/docs/em/docs/advanced/index.md
@@ -6,10 +6,13 @@
⏭ 📄 👆 🔜 👀 🎏 🎛, 📳, & 🌖 ⚒.
-!!! tip
- ⏭ 📄 **🚫 🎯 "🏧"**.
+/// tip
- & ⚫️ 💪 👈 👆 ⚙️ 💼, ⚗ 1️⃣ 👫.
+⏭ 📄 **🚫 🎯 "🏧"**.
+
+ & ⚫️ 💪 👈 👆 ⚙️ 💼, ⚗ 1️⃣ 👫.
+
+///
## ✍ 🔰 🥇
diff --git a/docs/em/docs/advanced/middleware.md b/docs/em/docs/advanced/middleware.md
index b3e722ed0..23d2918d7 100644
--- a/docs/em/docs/advanced/middleware.md
+++ b/docs/em/docs/advanced/middleware.md
@@ -43,10 +43,13 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow")
**FastAPI** 🔌 📚 🛠️ ⚠ ⚙️ 💼, 👥 🔜 👀 ⏭ ❔ ⚙️ 👫.
-!!! note "📡 ℹ"
- ⏭ 🖼, 👆 💪 ⚙️ `from starlette.middleware.something import SomethingMiddleware`.
+/// note | "📡 ℹ"
- **FastAPI** 🚚 📚 🛠️ `fastapi.middleware` 🏪 👆, 👩💻. ✋️ 🌅 💪 🛠️ 👟 🔗 ⚪️➡️ 💃.
+⏭ 🖼, 👆 💪 ⚙️ `from starlette.middleware.something import SomethingMiddleware`.
+
+**FastAPI** 🚚 📚 🛠️ `fastapi.middleware` 🏪 👆, 👩💻. ✋️ 🌅 💪 🛠️ 👟 🔗 ⚪️➡️ 💃.
+
+///
## `HTTPSRedirectMiddleware`
@@ -55,7 +58,7 @@ 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!}
```
## `TrustedHostMiddleware`
@@ -63,7 +66,7 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow")
🛠️ 👈 🌐 📨 📨 ✔️ ☑ ⚒ `Host` 🎚, ✔ 💂♂ 🛡 🇺🇸🔍 🦠 🎚 👊.
```Python hl_lines="2 6-8"
-{!../../../docs_src/advanced_middleware/tutorial002.py!}
+{!../../docs_src/advanced_middleware/tutorial002.py!}
```
📄 ❌ 🐕🦺:
@@ -79,7 +82,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!}
```
📄 ❌ 🐕🦺:
@@ -92,7 +95,6 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow")
🖼:
-* 🔫
* Uvicorn `ProxyHeadersMiddleware`
* 🇸🇲
diff --git a/docs/em/docs/advanced/openapi-callbacks.md b/docs/em/docs/advanced/openapi-callbacks.md
index 3355d6071..f7b5e7ed9 100644
--- a/docs/em/docs/advanced/openapi-callbacks.md
+++ b/docs/em/docs/advanced/openapi-callbacks.md
@@ -32,11 +32,14 @@
👉 🍕 📶 😐, 🌅 📟 🎲 ⏪ 😰 👆:
```Python hl_lines="9-13 36-53"
-{!../../../docs_src/openapi_callbacks/tutorial001.py!}
+{!../../docs_src/openapi_callbacks/tutorial001.py!}
```
-!!! tip
- `callback_url` 🔢 🔢 ⚙️ Pydantic 📛 🆎.
+/// tip
+
+`callback_url` 🔢 🔢 ⚙️ Pydantic 📛 🆎.
+
+///
🕴 🆕 👜 `callbacks=messages_callback_router.routes` ❌ *➡ 🛠️ 👨🎨*. 👥 🔜 👀 ⚫️❔ 👈 ⏭.
@@ -61,10 +64,13 @@ httpx.post(callback_url, json={"description": "Invoice paid", "paid": True})
👉 🖼 🚫 🛠️ ⏲ ⚫️ (👈 💪 ⏸ 📟), 🕴 🧾 🍕.
-!!! tip
- ☑ ⏲ 🇺🇸🔍 📨.
+/// tip
- 🕐❔ 🛠️ ⏲ 👆, 👆 💪 ⚙️ 🕳 💖 🇸🇲 ⚖️ 📨.
+☑ ⏲ 🇺🇸🔍 📨.
+
+🕐❔ 🛠️ ⏲ 👆, 👆 💪 ⚙️ 🕳 💖 🇸🇲 ⚖️ 📨.
+
+///
## ✍ ⏲ 🧾 📟
@@ -74,17 +80,20 @@ httpx.post(callback_url, json={"description": "Invoice paid", "paid": True})
👥 🔜 ⚙️ 👈 🎏 💡 📄 ❔ *🔢 🛠️* 🔜 👀 💖... 🏗 *➡ 🛠️(Ⓜ)* 👈 🔢 🛠️ 🔜 🛠️ (🕐 👆 🛠️ 🔜 🤙).
-!!! tip
- 🕐❔ ✍ 📟 📄 ⏲, ⚫️ 💪 ⚠ 🌈 👈 👆 👈 *🔢 👩💻*. & 👈 👆 ⏳ 🛠️ *🔢 🛠️*, 🚫 *👆 🛠️*.
+/// tip
- 🍕 🛠️ 👉 ☝ 🎑 ( *🔢 👩💻*) 💪 ℹ 👆 💭 💖 ⚫️ 🌅 ⭐ 🌐❔ 🚮 🔢, Pydantic 🏷 💪, 📨, ♒️. 👈 *🔢 🛠️*.
+🕐❔ ✍ 📟 📄 ⏲, ⚫️ 💪 ⚠ 🌈 👈 👆 👈 *🔢 👩💻*. & 👈 👆 ⏳ 🛠️ *🔢 🛠️*, 🚫 *👆 🛠️*.
+
+🍕 🛠️ 👉 ☝ 🎑 ( *🔢 👩💻*) 💪 ℹ 👆 💭 💖 ⚫️ 🌅 ⭐ 🌐❔ 🚮 🔢, Pydantic 🏷 💪, 📨, ♒️. 👈 *🔢 🛠️*.
+
+///
### ✍ ⏲ `APIRouter`
🥇 ✍ 🆕 `APIRouter` 👈 🔜 🔌 1️⃣ ⚖️ 🌅 ⏲.
```Python hl_lines="3 25"
-{!../../../docs_src/openapi_callbacks/tutorial001.py!}
+{!../../docs_src/openapi_callbacks/tutorial001.py!}
```
### ✍ ⏲ *➡ 🛠️*
@@ -97,7 +106,7 @@ httpx.post(callback_url, json={"description": "Invoice paid", "paid": True})
* & ⚫️ 💪 ✔️ 📄 📨 ⚫️ 🔜 📨, ✅ `response_model=InvoiceEventReceived`.
```Python hl_lines="16-18 21-22 28-32"
-{!../../../docs_src/openapi_callbacks/tutorial001.py!}
+{!../../docs_src/openapi_callbacks/tutorial001.py!}
```
📤 2️⃣ 👑 🔺 ⚪️➡️ 😐 *➡ 🛠️*:
@@ -154,8 +163,11 @@ https://www.external.org/events/invoices/2expen51ve
}
```
-!!! tip
- 👀 ❔ ⏲ 📛 ⚙️ 🔌 📛 📨 🔢 🔢 `callback_url` (`https://www.external.org/events`) & 🧾 `id` ⚪️➡️ 🔘 🎻 💪 (`2expen51ve`).
+/// tip
+
+👀 ❔ ⏲ 📛 ⚙️ 🔌 📛 📨 🔢 🔢 `callback_url` (`https://www.external.org/events`) & 🧾 `id` ⚪️➡️ 🔘 🎻 💪 (`2expen51ve`).
+
+///
### 🚮 ⏲ 📻
@@ -164,11 +176,14 @@ 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!}
```
-!!! tip
- 👀 👈 👆 🚫 🚶♀️ 📻 ⚫️ (`invoices_callback_router`) `callback=`, ✋️ 🔢 `.routes`, `invoices_callback_router.routes`.
+/// tip
+
+👀 👈 👆 🚫 🚶♀️ 📻 ⚫️ (`invoices_callback_router`) `callback=`, ✋️ 🔢 `.routes`, `invoices_callback_router.routes`.
+
+///
### ✅ 🩺
diff --git a/docs/em/docs/advanced/path-operation-advanced-configuration.md b/docs/em/docs/advanced/path-operation-advanced-configuration.md
index 3dc5ac536..805bfdf30 100644
--- a/docs/em/docs/advanced/path-operation-advanced-configuration.md
+++ b/docs/em/docs/advanced/path-operation-advanced-configuration.md
@@ -2,15 +2,18 @@
## 🗄 {
-!!! warning
- 🚥 👆 🚫 "🕴" 🗄, 👆 🎲 🚫 💪 👉.
+/// warning
+
+🚥 👆 🚫 "🕴" 🗄, 👆 🎲 🚫 💪 👉.
+
+///
👆 💪 ⚒ 🗄 `operationId` ⚙️ 👆 *➡ 🛠️* ⏮️ 🔢 `operation_id`.
👆 🔜 ✔️ ⚒ 💭 👈 ⚫️ 😍 🔠 🛠️.
```Python hl_lines="6"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial001.py!}
+{!../../docs_src/path_operation_advanced_configuration/tutorial001.py!}
```
### ⚙️ *➡ 🛠️ 🔢* 📛 {
@@ -20,23 +23,29 @@
👆 🔜 ⚫️ ⏮️ ❎ 🌐 👆 *➡ 🛠️*.
```Python hl_lines="2 12-21 24"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!}
+{!../../docs_src/path_operation_advanced_configuration/tutorial002.py!}
```
-!!! tip
- 🚥 👆 ❎ 🤙 `app.openapi()`, 👆 🔜 ℹ `operationId`Ⓜ ⏭ 👈.
+/// tip
-!!! warning
- 🚥 👆 👉, 👆 ✔️ ⚒ 💭 🔠 1️⃣ 👆 *➡ 🛠️ 🔢* ✔️ 😍 📛.
+🚥 👆 ❎ 🤙 `app.openapi()`, 👆 🔜 ℹ `operationId`Ⓜ ⏭ 👈.
- 🚥 👫 🎏 🕹 (🐍 📁).
+///
+
+/// warning
+
+🚥 👆 👉, 👆 ✔️ ⚒ 💭 🔠 1️⃣ 👆 *➡ 🛠️ 🔢* ✔️ 😍 📛.
+
+🚥 👫 🎏 🕹 (🐍 📁).
+
+///
## 🚫 ⚪️➡️ 🗄
🚫 *➡ 🛠️* ⚪️➡️ 🏗 🗄 🔗 (& ➡️, ⚪️➡️ 🏧 🧾 ⚙️), ⚙️ 🔢 `include_in_schema` & ⚒ ⚫️ `False`:
```Python hl_lines="6"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial003.py!}
+{!../../docs_src/path_operation_advanced_configuration/tutorial003.py!}
```
## 🏧 📛 ⚪️➡️ #️⃣
@@ -48,7 +57,7 @@
⚫️ 🏆 🚫 🎦 🆙 🧾, ✋️ 🎏 🧰 (✅ 🐉) 🔜 💪 ⚙️ 🎂.
```Python hl_lines="19-29"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial004.py!}
+{!../../docs_src/path_operation_advanced_configuration/tutorial004.py!}
```
## 🌖 📨
@@ -65,8 +74,11 @@
🕐❔ 👆 📣 *➡ 🛠️* 👆 🈸, **FastAPI** 🔁 🏗 🔗 🗃 🔃 👈 *➡ 🛠️* 🔌 🗄 🔗.
-!!! note "📡 ℹ"
- 🗄 🔧 ⚫️ 🤙 🛠️ 🎚.
+/// note | "📡 ℹ"
+
+🗄 🔧 ⚫️ 🤙 🛠️ 🎚.
+
+///
⚫️ ✔️ 🌐 ℹ 🔃 *➡ 🛠️* & ⚙️ 🏗 🏧 🧾.
@@ -74,10 +86,13 @@
👉 *➡ 🛠️*-🎯 🗄 🔗 🛎 🏗 🔁 **FastAPI**, ✋️ 👆 💪 ↔ ⚫️.
-!!! tip
- 👉 🔅 🎚 ↔ ☝.
+/// tip
- 🚥 👆 🕴 💪 📣 🌖 📨, 🌅 🏪 🌌 ⚫️ ⏮️ [🌖 📨 🗄](additional-responses.md){.internal-link target=_blank}.
+👉 🔅 🎚 ↔ ☝.
+
+🚥 👆 🕴 💪 📣 🌖 📨, 🌅 🏪 🌌 ⚫️ ⏮️ [🌖 📨 🗄](additional-responses.md){.internal-link target=_blank}.
+
+///
👆 💪 ↔ 🗄 🔗 *➡ 🛠️* ⚙️ 🔢 `openapi_extra`.
@@ -86,7 +101,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!}
```
🚥 👆 📂 🏧 🛠️ 🩺, 👆 ↔ 🔜 🎦 🆙 🔝 🎯 *➡ 🛠️*.
@@ -135,7 +150,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!}
```
👉 🖼, 👥 🚫 📣 🙆 Pydantic 🏷. 👐, 📨 💪 🚫 🎻 🎻, ⚫️ ✍ 🔗 `bytes`, & 🔢 `magic_data_reader()` 🔜 🈚 🎻 ⚫️ 🌌.
@@ -151,7 +166,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!}
```
👐, 👐 👥 🚫 ⚙️ 🔢 🛠️ 🛠️, 👥 ⚙️ Pydantic 🏷 ❎ 🏗 🎻 🔗 💽 👈 👥 💚 📨 📁.
@@ -161,10 +176,13 @@
& ⤴️ 👆 📟, 👥 🎻 👈 📁 🎚 🔗, & ⤴️ 👥 🔄 ⚙️ 🎏 Pydantic 🏷 ✔ 📁 🎚:
```Python hl_lines="26-33"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial007.py!}
+{!../../docs_src/path_operation_advanced_configuration/tutorial007.py!}
```
-!!! tip
- 📥 👥 🏤-⚙️ 🎏 Pydantic 🏷.
+/// tip
- ✋️ 🎏 🌌, 👥 💪 ✔️ ✔ ⚫️ 🎏 🌌.
+📥 👥 🏤-⚙️ 🎏 Pydantic 🏷.
+
+✋️ 🎏 🌌, 👥 💪 ✔️ ✔ ⚫️ 🎏 🌌.
+
+///
diff --git a/docs/em/docs/advanced/response-change-status-code.md b/docs/em/docs/advanced/response-change-status-code.md
index 156efcc16..7f2e8c157 100644
--- a/docs/em/docs/advanced/response-change-status-code.md
+++ b/docs/em/docs/advanced/response-change-status-code.md
@@ -21,7 +21,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!}
```
& ⤴️ 👆 💪 📨 🙆 🎚 👆 💪, 👆 🛎 🔜 ( `dict`, 💽 🏷, ♒️).
diff --git a/docs/em/docs/advanced/response-cookies.md b/docs/em/docs/advanced/response-cookies.md
index 23fffe1dd..6b9e9a4d9 100644
--- a/docs/em/docs/advanced/response-cookies.md
+++ b/docs/em/docs/advanced/response-cookies.md
@@ -7,7 +7,7 @@
& ⤴️ 👆 💪 ⚒ 🍪 👈 *🔀* 📨 🎚.
```Python hl_lines="1 8-9"
-{!../../../docs_src/response_cookies/tutorial002.py!}
+{!../../docs_src/response_cookies/tutorial002.py!}
```
& ⤴️ 👆 💪 📨 🙆 🎚 👆 💪, 👆 🛎 🔜 ( `dict`, 💽 🏷, ♒️).
@@ -27,23 +27,29 @@
⤴️ ⚒ 🍪 ⚫️, & ⤴️ 📨 ⚫️:
```Python hl_lines="10-12"
-{!../../../docs_src/response_cookies/tutorial001.py!}
+{!../../docs_src/response_cookies/tutorial001.py!}
```
-!!! tip
- ✔️ 🤯 👈 🚥 👆 📨 📨 🔗 ↩️ ⚙️ `Response` 🔢, FastAPI 🔜 📨 ⚫️ 🔗.
+/// tip
- , 👆 🔜 ✔️ ⚒ 💭 👆 💽 ☑ 🆎. 🤶 Ⓜ. ⚫️ 🔗 ⏮️ 🎻, 🚥 👆 🛬 `JSONResponse`.
+✔️ 🤯 👈 🚥 👆 📨 📨 🔗 ↩️ ⚙️ `Response` 🔢, FastAPI 🔜 📨 ⚫️ 🔗.
- & 👈 👆 🚫 📨 🙆 📊 👈 🔜 ✔️ ⛽ `response_model`.
+, 👆 🔜 ✔️ ⚒ 💭 👆 💽 ☑ 🆎. 🤶 Ⓜ. ⚫️ 🔗 ⏮️ 🎻, 🚥 👆 🛬 `JSONResponse`.
+
+ & 👈 👆 🚫 📨 🙆 📊 👈 🔜 ✔️ ⛽ `response_model`.
+
+///
### 🌅 ℹ
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette.responses import Response` ⚖️ `from starlette.responses import JSONResponse`.
+/// note | "📡 ℹ"
- **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃.
+👆 💪 ⚙️ `from starlette.responses import Response` ⚖️ `from starlette.responses import JSONResponse`.
- & `Response` 💪 ⚙️ 🛎 ⚒ 🎚 & 🍪, **FastAPI** 🚚 ⚫️ `fastapi.Response`.
+**FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃.
+
+ & `Response` 💪 ⚙️ 🛎 ⚒ 🎚 & 🍪, **FastAPI** 🚚 ⚫️ `fastapi.Response`.
+
+///
👀 🌐 💪 🔢 & 🎛, ✅ 🧾 💃.
diff --git a/docs/em/docs/advanced/response-directly.md b/docs/em/docs/advanced/response-directly.md
index ba09734fb..dcffc56c6 100644
--- a/docs/em/docs/advanced/response-directly.md
+++ b/docs/em/docs/advanced/response-directly.md
@@ -14,8 +14,11 @@
👐, 👆 💪 📨 🙆 `Response` ⚖️ 🙆 🎧-🎓 ⚫️.
-!!! tip
- `JSONResponse` ⚫️ 🎧-🎓 `Response`.
+/// tip
+
+`JSONResponse` ⚫️ 🎧-🎓 `Response`.
+
+///
& 🕐❔ 👆 📨 `Response`, **FastAPI** 🔜 🚶♀️ ⚫️ 🔗.
@@ -32,13 +35,16 @@
📚 💼, 👆 💪 ⚙️ `jsonable_encoder` 🗜 👆 📊 ⏭ 🚶♀️ ⚫️ 📨:
```Python hl_lines="6-7 21-22"
-{!../../../docs_src/response_directly/tutorial001.py!}
+{!../../docs_src/response_directly/tutorial001.py!}
```
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette.responses import JSONResponse`.
+/// note | "📡 ℹ"
- **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃.
+👆 💪 ⚙️ `from starlette.responses import JSONResponse`.
+
+**FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃.
+
+///
## 🛬 🛃 `Response`
@@ -51,7 +57,7 @@
👆 💪 🚮 👆 📂 🎚 🎻, 🚮 ⚫️ `Response`, & 📨 ⚫️:
```Python hl_lines="1 18"
-{!../../../docs_src/response_directly/tutorial002.py!}
+{!../../docs_src/response_directly/tutorial002.py!}
```
## 🗒
diff --git a/docs/em/docs/advanced/response-headers.md b/docs/em/docs/advanced/response-headers.md
index de798982a..cbbbae237 100644
--- a/docs/em/docs/advanced/response-headers.md
+++ b/docs/em/docs/advanced/response-headers.md
@@ -7,7 +7,7 @@
& ⤴️ 👆 💪 ⚒ 🎚 👈 *🔀* 📨 🎚.
```Python hl_lines="1 7-8"
-{!../../../docs_src/response_headers/tutorial002.py!}
+{!../../docs_src/response_headers/tutorial002.py!}
```
& ⤴️ 👆 💪 📨 🙆 🎚 👆 💪, 👆 🛎 🔜 ( `dict`, 💽 🏷, ♒️).
@@ -25,15 +25,18 @@
✍ 📨 🔬 [📨 📨 🔗](response-directly.md){.internal-link target=_blank} & 🚶♀️ 🎚 🌖 🔢:
```Python hl_lines="10-12"
-{!../../../docs_src/response_headers/tutorial001.py!}
+{!../../docs_src/response_headers/tutorial001.py!}
```
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette.responses import Response` ⚖️ `from starlette.responses import JSONResponse`.
+/// note | "📡 ℹ"
- **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃.
+👆 💪 ⚙️ `from starlette.responses import Response` ⚖️ `from starlette.responses import JSONResponse`.
- & `Response` 💪 ⚙️ 🛎 ⚒ 🎚 & 🍪, **FastAPI** 🚚 ⚫️ `fastapi.Response`.
+**FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃.
+
+ & `Response` 💪 ⚙️ 🛎 ⚒ 🎚 & 🍪, **FastAPI** 🚚 ⚫️ `fastapi.Response`.
+
+///
## 🛃 🎚
diff --git a/docs/em/docs/advanced/security/http-basic-auth.md b/docs/em/docs/advanced/security/http-basic-auth.md
index 33470a726..e6fe3e32c 100644
--- a/docs/em/docs/advanced/security/http-basic-auth.md
+++ b/docs/em/docs/advanced/security/http-basic-auth.md
@@ -21,7 +21,7 @@
* ⚫️ 🔌 `username` & `password` 📨.
```Python hl_lines="2 6 10"
-{!../../../docs_src/security/tutorial006.py!}
+{!../../docs_src/security/tutorial006.py!}
```
🕐❔ 👆 🔄 📂 📛 🥇 🕰 (⚖️ 🖊 "🛠️" 🔼 🩺) 🖥 🔜 💭 👆 👆 🆔 & 🔐:
@@ -43,7 +43,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!}
```
👉 🔜 🎏:
@@ -109,5 +109,5 @@ 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!}
```
diff --git a/docs/em/docs/advanced/security/index.md b/docs/em/docs/advanced/security/index.md
index 10291338e..5cdc47505 100644
--- a/docs/em/docs/advanced/security/index.md
+++ b/docs/em/docs/advanced/security/index.md
@@ -4,10 +4,13 @@
📤 ➕ ⚒ 🍵 💂♂ ↖️ ⚪️➡️ 🕐 📔 [🔰 - 👩💻 🦮: 💂♂](../../tutorial/security/index.md){.internal-link target=_blank}.
-!!! tip
- ⏭ 📄 **🚫 🎯 "🏧"**.
+/// tip
- & ⚫️ 💪 👈 👆 ⚙️ 💼, ⚗ 1️⃣ 👫.
+⏭ 📄 **🚫 🎯 "🏧"**.
+
+ & ⚫️ 💪 👈 👆 ⚙️ 💼, ⚗ 1️⃣ 👫.
+
+///
## ✍ 🔰 🥇
diff --git a/docs/em/docs/advanced/security/oauth2-scopes.md b/docs/em/docs/advanced/security/oauth2-scopes.md
index d82fe152b..661be034e 100644
--- a/docs/em/docs/advanced/security/oauth2-scopes.md
+++ b/docs/em/docs/advanced/security/oauth2-scopes.md
@@ -10,18 +10,21 @@ Oauth2️⃣ ⏮️ ↔ 🛠️ ⚙️ 📚 🦏 🤝 🐕🦺, 💖 👱📔
👉 📄 👆 🔜 👀 ❔ 🛠️ 🤝 & ✔ ⏮️ 🎏 Oauth2️⃣ ⏮️ ↔ 👆 **FastAPI** 🈸.
-!!! warning
- 👉 🌅 ⚖️ 🌘 🏧 📄. 🚥 👆 ▶️, 👆 💪 🚶 ⚫️.
+/// warning
- 👆 🚫 🎯 💪 Oauth2️⃣ ↔, & 👆 💪 🍵 🤝 & ✔ 👐 👆 💚.
+👉 🌅 ⚖️ 🌘 🏧 📄. 🚥 👆 ▶️, 👆 💪 🚶 ⚫️.
- ✋️ Oauth2️⃣ ⏮️ ↔ 💪 🎆 🛠️ 🔘 👆 🛠️ (⏮️ 🗄) & 👆 🛠️ 🩺.
+👆 🚫 🎯 💪 Oauth2️⃣ ↔, & 👆 💪 🍵 🤝 & ✔ 👐 👆 💚.
- 👐, 👆 🛠️ 📚 ↔, ⚖️ 🙆 🎏 💂♂/✔ 📄, 👐 👆 💪, 👆 📟.
+✋️ Oauth2️⃣ ⏮️ ↔ 💪 🎆 🛠️ 🔘 👆 🛠️ (⏮️ 🗄) & 👆 🛠️ 🩺.
- 📚 💼, Oauth2️⃣ ⏮️ ↔ 💪 👹.
+👐, 👆 🛠️ 📚 ↔, ⚖️ 🙆 🎏 💂♂/✔ 📄, 👐 👆 💪, 👆 📟.
- ✋️ 🚥 👆 💭 👆 💪 ⚫️, ⚖️ 👆 😟, 🚧 👂.
+📚 💼, Oauth2️⃣ ⏮️ ↔ 💪 👹.
+
+✋️ 🚥 👆 💭 👆 💪 ⚫️, ⚖️ 👆 😟, 🚧 👂.
+
+///
## Oauth2️⃣ ↔ & 🗄
@@ -43,21 +46,24 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀.
* `instagram_basic` ⚙️ 👱📔 / 👱📔.
* `https://www.googleapis.com/auth/drive` ⚙️ 🇺🇸🔍.
-!!! info
- Oauth2️⃣ "↔" 🎻 👈 📣 🎯 ✔ ✔.
+/// info
- ⚫️ 🚫 🤔 🚥 ⚫️ ✔️ 🎏 🦹 💖 `:` ⚖️ 🚥 ⚫️ 📛.
+Oauth2️⃣ "↔" 🎻 👈 📣 🎯 ✔ ✔.
- 👈 ℹ 🛠️ 🎯.
+⚫️ 🚫 🤔 🚥 ⚫️ ✔️ 🎏 🦹 💖 `:` ⚖️ 🚥 ⚫️ 📛.
- Oauth2️⃣ 👫 🎻.
+👈 ℹ 🛠️ 🎯.
+
+Oauth2️⃣ 👫 🎻.
+
+///
## 🌐 🎑
🥇, ➡️ 🔜 👀 🍕 👈 🔀 ⚪️➡️ 🖼 👑 **🔰 - 👩💻 🦮** [Oauth2️⃣ ⏮️ 🔐 (& 🔁), 📨 ⏮️ 🥙 🤝](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. 🔜 ⚙️ Oauth2️⃣ ↔:
```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155"
-{!../../../docs_src/security/tutorial005.py!}
+{!../../docs_src/security/tutorial005.py!}
```
🔜 ➡️ 📄 👈 🔀 🔁 🔁.
@@ -69,7 +75,7 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀.
`scopes` 🔢 📨 `dict` ⏮️ 🔠 ↔ 🔑 & 📛 💲:
```Python hl_lines="62-65"
-{!../../../docs_src/security/tutorial005.py!}
+{!../../docs_src/security/tutorial005.py!}
```
↩️ 👥 🔜 📣 📚 ↔, 👫 🔜 🎦 🆙 🛠️ 🩺 🕐❔ 👆 🕹-/✔.
@@ -88,13 +94,16 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀.
& 👥 📨 ↔ 🍕 🥙 🤝.
-!!! danger
- 🦁, 📥 👥 ❎ ↔ 📨 🔗 🤝.
+/// danger
- ✋️ 👆 🈸, 💂♂, 👆 🔜 ⚒ 💭 👆 🕴 🚮 ↔ 👈 👩💻 🤙 💪 ✔️, ⚖️ 🕐 👆 ✔️ 🔁.
+🦁, 📥 👥 ❎ ↔ 📨 🔗 🤝.
+
+✋️ 👆 🈸, 💂♂, 👆 🔜 ⚒ 💭 👆 🕴 🚮 ↔ 👈 👩💻 🤙 💪 ✔️, ⚖️ 🕐 👆 ✔️ 🔁.
+
+///
```Python hl_lines="155"
-{!../../../docs_src/security/tutorial005.py!}
+{!../../docs_src/security/tutorial005.py!}
```
## 📣 ↔ *➡ 🛠️* & 🔗
@@ -113,21 +122,27 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀.
👉 💼, ⚫️ 🚚 ↔ `me` (⚫️ 💪 🚚 🌅 🌘 1️⃣ ↔).
-!!! note
- 👆 🚫 🎯 💪 🚮 🎏 ↔ 🎏 🥉.
+/// note
- 👥 🔨 ⚫️ 📥 🎦 ❔ **FastAPI** 🍵 ↔ 📣 🎏 🎚.
+👆 🚫 🎯 💪 🚮 🎏 ↔ 🎏 🥉.
+
+👥 🔨 ⚫️ 📥 🎦 ❔ **FastAPI** 🍵 ↔ 📣 🎏 🎚.
+
+///
```Python hl_lines="4 139 168"
-{!../../../docs_src/security/tutorial005.py!}
+{!../../docs_src/security/tutorial005.py!}
```
-!!! info "📡 ℹ"
- `Security` 🤙 🏿 `Depends`, & ⚫️ ✔️ 1️⃣ ➕ 🔢 👈 👥 🔜 👀 ⏪.
+/// info | "📡 ℹ"
- ✋️ ⚙️ `Security` ↩️ `Depends`, **FastAPI** 🔜 💭 👈 ⚫️ 💪 📣 💂♂ ↔, ⚙️ 👫 🔘, & 📄 🛠️ ⏮️ 🗄.
+`Security` 🤙 🏿 `Depends`, & ⚫️ ✔️ 1️⃣ ➕ 🔢 👈 👥 🔜 👀 ⏪.
- ✋️ 🕐❔ 👆 🗄 `Query`, `Path`, `Depends`, `Security` & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓.
+✋️ ⚙️ `Security` ↩️ `Depends`, **FastAPI** 🔜 💭 👈 ⚫️ 💪 📣 💂♂ ↔, ⚙️ 👫 🔘, & 📄 🛠️ ⏮️ 🗄.
+
+✋️ 🕐❔ 👆 🗄 `Query`, `Path`, `Depends`, `Security` & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓.
+
+///
## ⚙️ `SecurityScopes`
@@ -144,7 +159,7 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀.
👉 `SecurityScopes` 🎓 🎏 `Request` (`Request` ⚙️ 🤚 📨 🎚 🔗).
```Python hl_lines="8 105"
-{!../../../docs_src/security/tutorial005.py!}
+{!../../docs_src/security/tutorial005.py!}
```
## ⚙️ `scopes`
@@ -160,7 +175,7 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀.
👉 ⚠, 👥 🔌 ↔ 🚚 (🚥 🙆) 🎻 👽 🚀 (⚙️ `scope_str`). 👥 🚮 👈 🎻 ⚗ ↔ `WWW-Authenticate` 🎚 (👉 🍕 🔌).
```Python hl_lines="105 107-115"
-{!../../../docs_src/security/tutorial005.py!}
+{!../../docs_src/security/tutorial005.py!}
```
## ✔ `username` & 💽 💠
@@ -178,7 +193,7 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀.
👥 ✔ 👈 👥 ✔️ 👩💻 ⏮️ 👈 🆔, & 🚥 🚫, 👥 🤚 👈 🎏 ⚠ 👥 ✍ ⏭.
```Python hl_lines="46 116-127"
-{!../../../docs_src/security/tutorial005.py!}
+{!../../docs_src/security/tutorial005.py!}
```
## ✔ `scopes`
@@ -188,7 +203,7 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀.
👉, 👥 ⚙️ `security_scopes.scopes`, 👈 🔌 `list` ⏮️ 🌐 👫 ↔ `str`.
```Python hl_lines="128-134"
-{!../../../docs_src/security/tutorial005.py!}
+{!../../docs_src/security/tutorial005.py!}
```
## 🔗 🌲 & ↔
@@ -216,10 +231,13 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀.
* `security_scopes.scopes` 🔜 🔌 `["me"]` *➡ 🛠️* `read_users_me`, ↩️ ⚫️ 📣 🔗 `get_current_active_user`.
* `security_scopes.scopes` 🔜 🔌 `[]` (🕳) *➡ 🛠️* `read_system_status`, ↩️ ⚫️ 🚫 📣 🙆 `Security` ⏮️ `scopes`, & 🚮 🔗, `get_current_user`, 🚫 📣 🙆 `scope` 👯♂️.
-!!! tip
- ⚠ & "🎱" 👜 📥 👈 `get_current_user` 🔜 ✔️ 🎏 📇 `scopes` ✅ 🔠 *➡ 🛠️*.
+/// tip
- 🌐 ⚓️ 🔛 `scopes` 📣 🔠 *➡ 🛠️* & 🔠 🔗 🔗 🌲 👈 🎯 *➡ 🛠️*.
+⚠ & "🎱" 👜 📥 👈 `get_current_user` 🔜 ✔️ 🎏 📇 `scopes` ✅ 🔠 *➡ 🛠️*.
+
+🌐 ⚓️ 🔛 `scopes` 📣 🔠 *➡ 🛠️* & 🔠 🔗 🔗 🌲 👈 🎯 *➡ 🛠️*.
+
+///
## 🌖 ℹ 🔃 `SecurityScopes`
@@ -257,10 +275,13 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀.
🏆 🔐 📟 💧, ✋️ 🌖 🏗 🛠️ ⚫️ 🚚 🌅 📶. ⚫️ 🌅 🏗, 📚 🐕🦺 🔚 🆙 ✔ 🔑 💧.
-!!! note
- ⚫️ ⚠ 👈 🔠 🤝 🐕🦺 📛 👫 💧 🎏 🌌, ⚒ ⚫️ 🍕 👫 🏷.
+/// note
- ✋️ 🔚, 👫 🛠️ 🎏 Oauth2️⃣ 🐩.
+⚫️ ⚠ 👈 🔠 🤝 🐕🦺 📛 👫 💧 🎏 🌌, ⚒ ⚫️ 🍕 👫 🏷.
+
+✋️ 🔚, 👫 🛠️ 🎏 Oauth2️⃣ 🐩.
+
+///
**FastAPI** 🔌 🚙 🌐 👫 Oauth2️⃣ 🤝 💧 `fastapi.security.oauth2`.
diff --git a/docs/em/docs/advanced/settings.md b/docs/em/docs/advanced/settings.md
index c17212023..59fb71d73 100644
--- a/docs/em/docs/advanced/settings.md
+++ b/docs/em/docs/advanced/settings.md
@@ -8,44 +8,51 @@
## 🌐 🔢
-!!! tip
- 🚥 👆 ⏪ 💭 ⚫️❔ "🌐 🔢" & ❔ ⚙️ 👫, 💭 🆓 🚶 ⏭ 📄 🔛.
+/// tip
+
+🚥 👆 ⏪ 💭 ⚫️❔ "🌐 🔢" & ❔ ⚙️ 👫, 💭 🆓 🚶 ⏭ 📄 🔛.
+
+///
🌐 🔢 (💭 "🇨🇻 {") 🔢 👈 🖖 🏞 🐍 📟, 🏃♂ ⚙️, & 💪 ✍ 👆 🐍 📟 (⚖️ 🎏 📋 👍).
👆 💪 ✍ & ⚙️ 🌐 🔢 🐚, 🍵 💆♂ 🐍:
-=== "💾, 🇸🇻, 🚪 🎉"
+//// tab | 💾, 🇸🇻, 🚪 🎉
-
-!!! info
- 🌹 🖼 👯 🍏. 👶
+/// info
+
+🌹 🖼 👯 🍏. 👶
+
+///
---
@@ -199,8 +205,11 @@ def results():
📤 🚫 🌅 💬 ⚖️ 😏 🌅 🕰 💸 ⌛ 👶 🚪 ⏲. 👶
-!!! info
- 🌹 🖼 👯 🍏. 👶
+/// info
+
+🌹 🖼 👯 🍏. 👶
+
+///
---
@@ -392,12 +401,15 @@ async def read_burgers():
## 📶 📡 ℹ
-!!! warning
- 👆 💪 🎲 🚶 👉.
+/// warning
- 👉 📶 📡 ℹ ❔ **FastAPI** 👷 🔘.
+👆 💪 🎲 🚶 👉.
- 🚥 👆 ✔️ 📡 💡 (🈶-🏋, 🧵, 🍫, ♒️.) & 😟 🔃 ❔ FastAPI 🍵 `async def` 🆚 😐 `def`, 🚶 ⤴️.
+👉 📶 📡 ℹ ❔ **FastAPI** 👷 🔘.
+
+🚥 👆 ✔️ 📡 💡 (🈶-🏋, 🧵, 🍫, ♒️.) & 😟 🔃 ❔ FastAPI 🍵 `async def` 🆚 😐 `def`, 🚶 ⤴️.
+
+///
### ➡ 🛠️ 🔢
diff --git a/docs/em/docs/contributing.md b/docs/em/docs/contributing.md
index 08561d8f8..3ac1afda4 100644
--- a/docs/em/docs/contributing.md
+++ b/docs/em/docs/contributing.md
@@ -24,63 +24,73 @@ $ python -m venv env
🔓 🆕 🌐 ⏮️:
-=== "💾, 🇸🇻"
+//// tab | 💾, 🇸🇻
- email_validator - 📧 🔬.
+* email-validator - 📧 🔬.
⚙️ 💃:
diff --git a/docs/em/docs/python-types.md b/docs/em/docs/python-types.md
index b3026917a..d2af23bb9 100644
--- a/docs/em/docs/python-types.md
+++ b/docs/em/docs/python-types.md
@@ -12,15 +12,18 @@
✋️ 🚥 👆 🙅 ⚙️ **FastAPI**, 👆 🔜 💰 ⚪️➡️ 🏫 🍖 🔃 👫.
-!!! note
- 🚥 👆 🐍 🕴, & 👆 ⏪ 💭 🌐 🔃 🆎 🔑, 🚶 ⏭ 📃.
+/// note
+
+🚥 👆 🐍 🕴, & 👆 ⏪ 💭 🌐 🔃 🆎 🔑, 🚶 ⏭ 📃.
+
+///
## 🎯
➡️ ▶️ ⏮️ 🙅 🖼:
```Python
-{!../../../docs_src/python_types/tutorial001.py!}
+{!../../docs_src/python_types/tutorial001.py!}
```
🤙 👉 📋 🔢:
@@ -36,7 +39,7 @@ John Doe
* 🔢 👫 ⏮️ 🚀 🖕.
```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial001.py!}
+{!../../docs_src/python_types/tutorial001.py!}
```
### ✍ ⚫️
@@ -80,7 +83,7 @@ John Doe
👈 "🆎 🔑":
```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial002.py!}
+{!../../docs_src/python_types/tutorial002.py!}
```
👈 🚫 🎏 📣 🔢 💲 💖 🔜 ⏮️:
@@ -110,7 +113,7 @@ John Doe
✅ 👉 🔢, ⚫️ ⏪ ✔️ 🆎 🔑:
```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial003.py!}
+{!../../docs_src/python_types/tutorial003.py!}
```
↩️ 👨🎨 💭 🆎 🔢, 👆 🚫 🕴 🤚 🛠️, 👆 🤚 ❌ ✅:
@@ -120,7 +123,7 @@ John Doe
🔜 👆 💭 👈 👆 ✔️ 🔧 ⚫️, 🗜 `age` 🎻 ⏮️ `str(age)`:
```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial004.py!}
+{!../../docs_src/python_types/tutorial004.py!}
```
## 📣 🆎
@@ -141,7 +144,7 @@ John Doe
* `bytes`
```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial005.py!}
+{!../../docs_src/python_types/tutorial005.py!}
```
### 💊 🆎 ⏮️ 🆎 🔢
@@ -164,45 +167,55 @@ John Doe
🖼, ➡️ 🔬 🔢 `list` `str`.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ⚪️➡️ `typing`, 🗄 `List` (⏮️ 🔠 `L`):
+⚪️➡️ `typing`, 🗄 `List` (⏮️ 🔠 `L`):
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial006.py!}
- ```
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial006.py!}
+```
- 📣 🔢, ⏮️ 🎏 ❤ (`:`) ❕.
+📣 🔢, ⏮️ 🎏 ❤ (`:`) ❕.
- 🆎, 🚮 `List` 👈 👆 🗄 ⚪️➡️ `typing`.
+🆎, 🚮 `List` 👈 👆 🗄 ⚪️➡️ `typing`.
- 📇 🆎 👈 🔌 🔗 🆎, 👆 🚮 👫 ⬜ 🗜:
+📇 🆎 👈 🔌 🔗 🆎, 👆 🚮 👫 ⬜ 🗜:
- ```Python hl_lines="4"
- {!> ../../../docs_src/python_types/tutorial006.py!}
- ```
+```Python hl_lines="4"
+{!> ../../docs_src/python_types/tutorial006.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- 📣 🔢, ⏮️ 🎏 ❤ (`:`) ❕.
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
- 🆎, 🚮 `list`.
+📣 🔢, ⏮️ 🎏 ❤ (`:`) ❕.
- 📇 🆎 👈 🔌 🔗 🆎, 👆 🚮 👫 ⬜ 🗜:
+🆎, 🚮 `list`.
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial006_py39.py!}
- ```
+📇 🆎 👈 🔌 🔗 🆎, 👆 🚮 👫 ⬜ 🗜:
-!!! info
- 👈 🔗 🆎 ⬜ 🗜 🤙 "🆎 🔢".
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial006_py39.py!}
+```
- 👉 💼, `str` 🆎 🔢 🚶♀️ `List` (⚖️ `list` 🐍 3️⃣.9️⃣ & 🔛).
+////
+
+/// info
+
+👈 🔗 🆎 ⬜ 🗜 🤙 "🆎 🔢".
+
+👉 💼, `str` 🆎 🔢 🚶♀️ `List` (⚖️ `list` 🐍 3️⃣.9️⃣ & 🔛).
+
+///
👈 ⛓: "🔢 `items` `list`, & 🔠 🏬 👉 📇 `str`".
-!!! tip
- 🚥 👆 ⚙️ 🐍 3️⃣.9️⃣ ⚖️ 🔛, 👆 🚫 ✔️ 🗄 `List` ⚪️➡️ `typing`, 👆 💪 ⚙️ 🎏 🥔 `list` 🆎 ↩️.
+/// tip
+
+🚥 👆 ⚙️ 🐍 3️⃣.9️⃣ ⚖️ 🔛, 👆 🚫 ✔️ 🗄 `List` ⚪️➡️ `typing`, 👆 💪 ⚙️ 🎏 🥔 `list` 🆎 ↩️.
+
+///
🔨 👈, 👆 👨🎨 💪 🚚 🐕🦺 ⏪ 🏭 🏬 ⚪️➡️ 📇:
@@ -218,17 +231,21 @@ John Doe
👆 🔜 🎏 📣 `tuple`Ⓜ & `set`Ⓜ:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial007.py!}
- ```
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial007.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial007_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
+
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial007_py39.py!}
+```
+
+////
👉 ⛓:
@@ -243,17 +260,21 @@ John Doe
🥈 🆎 🔢 💲 `dict`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial008.py!}
- ```
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial008.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial008_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
+
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial008_py39.py!}
+```
+
+////
👉 ⛓:
@@ -269,17 +290,21 @@ John Doe
🐍 3️⃣.1️⃣0️⃣ 📤 **🎛 ❕** 🌐❔ 👆 💪 🚮 💪 🆎 👽 ⏸ ⏸ (`|`).
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial008b.py!}
- ```
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial008b.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial008b_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial008b_py310.py!}
+```
+
+////
👯♂️ 💼 👉 ⛓ 👈 `item` 💪 `int` ⚖️ `str`.
@@ -290,7 +315,7 @@ John Doe
🐍 3️⃣.6️⃣ & 🔛 (✅ 🐍 3️⃣.1️⃣0️⃣) 👆 💪 📣 ⚫️ 🏭 & ⚙️ `Optional` ⚪️➡️ `typing` 🕹.
```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009.py!}
+{!../../docs_src/python_types/tutorial009.py!}
```
⚙️ `Optional[str]` ↩️ `str` 🔜 ➡️ 👨🎨 ℹ 👆 🔍 ❌ 🌐❔ 👆 💪 🤔 👈 💲 🕧 `str`, 🕐❔ ⚫️ 💪 🤙 `None` 💁♂️.
@@ -299,23 +324,29 @@ John Doe
👉 ⛓ 👈 🐍 3️⃣.1️⃣0️⃣, 👆 💪 ⚙️ `Something | None`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial009.py!}
- ```
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial009.py!}
+```
-=== "🐍 3️⃣.6️⃣ & 🔛 - 🎛"
+////
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial009b.py!}
- ```
+//// tab | 🐍 3️⃣.6️⃣ & 🔛 - 🎛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial009b.py!}
+```
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial009_py310.py!}
- ```
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial009_py310.py!}
+```
+
+////
#### ⚙️ `Union` ⚖️ `Optional`
@@ -333,7 +364,7 @@ John Doe
🖼, ➡️ ✊ 👉 🔢:
```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009c.py!}
+{!../../docs_src/python_types/tutorial009c.py!}
```
🔢 `name` 🔬 `Optional[str]`, ✋️ ⚫️ **🚫 📦**, 👆 🚫🔜 🤙 🔢 🍵 🔢:
@@ -351,7 +382,7 @@ say_hi(name=None) # This works, None is valid 🎉
👍 📰, 🕐 👆 🔛 🐍 3️⃣.1️⃣0️⃣ 👆 🏆 🚫 ✔️ 😟 🔃 👈, 👆 🔜 💪 🎯 ⚙️ `|` 🔬 🇪🇺 🆎:
```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009c_py310.py!}
+{!../../docs_src/python_types/tutorial009c_py310.py!}
```
& ⤴️ 👆 🏆 🚫 ✔️ 😟 🔃 📛 💖 `Optional` & `Union`. 👶
@@ -360,47 +391,53 @@ say_hi(name=None) # This works, None is valid 🎉
👉 🆎 👈 ✊ 🆎 🔢 ⬜ 🗜 🤙 **💊 🆎** ⚖️ **💊**, 🖼:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- * `List`
- * `Tuple`
- * `Set`
- * `Dict`
- * `Union`
- * `Optional`
- * ...& 🎏.
+* `List`
+* `Tuple`
+* `Set`
+* `Dict`
+* `Union`
+* `Optional`
+* ...& 🎏.
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- 👆 💪 ⚙️ 🎏 💽 🆎 💊 (⏮️ ⬜ 🗜 & 🆎 🔘):
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
- * `list`
- * `tuple`
- * `set`
- * `dict`
+👆 💪 ⚙️ 🎏 💽 🆎 💊 (⏮️ ⬜ 🗜 & 🆎 🔘):
- & 🎏 ⏮️ 🐍 3️⃣.6️⃣, ⚪️➡️ `typing` 🕹:
+* `list`
+* `tuple`
+* `set`
+* `dict`
- * `Union`
- * `Optional`
- * ...& 🎏.
+ & 🎏 ⏮️ 🐍 3️⃣.6️⃣, ⚪️➡️ `typing` 🕹:
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+* `Union`
+* `Optional`
+* ...& 🎏.
- 👆 💪 ⚙️ 🎏 💽 🆎 💊 (⏮️ ⬜ 🗜 & 🆎 🔘):
+////
- * `list`
- * `tuple`
- * `set`
- * `dict`
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
- & 🎏 ⏮️ 🐍 3️⃣.6️⃣, ⚪️➡️ `typing` 🕹:
+👆 💪 ⚙️ 🎏 💽 🆎 💊 (⏮️ ⬜ 🗜 & 🆎 🔘):
- * `Union`
- * `Optional` (🎏 ⏮️ 🐍 3️⃣.6️⃣)
- * ...& 🎏.
+* `list`
+* `tuple`
+* `set`
+* `dict`
- 🐍 3️⃣.1️⃣0️⃣, 🎛 ⚙️ 💊 `Union` & `Optional`, 👆 💪 ⚙️ ⏸ ⏸ (`|`) 📣 🇪🇺 🆎.
+ & 🎏 ⏮️ 🐍 3️⃣.6️⃣, ⚪️➡️ `typing` 🕹:
+
+* `Union`
+* `Optional` (🎏 ⏮️ 🐍 3️⃣.6️⃣)
+* ...& 🎏.
+
+🐍 3️⃣.1️⃣0️⃣, 🎛 ⚙️ 💊 `Union` & `Optional`, 👆 💪 ⚙️ ⏸ ⏸ (`|`) 📣 🇪🇺 🆎.
+
+////
### 🎓 🆎
@@ -409,13 +446,13 @@ say_hi(name=None) # This works, None is valid 🎉
➡️ 💬 👆 ✔️ 🎓 `Person`, ⏮️ 📛:
```Python hl_lines="1-3"
-{!../../../docs_src/python_types/tutorial010.py!}
+{!../../docs_src/python_types/tutorial010.py!}
```
⤴️ 👆 💪 📣 🔢 🆎 `Person`:
```Python hl_lines="6"
-{!../../../docs_src/python_types/tutorial010.py!}
+{!../../docs_src/python_types/tutorial010.py!}
```
& ⤴️, 🔄, 👆 🤚 🌐 👨🎨 🐕🦺:
@@ -436,33 +473,45 @@ say_hi(name=None) # This works, None is valid 🎉
🖼 ⚪️➡️ 🛂 Pydantic 🩺:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python
- {!> ../../../docs_src/python_types/tutorial011.py!}
- ```
+```Python
+{!> ../../docs_src/python_types/tutorial011.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python
- {!> ../../../docs_src/python_types/tutorial011_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python
+{!> ../../docs_src/python_types/tutorial011_py39.py!}
+```
- ```Python
- {!> ../../../docs_src/python_types/tutorial011_py310.py!}
- ```
+////
-!!! info
- 💡 🌖 🔃 Pydantic, ✅ 🚮 🩺.
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python
+{!> ../../docs_src/python_types/tutorial011_py310.py!}
+```
+
+////
+
+/// info
+
+💡 🌖 🔃 Pydantic, ✅ 🚮 🩺.
+
+///
**FastAPI** 🌐 ⚓️ 🔛 Pydantic.
👆 🔜 👀 📚 🌅 🌐 👉 💡 [🔰 - 👩💻 🦮](tutorial/index.md){.internal-link target=_blank}.
-!!! tip
- Pydantic ✔️ 🎁 🎭 🕐❔ 👆 ⚙️ `Optional` ⚖️ `Union[Something, None]` 🍵 🔢 💲, 👆 💪 ✍ 🌅 🔃 ⚫️ Pydantic 🩺 🔃 ✔ 📦 🏑.
+/// tip
+
+Pydantic ✔️ 🎁 🎭 🕐❔ 👆 ⚙️ `Optional` ⚖️ `Union[Something, None]` 🍵 🔢 💲, 👆 💪 ✍ 🌅 🔃 ⚫️ Pydantic 🩺 🔃 ✔ 📦 🏑.
+
+///
## 🆎 🔑 **FastAPI**
@@ -486,5 +535,8 @@ say_hi(name=None) # This works, None is valid 🎉
⚠ 👜 👈 ⚙️ 🐩 🐍 🆎, 👁 🥉 (↩️ ❎ 🌖 🎓, 👨🎨, ♒️), **FastAPI** 🔜 📚 👷 👆.
-!!! info
- 🚥 👆 ⏪ 🚶 🔘 🌐 🔰 & 👟 🔙 👀 🌅 🔃 🆎, 👍 ℹ "🎮 🎼" ⚪️➡️ `mypy`.
+/// info
+
+🚥 👆 ⏪ 🚶 🔘 🌐 🔰 & 👟 🔙 👀 🌅 🔃 🆎, 👍 ℹ "🎮 🎼" ⚪️➡️ `mypy`.
+
+///
diff --git a/docs/em/docs/tutorial/background-tasks.md b/docs/em/docs/tutorial/background-tasks.md
index e28ead415..0f4585ebe 100644
--- a/docs/em/docs/tutorial/background-tasks.md
+++ b/docs/em/docs/tutorial/background-tasks.md
@@ -16,7 +16,7 @@
🥇, 🗄 `BackgroundTasks` & 🔬 🔢 👆 *➡ 🛠️ 🔢* ⏮️ 🆎 📄 `BackgroundTasks`:
```Python hl_lines="1 13"
-{!../../../docs_src/background_tasks/tutorial001.py!}
+{!../../docs_src/background_tasks/tutorial001.py!}
```
**FastAPI** 🔜 ✍ 🎚 🆎 `BackgroundTasks` 👆 & 🚶♀️ ⚫️ 👈 🔢.
@@ -34,7 +34,7 @@
& ✍ 🛠️ 🚫 ⚙️ `async` & `await`, 👥 🔬 🔢 ⏮️ 😐 `def`:
```Python hl_lines="6-9"
-{!../../../docs_src/background_tasks/tutorial001.py!}
+{!../../docs_src/background_tasks/tutorial001.py!}
```
## 🚮 🖥 📋
@@ -42,7 +42,7 @@
🔘 👆 *➡ 🛠️ 🔢*, 🚶♀️ 👆 📋 🔢 *🖥 📋* 🎚 ⏮️ 👩🔬 `.add_task()`:
```Python hl_lines="14"
-{!../../../docs_src/background_tasks/tutorial001.py!}
+{!../../docs_src/background_tasks/tutorial001.py!}
```
`.add_task()` 📨 ❌:
@@ -57,17 +57,21 @@
**FastAPI** 💭 ⚫️❔ 🔠 💼 & ❔ 🏤-⚙️ 🎏 🎚, 👈 🌐 🖥 📋 🔗 👯♂️ & 🏃 🖥 ⏮️:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="13 15 22 25"
- {!> ../../../docs_src/background_tasks/tutorial002.py!}
- ```
+```Python hl_lines="13 15 22 25"
+{!> ../../docs_src/background_tasks/tutorial002.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="11 13 20 23"
- {!> ../../../docs_src/background_tasks/tutorial002_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="11 13 20 23"
+{!> ../../docs_src/background_tasks/tutorial002_py310.py!}
+```
+
+////
👉 🖼, 📧 🔜 ✍ `log.txt` 📁 *⏮️* 📨 📨.
diff --git a/docs/em/docs/tutorial/bigger-applications.md b/docs/em/docs/tutorial/bigger-applications.md
index fc9076aa8..074ab302c 100644
--- a/docs/em/docs/tutorial/bigger-applications.md
+++ b/docs/em/docs/tutorial/bigger-applications.md
@@ -4,8 +4,11 @@
**FastAPI** 🚚 🏪 🧰 📊 👆 🈸 ⏪ 🚧 🌐 💪.
-!!! info
- 🚥 👆 👟 ⚪️➡️ 🏺, 👉 🔜 🌓 🏺 📗.
+/// info
+
+🚥 👆 👟 ⚪️➡️ 🏺, 👉 🔜 🌓 🏺 📗.
+
+///
## 🖼 📁 📊
@@ -26,16 +29,19 @@
│ └── admin.py
```
-!!! tip
- 📤 📚 `__init__.py` 📁: 1️⃣ 🔠 📁 ⚖️ 📁.
+/// tip
- 👉 ⚫️❔ ✔ 🏭 📟 ⚪️➡️ 1️⃣ 📁 🔘 ➕1️⃣.
+📤 📚 `__init__.py` 📁: 1️⃣ 🔠 📁 ⚖️ 📁.
- 🖼, `app/main.py` 👆 💪 ✔️ ⏸ 💖:
+👉 ⚫️❔ ✔ 🏭 📟 ⚪️➡️ 1️⃣ 📁 🔘 ➕1️⃣.
- ```
- from app.routers import items
- ```
+🖼, `app/main.py` 👆 💪 ✔️ ⏸ 💖:
+
+```
+from app.routers import items
+```
+
+///
* `app` 📁 🔌 🌐. & ⚫️ ✔️ 🛁 📁 `app/__init__.py`, ⚫️ "🐍 📦" (🗃 "🐍 🕹"): `app`.
* ⚫️ 🔌 `app/main.py` 📁. ⚫️ 🔘 🐍 📦 (📁 ⏮️ 📁 `__init__.py`), ⚫️ "🕹" 👈 📦: `app.main`.
@@ -80,7 +86,7 @@
👆 🗄 ⚫️ & ✍ "👐" 🎏 🌌 👆 🔜 ⏮️ 🎓 `FastAPI`:
```Python hl_lines="1 3" title="app/routers/users.py"
-{!../../../docs_src/bigger_applications/app/routers/users.py!}
+{!../../docs_src/bigger_applications/app/routers/users.py!}
```
### *➡ 🛠️* ⏮️ `APIRouter`
@@ -90,7 +96,7 @@
⚙️ ⚫️ 🎏 🌌 👆 🔜 ⚙️ `FastAPI` 🎓:
```Python hl_lines="6 11 16" title="app/routers/users.py"
-{!../../../docs_src/bigger_applications/app/routers/users.py!}
+{!../../docs_src/bigger_applications/app/routers/users.py!}
```
👆 💪 💭 `APIRouter` "🐩 `FastAPI`" 🎓.
@@ -99,8 +105,11 @@
🌐 🎏 `parameters`, `responses`, `dependencies`, `tags`, ♒️.
-!!! tip
- 👉 🖼, 🔢 🤙 `router`, ✋️ 👆 💪 📛 ⚫️ 👐 👆 💚.
+/// tip
+
+👉 🖼, 🔢 🤙 `router`, ✋️ 👆 💪 📛 ⚫️ 👐 👆 💚.
+
+///
👥 🔜 🔌 👉 `APIRouter` 👑 `FastAPI` 📱, ✋️ 🥇, ➡️ ✅ 🔗 & ➕1️⃣ `APIRouter`.
@@ -113,13 +122,16 @@
👥 🔜 🔜 ⚙️ 🙅 🔗 ✍ 🛃 `X-Token` 🎚:
```Python hl_lines="1 4-6" title="app/dependencies.py"
-{!../../../docs_src/bigger_applications/app/dependencies.py!}
+{!../../docs_src/bigger_applications/app/dependencies.py!}
```
-!!! tip
- 👥 ⚙️ 💭 🎚 📉 👉 🖼.
+/// tip
- ✋️ 🎰 💼 👆 🔜 🤚 👍 🏁 ⚙️ 🛠️ [💂♂ 🚙](security/index.md){.internal-link target=_blank}.
+👥 ⚙️ 💭 🎚 📉 👉 🖼.
+
+✋️ 🎰 💼 👆 🔜 🤚 👍 🏁 ⚙️ 🛠️ [💂♂ 🚙](security/index.md){.internal-link target=_blank}.
+
+///
## ➕1️⃣ 🕹 ⏮️ `APIRouter`
@@ -144,7 +156,7 @@
, ↩️ ❎ 🌐 👈 🔠 *➡ 🛠️*, 👥 💪 🚮 ⚫️ `APIRouter`.
```Python hl_lines="5-10 16 21" title="app/routers/items.py"
-{!../../../docs_src/bigger_applications/app/routers/items.py!}
+{!../../docs_src/bigger_applications/app/routers/items.py!}
```
➡ 🔠 *➡ 🛠️* ✔️ ▶️ ⏮️ `/`, 💖:
@@ -163,8 +175,11 @@ async def read_item(item_id: str):
& 👥 💪 🚮 📇 `dependencies` 👈 🔜 🚮 🌐 *➡ 🛠️* 📻 & 🔜 🛠️/❎ 🔠 📨 ⚒ 👫.
-!!! tip
- 🗒 👈, 🌅 💖 [🔗 *➡ 🛠️ 👨🎨*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, 🙅♂ 💲 🔜 🚶♀️ 👆 *➡ 🛠️ 🔢*.
+/// tip
+
+🗒 👈, 🌅 💖 [🔗 *➡ 🛠️ 👨🎨*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, 🙅♂ 💲 🔜 🚶♀️ 👆 *➡ 🛠️ 🔢*.
+
+///
🔚 🏁 👈 🏬 ➡ 🔜:
@@ -181,11 +196,17 @@ async def read_item(item_id: str):
* 📻 🔗 🛠️ 🥇, ⤴️ [`dependencies` 👨🎨](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, & ⤴️ 😐 🔢 🔗.
* 👆 💪 🚮 [`Security` 🔗 ⏮️ `scopes`](../advanced/security/oauth2-scopes.md){.internal-link target=_blank}.
-!!! tip
- ✔️ `dependencies` `APIRouter` 💪 ⚙️, 🖼, 🚚 🤝 🎂 👪 *➡ 🛠️*. 🚥 🔗 🚫 🚮 📦 🔠 1️⃣ 👫.
+/// tip
-!!! check
- `prefix`, `tags`, `responses`, & `dependencies` 🔢 (📚 🎏 💼) ⚒ ⚪️➡️ **FastAPI** ℹ 👆 ❎ 📟 ❎.
+✔️ `dependencies` `APIRouter` 💪 ⚙️, 🖼, 🚚 🤝 🎂 👪 *➡ 🛠️*. 🚥 🔗 🚫 🚮 📦 🔠 1️⃣ 👫.
+
+///
+
+/// check
+
+`prefix`, `tags`, `responses`, & `dependencies` 🔢 (📚 🎏 💼) ⚒ ⚪️➡️ **FastAPI** ℹ 👆 ❎ 📟 ❎.
+
+///
### 🗄 🔗
@@ -196,13 +217,16 @@ async def read_item(item_id: str):
👥 ⚙️ ⚖ 🗄 ⏮️ `..` 🔗:
```Python hl_lines="3" title="app/routers/items.py"
-{!../../../docs_src/bigger_applications/app/routers/items.py!}
+{!../../docs_src/bigger_applications/app/routers/items.py!}
```
#### ❔ ⚖ 🗄 👷
-!!! tip
- 🚥 👆 💭 👌 ❔ 🗄 👷, 😣 ⏭ 📄 🔛.
+/// tip
+
+🚥 👆 💭 👌 ❔ 🗄 👷, 😣 ⏭ 📄 🔛.
+
+///
👁 ❣ `.`, 💖:
@@ -266,13 +290,16 @@ that 🔜 ⛓:
✋️ 👥 💪 🚮 _🌅_ `tags` 👈 🔜 ✔ 🎯 *➡ 🛠️*, & ➕ `responses` 🎯 👈 *➡ 🛠️*:
```Python hl_lines="30-31" title="app/routers/items.py"
-{!../../../docs_src/bigger_applications/app/routers/items.py!}
+{!../../docs_src/bigger_applications/app/routers/items.py!}
```
-!!! tip
- 👉 🏁 ➡ 🛠️ 🔜 ✔️ 🌀 🔖: `["items", "custom"]`.
+/// tip
- & ⚫️ 🔜 ✔️ 👯♂️ 📨 🧾, 1️⃣ `404` & 1️⃣ `403`.
+👉 🏁 ➡ 🛠️ 🔜 ✔️ 🌀 🔖: `["items", "custom"]`.
+
+ & ⚫️ 🔜 ✔️ 👯♂️ 📨 🧾, 1️⃣ `404` & 1️⃣ `403`.
+
+///
## 👑 `FastAPI`
@@ -291,7 +318,7 @@ that 🔜 ⛓:
& 👥 💪 📣 [🌐 🔗](dependencies/global-dependencies.md){.internal-link target=_blank} 👈 🔜 🌀 ⏮️ 🔗 🔠 `APIRouter`:
```Python hl_lines="1 3 7" title="app/main.py"
-{!../../../docs_src/bigger_applications/app/main.py!}
+{!../../docs_src/bigger_applications/app/main.py!}
```
### 🗄 `APIRouter`
@@ -299,7 +326,7 @@ that 🔜 ⛓:
🔜 👥 🗄 🎏 🔁 👈 ✔️ `APIRouter`Ⓜ:
```Python hl_lines="5" title="app/main.py"
-{!../../../docs_src/bigger_applications/app/main.py!}
+{!../../docs_src/bigger_applications/app/main.py!}
```
📁 `app/routers/users.py` & `app/routers/items.py` 🔁 👈 🍕 🎏 🐍 📦 `app`, 👥 💪 ⚙️ 👁 ❣ `.` 🗄 👫 ⚙️ "⚖ 🗄".
@@ -328,20 +355,23 @@ from .routers import items, users
from app.routers import items, users
```
-!!! info
- 🥇 ⏬ "⚖ 🗄":
+/// info
- ```Python
- from .routers import items, users
- ```
+🥇 ⏬ "⚖ 🗄":
- 🥈 ⏬ "🎆 🗄":
+```Python
+from .routers import items, users
+```
- ```Python
- from app.routers import items, users
- ```
+🥈 ⏬ "🎆 🗄":
- 💡 🌅 🔃 🐍 📦 & 🕹, ✍ 🛂 🐍 🧾 🔃 🕹.
+```Python
+from app.routers import items, users
+```
+
+💡 🌅 🔃 🐍 📦 & 🕹, ✍ 🛂 🐍 🧾 🔃 🕹.
+
+///
### ❎ 📛 💥
@@ -361,7 +391,7 @@ from .routers.users import router
, 💪 ⚙️ 👯♂️ 👫 🎏 📁, 👥 🗄 🔁 🔗:
```Python hl_lines="5" title="app/main.py"
-{!../../../docs_src/bigger_applications/app/main.py!}
+{!../../docs_src/bigger_applications/app/main.py!}
```
### 🔌 `APIRouter`Ⓜ `users` & `items`
@@ -369,29 +399,38 @@ from .routers.users import router
🔜, ➡️ 🔌 `router`Ⓜ ⚪️➡️ 🔁 `users` & `items`:
```Python hl_lines="10-11" title="app/main.py"
-{!../../../docs_src/bigger_applications/app/main.py!}
+{!../../docs_src/bigger_applications/app/main.py!}
```
-!!! info
- `users.router` 🔌 `APIRouter` 🔘 📁 `app/routers/users.py`.
+/// info
- & `items.router` 🔌 `APIRouter` 🔘 📁 `app/routers/items.py`.
+`users.router` 🔌 `APIRouter` 🔘 📁 `app/routers/users.py`.
+
+ & `items.router` 🔌 `APIRouter` 🔘 📁 `app/routers/items.py`.
+
+///
⏮️ `app.include_router()` 👥 💪 🚮 🔠 `APIRouter` 👑 `FastAPI` 🈸.
⚫️ 🔜 🔌 🌐 🛣 ⚪️➡️ 👈 📻 🍕 ⚫️.
-!!! note "📡 ℹ"
- ⚫️ 🔜 🤙 🔘 ✍ *➡ 🛠️* 🔠 *➡ 🛠️* 👈 📣 `APIRouter`.
+/// note | "📡 ℹ"
- , ⛅ 🎑, ⚫️ 🔜 🤙 👷 🚥 🌐 🎏 👁 📱.
+⚫️ 🔜 🤙 🔘 ✍ *➡ 🛠️* 🔠 *➡ 🛠️* 👈 📣 `APIRouter`.
-!!! check
- 👆 🚫 ✔️ 😟 🔃 🎭 🕐❔ ✅ 📻.
+, ⛅ 🎑, ⚫️ 🔜 🤙 👷 🚥 🌐 🎏 👁 📱.
- 👉 🔜 ✊ ⏲ & 🔜 🕴 🔨 🕴.
+///
- ⚫️ 🏆 🚫 📉 🎭. 👶
+/// check
+
+👆 🚫 ✔️ 😟 🔃 🎭 🕐❔ ✅ 📻.
+
+👉 🔜 ✊ ⏲ & 🔜 🕴 🔨 🕴.
+
+⚫️ 🏆 🚫 📉 🎭. 👶
+
+///
### 🔌 `APIRouter` ⏮️ 🛃 `prefix`, `tags`, `responses`, & `dependencies`
@@ -402,7 +441,7 @@ from .routers.users import router
👉 🖼 ⚫️ 🔜 💎 🙅. ✋️ ➡️ 💬 👈 ↩️ ⚫️ 💰 ⏮️ 🎏 🏗 🏢, 👥 🚫🔜 🔀 ⚫️ & 🚮 `prefix`, `dependencies`, `tags`, ♒️. 🔗 `APIRouter`:
```Python hl_lines="3" title="app/internal/admin.py"
-{!../../../docs_src/bigger_applications/app/internal/admin.py!}
+{!../../docs_src/bigger_applications/app/internal/admin.py!}
```
✋️ 👥 💚 ⚒ 🛃 `prefix` 🕐❔ ✅ `APIRouter` 👈 🌐 🚮 *➡ 🛠️* ▶️ ⏮️ `/admin`, 👥 💚 🔐 ⚫️ ⏮️ `dependencies` 👥 ⏪ ✔️ 👉 🏗, & 👥 💚 🔌 `tags` & `responses`.
@@ -410,7 +449,7 @@ from .routers.users import router
👥 💪 📣 🌐 👈 🍵 ✔️ 🔀 ⏮️ `APIRouter` 🚶♀️ 👈 🔢 `app.include_router()`:
```Python hl_lines="14-17" title="app/main.py"
-{!../../../docs_src/bigger_applications/app/main.py!}
+{!../../docs_src/bigger_applications/app/main.py!}
```
👈 🌌, ⏮️ `APIRouter` 🔜 🚧 ⚗, 👥 💪 💰 👈 🎏 `app/internal/admin.py` 📁 ⏮️ 🎏 🏗 🏢.
@@ -433,21 +472,24 @@ from .routers.users import router
📥 👥 ⚫️... 🎦 👈 👥 💪 🤷:
```Python hl_lines="21-23" title="app/main.py"
-{!../../../docs_src/bigger_applications/app/main.py!}
+{!../../docs_src/bigger_applications/app/main.py!}
```
& ⚫️ 🔜 👷 ☑, 👯♂️ ⏮️ 🌐 🎏 *➡ 🛠️* 🚮 ⏮️ `app.include_router()`.
-!!! info "📶 📡 ℹ"
- **🗒**: 👉 📶 📡 ℹ 👈 👆 🎲 💪 **🚶**.
+/// info | "📶 📡 ℹ"
- ---
+**🗒**: 👉 📶 📡 ℹ 👈 👆 🎲 💪 **🚶**.
- `APIRouter`Ⓜ 🚫 "🗻", 👫 🚫 👽 ⚪️➡️ 🎂 🈸.
+---
- 👉 ↩️ 👥 💚 🔌 👫 *➡ 🛠️* 🗄 🔗 & 👩💻 🔢.
+ `APIRouter`Ⓜ 🚫 "🗻", 👫 🚫 👽 ⚪️➡️ 🎂 🈸.
- 👥 🚫🔜 ❎ 👫 & "🗻" 👫 ➡ 🎂, *➡ 🛠️* "🖖" (🏤-✍), 🚫 🔌 🔗.
+👉 ↩️ 👥 💚 🔌 👫 *➡ 🛠️* 🗄 🔗 & 👩💻 🔢.
+
+👥 🚫🔜 ❎ 👫 & "🗻" 👫 ➡ 🎂, *➡ 🛠️* "🖖" (🏤-✍), 🚫 🔌 🔗.
+
+///
## ✅ 🏧 🛠️ 🩺
diff --git a/docs/em/docs/tutorial/body-fields.md b/docs/em/docs/tutorial/body-fields.md
index 9f2c914f4..eb3093de2 100644
--- a/docs/em/docs/tutorial/body-fields.md
+++ b/docs/em/docs/tutorial/body-fields.md
@@ -6,50 +6,67 @@
🥇, 👆 ✔️ 🗄 ⚫️:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001.py!}
- ```
+```Python hl_lines="4"
+{!> ../../docs_src/body_fields/tutorial001.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="2"
- {!> ../../../docs_src/body_fields/tutorial001_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-!!! warning
- 👀 👈 `Field` 🗄 🔗 ⚪️➡️ `pydantic`, 🚫 ⚪️➡️ `fastapi` 🌐 🎂 (`Query`, `Path`, `Body`, ♒️).
+```Python hl_lines="2"
+{!> ../../docs_src/body_fields/tutorial001_py310.py!}
+```
+
+////
+
+/// warning
+
+👀 👈 `Field` 🗄 🔗 ⚪️➡️ `pydantic`, 🚫 ⚪️➡️ `fastapi` 🌐 🎂 (`Query`, `Path`, `Body`, ♒️).
+
+///
## 📣 🏷 🔢
👆 💪 ⤴️ ⚙️ `Field` ⏮️ 🏷 🔢:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001.py!}
- ```
+```Python hl_lines="11-14"
+{!> ../../docs_src/body_fields/tutorial001.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="9-12"
- {!> ../../../docs_src/body_fields/tutorial001_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="9-12"
+{!> ../../docs_src/body_fields/tutorial001_py310.py!}
+```
+
+////
`Field` 👷 🎏 🌌 `Query`, `Path` & `Body`, ⚫️ ✔️ 🌐 🎏 🔢, ♒️.
-!!! note "📡 ℹ"
- 🤙, `Query`, `Path` & 🎏 👆 🔜 👀 ⏭ ✍ 🎚 🏿 ⚠ `Param` 🎓, ❔ ⚫️ 🏿 Pydantic `FieldInfo` 🎓.
+/// note | "📡 ℹ"
- & Pydantic `Field` 📨 👐 `FieldInfo` 👍.
+🤙, `Query`, `Path` & 🎏 👆 🔜 👀 ⏭ ✍ 🎚 🏿 ⚠ `Param` 🎓, ❔ ⚫️ 🏿 Pydantic `FieldInfo` 🎓.
- `Body` 📨 🎚 🏿 `FieldInfo` 🔗. & 📤 🎏 👆 🔜 👀 ⏪ 👈 🏿 `Body` 🎓.
+ & Pydantic `Field` 📨 👐 `FieldInfo` 👍.
- 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓.
+`Body` 📨 🎚 🏿 `FieldInfo` 🔗. & 📤 🎏 👆 🔜 👀 ⏪ 👈 🏿 `Body` 🎓.
-!!! tip
- 👀 ❔ 🔠 🏷 🔢 ⏮️ 🆎, 🔢 💲 & `Field` ✔️ 🎏 📊 *➡ 🛠️ 🔢* 🔢, ⏮️ `Field` ↩️ `Path`, `Query` & `Body`.
+💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓.
+
+///
+
+/// tip
+
+👀 ❔ 🔠 🏷 🔢 ⏮️ 🆎, 🔢 💲 & `Field` ✔️ 🎏 📊 *➡ 🛠️ 🔢* 🔢, ⏮️ `Field` ↩️ `Path`, `Query` & `Body`.
+
+///
## 🚮 ➕ ℹ
@@ -57,9 +74,12 @@
👆 🔜 💡 🌅 🔃 ❎ ➕ ℹ ⏪ 🩺, 🕐❔ 🏫 📣 🖼.
-!!! warning
- ➕ 🔑 🚶♀️ `Field` 🔜 🎁 📉 🗄 🔗 👆 🈸.
- 👫 🔑 5️⃣📆 🚫 🎯 🍕 🗄 🔧, 🗄 🧰, 🖼 [🗄 💳](https://validator.swagger.io/), 5️⃣📆 🚫 👷 ⏮️ 👆 🏗 🔗.
+/// warning
+
+➕ 🔑 🚶♀️ `Field` 🔜 🎁 📉 🗄 🔗 👆 🈸.
+👫 🔑 5️⃣📆 🚫 🎯 🍕 🗄 🔧, 🗄 🧰, 🖼 [🗄 💳](https://validator.swagger.io/), 5️⃣📆 🚫 👷 ⏮️ 👆 🏗 🔗.
+
+///
## 🌃
diff --git a/docs/em/docs/tutorial/body-multiple-params.md b/docs/em/docs/tutorial/body-multiple-params.md
index 9ada7dee1..2e20c83f9 100644
--- a/docs/em/docs/tutorial/body-multiple-params.md
+++ b/docs/em/docs/tutorial/body-multiple-params.md
@@ -8,20 +8,27 @@
& 👆 💪 📣 💪 🔢 📦, ⚒ 🔢 `None`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="19-21"
- {!> ../../../docs_src/body_multiple_params/tutorial001.py!}
- ```
+```Python hl_lines="19-21"
+{!> ../../docs_src/body_multiple_params/tutorial001.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="17-19"
- {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-!!! note
- 👀 👈, 👉 💼, `item` 👈 🔜 ✊ ⚪️➡️ 💪 📦. ⚫️ ✔️ `None` 🔢 💲.
+```Python hl_lines="17-19"
+{!> ../../docs_src/body_multiple_params/tutorial001_py310.py!}
+```
+
+////
+
+/// note
+
+👀 👈, 👉 💼, `item` 👈 🔜 ✊ ⚪️➡️ 💪 📦. ⚫️ ✔️ `None` 🔢 💲.
+
+///
## 💗 💪 🔢
@@ -38,17 +45,21 @@
✋️ 👆 💪 📣 💗 💪 🔢, ✅ `item` & `user`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="22"
- {!> ../../../docs_src/body_multiple_params/tutorial002.py!}
- ```
+```Python hl_lines="22"
+{!> ../../docs_src/body_multiple_params/tutorial002.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="20"
+{!> ../../docs_src/body_multiple_params/tutorial002_py310.py!}
+```
+
+////
👉 💼, **FastAPI** 🔜 👀 👈 📤 🌅 🌘 1️⃣ 💪 🔢 🔢 (2️⃣ 🔢 👈 Pydantic 🏷).
@@ -69,9 +80,11 @@
}
```
-!!! note
- 👀 👈 ✋️ `item` 📣 🎏 🌌 ⏭, ⚫️ 🔜 ⌛ 🔘 💪 ⏮️ 🔑 `item`.
+/// note
+👀 👈 ✋️ `item` 📣 🎏 🌌 ⏭, ⚫️ 🔜 ⌛ 🔘 💪 ⏮️ 🔑 `item`.
+
+///
**FastAPI** 🔜 🏧 🛠️ ⚪️➡️ 📨, 👈 🔢 `item` 📨 ⚫️ 🎯 🎚 & 🎏 `user`.
@@ -87,17 +100,21 @@
✋️ 👆 💪 💡 **FastAPI** 😥 ⚫️ ➕1️⃣ 💪 🔑 ⚙️ `Body`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="22"
- {!> ../../../docs_src/body_multiple_params/tutorial003.py!}
- ```
+```Python hl_lines="22"
+{!> ../../docs_src/body_multiple_params/tutorial003.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="20"
+{!> ../../docs_src/body_multiple_params/tutorial003_py310.py!}
+```
+
+////
👉 💼, **FastAPI** 🔜 ⌛ 💪 💖:
@@ -137,20 +154,27 @@ q: str | None = None
🖼:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004.py!}
- ```
+```Python hl_lines="27"
+{!> ../../docs_src/body_multiple_params/tutorial004.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="26"
- {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-!!! info
- `Body` ✔️ 🌐 🎏 ➕ 🔬 & 🗃 🔢 `Query`,`Path` & 🎏 👆 🔜 👀 ⏪.
+```Python hl_lines="26"
+{!> ../../docs_src/body_multiple_params/tutorial004_py310.py!}
+```
+
+////
+
+/// info
+
+`Body` ✔️ 🌐 🎏 ➕ 🔬 & 🗃 🔢 `Query`,`Path` & 🎏 👆 🔜 👀 ⏪.
+
+///
## ⏯ 👁 💪 🔢
@@ -166,17 +190,21 @@ item: Item = Body(embed=True)
:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="17"
- {!> ../../../docs_src/body_multiple_params/tutorial005.py!}
- ```
+```Python hl_lines="17"
+{!> ../../docs_src/body_multiple_params/tutorial005.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="15"
- {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="15"
+{!> ../../docs_src/body_multiple_params/tutorial005_py310.py!}
+```
+
+////
👉 💼 **FastAPI** 🔜 ⌛ 💪 💖:
diff --git a/docs/em/docs/tutorial/body-nested-models.md b/docs/em/docs/tutorial/body-nested-models.md
index c941fa08a..3b56b7a07 100644
--- a/docs/em/docs/tutorial/body-nested-models.md
+++ b/docs/em/docs/tutorial/body-nested-models.md
@@ -6,17 +6,21 @@
👆 💪 🔬 🔢 🏾. 🖼, 🐍 `list`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial001.py!}
- ```
+```Python hl_lines="14"
+{!> ../../docs_src/body_nested_models/tutorial001.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="12"
- {!> ../../../docs_src/body_nested_models/tutorial001_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="12"
+{!> ../../docs_src/body_nested_models/tutorial001_py310.py!}
+```
+
+////
👉 🔜 ⚒ `tags` 📇, 👐 ⚫️ 🚫 📣 🆎 🔣 📇.
@@ -31,7 +35,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!}
```
### 📣 `list` ⏮️ 🆎 🔢
@@ -61,23 +65,29 @@ my_list: List[str]
, 👆 🖼, 👥 💪 ⚒ `tags` 🎯 "📇 🎻":
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial002.py!}
- ```
+```Python hl_lines="14"
+{!> ../../docs_src/body_nested_models/tutorial002.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial002_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="14"
+{!> ../../docs_src/body_nested_models/tutorial002_py39.py!}
+```
- ```Python hl_lines="12"
- {!> ../../../docs_src/body_nested_models/tutorial002_py310.py!}
- ```
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="12"
+{!> ../../docs_src/body_nested_models/tutorial002_py310.py!}
+```
+
+////
## ⚒ 🆎
@@ -87,23 +97,29 @@ my_list: List[str]
⤴️ 👥 💪 📣 `tags` ⚒ 🎻:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="1 14"
- {!> ../../../docs_src/body_nested_models/tutorial003.py!}
- ```
+```Python hl_lines="1 14"
+{!> ../../docs_src/body_nested_models/tutorial003.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial003_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="14"
+{!> ../../docs_src/body_nested_models/tutorial003_py39.py!}
+```
- ```Python hl_lines="12"
- {!> ../../../docs_src/body_nested_models/tutorial003_py310.py!}
- ```
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="12"
+{!> ../../docs_src/body_nested_models/tutorial003_py310.py!}
+```
+
+////
⏮️ 👉, 🚥 👆 📨 📨 ⏮️ ❎ 📊, ⚫️ 🔜 🗜 ⚒ 😍 🏬.
@@ -125,45 +141,57 @@ my_list: List[str]
🖼, 👥 💪 🔬 `Image` 🏷:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="9-11"
- {!> ../../../docs_src/body_nested_models/tutorial004.py!}
- ```
+```Python hl_lines="9-11"
+{!> ../../docs_src/body_nested_models/tutorial004.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="9-11"
- {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="9-11"
+{!> ../../docs_src/body_nested_models/tutorial004_py39.py!}
+```
- ```Python hl_lines="7-9"
- {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!}
- ```
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="7-9"
+{!> ../../docs_src/body_nested_models/tutorial004_py310.py!}
+```
+
+////
### ⚙️ 📊 🆎
& ⤴️ 👥 💪 ⚙️ ⚫️ 🆎 🔢:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial004.py!}
- ```
+```Python hl_lines="20"
+{!> ../../docs_src/body_nested_models/tutorial004.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="20"
+{!> ../../docs_src/body_nested_models/tutorial004_py39.py!}
+```
- ```Python hl_lines="18"
- {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!}
- ```
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="18"
+{!> ../../docs_src/body_nested_models/tutorial004_py310.py!}
+```
+
+////
👉 🔜 ⛓ 👈 **FastAPI** 🔜 ⌛ 💪 🎏:
@@ -196,23 +224,29 @@ my_list: List[str]
🖼, `Image` 🏷 👥 ✔️ `url` 🏑, 👥 💪 📣 ⚫️ ↩️ `str`, Pydantic `HttpUrl`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="4 10"
- {!> ../../../docs_src/body_nested_models/tutorial005.py!}
- ```
+```Python hl_lines="4 10"
+{!> ../../docs_src/body_nested_models/tutorial005.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="4 10"
- {!> ../../../docs_src/body_nested_models/tutorial005_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="4 10"
+{!> ../../docs_src/body_nested_models/tutorial005_py39.py!}
+```
- ```Python hl_lines="2 8"
- {!> ../../../docs_src/body_nested_models/tutorial005_py310.py!}
- ```
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="2 8"
+{!> ../../docs_src/body_nested_models/tutorial005_py310.py!}
+```
+
+////
🎻 🔜 ✅ ☑ 📛, & 📄 🎻 🔗 / 🗄 ✅.
@@ -220,23 +254,29 @@ my_list: List[str]
👆 💪 ⚙️ Pydantic 🏷 🏾 `list`, `set`, ♒️:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial006.py!}
- ```
+```Python hl_lines="20"
+{!> ../../docs_src/body_nested_models/tutorial006.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial006_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="20"
+{!> ../../docs_src/body_nested_models/tutorial006_py39.py!}
+```
- ```Python hl_lines="18"
- {!> ../../../docs_src/body_nested_models/tutorial006_py310.py!}
- ```
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="18"
+{!> ../../docs_src/body_nested_models/tutorial006_py310.py!}
+```
+
+////
👉 🔜 ⌛ (🗜, ✔, 📄, ♒️) 🎻 💪 💖:
@@ -264,33 +304,45 @@ my_list: List[str]
}
```
-!!! info
- 👀 ❔ `images` 🔑 🔜 ✔️ 📇 🖼 🎚.
+/// info
+
+👀 ❔ `images` 🔑 🔜 ✔️ 📇 🖼 🎚.
+
+///
## 🙇 🐦 🏷
👆 💪 🔬 🎲 🙇 🐦 🏷:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="9 14 20 23 27"
- {!> ../../../docs_src/body_nested_models/tutorial007.py!}
- ```
+```Python hl_lines="9 14 20 23 27"
+{!> ../../docs_src/body_nested_models/tutorial007.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="9 14 20 23 27"
- {!> ../../../docs_src/body_nested_models/tutorial007_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="9 14 20 23 27"
+{!> ../../docs_src/body_nested_models/tutorial007_py39.py!}
+```
- ```Python hl_lines="7 12 18 21 25"
- {!> ../../../docs_src/body_nested_models/tutorial007_py310.py!}
- ```
+////
-!!! info
- 👀 ❔ `Offer` ✔️ 📇 `Item`Ⓜ, ❔ 🔄 ✔️ 📦 📇 `Image`Ⓜ
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="7 12 18 21 25"
+{!> ../../docs_src/body_nested_models/tutorial007_py310.py!}
+```
+
+////
+
+/// info
+
+👀 ❔ `Offer` ✔️ 📇 `Item`Ⓜ, ❔ 🔄 ✔️ 📦 📇 `Image`Ⓜ
+
+///
## 💪 😁 📇
@@ -308,17 +360,21 @@ images: list[Image]
:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="15"
- {!> ../../../docs_src/body_nested_models/tutorial008.py!}
- ```
+```Python hl_lines="15"
+{!> ../../docs_src/body_nested_models/tutorial008.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="13"
- {!> ../../../docs_src/body_nested_models/tutorial008_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
+
+```Python hl_lines="13"
+{!> ../../docs_src/body_nested_models/tutorial008_py39.py!}
+```
+
+////
## 👨🎨 🐕🦺 🌐
@@ -348,26 +404,33 @@ images: list[Image]
👉 💼, 👆 🔜 🚫 🙆 `dict` 📏 ⚫️ ✔️ `int` 🔑 ⏮️ `float` 💲:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="9"
- {!> ../../../docs_src/body_nested_models/tutorial009.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/body_nested_models/tutorial009.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/body_nested_models/tutorial009_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-!!! tip
- ✔️ 🤯 👈 🎻 🕴 🐕🦺 `str` 🔑.
+```Python hl_lines="7"
+{!> ../../docs_src/body_nested_models/tutorial009_py39.py!}
+```
- ✋️ Pydantic ✔️ 🏧 💽 🛠️.
+////
- 👉 ⛓ 👈, ✋️ 👆 🛠️ 👩💻 💪 🕴 📨 🎻 🔑, 📏 👈 🎻 🔌 😁 🔢, Pydantic 🔜 🗜 👫 & ✔ 👫.
+/// tip
- & `dict` 👆 📨 `weights` 🔜 🤙 ✔️ `int` 🔑 & `float` 💲.
+✔️ 🤯 👈 🎻 🕴 🐕🦺 `str` 🔑.
+
+✋️ Pydantic ✔️ 🏧 💽 🛠️.
+
+👉 ⛓ 👈, ✋️ 👆 🛠️ 👩💻 💪 🕴 📨 🎻 🔑, 📏 👈 🎻 🔌 😁 🔢, Pydantic 🔜 🗜 👫 & ✔ 👫.
+
+ & `dict` 👆 📨 `weights` 🔜 🤙 ✔️ `int` 🔑 & `float` 💲.
+
+///
## 🌃
diff --git a/docs/em/docs/tutorial/body-updates.md b/docs/em/docs/tutorial/body-updates.md
index 89bb615f6..4a4b3b6b8 100644
--- a/docs/em/docs/tutorial/body-updates.md
+++ b/docs/em/docs/tutorial/body-updates.md
@@ -6,23 +6,29 @@
👆 💪 ⚙️ `jsonable_encoder` 🗜 🔢 💽 📊 👈 💪 🏪 🎻 (✅ ⏮️ ☁ 💽). 🖼, 🏭 `datetime` `str`.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="30-35"
- {!> ../../../docs_src/body_updates/tutorial001.py!}
- ```
+```Python hl_lines="30-35"
+{!> ../../docs_src/body_updates/tutorial001.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="30-35"
- {!> ../../../docs_src/body_updates/tutorial001_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="30-35"
+{!> ../../docs_src/body_updates/tutorial001_py39.py!}
+```
- ```Python hl_lines="28-33"
- {!> ../../../docs_src/body_updates/tutorial001_py310.py!}
- ```
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="28-33"
+{!> ../../docs_src/body_updates/tutorial001_py310.py!}
+```
+
+////
`PUT` ⚙️ 📨 💽 👈 🔜 ❎ ♻ 💽.
@@ -48,14 +54,17 @@
👉 ⛓ 👈 👆 💪 📨 🕴 💽 👈 👆 💚 ℹ, 🍂 🎂 🐣.
-!!! note
- `PATCH` 🌘 🛎 ⚙️ & 💭 🌘 `PUT`.
+/// note
- & 📚 🏉 ⚙️ 🕴 `PUT`, 🍕 ℹ.
+`PATCH` 🌘 🛎 ⚙️ & 💭 🌘 `PUT`.
- 👆 **🆓** ⚙️ 👫 👐 👆 💚, **FastAPI** 🚫 🚫 🙆 🚫.
+ & 📚 🏉 ⚙️ 🕴 `PUT`, 🍕 ℹ.
- ✋️ 👉 🦮 🎦 👆, 🌖 ⚖️ 🌘, ❔ 👫 🎯 ⚙️.
+👆 **🆓** ⚙️ 👫 👐 👆 💚, **FastAPI** 🚫 🚫 🙆 🚫.
+
+✋️ 👉 🦮 🎦 👆, 🌖 ⚖️ 🌘, ❔ 👫 🎯 ⚙️.
+
+///
### ⚙️ Pydantic `exclude_unset` 🔢
@@ -67,23 +76,29 @@
⤴️ 👆 💪 ⚙️ 👉 🏗 `dict` ⏮️ 🕴 💽 👈 ⚒ (📨 📨), 🚫 🔢 💲:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="34"
- {!> ../../../docs_src/body_updates/tutorial002.py!}
- ```
+```Python hl_lines="34"
+{!> ../../docs_src/body_updates/tutorial002.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="34"
- {!> ../../../docs_src/body_updates/tutorial002_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="34"
+{!> ../../docs_src/body_updates/tutorial002_py39.py!}
+```
- ```Python hl_lines="32"
- {!> ../../../docs_src/body_updates/tutorial002_py310.py!}
- ```
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="32"
+{!> ../../docs_src/body_updates/tutorial002_py310.py!}
+```
+
+////
### ⚙️ Pydantic `update` 🔢
@@ -91,23 +106,29 @@
💖 `stored_item_model.copy(update=update_data)`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="35"
- {!> ../../../docs_src/body_updates/tutorial002.py!}
- ```
+```Python hl_lines="35"
+{!> ../../docs_src/body_updates/tutorial002.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="35"
- {!> ../../../docs_src/body_updates/tutorial002_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="35"
+{!> ../../docs_src/body_updates/tutorial002_py39.py!}
+```
- ```Python hl_lines="33"
- {!> ../../../docs_src/body_updates/tutorial002_py310.py!}
- ```
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="33"
+{!> ../../docs_src/body_updates/tutorial002_py310.py!}
+```
+
+////
### 🍕 ℹ 🌃
@@ -124,32 +145,44 @@
* 🖊 💽 👆 💽.
* 📨 ℹ 🏷.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="30-37"
- {!> ../../../docs_src/body_updates/tutorial002.py!}
- ```
+```Python hl_lines="30-37"
+{!> ../../docs_src/body_updates/tutorial002.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="30-37"
- {!> ../../../docs_src/body_updates/tutorial002_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="30-37"
+{!> ../../docs_src/body_updates/tutorial002_py39.py!}
+```
- ```Python hl_lines="28-35"
- {!> ../../../docs_src/body_updates/tutorial002_py310.py!}
- ```
+////
-!!! tip
- 👆 💪 🤙 ⚙️ 👉 🎏 ⚒ ⏮️ 🇺🇸🔍 `PUT` 🛠️.
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
- ✋️ 🖼 📥 ⚙️ `PATCH` ↩️ ⚫️ ✍ 👫 ⚙️ 💼.
+```Python hl_lines="28-35"
+{!> ../../docs_src/body_updates/tutorial002_py310.py!}
+```
-!!! note
- 👀 👈 🔢 🏷 ✔.
+////
- , 🚥 👆 💚 📨 🍕 ℹ 👈 💪 🚫 🌐 🔢, 👆 💪 ✔️ 🏷 ⏮️ 🌐 🔢 ™ 📦 (⏮️ 🔢 💲 ⚖️ `None`).
+/// tip
- 🔬 ⚪️➡️ 🏷 ⏮️ 🌐 📦 💲 **ℹ** & 🏷 ⏮️ ✔ 💲 **🏗**, 👆 💪 ⚙️ 💭 🔬 [➕ 🏷](extra-models.md){.internal-link target=_blank}.
+👆 💪 🤙 ⚙️ 👉 🎏 ⚒ ⏮️ 🇺🇸🔍 `PUT` 🛠️.
+
+✋️ 🖼 📥 ⚙️ `PATCH` ↩️ ⚫️ ✍ 👫 ⚙️ 💼.
+
+///
+
+/// note
+
+👀 👈 🔢 🏷 ✔.
+
+, 🚥 👆 💚 📨 🍕 ℹ 👈 💪 🚫 🌐 🔢, 👆 💪 ✔️ 🏷 ⏮️ 🌐 🔢 ™ 📦 (⏮️ 🔢 💲 ⚖️ `None`).
+
+🔬 ⚪️➡️ 🏷 ⏮️ 🌐 📦 💲 **ℹ** & 🏷 ⏮️ ✔ 💲 **🏗**, 👆 💪 ⚙️ 💭 🔬 [➕ 🏷](extra-models.md){.internal-link target=_blank}.
+
+///
diff --git a/docs/em/docs/tutorial/body.md b/docs/em/docs/tutorial/body.md
index 12f5a6315..3468fc512 100644
--- a/docs/em/docs/tutorial/body.md
+++ b/docs/em/docs/tutorial/body.md
@@ -8,28 +8,35 @@
📣 **📨** 💪, 👆 ⚙️ Pydantic 🏷 ⏮️ 🌐 👫 🏋️ & 💰.
-!!! info
- 📨 💽, 👆 🔜 ⚙️ 1️⃣: `POST` (🌅 ⚠), `PUT`, `DELETE` ⚖️ `PATCH`.
+/// info
- 📨 💪 ⏮️ `GET` 📨 ✔️ ⚠ 🎭 🔧, 👐, ⚫️ 🐕🦺 FastAPI, 🕴 📶 🏗/😕 ⚙️ 💼.
+📨 💽, 👆 🔜 ⚙️ 1️⃣: `POST` (🌅 ⚠), `PUT`, `DELETE` ⚖️ `PATCH`.
- ⚫️ 🚫, 🎓 🩺 ⏮️ 🦁 🎚 🏆 🚫 🎦 🧾 💪 🕐❔ ⚙️ `GET`, & 🗳 🖕 💪 🚫 🐕🦺 ⚫️.
+📨 💪 ⏮️ `GET` 📨 ✔️ ⚠ 🎭 🔧, 👐, ⚫️ 🐕🦺 FastAPI, 🕴 📶 🏗/😕 ⚙️ 💼.
+
+⚫️ 🚫, 🎓 🩺 ⏮️ 🦁 🎚 🏆 🚫 🎦 🧾 💪 🕐❔ ⚙️ `GET`, & 🗳 🖕 💪 🚫 🐕🦺 ⚫️.
+
+///
## 🗄 Pydantic `BaseModel`
🥇, 👆 💪 🗄 `BaseModel` ⚪️➡️ `pydantic`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="4"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
+```Python hl_lines="4"
+{!> ../../docs_src/body/tutorial001.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="2"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="2"
+{!> ../../docs_src/body/tutorial001_py310.py!}
+```
+
+////
## ✍ 👆 💽 🏷
@@ -37,17 +44,21 @@
⚙️ 🐩 🐍 🆎 🌐 🔢:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="7-11"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
+```Python hl_lines="7-11"
+{!> ../../docs_src/body/tutorial001.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="5-9"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="5-9"
+{!> ../../docs_src/body/tutorial001_py310.py!}
+```
+
+////
🎏 🕐❔ 📣 🔢 🔢, 🕐❔ 🏷 🔢 ✔️ 🔢 💲, ⚫️ 🚫 ✔. ⏪, ⚫️ ✔. ⚙️ `None` ⚒ ⚫️ 📦.
@@ -75,17 +86,21 @@
🚮 ⚫️ 👆 *➡ 🛠️*, 📣 ⚫️ 🎏 🌌 👆 📣 ➡ & 🔢 🔢:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="18"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
+```Python hl_lines="18"
+{!> ../../docs_src/body/tutorial001.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="16"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="16"
+{!> ../../docs_src/body/tutorial001_py310.py!}
+```
+
+////
...& 📣 🚮 🆎 🏷 👆 ✍, `Item`.
@@ -134,32 +149,39 @@
-!!! tip
- 🚥 👆 ⚙️ 🗒 👆 👨🎨, 👆 💪 ⚙️ Pydantic 🗒 📁.
+/// tip
- ⚫️ 📉 👨🎨 🐕🦺 Pydantic 🏷, ⏮️:
+🚥 👆 ⚙️ 🗒 👆 👨🎨, 👆 💪 ⚙️ Pydantic 🗒 📁.
- * 🚘-🛠️
- * 🆎 ✅
- * 🛠️
- * 🔎
- * 🔬
+⚫️ 📉 👨🎨 🐕🦺 Pydantic 🏷, ⏮️:
+
+* 🚘-🛠️
+* 🆎 ✅
+* 🛠️
+* 🔎
+* 🔬
+
+///
## ⚙️ 🏷
🔘 🔢, 👆 💪 🔐 🌐 🔢 🏷 🎚 🔗:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="21"
- {!> ../../../docs_src/body/tutorial002.py!}
- ```
+```Python hl_lines="21"
+{!> ../../docs_src/body/tutorial002.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="19"
- {!> ../../../docs_src/body/tutorial002_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="19"
+{!> ../../docs_src/body/tutorial002_py310.py!}
+```
+
+////
## 📨 💪 ➕ ➡ 🔢
@@ -167,17 +189,21 @@
**FastAPI** 🔜 🤔 👈 🔢 🔢 👈 🏏 ➡ 🔢 🔜 **✊ ⚪️➡️ ➡**, & 👈 🔢 🔢 👈 📣 Pydantic 🏷 🔜 **✊ ⚪️➡️ 📨 💪**.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="17-18"
- {!> ../../../docs_src/body/tutorial003.py!}
- ```
+```Python hl_lines="17-18"
+{!> ../../docs_src/body/tutorial003.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="15-16"
- {!> ../../../docs_src/body/tutorial003_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="15-16"
+{!> ../../docs_src/body/tutorial003_py310.py!}
+```
+
+////
## 📨 💪 ➕ ➡ ➕ 🔢 🔢
@@ -185,17 +211,21 @@
**FastAPI** 🔜 🤔 🔠 👫 & ✊ 📊 ⚪️➡️ ☑ 🥉.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="18"
- {!> ../../../docs_src/body/tutorial004.py!}
- ```
+```Python hl_lines="18"
+{!> ../../docs_src/body/tutorial004.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="16"
- {!> ../../../docs_src/body/tutorial004_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="16"
+{!> ../../docs_src/body/tutorial004_py310.py!}
+```
+
+////
🔢 🔢 🔜 🤔 ⏩:
@@ -203,10 +233,13 @@
* 🚥 🔢 **⭐ 🆎** (💖 `int`, `float`, `str`, `bool`, ♒️) ⚫️ 🔜 🔬 **🔢** 🔢.
* 🚥 🔢 📣 🆎 **Pydantic 🏷**, ⚫️ 🔜 🔬 📨 **💪**.
-!!! note
- FastAPI 🔜 💭 👈 💲 `q` 🚫 ✔ ↩️ 🔢 💲 `= None`.
+/// note
- `Union` `Union[str, None]` 🚫 ⚙️ FastAPI, ✋️ 🔜 ✔ 👆 👨🎨 🤝 👆 👍 🐕🦺 & 🔍 ❌.
+FastAPI 🔜 💭 👈 💲 `q` 🚫 ✔ ↩️ 🔢 💲 `= None`.
+
+ `Union` `Union[str, None]` 🚫 ⚙️ FastAPI, ✋️ 🔜 ✔ 👆 👨🎨 🤝 👆 👍 🐕🦺 & 🔍 ❌.
+
+///
## 🍵 Pydantic
diff --git a/docs/em/docs/tutorial/cookie-params.md b/docs/em/docs/tutorial/cookie-params.md
index 47f4a62f5..f4956e76f 100644
--- a/docs/em/docs/tutorial/cookie-params.md
+++ b/docs/em/docs/tutorial/cookie-params.md
@@ -6,17 +6,21 @@
🥇 🗄 `Cookie`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001.py!}
- ```
+```Python hl_lines="3"
+{!> ../../docs_src/cookie_params/tutorial001.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="1"
+{!> ../../docs_src/cookie_params/tutorial001_py310.py!}
+```
+
+////
## 📣 `Cookie` 🔢
@@ -24,25 +28,35 @@
🥇 💲 🔢 💲, 👆 💪 🚶♀️ 🌐 ➕ 🔬 ⚖️ ✍ 🔢:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="9"
- {!> ../../../docs_src/cookie_params/tutorial001.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/cookie_params/tutorial001.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-!!! note "📡 ℹ"
- `Cookie` "👭" 🎓 `Path` & `Query`. ⚫️ 😖 ⚪️➡️ 🎏 ⚠ `Param` 🎓.
+```Python hl_lines="7"
+{!> ../../docs_src/cookie_params/tutorial001_py310.py!}
+```
- ✋️ 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, `Cookie` & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓.
+////
-!!! info
- 📣 🍪, 👆 💪 ⚙️ `Cookie`, ↩️ ⏪ 🔢 🔜 🔬 🔢 🔢.
+/// note | "📡 ℹ"
+
+`Cookie` "👭" 🎓 `Path` & `Query`. ⚫️ 😖 ⚪️➡️ 🎏 ⚠ `Param` 🎓.
+
+✋️ 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, `Cookie` & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓.
+
+///
+
+/// info
+
+📣 🍪, 👆 💪 ⚙️ `Cookie`, ↩️ ⏪ 🔢 🔜 🔬 🔢 🔢.
+
+///
## 🌃
diff --git a/docs/em/docs/tutorial/cors.md b/docs/em/docs/tutorial/cors.md
index 8c5e33ed7..5829319cb 100644
--- a/docs/em/docs/tutorial/cors.md
+++ b/docs/em/docs/tutorial/cors.md
@@ -47,7 +47,7 @@
* 🎯 🇺🇸🔍 🎚 ⚖️ 🌐 👫 ⏮️ 🃏 `"*"`.
```Python hl_lines="2 6-11 13-19"
-{!../../../docs_src/cors/tutorial001.py!}
+{!../../docs_src/cors/tutorial001.py!}
```
🔢 🔢 ⚙️ `CORSMiddleware` 🛠️ 🚫 🔢, 👆 🔜 💪 🎯 🛠️ 🎯 🇨🇳, 👩🔬, ⚖️ 🎚, ✔ 🖥 ✔ ⚙️ 👫 ✖️-🆔 🔑.
@@ -78,7 +78,10 @@
🌖 ℹ 🔃 ⚜, ✅ 🦎 ⚜ 🧾.
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette.middleware.cors import CORSMiddleware`.
+/// note | "📡 ℹ"
- **FastAPI** 🚚 📚 🛠️ `fastapi.middleware` 🏪 👆, 👩💻. ✋️ 🌅 💪 🛠️ 👟 🔗 ⚪️➡️ 💃.
+👆 💪 ⚙️ `from starlette.middleware.cors import CORSMiddleware`.
+
+**FastAPI** 🚚 📚 🛠️ `fastapi.middleware` 🏪 👆, 👩💻. ✋️ 🌅 💪 🛠️ 👟 🔗 ⚪️➡️ 💃.
+
+///
diff --git a/docs/em/docs/tutorial/debugging.md b/docs/em/docs/tutorial/debugging.md
index c7c11b5ce..9320370d6 100644
--- a/docs/em/docs/tutorial/debugging.md
+++ b/docs/em/docs/tutorial/debugging.md
@@ -7,7 +7,7 @@
👆 FastAPI 🈸, 🗄 & 🏃 `uvicorn` 🔗:
```Python hl_lines="1 15"
-{!../../../docs_src/debugging/tutorial001.py!}
+{!../../docs_src/debugging/tutorial001.py!}
```
### 🔃 `__name__ == "__main__"`
@@ -74,8 +74,11 @@ from myapp import app
🔜 🚫 🛠️.
-!!! info
- 🌅 ℹ, ✅ 🛂 🐍 🩺.
+/// info
+
+🌅 ℹ, ✅ 🛂 🐍 🩺.
+
+///
## 🏃 👆 📟 ⏮️ 👆 🕹
diff --git a/docs/em/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/em/docs/tutorial/dependencies/classes-as-dependencies.md
index e2d2686d3..3e58d506c 100644
--- a/docs/em/docs/tutorial/dependencies/classes-as-dependencies.md
+++ b/docs/em/docs/tutorial/dependencies/classes-as-dependencies.md
@@ -6,17 +6,21 @@
⏮️ 🖼, 👥 🛬 `dict` ⚪️➡️ 👆 🔗 ("☑"):
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="9"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/dependencies/tutorial001.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="7"
+{!> ../../docs_src/dependencies/tutorial001_py310.py!}
+```
+
+////
✋️ ⤴️ 👥 🤚 `dict` 🔢 `commons` *➡ 🛠️ 🔢*.
@@ -79,45 +83,57 @@ fluffy = Cat(name="Mr Fluffy")
⤴️, 👥 💪 🔀 🔗 "☑" `common_parameters` ⚪️➡️ 🔛 🎓 `CommonQueryParams`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="11-15"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
- ```
+```Python hl_lines="11-15"
+{!> ../../docs_src/dependencies/tutorial002.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="9-13"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="9-13"
+{!> ../../docs_src/dependencies/tutorial002_py310.py!}
+```
+
+////
💸 🙋 `__init__` 👩🔬 ⚙️ ✍ 👐 🎓:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="12"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
- ```
+```Python hl_lines="12"
+{!> ../../docs_src/dependencies/tutorial002.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="10"
+{!> ../../docs_src/dependencies/tutorial002_py310.py!}
+```
+
+////
...⚫️ ✔️ 🎏 🔢 👆 ⏮️ `common_parameters`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="9"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/dependencies/tutorial001.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="6"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="6"
+{!> ../../docs_src/dependencies/tutorial001_py310.py!}
+```
+
+////
📚 🔢 ⚫️❔ **FastAPI** 🔜 ⚙️ "❎" 🔗.
@@ -133,17 +149,21 @@ fluffy = Cat(name="Mr Fluffy")
🔜 👆 💪 📣 👆 🔗 ⚙️ 👉 🎓.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
- ```
+```Python hl_lines="19"
+{!> ../../docs_src/dependencies/tutorial002.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="17"
+{!> ../../docs_src/dependencies/tutorial002_py310.py!}
+```
+
+////
**FastAPI** 🤙 `CommonQueryParams` 🎓. 👉 ✍ "👐" 👈 🎓 & 👐 🔜 🚶♀️ 🔢 `commons` 👆 🔢.
@@ -183,17 +203,21 @@ commons = Depends(CommonQueryParams)
...:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial003.py!}
- ```
+```Python hl_lines="19"
+{!> ../../docs_src/dependencies/tutorial003.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial003_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="17"
+{!> ../../docs_src/dependencies/tutorial003_py310.py!}
+```
+
+////
✋️ 📣 🆎 💡 👈 🌌 👆 👨🎨 🔜 💭 ⚫️❔ 🔜 🚶♀️ 🔢 `commons`, & ⤴️ ⚫️ 💪 ℹ 👆 ⏮️ 📟 🛠️, 🆎 ✅, ♒️:
@@ -227,21 +251,28 @@ commons: CommonQueryParams = Depends()
🎏 🖼 🔜 ⤴️ 👀 💖:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial004.py!}
- ```
+```Python hl_lines="19"
+{!> ../../docs_src/dependencies/tutorial004.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial004_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="17"
+{!> ../../docs_src/dependencies/tutorial004_py310.py!}
+```
+
+////
...& **FastAPI** 🔜 💭 ⚫️❔.
-!!! tip
- 🚥 👈 😑 🌅 😨 🌘 👍, 🤷♂ ⚫️, 👆 🚫 *💪* ⚫️.
+/// tip
- ⚫️ ⌨. ↩️ **FastAPI** 💅 🔃 🤝 👆 📉 📟 🔁.
+🚥 👈 😑 🌅 😨 🌘 👍, 🤷♂ ⚫️, 👆 🚫 *💪* ⚫️.
+
+⚫️ ⌨. ↩️ **FastAPI** 💅 🔃 🤝 👆 📉 📟 🔁.
+
+///
diff --git a/docs/em/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/em/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
index 4d54b91c7..cd36ad100 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
@@ -15,22 +15,28 @@
⚫️ 🔜 `list` `Depends()`:
```Python hl_lines="17"
-{!../../../docs_src/dependencies/tutorial006.py!}
+{!../../docs_src/dependencies/tutorial006.py!}
```
👉 🔗 🔜 🛠️/❎ 🎏 🌌 😐 🔗. ✋️ 👫 💲 (🚥 👫 📨 🙆) 🏆 🚫 🚶♀️ 👆 *➡ 🛠️ 🔢*.
-!!! tip
- 👨🎨 ✅ ♻ 🔢 🔢, & 🎦 👫 ❌.
+/// tip
- ⚙️ 👉 `dependencies` *➡ 🛠️ 👨🎨* 👆 💪 ⚒ 💭 👫 🛠️ ⏪ ❎ 👨🎨/🏭 ❌.
+👨🎨 ✅ ♻ 🔢 🔢, & 🎦 👫 ❌.
- ⚫️ 💪 ℹ ❎ 😨 🆕 👩💻 👈 👀 ♻ 🔢 👆 📟 & 💪 💭 ⚫️ 🙃.
+⚙️ 👉 `dependencies` *➡ 🛠️ 👨🎨* 👆 💪 ⚒ 💭 👫 🛠️ ⏪ ❎ 👨🎨/🏭 ❌.
-!!! info
- 👉 🖼 👥 ⚙️ 💭 🛃 🎚 `X-Key` & `X-Token`.
+⚫️ 💪 ℹ ❎ 😨 🆕 👩💻 👈 👀 ♻ 🔢 👆 📟 & 💪 💭 ⚫️ 🙃.
- ✋️ 🎰 💼, 🕐❔ 🛠️ 💂♂, 👆 🔜 🤚 🌖 💰 ⚪️➡️ ⚙️ 🛠️ [💂♂ 🚙 (⏭ 📃)](../security/index.md){.internal-link target=_blank}.
+///
+
+/// info
+
+👉 🖼 👥 ⚙️ 💭 🛃 🎚 `X-Key` & `X-Token`.
+
+✋️ 🎰 💼, 🕐❔ 🛠️ 💂♂, 👆 🔜 🤚 🌖 💰 ⚪️➡️ ⚙️ 🛠️ [💂♂ 🚙 (⏭ 📃)](../security/index.md){.internal-link target=_blank}.
+
+///
## 🔗 ❌ & 📨 💲
@@ -41,7 +47,7 @@
👫 💪 📣 📨 📄 (💖 🎚) ⚖️ 🎏 🎧-🔗:
```Python hl_lines="6 11"
-{!../../../docs_src/dependencies/tutorial006.py!}
+{!../../docs_src/dependencies/tutorial006.py!}
```
### 🤚 ⚠
@@ -49,7 +55,7 @@
👫 🔗 💪 `raise` ⚠, 🎏 😐 🔗:
```Python hl_lines="8 13"
-{!../../../docs_src/dependencies/tutorial006.py!}
+{!../../docs_src/dependencies/tutorial006.py!}
```
### 📨 💲
@@ -59,7 +65,7 @@
, 👆 💪 🏤-⚙️ 😐 🔗 (👈 📨 💲) 👆 ⏪ ⚙️ 👱 🙆, & ✋️ 💲 🏆 🚫 ⚙️, 🔗 🔜 🛠️:
```Python hl_lines="9 14"
-{!../../../docs_src/dependencies/tutorial006.py!}
+{!../../docs_src/dependencies/tutorial006.py!}
```
## 🔗 👪 *➡ 🛠️*
diff --git a/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md
index 3ed5aeba5..e0d6dba24 100644
--- a/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md
+++ b/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md
@@ -4,18 +4,24 @@ FastAPI 🐕🦺 🔗 👈 🔑 👨💼.
+/// note | "📡 ℹ"
- **FastAPI** ⚙️ 👫 🔘 🏆 👉.
+👉 👷 👏 🐍 🔑 👨💼.
+
+**FastAPI** ⚙️ 👫 🔘 🏆 👉.
+
+///
## 🔗 ⏮️ `yield` & `HTTPException`
@@ -113,8 +125,11 @@ FastAPI 🐕🦺 🔗 👈 .
+/// tip
- ✋️ 🚥 👆 ✔️ 🛃 🎚 👈 👆 💚 👩💻 🖥 💪 👀, 👆 💪 🚮 👫 👆 ⚜ 📳 ([⚜ (✖️-🇨🇳 ℹ 🤝)](cors.md){.internal-link target=_blank}) ⚙️ 🔢 `expose_headers` 📄 💃 ⚜ 🩺.
+✔️ 🤯 👈 🛃 © 🎚 💪 🚮 ⚙️ '✖-' 🔡.
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette.requests import Request`.
+✋️ 🚥 👆 ✔️ 🛃 🎚 👈 👆 💚 👩💻 🖥 💪 👀, 👆 💪 🚮 👫 👆 ⚜ 📳 ([⚜ (✖️-🇨🇳 ℹ 🤝)](cors.md){.internal-link target=_blank}) ⚙️ 🔢 `expose_headers` 📄 💃 ⚜ 🩺.
- **FastAPI** 🚚 ⚫️ 🏪 👆, 👩💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃.
+///
+
+/// note | "📡 ℹ"
+
+👆 💪 ⚙️ `from starlette.requests import Request`.
+
+**FastAPI** 🚚 ⚫️ 🏪 👆, 👩💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃.
+
+///
### ⏭ & ⏮️ `response`
@@ -51,7 +60,7 @@
🖼, 👆 💪 🚮 🛃 🎚 `X-Process-Time` ⚗ 🕰 🥈 👈 ⚫️ ✊ 🛠️ 📨 & 🏗 📨:
```Python hl_lines="10 12-13"
-{!../../../docs_src/middleware/tutorial001.py!}
+{!../../docs_src/middleware/tutorial001.py!}
```
## 🎏 🛠️
diff --git a/docs/em/docs/tutorial/path-operation-configuration.md b/docs/em/docs/tutorial/path-operation-configuration.md
index 916529258..9529928fb 100644
--- a/docs/em/docs/tutorial/path-operation-configuration.md
+++ b/docs/em/docs/tutorial/path-operation-configuration.md
@@ -2,8 +2,11 @@
📤 📚 🔢 👈 👆 💪 🚶♀️ 👆 *➡ 🛠️ 👨🎨* 🔗 ⚫️.
-!!! warning
- 👀 👈 👫 🔢 🚶♀️ 🔗 *➡ 🛠️ 👨🎨*, 🚫 👆 *➡ 🛠️ 🔢*.
+/// warning
+
+👀 👈 👫 🔢 🚶♀️ 🔗 *➡ 🛠️ 👨🎨*, 🚫 👆 *➡ 🛠️ 🔢*.
+
+///
## 📨 👔 📟
@@ -13,52 +16,67 @@
✋️ 🚥 👆 🚫 💭 ⚫️❔ 🔠 🔢 📟, 👆 💪 ⚙️ ⌨ 📉 `status`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="3 17"
- {!> ../../../docs_src/path_operation_configuration/tutorial001.py!}
- ```
+```Python hl_lines="3 17"
+{!> ../../docs_src/path_operation_configuration/tutorial001.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="3 17"
- {!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="3 17"
+{!> ../../docs_src/path_operation_configuration/tutorial001_py39.py!}
+```
- ```Python hl_lines="1 15"
- {!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!}
- ```
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="1 15"
+{!> ../../docs_src/path_operation_configuration/tutorial001_py310.py!}
+```
+
+////
👈 👔 📟 🔜 ⚙️ 📨 & 🔜 🚮 🗄 🔗.
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette import status`.
+/// note | "📡 ℹ"
- **FastAPI** 🚚 🎏 `starlette.status` `fastapi.status` 🏪 👆, 👩💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃.
+👆 💪 ⚙️ `from starlette import status`.
+
+**FastAPI** 🚚 🎏 `starlette.status` `fastapi.status` 🏪 👆, 👩💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃.
+
+///
## 🔖
👆 💪 🚮 🔖 👆 *➡ 🛠️*, 🚶♀️ 🔢 `tags` ⏮️ `list` `str` (🛎 1️⃣ `str`):
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="17 22 27"
- {!> ../../../docs_src/path_operation_configuration/tutorial002.py!}
- ```
+```Python hl_lines="17 22 27"
+{!> ../../docs_src/path_operation_configuration/tutorial002.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="17 22 27"
- {!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="17 22 27"
+{!> ../../docs_src/path_operation_configuration/tutorial002_py39.py!}
+```
- ```Python hl_lines="15 20 25"
- {!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!}
- ```
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="15 20 25"
+{!> ../../docs_src/path_operation_configuration/tutorial002_py310.py!}
+```
+
+////
👫 🔜 🚮 🗄 🔗 & ⚙️ 🏧 🧾 🔢:
@@ -73,30 +91,36 @@
**FastAPI** 🐕🦺 👈 🎏 🌌 ⏮️ ✅ 🎻:
```Python hl_lines="1 8-10 13 18"
-{!../../../docs_src/path_operation_configuration/tutorial002b.py!}
+{!../../docs_src/path_operation_configuration/tutorial002b.py!}
```
## 📄 & 📛
👆 💪 🚮 `summary` & `description`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="20-21"
- {!> ../../../docs_src/path_operation_configuration/tutorial003.py!}
- ```
+```Python hl_lines="20-21"
+{!> ../../docs_src/path_operation_configuration/tutorial003.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="20-21"
- {!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="20-21"
+{!> ../../docs_src/path_operation_configuration/tutorial003_py39.py!}
+```
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!}
- ```
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="18-19"
+{!> ../../docs_src/path_operation_configuration/tutorial003_py310.py!}
+```
+
+////
## 📛 ⚪️➡️ #️⃣
@@ -104,23 +128,29 @@
👆 💪 ✍ ✍ #️⃣ , ⚫️ 🔜 🔬 & 🖥 ☑ (✊ 🔘 🏧 #️⃣ 📐).
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="19-27"
- {!> ../../../docs_src/path_operation_configuration/tutorial004.py!}
- ```
+```Python hl_lines="19-27"
+{!> ../../docs_src/path_operation_configuration/tutorial004.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="19-27"
- {!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="19-27"
+{!> ../../docs_src/path_operation_configuration/tutorial004_py39.py!}
+```
- ```Python hl_lines="17-25"
- {!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!}
- ```
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="17-25"
+{!> ../../docs_src/path_operation_configuration/tutorial004_py310.py!}
+```
+
+////
⚫️ 🔜 ⚙️ 🎓 🩺:
@@ -130,31 +160,43 @@
👆 💪 ✔ 📨 📛 ⏮️ 🔢 `response_description`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="21"
- {!> ../../../docs_src/path_operation_configuration/tutorial005.py!}
- ```
+```Python hl_lines="21"
+{!> ../../docs_src/path_operation_configuration/tutorial005.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="21"
- {!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="21"
+{!> ../../docs_src/path_operation_configuration/tutorial005_py39.py!}
+```
- ```Python hl_lines="19"
- {!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!}
- ```
+////
-!!! info
- 👀 👈 `response_description` 🔗 🎯 📨, `description` 🔗 *➡ 🛠️* 🏢.
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-!!! check
- 🗄 ✔ 👈 🔠 *➡ 🛠️* 🚚 📨 📛.
+```Python hl_lines="19"
+{!> ../../docs_src/path_operation_configuration/tutorial005_py310.py!}
+```
- , 🚥 👆 🚫 🚚 1️⃣, **FastAPI** 🔜 🔁 🏗 1️⃣ "🏆 📨".
+////
+
+/// info
+
+👀 👈 `response_description` 🔗 🎯 📨, `description` 🔗 *➡ 🛠️* 🏢.
+
+///
+
+/// check
+
+🗄 ✔ 👈 🔠 *➡ 🛠️* 🚚 📨 📛.
+
+, 🚥 👆 🚫 🚚 1️⃣, **FastAPI** 🔜 🔁 🏗 1️⃣ "🏆 📨".
+
+///
@@ -163,7 +205,7 @@
🚥 👆 💪 ™ *➡ 🛠️* 😢, ✋️ 🍵 ❎ ⚫️, 🚶♀️ 🔢 `deprecated`:
```Python hl_lines="16"
-{!../../../docs_src/path_operation_configuration/tutorial006.py!}
+{!../../docs_src/path_operation_configuration/tutorial006.py!}
```
⚫️ 🔜 🎯 ™ 😢 🎓 🩺:
diff --git a/docs/em/docs/tutorial/path-params-numeric-validations.md b/docs/em/docs/tutorial/path-params-numeric-validations.md
index b1ba2670b..c25f0323e 100644
--- a/docs/em/docs/tutorial/path-params-numeric-validations.md
+++ b/docs/em/docs/tutorial/path-params-numeric-validations.md
@@ -6,17 +6,21 @@
🥇, 🗄 `Path` ⚪️➡️ `fastapi`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
- ```
+```Python hl_lines="3"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="1"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
+```
+
+////
## 📣 🗃
@@ -24,24 +28,31 @@
🖼, 📣 `title` 🗃 💲 ➡ 🔢 `item_id` 👆 💪 🆎:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
- ```
+```Python hl_lines="10"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-!!! note
- ➡ 🔢 🕧 ✔ ⚫️ ✔️ 🍕 ➡.
+```Python hl_lines="8"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
+```
- , 👆 🔜 📣 ⚫️ ⏮️ `...` ™ ⚫️ ✔.
+////
- 👐, 🚥 👆 📣 ⚫️ ⏮️ `None` ⚖️ ⚒ 🔢 💲, ⚫️ 🔜 🚫 📉 🕳, ⚫️ 🔜 🕧 🚚.
+/// note
+
+➡ 🔢 🕧 ✔ ⚫️ ✔️ 🍕 ➡.
+
+, 👆 🔜 📣 ⚫️ ⏮️ `...` ™ ⚫️ ✔.
+
+👐, 🚥 👆 📣 ⚫️ ⏮️ `None` ⚖️ ⚒ 🔢 💲, ⚫️ 🔜 🚫 📉 🕳, ⚫️ 🔜 🕧 🚚.
+
+///
## ✔ 🔢 👆 💪
@@ -60,7 +71,7 @@
, 👆 💪 📣 👆 🔢:
```Python hl_lines="7"
-{!../../../docs_src/path_params_numeric_validations/tutorial002.py!}
+{!../../docs_src/path_params_numeric_validations/tutorial002.py!}
```
## ✔ 🔢 👆 💪, 🎱
@@ -72,7 +83,7 @@
🐍 🏆 🚫 🕳 ⏮️ 👈 `*`, ✋️ ⚫️ 🔜 💭 👈 🌐 📄 🔢 🔜 🤙 🇨🇻 ❌ (🔑-💲 👫), 💭 kwargs. 🚥 👫 🚫 ✔️ 🔢 💲.
```Python hl_lines="7"
-{!../../../docs_src/path_params_numeric_validations/tutorial003.py!}
+{!../../docs_src/path_params_numeric_validations/tutorial003.py!}
```
## 🔢 🔬: 👑 🌘 ⚖️ 🌓
@@ -82,7 +93,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!}
```
## 🔢 🔬: 🌘 🌘 & 🌘 🌘 ⚖️ 🌓
@@ -93,7 +104,7 @@
* `le`: `l`👭 🌘 ⚖️ `e`🅾
```Python hl_lines="9"
-{!../../../docs_src/path_params_numeric_validations/tutorial005.py!}
+{!../../docs_src/path_params_numeric_validations/tutorial005.py!}
```
## 🔢 🔬: 🎈, 🌘 🌘 & 🌘 🌘
@@ -107,7 +118,7 @@
& 🎏 lt.
```Python hl_lines="11"
-{!../../../docs_src/path_params_numeric_validations/tutorial006.py!}
+{!../../docs_src/path_params_numeric_validations/tutorial006.py!}
```
## 🌃
@@ -121,18 +132,24 @@
* `lt`: `l`👭 `t`👲
* `le`: `l`👭 🌘 ⚖️ `e`🅾
-!!! info
- `Query`, `Path`, & 🎏 🎓 👆 🔜 👀 ⏪ 🏿 ⚠ `Param` 🎓.
+/// info
- 🌐 👫 💰 🎏 🔢 🌖 🔬 & 🗃 👆 ✔️ 👀.
+`Query`, `Path`, & 🎏 🎓 👆 🔜 👀 ⏪ 🏿 ⚠ `Param` 🎓.
-!!! note "📡 ℹ"
- 🕐❔ 👆 🗄 `Query`, `Path` & 🎏 ⚪️➡️ `fastapi`, 👫 🤙 🔢.
+🌐 👫 💰 🎏 🔢 🌖 🔬 & 🗃 👆 ✔️ 👀.
- 👈 🕐❔ 🤙, 📨 👐 🎓 🎏 📛.
+///
- , 👆 🗄 `Query`, ❔ 🔢. & 🕐❔ 👆 🤙 ⚫️, ⚫️ 📨 👐 🎓 🌟 `Query`.
+/// note | "📡 ℹ"
- 👫 🔢 📤 (↩️ ⚙️ 🎓 🔗) 👈 👆 👨🎨 🚫 ™ ❌ 🔃 👫 🆎.
+🕐❔ 👆 🗄 `Query`, `Path` & 🎏 ⚪️➡️ `fastapi`, 👫 🤙 🔢.
- 👈 🌌 👆 💪 ⚙️ 👆 😐 👨🎨 & 🛠️ 🧰 🍵 ✔️ 🚮 🛃 📳 🤷♂ 📚 ❌.
+👈 🕐❔ 🤙, 📨 👐 🎓 🎏 📛.
+
+, 👆 🗄 `Query`, ❔ 🔢. & 🕐❔ 👆 🤙 ⚫️, ⚫️ 📨 👐 🎓 🌟 `Query`.
+
+👫 🔢 📤 (↩️ ⚙️ 🎓 🔗) 👈 👆 👨🎨 🚫 ™ ❌ 🔃 👫 🆎.
+
+👈 🌌 👆 💪 ⚙️ 👆 😐 👨🎨 & 🛠️ 🧰 🍵 ✔️ 🚮 🛃 📳 🤷♂ 📚 ❌.
+
+///
diff --git a/docs/em/docs/tutorial/path-params.md b/docs/em/docs/tutorial/path-params.md
index ac64d2ebb..daf5417eb 100644
--- a/docs/em/docs/tutorial/path-params.md
+++ b/docs/em/docs/tutorial/path-params.md
@@ -3,7 +3,7 @@
👆 💪 📣 ➡ "🔢" ⚖️ "🔢" ⏮️ 🎏 ❕ ⚙️ 🐍 📁 🎻:
```Python hl_lines="6-7"
-{!../../../docs_src/path_params/tutorial001.py!}
+{!../../docs_src/path_params/tutorial001.py!}
```
💲 ➡ 🔢 `item_id` 🔜 🚶♀️ 👆 🔢 ❌ `item_id`.
@@ -19,13 +19,16 @@
👆 💪 📣 🆎 ➡ 🔢 🔢, ⚙️ 🐩 🐍 🆎 ✍:
```Python hl_lines="7"
-{!../../../docs_src/path_params/tutorial002.py!}
+{!../../docs_src/path_params/tutorial002.py!}
```
👉 💼, `item_id` 📣 `int`.
-!!! check
- 👉 🔜 🤝 👆 👨🎨 🐕🦺 🔘 👆 🔢, ⏮️ ❌ ✅, 🛠️, ♒️.
+/// check
+
+👉 🔜 🤝 👆 👨🎨 🐕🦺 🔘 👆 🔢, ⏮️ ❌ ✅, 🛠️, ♒️.
+
+///
## 💽 🛠️
@@ -35,10 +38,13 @@
{"item_id":3}
```
-!!! check
- 👀 👈 💲 👆 🔢 📨 (& 📨) `3`, 🐍 `int`, 🚫 🎻 `"3"`.
+/// check
- , ⏮️ 👈 🆎 📄, **FastAPI** 🤝 👆 🏧 📨 "✍".
+👀 👈 💲 👆 🔢 📨 (& 📨) `3`, 🐍 `int`, 🚫 🎻 `"3"`.
+
+, ⏮️ 👈 🆎 📄, **FastAPI** 🤝 👆 🏧 📨 "✍".
+
+///
## 💽 🔬
@@ -63,12 +69,15 @@
🎏 ❌ 🔜 😑 🚥 👆 🚚 `float` ↩️ `int`,: http://127.0.0.1:8000/items/4.2
-!!! check
- , ⏮️ 🎏 🐍 🆎 📄, **FastAPI** 🤝 👆 💽 🔬.
+/// check
- 👀 👈 ❌ 🎯 🇵🇸 ⚫️❔ ☝ 🌐❔ 🔬 🚫 🚶♀️.
+, ⏮️ 🎏 🐍 🆎 📄, **FastAPI** 🤝 👆 💽 🔬.
- 👉 🙃 👍 ⏪ 🛠️ & 🛠️ 📟 👈 🔗 ⏮️ 👆 🛠️.
+👀 👈 ❌ 🎯 🇵🇸 ⚫️❔ ☝ 🌐❔ 🔬 🚫 🚶♀️.
+
+👉 🙃 👍 ⏪ 🛠️ & 🛠️ 📟 👈 🔗 ⏮️ 👆 🛠️.
+
+///
## 🧾
@@ -76,10 +85,13 @@
-!!! check
- 🔄, ⏮️ 👈 🎏 🐍 🆎 📄, **FastAPI** 🤝 👆 🏧, 🎓 🧾 (🛠️ 🦁 🎚).
+/// check
- 👀 👈 ➡ 🔢 📣 🔢.
+🔄, ⏮️ 👈 🎏 🐍 🆎 📄, **FastAPI** 🤝 👆 🏧, 🎓 🧾 (🛠️ 🦁 🎚).
+
+👀 👈 ➡ 🔢 📣 🔢.
+
+///
## 🐩-⚓️ 💰, 🎛 🧾
@@ -110,7 +122,7 @@
↩️ *➡ 🛠️* 🔬 ✔, 👆 💪 ⚒ 💭 👈 ➡ `/users/me` 📣 ⏭ 1️⃣ `/users/{user_id}`:
```Python hl_lines="6 11"
-{!../../../docs_src/path_params/tutorial003.py!}
+{!../../docs_src/path_params/tutorial003.py!}
```
⏪, ➡ `/users/{user_id}` 🔜 🏏 `/users/me`, "💭" 👈 ⚫️ 📨 🔢 `user_id` ⏮️ 💲 `"me"`.
@@ -118,7 +130,7 @@
➡, 👆 🚫🔜 ↔ ➡ 🛠️:
```Python hl_lines="6 11"
-{!../../../docs_src/path_params/tutorial003b.py!}
+{!../../docs_src/path_params/tutorial003b.py!}
```
🥇 🕐 🔜 🕧 ⚙️ ↩️ ➡ 🏏 🥇.
@@ -136,21 +148,27 @@
⤴️ ✍ 🎓 🔢 ⏮️ 🔧 💲, ❔ 🔜 💪 ☑ 💲:
```Python hl_lines="1 6-9"
-{!../../../docs_src/path_params/tutorial005.py!}
+{!../../docs_src/path_params/tutorial005.py!}
```
-!!! info
- 🔢 (⚖️ 🔢) 💪 🐍 ↩️ ⏬ 3️⃣.4️⃣.
+/// info
-!!! tip
- 🚥 👆 💭, "📊", "🎓", & "🍏" 📛 🎰 🏫 🏷.
+🔢 (⚖️ 🔢) 💪 🐍 ↩️ ⏬ 3️⃣.4️⃣.
+
+///
+
+/// tip
+
+🚥 👆 💭, "📊", "🎓", & "🍏" 📛 🎰 🏫 🏷.
+
+///
### 📣 *➡ 🔢*
⤴️ ✍ *➡ 🔢* ⏮️ 🆎 ✍ ⚙️ 🔢 🎓 👆 ✍ (`ModelName`):
```Python hl_lines="16"
-{!../../../docs_src/path_params/tutorial005.py!}
+{!../../docs_src/path_params/tutorial005.py!}
```
### ✅ 🩺
@@ -168,7 +186,7 @@
👆 💪 🔬 ⚫️ ⏮️ *🔢 👨🎓* 👆 ✍ 🔢 `ModelName`:
```Python hl_lines="17"
-{!../../../docs_src/path_params/tutorial005.py!}
+{!../../docs_src/path_params/tutorial005.py!}
```
#### 🤚 *🔢 💲*
@@ -176,11 +194,14 @@
👆 💪 🤚 ☑ 💲 ( `str` 👉 💼) ⚙️ `model_name.value`, ⚖️ 🏢, `your_enum_member.value`:
```Python hl_lines="20"
-{!../../../docs_src/path_params/tutorial005.py!}
+{!../../docs_src/path_params/tutorial005.py!}
```
-!!! tip
- 👆 💪 🔐 💲 `"lenet"` ⏮️ `ModelName.lenet.value`.
+/// tip
+
+👆 💪 🔐 💲 `"lenet"` ⏮️ `ModelName.lenet.value`.
+
+///
#### 📨 *🔢 👨🎓*
@@ -189,7 +210,7 @@
👫 🔜 🗜 👫 🔗 💲 (🎻 👉 💼) ⏭ 🛬 👫 👩💻:
```Python hl_lines="18 21 23"
-{!../../../docs_src/path_params/tutorial005.py!}
+{!../../docs_src/path_params/tutorial005.py!}
```
👆 👩💻 👆 🔜 🤚 🎻 📨 💖:
@@ -230,13 +251,16 @@
, 👆 💪 ⚙️ ⚫️ ⏮️:
```Python hl_lines="6"
-{!../../../docs_src/path_params/tutorial004.py!}
+{!../../docs_src/path_params/tutorial004.py!}
```
-!!! tip
- 👆 💪 💪 🔢 🔌 `/home/johndoe/myfile.txt`, ⏮️ 🏁 🔪 (`/`).
+/// tip
- 👈 💼, 📛 🔜: `/files//home/johndoe/myfile.txt`, ⏮️ 2️⃣✖️ 🔪 (`//`) 🖖 `files` & `home`.
+👆 💪 💪 🔢 🔌 `/home/johndoe/myfile.txt`, ⏮️ 🏁 🔪 (`/`).
+
+👈 💼, 📛 🔜: `/files//home/johndoe/myfile.txt`, ⏮️ 2️⃣✖️ 🔪 (`//`) 🖖 `files` & `home`.
+
+///
## 🌃
diff --git a/docs/em/docs/tutorial/query-params-str-validations.md b/docs/em/docs/tutorial/query-params-str-validations.md
index 1268c0d6e..f75c0a26f 100644
--- a/docs/em/docs/tutorial/query-params-str-validations.md
+++ b/docs/em/docs/tutorial/query-params-str-validations.md
@@ -4,24 +4,31 @@
➡️ ✊ 👉 🈸 🖼:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial001.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/query_params_str_validations/tutorial001.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="7"
+{!> ../../docs_src/query_params_str_validations/tutorial001_py310.py!}
+```
+
+////
🔢 🔢 `q` 🆎 `Union[str, None]` (⚖️ `str | None` 🐍 3️⃣.1️⃣0️⃣), 👈 ⛓ 👈 ⚫️ 🆎 `str` ✋️ 💪 `None`, & 👐, 🔢 💲 `None`, FastAPI 🔜 💭 ⚫️ 🚫 ✔.
-!!! note
- FastAPI 🔜 💭 👈 💲 `q` 🚫 ✔ ↩️ 🔢 💲 `= None`.
+/// note
- `Union` `Union[str, None]` 🔜 ✔ 👆 👨🎨 🤝 👆 👍 🐕🦺 & 🔍 ❌.
+FastAPI 🔜 💭 👈 💲 `q` 🚫 ✔ ↩️ 🔢 💲 `= None`.
+
+ `Union` `Union[str, None]` 🔜 ✔ 👆 👨🎨 🤝 👆 👍 🐕🦺 & 🔍 ❌.
+
+///
## 🌖 🔬
@@ -31,33 +38,41 @@
🏆 👈, 🥇 🗄 `Query` ⚪️➡️ `fastapi`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="3"
- {!> ../../../docs_src/query_params_str_validations/tutorial002.py!}
- ```
+```Python hl_lines="3"
+{!> ../../docs_src/query_params_str_validations/tutorial002.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="1"
+{!> ../../docs_src/query_params_str_validations/tutorial002_py310.py!}
+```
+
+////
## ⚙️ `Query` 🔢 💲
& 🔜 ⚙️ ⚫️ 🔢 💲 👆 🔢, ⚒ 🔢 `max_length` 5️⃣0️⃣:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial002.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/query_params_str_validations/tutorial002.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="7"
+{!> ../../docs_src/query_params_str_validations/tutorial002_py310.py!}
+```
+
+////
👥 ✔️ ❎ 🔢 💲 `None` 🔢 ⏮️ `Query()`, 👥 💪 🔜 ⚒ 🔢 💲 ⏮️ 🔢 `Query(default=None)`, ⚫️ 🍦 🎏 🎯 ⚖ 👈 🔢 💲.
@@ -87,22 +102,25 @@ q: str | None = None
✋️ ⚫️ 📣 ⚫️ 🎯 💆♂ 🔢 🔢.
-!!! info
- ✔️ 🤯 👈 🌅 ⚠ 🍕 ⚒ 🔢 📦 🍕:
+/// info
- ```Python
- = None
- ```
+✔️ 🤯 👈 🌅 ⚠ 🍕 ⚒ 🔢 📦 🍕:
- ⚖️:
+```Python
+= None
+```
- ```Python
- = Query(default=None)
- ```
+⚖️:
- ⚫️ 🔜 ⚙️ 👈 `None` 🔢 💲, & 👈 🌌 ⚒ 🔢 **🚫 ✔**.
+```Python
+= Query(default=None)
+```
- `Union[str, None]` 🍕 ✔ 👆 👨🎨 🚚 👻 🐕🦺, ✋️ ⚫️ 🚫 ⚫️❔ 💬 FastAPI 👈 👉 🔢 🚫 ✔.
+⚫️ 🔜 ⚙️ 👈 `None` 🔢 💲, & 👈 🌌 ⚒ 🔢 **🚫 ✔**.
+
+ `Union[str, None]` 🍕 ✔ 👆 👨🎨 🚚 👻 🐕🦺, ✋️ ⚫️ 🚫 ⚫️❔ 💬 FastAPI 👈 👉 🔢 🚫 ✔.
+
+///
⤴️, 👥 💪 🚶♀️ 🌅 🔢 `Query`. 👉 💼, `max_length` 🔢 👈 ✔ 🎻:
@@ -116,33 +134,41 @@ q: Union[str, None] = Query(default=None, max_length=50)
👆 💪 🚮 🔢 `min_length`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial003.py!}
- ```
+```Python hl_lines="10"
+{!> ../../docs_src/query_params_str_validations/tutorial003.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="7"
+{!> ../../docs_src/query_params_str_validations/tutorial003_py310.py!}
+```
+
+////
## 🚮 🥔 🧬
👆 💪 🔬 🥔 🧬 👈 🔢 🔜 🏏:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial004.py!}
- ```
+```Python hl_lines="11"
+{!> ../../docs_src/query_params_str_validations/tutorial004.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="9"
+{!> ../../docs_src/query_params_str_validations/tutorial004_py310.py!}
+```
+
+////
👉 🎯 🥔 🧬 ✅ 👈 📨 🔢 💲:
@@ -161,11 +187,14 @@ 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!}
```
-!!! note
- ✔️ 🔢 💲 ⚒ 🔢 📦.
+/// note
+
+✔️ 🔢 💲 ⚒ 🔢 📦.
+
+///
## ⚒ ⚫️ ✔
@@ -190,7 +219,7 @@ q: Union[str, None] = Query(default=None, min_length=3)
, 🕐❔ 👆 💪 📣 💲 ✔ ⏪ ⚙️ `Query`, 👆 💪 🎯 🚫 📣 🔢 💲:
```Python hl_lines="7"
-{!../../../docs_src/query_params_str_validations/tutorial006.py!}
+{!../../docs_src/query_params_str_validations/tutorial006.py!}
```
### ✔ ⏮️ ❕ (`...`)
@@ -198,13 +227,16 @@ q: Union[str, None] = Query(default=None, min_length=3)
📤 🎛 🌌 🎯 📣 👈 💲 ✔. 👆 💪 ⚒ `default` 🔢 🔑 💲 `...`:
```Python hl_lines="7"
-{!../../../docs_src/query_params_str_validations/tutorial006b.py!}
+{!../../docs_src/query_params_str_validations/tutorial006b.py!}
```
-!!! info
- 🚥 👆 🚫 👀 👈 `...` ⏭: ⚫️ 🎁 👁 💲, ⚫️ 🍕 🐍 & 🤙 "❕".
+/// info
- ⚫️ ⚙️ Pydantic & FastAPI 🎯 📣 👈 💲 ✔.
+🚥 👆 🚫 👀 👈 `...` ⏭: ⚫️ 🎁 👁 💲, ⚫️ 🍕 🐍 & 🤙 "❕".
+
+⚫️ ⚙️ Pydantic & FastAPI 🎯 📣 👈 💲 ✔.
+
+///
👉 🔜 ➡️ **FastAPI** 💭 👈 👉 🔢 ✔.
@@ -214,31 +246,41 @@ q: Union[str, None] = Query(default=None, min_length=3)
👈, 👆 💪 📣 👈 `None` ☑ 🆎 ✋️ ⚙️ `default=...`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial006c.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/query_params_str_validations/tutorial006c.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-!!! tip
- Pydantic, ❔ ⚫️❔ 🏋️ 🌐 💽 🔬 & 🛠️ FastAPI, ✔️ 🎁 🎭 🕐❔ 👆 ⚙️ `Optional` ⚖️ `Union[Something, None]` 🍵 🔢 💲, 👆 💪 ✍ 🌅 🔃 ⚫️ Pydantic 🩺 🔃 ✔ 📦 🏑.
+```Python hl_lines="7"
+{!> ../../docs_src/query_params_str_validations/tutorial006c_py310.py!}
+```
+
+////
+
+/// tip
+
+Pydantic, ❔ ⚫️❔ 🏋️ 🌐 💽 🔬 & 🛠️ FastAPI, ✔️ 🎁 🎭 🕐❔ 👆 ⚙️ `Optional` ⚖️ `Union[Something, None]` 🍵 🔢 💲, 👆 💪 ✍ 🌅 🔃 ⚫️ Pydantic 🩺 🔃 ✔ 📦 🏑.
+
+///
### ⚙️ Pydantic `Required` ↩️ ❕ (`...`)
🚥 👆 💭 😬 ⚙️ `...`, 👆 💪 🗄 & ⚙️ `Required` ⚪️➡️ Pydantic:
```Python hl_lines="2 8"
-{!../../../docs_src/query_params_str_validations/tutorial006d.py!}
+{!../../docs_src/query_params_str_validations/tutorial006d.py!}
```
-!!! tip
- 💭 👈 🌅 💼, 🕐❔ 🕳 🚚, 👆 💪 🎯 🚫 `default` 🔢, 👆 🛎 🚫 ✔️ ⚙️ `...` 🚫 `Required`.
+/// tip
+
+💭 👈 🌅 💼, 🕐❔ 🕳 🚚, 👆 💪 🎯 🚫 `default` 🔢, 👆 🛎 🚫 ✔️ ⚙️ `...` 🚫 `Required`.
+
+///
## 🔢 🔢 📇 / 💗 💲
@@ -246,23 +288,29 @@ q: Union[str, None] = Query(default=None, min_length=3)
🖼, 📣 🔢 🔢 `q` 👈 💪 😑 💗 🕰 📛, 👆 💪 ✍:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial011.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/query_params_str_validations/tutorial011.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="9"
+{!> ../../docs_src/query_params_str_validations/tutorial011_py39.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial011_py310.py!}
- ```
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="7"
+{!> ../../docs_src/query_params_str_validations/tutorial011_py310.py!}
+```
+
+////
⤴️, ⏮️ 📛 💖:
@@ -283,8 +331,11 @@ http://localhost:8000/items/?q=foo&q=bar
}
```
-!!! tip
- 📣 🔢 🔢 ⏮️ 🆎 `list`, 💖 🖼 🔛, 👆 💪 🎯 ⚙️ `Query`, ⏪ ⚫️ 🔜 🔬 📨 💪.
+/// tip
+
+📣 🔢 🔢 ⏮️ 🆎 `list`, 💖 🖼 🔛, 👆 💪 🎯 ⚙️ `Query`, ⏪ ⚫️ 🔜 🔬 📨 💪.
+
+///
🎓 🛠️ 🩺 🔜 ℹ ➡️, ✔ 💗 💲:
@@ -294,17 +345,21 @@ http://localhost:8000/items/?q=foo&q=bar
& 👆 💪 🔬 🔢 `list` 💲 🚥 👌 🚚:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial012.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/query_params_str_validations/tutorial012.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
+
+```Python hl_lines="7"
+{!> ../../docs_src/query_params_str_validations/tutorial012_py39.py!}
+```
+
+////
🚥 👆 🚶:
@@ -328,13 +383,16 @@ 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!}
```
-!!! note
- ✔️ 🤯 👈 👉 💼, FastAPI 🏆 🚫 ✅ 🎚 📇.
+/// note
- 🖼, `List[int]` 🔜 ✅ (& 📄) 👈 🎚 📇 🔢. ✋️ `list` 😞 🚫🔜.
+✔️ 🤯 👈 👉 💼, FastAPI 🏆 🚫 ✅ 🎚 📇.
+
+🖼, `List[int]` 🔜 ✅ (& 📄) 👈 🎚 📇 🔢. ✋️ `list` 😞 🚫🔜.
+
+///
## 📣 🌅 🗃
@@ -342,38 +400,49 @@ http://localhost:8000/items/
👈 ℹ 🔜 🔌 🏗 🗄 & ⚙️ 🧾 👩💻 🔢 & 🔢 🧰.
-!!! note
- ✔️ 🤯 👈 🎏 🧰 5️⃣📆 ✔️ 🎏 🎚 🗄 🐕🦺.
+/// note
- 👫 💪 🚫 🎦 🌐 ➕ ℹ 📣, 👐 🌅 💼, ❌ ⚒ ⏪ 📄 🛠️.
+✔️ 🤯 👈 🎏 🧰 5️⃣📆 ✔️ 🎏 🎚 🗄 🐕🦺.
+
+👫 💪 🚫 🎦 🌐 ➕ ℹ 📣, 👐 🌅 💼, ❌ ⚒ ⏪ 📄 🛠️.
+
+///
👆 💪 🚮 `title`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial007.py!}
- ```
+```Python hl_lines="10"
+{!> ../../docs_src/query_params_str_validations/tutorial007.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="8"
+{!> ../../docs_src/query_params_str_validations/tutorial007_py310.py!}
+```
+
+////
& `description`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="13"
- {!> ../../../docs_src/query_params_str_validations/tutorial008.py!}
- ```
+```Python hl_lines="13"
+{!> ../../docs_src/query_params_str_validations/tutorial008.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="11"
+{!> ../../docs_src/query_params_str_validations/tutorial008_py310.py!}
+```
+
+////
## 📛 🔢
@@ -393,17 +462,21 @@ http://127.0.0.1:8000/items/?item-query=foobaritems
⤴️ 👆 💪 📣 `alias`, & 👈 📛 ⚫️❔ 🔜 ⚙️ 🔎 🔢 💲:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial009.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/query_params_str_validations/tutorial009.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="7"
+{!> ../../docs_src/query_params_str_validations/tutorial009_py310.py!}
+```
+
+////
## 😛 🔢
@@ -413,17 +486,21 @@ http://127.0.0.1:8000/items/?item-query=foobaritems
⤴️ 🚶♀️ 🔢 `deprecated=True` `Query`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="18"
- {!> ../../../docs_src/query_params_str_validations/tutorial010.py!}
- ```
+```Python hl_lines="18"
+{!> ../../docs_src/query_params_str_validations/tutorial010.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="16"
- {!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="16"
+{!> ../../docs_src/query_params_str_validations/tutorial010_py310.py!}
+```
+
+////
🩺 🔜 🎦 ⚫️ 💖 👉:
@@ -433,17 +510,21 @@ http://127.0.0.1:8000/items/?item-query=foobaritems
🚫 🔢 🔢 ⚪️➡️ 🏗 🗄 🔗 (& ➡️, ⚪️➡️ 🏧 🧾 ⚙️), ⚒ 🔢 `include_in_schema` `Query` `False`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial014.py!}
- ```
+```Python hl_lines="10"
+{!> ../../docs_src/query_params_str_validations/tutorial014.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="8"
+{!> ../../docs_src/query_params_str_validations/tutorial014_py310.py!}
+```
+
+////
## 🌃
diff --git a/docs/em/docs/tutorial/query-params.md b/docs/em/docs/tutorial/query-params.md
index 746b0af9e..c8432f182 100644
--- a/docs/em/docs/tutorial/query-params.md
+++ b/docs/em/docs/tutorial/query-params.md
@@ -3,7 +3,7 @@
🕐❔ 👆 📣 🎏 🔢 🔢 👈 🚫 🍕 ➡ 🔢, 👫 🔁 🔬 "🔢" 🔢.
```Python hl_lines="9"
-{!../../../docs_src/query_params/tutorial001.py!}
+{!../../docs_src/query_params/tutorial001.py!}
```
🔢 ⚒ 🔑-💲 👫 👈 🚶 ⏮️ `?` 📛, 🎏 `&` 🦹.
@@ -63,38 +63,49 @@ http://127.0.0.1:8000/items/?skip=20
🎏 🌌, 👆 💪 📣 📦 🔢 🔢, ⚒ 👫 🔢 `None`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params/tutorial002.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/query_params/tutorial002.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params/tutorial002_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="7"
+{!> ../../docs_src/query_params/tutorial002_py310.py!}
+```
+
+////
👉 💼, 🔢 🔢 `q` 🔜 📦, & 🔜 `None` 🔢.
-!!! check
- 👀 👈 **FastAPI** 🙃 🥃 👀 👈 ➡ 🔢 `item_id` ➡ 🔢 & `q` 🚫,, ⚫️ 🔢 🔢.
+/// check
+
+👀 👈 **FastAPI** 🙃 🥃 👀 👈 ➡ 🔢 `item_id` ➡ 🔢 & `q` 🚫,, ⚫️ 🔢 🔢.
+
+///
## 🔢 🔢 🆎 🛠️
👆 💪 📣 `bool` 🆎, & 👫 🔜 🗜:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params/tutorial003.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/query_params/tutorial003.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params/tutorial003_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="7"
+{!> ../../docs_src/query_params/tutorial003_py310.py!}
+```
+
+////
👉 💼, 🚥 👆 🚶:
@@ -137,17 +148,21 @@ http://127.0.0.1:8000/items/foo?short=yes
👫 🔜 🔬 📛:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="8 10"
- {!> ../../../docs_src/query_params/tutorial004.py!}
- ```
+```Python hl_lines="8 10"
+{!> ../../docs_src/query_params/tutorial004.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="6 8"
- {!> ../../../docs_src/query_params/tutorial004_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="6 8"
+{!> ../../docs_src/query_params/tutorial004_py310.py!}
+```
+
+////
## ✔ 🔢 🔢
@@ -158,7 +173,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!}
```
📥 🔢 🔢 `needy` ✔ 🔢 🔢 🆎 `str`.
@@ -203,17 +218,21 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
& ↗️, 👆 💪 🔬 🔢 ✔, ✔️ 🔢 💲, & 🍕 📦:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params/tutorial006.py!}
- ```
+```Python hl_lines="10"
+{!> ../../docs_src/query_params/tutorial006.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params/tutorial006_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="8"
+{!> ../../docs_src/query_params/tutorial006_py310.py!}
+```
+
+////
👉 💼, 📤 3️⃣ 🔢 🔢:
@@ -221,5 +240,8 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
* `skip`, `int` ⏮️ 🔢 💲 `0`.
* `limit`, 📦 `int`.
-!!! tip
- 👆 💪 ⚙️ `Enum`Ⓜ 🎏 🌌 ⏮️ [➡ 🔢](path-params.md#_7){.internal-link target=_blank}.
+/// tip
+
+👆 💪 ⚙️ `Enum`Ⓜ 🎏 🌌 ⏮️ [➡ 🔢](path-params.md#_7){.internal-link target=_blank}.
+
+///
diff --git a/docs/em/docs/tutorial/request-files.md b/docs/em/docs/tutorial/request-files.md
index be2218f89..102690f4b 100644
--- a/docs/em/docs/tutorial/request-files.md
+++ b/docs/em/docs/tutorial/request-files.md
@@ -2,19 +2,22 @@
👆 💪 🔬 📁 📂 👩💻 ⚙️ `File`.
-!!! info
- 📨 📂 📁, 🥇 ❎ `python-multipart`.
+/// info
- 🤶 Ⓜ. `pip install python-multipart`.
+📨 📂 📁, 🥇 ❎ `python-multipart`.
- 👉 ↩️ 📂 📁 📨 "📨 💽".
+🤶 Ⓜ. `pip install python-multipart`.
+
+👉 ↩️ 📂 📁 📨 "📨 💽".
+
+///
## 🗄 `File`
🗄 `File` & `UploadFile` ⚪️➡️ `fastapi`:
```Python hl_lines="1"
-{!../../../docs_src/request_files/tutorial001.py!}
+{!../../docs_src/request_files/tutorial001.py!}
```
## 🔬 `File` 🔢
@@ -22,16 +25,22 @@
✍ 📁 🔢 🎏 🌌 👆 🔜 `Body` ⚖️ `Form`:
```Python hl_lines="7"
-{!../../../docs_src/request_files/tutorial001.py!}
+{!../../docs_src/request_files/tutorial001.py!}
```
-!!! info
- `File` 🎓 👈 😖 🔗 ⚪️➡️ `Form`.
+/// info
- ✋️ 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, `File` & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓.
+`File` 🎓 👈 😖 🔗 ⚪️➡️ `Form`.
-!!! tip
- 📣 📁 💪, 👆 💪 ⚙️ `File`, ↩️ ⏪ 🔢 🔜 🔬 🔢 🔢 ⚖️ 💪 (🎻) 🔢.
+✋️ 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, `File` & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓.
+
+///
+
+/// tip
+
+📣 📁 💪, 👆 💪 ⚙️ `File`, ↩️ ⏪ 🔢 🔜 🔬 🔢 🔢 ⚖️ 💪 (🎻) 🔢.
+
+///
📁 🔜 📂 "📨 💽".
@@ -46,7 +55,7 @@
🔬 📁 🔢 ⏮️ 🆎 `UploadFile`:
```Python hl_lines="12"
-{!../../../docs_src/request_files/tutorial001.py!}
+{!../../docs_src/request_files/tutorial001.py!}
```
⚙️ `UploadFile` ✔️ 📚 📈 🤭 `bytes`:
@@ -90,11 +99,17 @@ contents = await myfile.read()
contents = myfile.file.read()
```
-!!! note "`async` 📡 ℹ"
- 🕐❔ 👆 ⚙️ `async` 👩🔬, **FastAPI** 🏃 📁 👩🔬 🧵 & ⌛ 👫.
+/// note | "`async` 📡 ℹ"
-!!! note "💃 📡 ℹ"
- **FastAPI**'Ⓜ `UploadFile` 😖 🔗 ⚪️➡️ **💃**'Ⓜ `UploadFile`, ✋️ 🚮 💪 🍕 ⚒ ⚫️ 🔗 ⏮️ **Pydantic** & 🎏 🍕 FastAPI.
+🕐❔ 👆 ⚙️ `async` 👩🔬, **FastAPI** 🏃 📁 👩🔬 🧵 & ⌛ 👫.
+
+///
+
+/// note | "💃 📡 ℹ"
+
+**FastAPI**'Ⓜ `UploadFile` 😖 🔗 ⚪️➡️ **💃**'Ⓜ `UploadFile`, ✋️ 🚮 💪 🍕 ⚒ ⚫️ 🔗 ⏮️ **Pydantic** & 🎏 🍕 FastAPI.
+
+///
## ⚫️❔ "📨 💽"
@@ -102,40 +117,50 @@ contents = myfile.file.read()
**FastAPI** 🔜 ⚒ 💭 ✍ 👈 📊 ⚪️➡️ ▶️️ 🥉 ↩️ 🎻.
-!!! note "📡 ℹ"
- 📊 ⚪️➡️ 📨 🛎 🗜 ⚙️ "📻 🆎" `application/x-www-form-urlencoded` 🕐❔ ⚫️ 🚫 🔌 📁.
+/// note | "📡 ℹ"
- ✋️ 🕐❔ 📨 🔌 📁, ⚫️ 🗜 `multipart/form-data`. 🚥 👆 ⚙️ `File`, **FastAPI** 🔜 💭 ⚫️ ✔️ 🤚 📁 ⚪️➡️ ☑ 🍕 💪.
+📊 ⚪️➡️ 📨 🛎 🗜 ⚙️ "📻 🆎" `application/x-www-form-urlencoded` 🕐❔ ⚫️ 🚫 🔌 📁.
- 🚥 👆 💚 ✍ 🌖 🔃 👉 🔢 & 📨 🏑, 👳 🏇 🕸 🩺 POST.
+✋️ 🕐❔ 📨 🔌 📁, ⚫️ 🗜 `multipart/form-data`. 🚥 👆 ⚙️ `File`, **FastAPI** 🔜 💭 ⚫️ ✔️ 🤚 📁 ⚪️➡️ ☑ 🍕 💪.
-!!! warning
- 👆 💪 📣 💗 `File` & `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `multipart/form-data` ↩️ `application/json`.
+🚥 👆 💚 ✍ 🌖 🔃 👉 🔢 & 📨 🏑, 👳 🏇 🕸 🩺 POST.
- 👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️.
+///
+
+/// warning
+
+👆 💪 📣 💗 `File` & `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `multipart/form-data` ↩️ `application/json`.
+
+👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️.
+
+///
## 📦 📁 📂
👆 💪 ⚒ 📁 📦 ⚙️ 🐩 🆎 ✍ & ⚒ 🔢 💲 `None`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="9 17"
- {!> ../../../docs_src/request_files/tutorial001_02.py!}
- ```
+```Python hl_lines="9 17"
+{!> ../../docs_src/request_files/tutorial001_02.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="7 14"
- {!> ../../../docs_src/request_files/tutorial001_02_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="7 14"
+{!> ../../docs_src/request_files/tutorial001_02_py310.py!}
+```
+
+////
## `UploadFile` ⏮️ 🌖 🗃
👆 💪 ⚙️ `File()` ⏮️ `UploadFile`, 🖼, ⚒ 🌖 🗃:
```Python hl_lines="13"
-{!../../../docs_src/request_files/tutorial001_03.py!}
+{!../../docs_src/request_files/tutorial001_03.py!}
```
## 💗 📁 📂
@@ -146,40 +171,51 @@ contents = myfile.file.read()
⚙️ 👈, 📣 📇 `bytes` ⚖️ `UploadFile`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="10 15"
- {!> ../../../docs_src/request_files/tutorial002.py!}
- ```
+```Python hl_lines="10 15"
+{!> ../../docs_src/request_files/tutorial002.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="8 13"
- {!> ../../../docs_src/request_files/tutorial002_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
+
+```Python hl_lines="8 13"
+{!> ../../docs_src/request_files/tutorial002_py39.py!}
+```
+
+////
👆 🔜 📨, 📣, `list` `bytes` ⚖️ `UploadFile`Ⓜ.
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette.responses import HTMLResponse`.
+/// note | "📡 ℹ"
- **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃.
+👆 💪 ⚙️ `from starlette.responses import HTMLResponse`.
+
+**FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃.
+
+///
### 💗 📁 📂 ⏮️ 🌖 🗃
& 🎏 🌌 ⏭, 👆 💪 ⚙️ `File()` ⚒ 🌖 🔢, `UploadFile`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="18"
- {!> ../../../docs_src/request_files/tutorial003.py!}
- ```
+```Python hl_lines="18"
+{!> ../../docs_src/request_files/tutorial003.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="16"
- {!> ../../../docs_src/request_files/tutorial003_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
+
+```Python hl_lines="16"
+{!> ../../docs_src/request_files/tutorial003_py39.py!}
+```
+
+////
## 🌃
diff --git a/docs/em/docs/tutorial/request-forms-and-files.md b/docs/em/docs/tutorial/request-forms-and-files.md
index 0415dbf01..80793dae4 100644
--- a/docs/em/docs/tutorial/request-forms-and-files.md
+++ b/docs/em/docs/tutorial/request-forms-and-files.md
@@ -2,15 +2,18 @@
👆 💪 🔬 📁 & 📨 🏑 🎏 🕰 ⚙️ `File` & `Form`.
-!!! info
- 📨 📂 📁 & /⚖️ 📨 📊, 🥇 ❎ `python-multipart`.
+/// info
- 🤶 Ⓜ. `pip install python-multipart`.
+📨 📂 📁 & /⚖️ 📨 📊, 🥇 ❎ `python-multipart`.
+
+🤶 Ⓜ. `pip install python-multipart`.
+
+///
## 🗄 `File` & `Form`
```Python hl_lines="1"
-{!../../../docs_src/request_forms_and_files/tutorial001.py!}
+{!../../docs_src/request_forms_and_files/tutorial001.py!}
```
## 🔬 `File` & `Form` 🔢
@@ -18,17 +21,20 @@
✍ 📁 & 📨 🔢 🎏 🌌 👆 🔜 `Body` ⚖️ `Query`:
```Python hl_lines="8"
-{!../../../docs_src/request_forms_and_files/tutorial001.py!}
+{!../../docs_src/request_forms_and_files/tutorial001.py!}
```
📁 & 📨 🏑 🔜 📂 📨 📊 & 👆 🔜 📨 📁 & 📨 🏑.
& 👆 💪 📣 📁 `bytes` & `UploadFile`.
-!!! warning
- 👆 💪 📣 💗 `File` & `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `multipart/form-data` ↩️ `application/json`.
+/// warning
- 👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️.
+👆 💪 📣 💗 `File` & `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `multipart/form-data` ↩️ `application/json`.
+
+👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️.
+
+///
## 🌃
diff --git a/docs/em/docs/tutorial/request-forms.md b/docs/em/docs/tutorial/request-forms.md
index f12d6e650..cbe4e2862 100644
--- a/docs/em/docs/tutorial/request-forms.md
+++ b/docs/em/docs/tutorial/request-forms.md
@@ -2,17 +2,20 @@
🕐❔ 👆 💪 📨 📨 🏑 ↩️ 🎻, 👆 💪 ⚙️ `Form`.
-!!! info
- ⚙️ 📨, 🥇 ❎ `python-multipart`.
+/// info
- 🤶 Ⓜ. `pip install python-multipart`.
+⚙️ 📨, 🥇 ❎ `python-multipart`.
+
+🤶 Ⓜ. `pip install python-multipart`.
+
+///
## 🗄 `Form`
🗄 `Form` ⚪️➡️ `fastapi`:
```Python hl_lines="1"
-{!../../../docs_src/request_forms/tutorial001.py!}
+{!../../docs_src/request_forms/tutorial001.py!}
```
## 🔬 `Form` 🔢
@@ -20,7 +23,7 @@
✍ 📨 🔢 🎏 🌌 👆 🔜 `Body` ⚖️ `Query`:
```Python hl_lines="7"
-{!../../../docs_src/request_forms/tutorial001.py!}
+{!../../docs_src/request_forms/tutorial001.py!}
```
🖼, 1️⃣ 🌌 Oauth2️⃣ 🔧 💪 ⚙️ (🤙 "🔐 💧") ⚫️ ✔ 📨 `username` & `password` 📨 🏑.
@@ -29,11 +32,17 @@
⏮️ `Form` 👆 💪 📣 🎏 📳 ⏮️ `Body` (& `Query`, `Path`, `Cookie`), 🔌 🔬, 🖼, 📛 (✅ `user-name` ↩️ `username`), ♒️.
-!!! info
- `Form` 🎓 👈 😖 🔗 ⚪️➡️ `Body`.
+/// info
-!!! tip
- 📣 📨 💪, 👆 💪 ⚙️ `Form` 🎯, ↩️ 🍵 ⚫️ 🔢 🔜 🔬 🔢 🔢 ⚖️ 💪 (🎻) 🔢.
+`Form` 🎓 👈 😖 🔗 ⚪️➡️ `Body`.
+
+///
+
+/// tip
+
+📣 📨 💪, 👆 💪 ⚙️ `Form` 🎯, ↩️ 🍵 ⚫️ 🔢 🔜 🔬 🔢 🔢 ⚖️ 💪 (🎻) 🔢.
+
+///
## 🔃 "📨 🏑"
@@ -41,17 +50,23 @@
**FastAPI** 🔜 ⚒ 💭 ✍ 👈 📊 ⚪️➡️ ▶️️ 🥉 ↩️ 🎻.
-!!! note "📡 ℹ"
- 📊 ⚪️➡️ 📨 🛎 🗜 ⚙️ "📻 🆎" `application/x-www-form-urlencoded`.
+/// note | "📡 ℹ"
- ✋️ 🕐❔ 📨 🔌 📁, ⚫️ 🗜 `multipart/form-data`. 👆 🔜 ✍ 🔃 🚚 📁 ⏭ 📃.
+📊 ⚪️➡️ 📨 🛎 🗜 ⚙️ "📻 🆎" `application/x-www-form-urlencoded`.
- 🚥 👆 💚 ✍ 🌖 🔃 👉 🔢 & 📨 🏑, 👳 🏇 🕸 🩺 POST.
+✋️ 🕐❔ 📨 🔌 📁, ⚫️ 🗜 `multipart/form-data`. 👆 🔜 ✍ 🔃 🚚 📁 ⏭ 📃.
-!!! warning
- 👆 💪 📣 💗 `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `application/x-www-form-urlencoded` ↩️ `application/json`.
+🚥 👆 💚 ✍ 🌖 🔃 👉 🔢 & 📨 🏑, 👳 🏇 🕸 🩺 POST.
- 👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️.
+///
+
+/// warning
+
+👆 💪 📣 💗 `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `application/x-www-form-urlencoded` ↩️ `application/json`.
+
+👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️.
+
+///
## 🌃
diff --git a/docs/em/docs/tutorial/response-model.md b/docs/em/docs/tutorial/response-model.md
index 7103e9176..fb5c17dd6 100644
--- a/docs/em/docs/tutorial/response-model.md
+++ b/docs/em/docs/tutorial/response-model.md
@@ -4,23 +4,29 @@
👆 💪 ⚙️ **🆎 ✍** 🎏 🌌 👆 🔜 🔢 💽 🔢 **🔢**, 👆 💪 ⚙️ Pydantic 🏷, 📇, 📖, 📊 💲 💖 🔢, 🎻, ♒️.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="18 23"
- {!> ../../../docs_src/response_model/tutorial001_01.py!}
- ```
+```Python hl_lines="18 23"
+{!> ../../docs_src/response_model/tutorial001_01.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="18 23"
- {!> ../../../docs_src/response_model/tutorial001_01_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="18 23"
+{!> ../../docs_src/response_model/tutorial001_01_py39.py!}
+```
- ```Python hl_lines="16 21"
- {!> ../../../docs_src/response_model/tutorial001_01_py310.py!}
- ```
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="16 21"
+{!> ../../docs_src/response_model/tutorial001_01_py310.py!}
+```
+
+////
FastAPI 🔜 ⚙️ 👉 📨 🆎:
@@ -53,35 +59,47 @@ FastAPI 🔜 ⚙️ 👉 📨 🆎:
* `@app.delete()`
* ♒️.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001.py!}
- ```
+```Python hl_lines="17 22 24-27"
+{!> ../../docs_src/response_model/tutorial001.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="17 22 24-27"
+{!> ../../docs_src/response_model/tutorial001_py39.py!}
+```
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001_py310.py!}
- ```
+////
-!!! note
- 👀 👈 `response_model` 🔢 "👨🎨" 👩🔬 (`get`, `post`, ♒️). 🚫 👆 *➡ 🛠️ 🔢*, 💖 🌐 🔢 & 💪.
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="17 22 24-27"
+{!> ../../docs_src/response_model/tutorial001_py310.py!}
+```
+
+////
+
+/// note
+
+👀 👈 `response_model` 🔢 "👨🎨" 👩🔬 (`get`, `post`, ♒️). 🚫 👆 *➡ 🛠️ 🔢*, 💖 🌐 🔢 & 💪.
+
+///
`response_model` 📨 🎏 🆎 👆 🔜 📣 Pydantic 🏷 🏑,, ⚫️ 💪 Pydantic 🏷, ✋️ ⚫️ 💪, ✅ `list` Pydantic 🏷, 💖 `List[Item]`.
FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & **🗜 & ⛽ 🔢 📊** 🚮 🆎 📄.
-!!! tip
- 🚥 👆 ✔️ ⚠ 🆎 ✅ 👆 👨🎨, ✍, ♒️, 👆 💪 📣 🔢 📨 🆎 `Any`.
+/// tip
- 👈 🌌 👆 💬 👨🎨 👈 👆 😫 🛬 🕳. ✋️ FastAPI 🔜 💽 🧾, 🔬, 🖥, ♒️. ⏮️ `response_model`.
+🚥 👆 ✔️ ⚠ 🆎 ✅ 👆 👨🎨, ✍, ♒️, 👆 💪 📣 🔢 📨 🆎 `Any`.
+
+👈 🌌 👆 💬 👨🎨 👈 👆 😫 🛬 🕳. ✋️ FastAPI 🔜 💽 🧾, 🔬, 🖥, ♒️. ⏮️ `response_model`.
+
+///
### `response_model` 📫
@@ -95,37 +113,48 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & **
📥 👥 📣 `UserIn` 🏷, ⚫️ 🔜 🔌 🔢 🔐:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="9 11"
- {!> ../../../docs_src/response_model/tutorial002.py!}
- ```
+```Python hl_lines="9 11"
+{!> ../../docs_src/response_model/tutorial002.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="7 9"
- {!> ../../../docs_src/response_model/tutorial002_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-!!! info
- ⚙️ `EmailStr`, 🥇 ❎ `email_validator`.
+```Python hl_lines="7 9"
+{!> ../../docs_src/response_model/tutorial002_py310.py!}
+```
- 🤶 Ⓜ. `pip install email-validator`
- ⚖️ `pip install pydantic[email]`.
+////
+
+/// info
+
+⚙️ `EmailStr`, 🥇 ❎ `email-validator`.
+
+🤶 Ⓜ. `pip install email-validator`
+⚖️ `pip install pydantic[email]`.
+
+///
& 👥 ⚙️ 👉 🏷 📣 👆 🔢 & 🎏 🏷 📣 👆 🔢:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="18"
- {!> ../../../docs_src/response_model/tutorial002.py!}
- ```
+```Python hl_lines="18"
+{!> ../../docs_src/response_model/tutorial002.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="16"
- {!> ../../../docs_src/response_model/tutorial002_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="16"
+{!> ../../docs_src/response_model/tutorial002_py310.py!}
+```
+
+////
🔜, 🕐❔ 🖥 🏗 👩💻 ⏮️ 🔐, 🛠️ 🔜 📨 🎏 🔐 📨.
@@ -133,52 +162,67 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & **
✋️ 🚥 👥 ⚙️ 🎏 🏷 ➕1️⃣ *➡ 🛠️*, 👥 💪 📨 👆 👩💻 🔐 🔠 👩💻.
-!!! danger
- 🙅 🏪 ✅ 🔐 👩💻 ⚖️ 📨 ⚫️ 📨 💖 👉, 🚥 👆 💭 🌐 ⚠ & 👆 💭 ⚫️❔ 👆 🔨.
+/// danger
+
+🙅 🏪 ✅ 🔐 👩💻 ⚖️ 📨 ⚫️ 📨 💖 👉, 🚥 👆 💭 🌐 ⚠ & 👆 💭 ⚫️❔ 👆 🔨.
+
+///
## 🚮 🔢 🏷
👥 💪 ↩️ ✍ 🔢 🏷 ⏮️ 🔢 🔐 & 🔢 🏷 🍵 ⚫️:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="9 11 16"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+```Python hl_lines="9 11 16"
+{!> ../../docs_src/response_model/tutorial003.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="9 11 16"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="9 11 16"
+{!> ../../docs_src/response_model/tutorial003_py310.py!}
+```
+
+////
📥, ✋️ 👆 *➡ 🛠️ 🔢* 🛬 🎏 🔢 👩💻 👈 🔌 🔐:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+```Python hl_lines="24"
+{!> ../../docs_src/response_model/tutorial003.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="24"
+{!> ../../docs_src/response_model/tutorial003_py310.py!}
+```
+
+////
...👥 📣 `response_model` 👆 🏷 `UserOut`, 👈 🚫 🔌 🔐:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+```Python hl_lines="22"
+{!> ../../docs_src/response_model/tutorial003.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="22"
+{!> ../../docs_src/response_model/tutorial003_py310.py!}
+```
+
+////
, **FastAPI** 🔜 ✊ 💅 🖥 👅 🌐 💽 👈 🚫 📣 🔢 🏷 (⚙️ Pydantic).
@@ -202,17 +246,21 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & **
& 👈 💼, 👥 💪 ⚙️ 🎓 & 🧬 ✊ 📈 🔢 **🆎 ✍** 🤚 👍 🐕🦺 👨🎨 & 🧰, & 🤚 FastAPI **💽 🖥**.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="9-13 15-16 20"
- {!> ../../../docs_src/response_model/tutorial003_01.py!}
- ```
+```Python hl_lines="9-13 15-16 20"
+{!> ../../docs_src/response_model/tutorial003_01.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="7-10 13-14 18"
- {!> ../../../docs_src/response_model/tutorial003_01_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="7-10 13-14 18"
+{!> ../../docs_src/response_model/tutorial003_01_py310.py!}
+```
+
+////
⏮️ 👉, 👥 🤚 🏭 🐕🦺, ⚪️➡️ 👨🎨 & ✍ 👉 📟 ☑ ⚖ 🆎, ✋️ 👥 🤚 💽 🖥 ⚪️➡️ FastAPI.
@@ -255,7 +303,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!}
```
👉 🙅 💼 🍵 🔁 FastAPI ↩️ 📨 🆎 ✍ 🎓 (⚖️ 🏿) `Response`.
@@ -267,7 +315,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓
👆 💪 ⚙️ 🏿 `Response` 🆎 ✍:
```Python hl_lines="8-9"
-{!> ../../../docs_src/response_model/tutorial003_03.py!}
+{!> ../../docs_src/response_model/tutorial003_03.py!}
```
👉 🔜 👷 ↩️ `RedirectResponse` 🏿 `Response`, & FastAPI 🔜 🔁 🍵 👉 🙅 💼.
@@ -278,17 +326,21 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓
🎏 🔜 🔨 🚥 👆 ✔️ 🕳 💖 🇪🇺 🖖 🎏 🆎 🌐❔ 1️⃣ ⚖️ 🌅 👫 🚫 ☑ Pydantic 🆎, 🖼 👉 🔜 ❌ 👶:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="10"
- {!> ../../../docs_src/response_model/tutorial003_04.py!}
- ```
+```Python hl_lines="10"
+{!> ../../docs_src/response_model/tutorial003_04.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/response_model/tutorial003_04_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="8"
+{!> ../../docs_src/response_model/tutorial003_04_py310.py!}
+```
+
+////
...👉 ❌ ↩️ 🆎 ✍ 🚫 Pydantic 🆎 & 🚫 👁 `Response` 🎓 ⚖️ 🏿, ⚫️ 🇪🇺 (🙆 2️⃣) 🖖 `Response` & `dict`.
@@ -300,17 +352,21 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓
👉 💼, 👆 💪 ❎ 📨 🏷 ⚡ ⚒ `response_model=None`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="9"
- {!> ../../../docs_src/response_model/tutorial003_05.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/response_model/tutorial003_05.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/response_model/tutorial003_05_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="7"
+{!> ../../docs_src/response_model/tutorial003_05_py310.py!}
+```
+
+////
👉 🔜 ⚒ FastAPI 🚶 📨 🏷 ⚡ & 👈 🌌 👆 💪 ✔️ 🙆 📨 🆎 ✍ 👆 💪 🍵 ⚫️ 🤕 👆 FastAPI 🈸. 👶
@@ -318,23 +374,29 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓
👆 📨 🏷 💪 ✔️ 🔢 💲, 💖:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="11 13-14"
- {!> ../../../docs_src/response_model/tutorial004.py!}
- ```
+```Python hl_lines="11 13-14"
+{!> ../../docs_src/response_model/tutorial004.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="11 13-14"
- {!> ../../../docs_src/response_model/tutorial004_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="11 13-14"
+{!> ../../docs_src/response_model/tutorial004_py39.py!}
+```
- ```Python hl_lines="9 11-12"
- {!> ../../../docs_src/response_model/tutorial004_py310.py!}
- ```
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="9 11-12"
+{!> ../../docs_src/response_model/tutorial004_py310.py!}
+```
+
+////
* `description: Union[str, None] = None` (⚖️ `str | None = None` 🐍 3️⃣.1️⃣0️⃣) ✔️ 🔢 `None`.
* `tax: float = 10.5` ✔️ 🔢 `10.5`.
@@ -348,23 +410,29 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓
👆 💪 ⚒ *➡ 🛠️ 👨🎨* 🔢 `response_model_exclude_unset=True`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial004.py!}
- ```
+```Python hl_lines="24"
+{!> ../../docs_src/response_model/tutorial004.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial004_py39.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="24"
+{!> ../../docs_src/response_model/tutorial004_py39.py!}
+```
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial004_py310.py!}
- ```
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="22"
+{!> ../../docs_src/response_model/tutorial004_py310.py!}
+```
+
+////
& 👈 🔢 💲 🏆 🚫 🔌 📨, 🕴 💲 🤙 ⚒.
@@ -377,16 +445,22 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓
}
```
-!!! info
- FastAPI ⚙️ Pydantic 🏷 `.dict()` ⏮️ 🚮 `exclude_unset` 🔢 🏆 👉.
+/// info
-!!! info
- 👆 💪 ⚙️:
+FastAPI ⚙️ Pydantic 🏷 `.dict()` ⏮️ 🚮 `exclude_unset` 🔢 🏆 👉.
- * `response_model_exclude_defaults=True`
- * `response_model_exclude_none=True`
+///
- 🔬 Pydantic 🩺 `exclude_defaults` & `exclude_none`.
+/// info
+
+👆 💪 ⚙️:
+
+* `response_model_exclude_defaults=True`
+* `response_model_exclude_none=True`
+
+🔬 Pydantic 🩺 `exclude_defaults` & `exclude_none`.
+
+///
#### 📊 ⏮️ 💲 🏑 ⏮️ 🔢
@@ -421,10 +495,13 @@ FastAPI 🙃 🥃 (🤙, Pydantic 🙃 🥃) 🤔 👈, ✋️ `description`, `t
, 👫 🔜 🔌 🎻 📨.
-!!! tip
- 👀 👈 🔢 💲 💪 🕳, 🚫 🕴 `None`.
+/// tip
- 👫 💪 📇 (`[]`), `float` `10.5`, ♒️.
+👀 👈 🔢 💲 💪 🕳, 🚫 🕴 `None`.
+
+👫 💪 📇 (`[]`), `float` `10.5`, ♒️.
+
+///
### `response_model_include` & `response_model_exclude`
@@ -434,45 +511,59 @@ FastAPI 🙃 🥃 (🤙, Pydantic 🙃 🥃) 🤔 👈, ✋️ `description`, `t
👉 💪 ⚙️ ⏩ ⌨ 🚥 👆 ✔️ 🕴 1️⃣ Pydantic 🏷 & 💚 ❎ 💽 ⚪️➡️ 🔢.
-!!! tip
- ✋️ ⚫️ 👍 ⚙️ 💭 🔛, ⚙️ 💗 🎓, ↩️ 👫 🔢.
+/// tip
- 👉 ↩️ 🎻 🔗 🏗 👆 📱 🗄 (& 🩺) 🔜 1️⃣ 🏁 🏷, 🚥 👆 ⚙️ `response_model_include` ⚖️ `response_model_exclude` 🚫 🔢.
+✋️ ⚫️ 👍 ⚙️ 💭 🔛, ⚙️ 💗 🎓, ↩️ 👫 🔢.
- 👉 ✔ `response_model_by_alias` 👈 👷 ➡.
+👉 ↩️ 🎻 🔗 🏗 👆 📱 🗄 (& 🩺) 🔜 1️⃣ 🏁 🏷, 🚥 👆 ⚙️ `response_model_include` ⚖️ `response_model_exclude` 🚫 🔢.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+👉 ✔ `response_model_by_alias` 👈 👷 ➡.
- ```Python hl_lines="31 37"
- {!> ../../../docs_src/response_model/tutorial005.py!}
- ```
+///
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="29 35"
- {!> ../../../docs_src/response_model/tutorial005_py310.py!}
- ```
+```Python hl_lines="31 37"
+{!> ../../docs_src/response_model/tutorial005.py!}
+```
-!!! tip
- ❕ `{"name", "description"}` ✍ `set` ⏮️ 📚 2️⃣ 💲.
+////
- ⚫️ 🌓 `set(["name", "description"])`.
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="29 35"
+{!> ../../docs_src/response_model/tutorial005_py310.py!}
+```
+
+////
+
+/// tip
+
+❕ `{"name", "description"}` ✍ `set` ⏮️ 📚 2️⃣ 💲.
+
+⚫️ 🌓 `set(["name", "description"])`.
+
+///
#### ⚙️ `list`Ⓜ ↩️ `set`Ⓜ
🚥 👆 💭 ⚙️ `set` & ⚙️ `list` ⚖️ `tuple` ↩️, FastAPI 🔜 🗜 ⚫️ `set` & ⚫️ 🔜 👷 ☑:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="31 37"
- {!> ../../../docs_src/response_model/tutorial006.py!}
- ```
+```Python hl_lines="31 37"
+{!> ../../docs_src/response_model/tutorial006.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="29 35"
- {!> ../../../docs_src/response_model/tutorial006_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="29 35"
+{!> ../../docs_src/response_model/tutorial006_py310.py!}
+```
+
+////
## 🌃
diff --git a/docs/em/docs/tutorial/response-status-code.md b/docs/em/docs/tutorial/response-status-code.md
index e5149de7d..cefff708f 100644
--- a/docs/em/docs/tutorial/response-status-code.md
+++ b/docs/em/docs/tutorial/response-status-code.md
@@ -9,16 +9,22 @@
* ♒️.
```Python hl_lines="6"
-{!../../../docs_src/response_status_code/tutorial001.py!}
+{!../../docs_src/response_status_code/tutorial001.py!}
```
-!!! note
- 👀 👈 `status_code` 🔢 "👨🎨" 👩🔬 (`get`, `post`, ♒️). 🚫 👆 *➡ 🛠️ 🔢*, 💖 🌐 🔢 & 💪.
+/// note
+
+👀 👈 `status_code` 🔢 "👨🎨" 👩🔬 (`get`, `post`, ♒️). 🚫 👆 *➡ 🛠️ 🔢*, 💖 🌐 🔢 & 💪.
+
+///
`status_code` 🔢 📨 🔢 ⏮️ 🇺🇸🔍 👔 📟.
-!!! info
- `status_code` 💪 👐 📨 `IntEnum`, ✅ 🐍 `http.HTTPStatus`.
+/// info
+
+`status_code` 💪 👐 📨 `IntEnum`, ✅ 🐍 `http.HTTPStatus`.
+
+///
⚫️ 🔜:
@@ -27,15 +33,21 @@
-!!! note
- 📨 📟 (👀 ⏭ 📄) 🎦 👈 📨 🔨 🚫 ✔️ 💪.
+/// note
- FastAPI 💭 👉, & 🔜 🏭 🗄 🩺 👈 🇵🇸 📤 🙅♂ 📨 💪.
+📨 📟 (👀 ⏭ 📄) 🎦 👈 📨 🔨 🚫 ✔️ 💪.
+
+FastAPI 💭 👉, & 🔜 🏭 🗄 🩺 👈 🇵🇸 📤 🙅♂ 📨 💪.
+
+///
## 🔃 🇺🇸🔍 👔 📟
-!!! note
- 🚥 👆 ⏪ 💭 ⚫️❔ 🇺🇸🔍 👔 📟, 🚶 ⏭ 📄.
+/// note
+
+🚥 👆 ⏪ 💭 ⚫️❔ 🇺🇸🔍 👔 📟, 🚶 ⏭ 📄.
+
+///
🇺🇸🔍, 👆 📨 🔢 👔 📟 3️⃣ 9️⃣ 🍕 📨.
@@ -54,15 +66,18 @@
* 💊 ❌ ⚪️➡️ 👩💻, 👆 💪 ⚙️ `400`.
* `500` & 🔛 💽 ❌. 👆 🌖 🙅 ⚙️ 👫 🔗. 🕐❔ 🕳 🚶 ❌ 🍕 👆 🈸 📟, ⚖️ 💽, ⚫️ 🔜 🔁 📨 1️⃣ 👫 👔 📟.
-!!! tip
- 💭 🌅 🔃 🔠 👔 📟 & ❔ 📟 ⚫️❔, ✅ 🏇 🧾 🔃 🇺🇸🔍 👔 📟.
+/// tip
+
+💭 🌅 🔃 🔠 👔 📟 & ❔ 📟 ⚫️❔, ✅ 🏇 🧾 🔃 🇺🇸🔍 👔 📟.
+
+///
## ⌨ 💭 📛
➡️ 👀 ⏮️ 🖼 🔄:
```Python hl_lines="6"
-{!../../../docs_src/response_status_code/tutorial001.py!}
+{!../../docs_src/response_status_code/tutorial001.py!}
```
`201` 👔 📟 "✍".
@@ -72,17 +87,20 @@
👆 💪 ⚙️ 🏪 🔢 ⚪️➡️ `fastapi.status`.
```Python hl_lines="1 6"
-{!../../../docs_src/response_status_code/tutorial002.py!}
+{!../../docs_src/response_status_code/tutorial002.py!}
```
👫 🏪, 👫 🧑🤝🧑 🎏 🔢, ✋️ 👈 🌌 👆 💪 ⚙️ 👨🎨 📋 🔎 👫:
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette import status`.
+/// note | "📡 ℹ"
- **FastAPI** 🚚 🎏 `starlette.status` `fastapi.status` 🏪 👆, 👩💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃.
+👆 💪 ⚙️ `from starlette import status`.
+
+**FastAPI** 🚚 🎏 `starlette.status` `fastapi.status` 🏪 👆, 👩💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃.
+
+///
## 🔀 🔢
diff --git a/docs/em/docs/tutorial/schema-extra-example.md b/docs/em/docs/tutorial/schema-extra-example.md
index 114d5a84a..e4f877a8e 100644
--- a/docs/em/docs/tutorial/schema-extra-example.md
+++ b/docs/em/docs/tutorial/schema-extra-example.md
@@ -8,24 +8,31 @@
👆 💪 📣 `example` Pydantic 🏷 ⚙️ `Config` & `schema_extra`, 🔬 Pydantic 🩺: 🔗 🛃:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="15-23"
- {!> ../../../docs_src/schema_extra_example/tutorial001.py!}
- ```
+```Python hl_lines="15-23"
+{!> ../../docs_src/schema_extra_example/tutorial001.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="13-21"
- {!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="13-21"
+{!> ../../docs_src/schema_extra_example/tutorial001_py310.py!}
+```
+
+////
👈 ➕ ℹ 🔜 🚮-🔢 **🎻 🔗** 👈 🏷, & ⚫️ 🔜 ⚙️ 🛠️ 🩺.
-!!! tip
- 👆 💪 ⚙️ 🎏 ⚒ ↔ 🎻 🔗 & 🚮 👆 👍 🛃 ➕ ℹ.
+/// tip
- 🖼 👆 💪 ⚙️ ⚫️ 🚮 🗃 🕸 👩💻 🔢, ♒️.
+👆 💪 ⚙️ 🎏 ⚒ ↔ 🎻 🔗 & 🚮 👆 👍 🛃 ➕ ℹ.
+
+🖼 👆 💪 ⚙️ ⚫️ 🚮 🗃 🕸 👩💻 🔢, ♒️.
+
+///
## `Field` 🌖 ❌
@@ -33,20 +40,27 @@
👆 💪 ⚙️ 👉 🚮 `example` 🔠 🏑:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="4 10-13"
- {!> ../../../docs_src/schema_extra_example/tutorial002.py!}
- ```
+```Python hl_lines="4 10-13"
+{!> ../../docs_src/schema_extra_example/tutorial002.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="2 8-11"
- {!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-!!! warning
- 🚧 🤯 👈 📚 ➕ ❌ 🚶♀️ 🏆 🚫 🚮 🙆 🔬, 🕴 ➕ ℹ, 🧾 🎯.
+```Python hl_lines="2 8-11"
+{!> ../../docs_src/schema_extra_example/tutorial002_py310.py!}
+```
+
+////
+
+/// warning
+
+🚧 🤯 👈 📚 ➕ ❌ 🚶♀️ 🏆 🚫 🚮 🙆 🔬, 🕴 ➕ ℹ, 🧾 🎯.
+
+///
## `example` & `examples` 🗄
@@ -66,17 +80,21 @@
📥 👥 🚶♀️ `example` 📊 ⌛ `Body()`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="20-25"
- {!> ../../../docs_src/schema_extra_example/tutorial003.py!}
- ```
+```Python hl_lines="20-25"
+{!> ../../docs_src/schema_extra_example/tutorial003.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="18-23"
- {!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="18-23"
+{!> ../../docs_src/schema_extra_example/tutorial003_py310.py!}
+```
+
+////
### 🖼 🩺 🎚
@@ -97,17 +115,21 @@
* `value`: 👉 ☑ 🖼 🎦, ✅ `dict`.
* `externalValue`: 🎛 `value`, 📛 ☝ 🖼. 👐 👉 5️⃣📆 🚫 🐕🦺 📚 🧰 `value`.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="21-47"
- {!> ../../../docs_src/schema_extra_example/tutorial004.py!}
- ```
+```Python hl_lines="21-47"
+{!> ../../docs_src/schema_extra_example/tutorial004.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="19-45"
- {!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="19-45"
+{!> ../../docs_src/schema_extra_example/tutorial004_py310.py!}
+```
+
+////
### 🖼 🩺 🎚
@@ -117,10 +139,13 @@
## 📡 ℹ
-!!! warning
- 👉 📶 📡 ℹ 🔃 🐩 **🎻 🔗** & **🗄**.
+/// warning
- 🚥 💭 🔛 ⏪ 👷 👆, 👈 💪 🥃, & 👆 🎲 🚫 💪 👉 ℹ, 💭 🆓 🚶 👫.
+👉 📶 📡 ℹ 🔃 🐩 **🎻 🔗** & **🗄**.
+
+🚥 💭 🔛 ⏪ 👷 👆, 👈 💪 🥃, & 👆 🎲 🚫 💪 👉 ℹ, 💭 🆓 🚶 👫.
+
+///
🕐❔ 👆 🚮 🖼 🔘 Pydantic 🏷, ⚙️ `schema_extra` ⚖️ `Field(example="something")` 👈 🖼 🚮 **🎻 🔗** 👈 Pydantic 🏷.
diff --git a/docs/em/docs/tutorial/security/first-steps.md b/docs/em/docs/tutorial/security/first-steps.md
index 8c2c95cfd..6245f52ab 100644
--- a/docs/em/docs/tutorial/security/first-steps.md
+++ b/docs/em/docs/tutorial/security/first-steps.md
@@ -21,17 +21,20 @@
📁 🖼 📁 `main.py`:
```Python
-{!../../../docs_src/security/tutorial001.py!}
+{!../../docs_src/security/tutorial001.py!}
```
## 🏃 ⚫️
-!!! info
- 🥇 ❎ `python-multipart`.
+/// info
- 🤶 Ⓜ. `pip install python-multipart`.
+🥇 ❎ `python-multipart`.
- 👉 ↩️ **Oauth2️⃣** ⚙️ "📨 📊" 📨 `username` & `password`.
+🤶 Ⓜ. `pip install python-multipart`.
+
+👉 ↩️ **Oauth2️⃣** ⚙️ "📨 📊" 📨 `username` & `password`.
+
+///
🏃 🖼 ⏮️:
@@ -53,17 +56,23 @@ $ uvicorn main:app --reload
-!!! check "✔ 🔼 ❗"
- 👆 ⏪ ✔️ ✨ 🆕 "✔" 🔼.
+/// check | "✔ 🔼 ❗"
- & 👆 *➡ 🛠️* ✔️ 🐥 🔒 🔝-▶️️ ↩ 👈 👆 💪 🖊.
+👆 ⏪ ✔️ ✨ 🆕 "✔" 🔼.
+
+ & 👆 *➡ 🛠️* ✔️ 🐥 🔒 🔝-▶️️ ↩ 👈 👆 💪 🖊.
+
+///
& 🚥 👆 🖊 ⚫️, 👆 ✔️ 🐥 ✔ 📨 🆎 `username` & `password` (& 🎏 📦 🏑):
-!!! note
- ⚫️ 🚫 🤔 ⚫️❔ 👆 🆎 📨, ⚫️ 🏆 🚫 👷. ✋️ 👥 🔜 🤚 📤.
+/// note
+
+⚫️ 🚫 🤔 ⚫️❔ 👆 🆎 📨, ⚫️ 🏆 🚫 👷. ✋️ 👥 🔜 🤚 📤.
+
+///
👉 ↗️ 🚫 🕸 🏁 👩💻, ✋️ ⚫️ 👑 🏧 🧰 📄 🖥 🌐 👆 🛠️.
@@ -105,36 +114,45 @@ Oauth2️⃣ 🔧 👈 👩💻 ⚖️ 🛠️ 💪 🔬 💽 👈 🔓 👩
👉 🖼 👥 🔜 ⚙️ **Oauth2️⃣**, ⏮️ **🔐** 💧, ⚙️ **📨** 🤝. 👥 👈 ⚙️ `OAuth2PasswordBearer` 🎓.
-!!! info
- "📨" 🤝 🚫 🕴 🎛.
+/// info
- ✋️ ⚫️ 🏆 1️⃣ 👆 ⚙️ 💼.
+"📨" 🤝 🚫 🕴 🎛.
- & ⚫️ 💪 🏆 🏆 ⚙️ 💼, 🚥 👆 Oauth2️⃣ 🕴 & 💭 ⚫️❔ ⚫️❔ 📤 ➕1️⃣ 🎛 👈 ♣ 👻 👆 💪.
+✋️ ⚫️ 🏆 1️⃣ 👆 ⚙️ 💼.
- 👈 💼, **FastAPI** 🚚 👆 ⏮️ 🧰 🏗 ⚫️.
+ & ⚫️ 💪 🏆 🏆 ⚙️ 💼, 🚥 👆 Oauth2️⃣ 🕴 & 💭 ⚫️❔ ⚫️❔ 📤 ➕1️⃣ 🎛 👈 ♣ 👻 👆 💪.
+
+👈 💼, **FastAPI** 🚚 👆 ⏮️ 🧰 🏗 ⚫️.
+
+///
🕐❔ 👥 ✍ 👐 `OAuth2PasswordBearer` 🎓 👥 🚶♀️ `tokenUrl` 🔢. 👉 🔢 🔌 📛 👈 👩💻 (🕸 🏃 👩💻 🖥) 🔜 ⚙️ 📨 `username` & `password` ✔ 🤚 🤝.
```Python hl_lines="6"
-{!../../../docs_src/security/tutorial001.py!}
+{!../../docs_src/security/tutorial001.py!}
```
-!!! tip
- 📥 `tokenUrl="token"` 🔗 ⚖ 📛 `token` 👈 👥 🚫 ✍. ⚫️ ⚖ 📛, ⚫️ 🌓 `./token`.
+/// tip
- ↩️ 👥 ⚙️ ⚖ 📛, 🚥 👆 🛠️ 🔎 `https://example.com/`, ⤴️ ⚫️ 🔜 🔗 `https://example.com/token`. ✋️ 🚥 👆 🛠️ 🔎 `https://example.com/api/v1/`, ⤴️ ⚫️ 🔜 🔗 `https://example.com/api/v1/token`.
+📥 `tokenUrl="token"` 🔗 ⚖ 📛 `token` 👈 👥 🚫 ✍. ⚫️ ⚖ 📛, ⚫️ 🌓 `./token`.
- ⚙️ ⚖ 📛 ⚠ ⚒ 💭 👆 🈸 🚧 👷 🏧 ⚙️ 💼 💖 [⛅ 🗳](../../advanced/behind-a-proxy.md){.internal-link target=_blank}.
+↩️ 👥 ⚙️ ⚖ 📛, 🚥 👆 🛠️ 🔎 `https://example.com/`, ⤴️ ⚫️ 🔜 🔗 `https://example.com/token`. ✋️ 🚥 👆 🛠️ 🔎 `https://example.com/api/v1/`, ⤴️ ⚫️ 🔜 🔗 `https://example.com/api/v1/token`.
+
+⚙️ ⚖ 📛 ⚠ ⚒ 💭 👆 🈸 🚧 👷 🏧 ⚙️ 💼 💖 [⛅ 🗳](../../advanced/behind-a-proxy.md){.internal-link target=_blank}.
+
+///
👉 🔢 🚫 ✍ 👈 🔗 / *➡ 🛠️*, ✋️ 📣 👈 📛 `/token` 🔜 1️⃣ 👈 👩💻 🔜 ⚙️ 🤚 🤝. 👈 ℹ ⚙️ 🗄, & ⤴️ 🎓 🛠️ 🧾 ⚙️.
👥 🔜 🔜 ✍ ☑ ➡ 🛠️.
-!!! info
- 🚥 👆 📶 ⚠ "✍" 👆 💪 👎 👗 🔢 📛 `tokenUrl` ↩️ `token_url`.
+/// info
- 👈 ↩️ ⚫️ ⚙️ 🎏 📛 🗄 🔌. 👈 🚥 👆 💪 🔬 🌅 🔃 🙆 👫 💂♂ ⚖ 👆 💪 📁 & 📋 ⚫️ 🔎 🌖 ℹ 🔃 ⚫️.
+🚥 👆 📶 ⚠ "✍" 👆 💪 👎 👗 🔢 📛 `tokenUrl` ↩️ `token_url`.
+
+👈 ↩️ ⚫️ ⚙️ 🎏 📛 🗄 🔌. 👈 🚥 👆 💪 🔬 🌅 🔃 🙆 👫 💂♂ ⚖ 👆 💪 📁 & 📋 ⚫️ 🔎 🌖 ℹ 🔃 ⚫️.
+
+///
`oauth2_scheme` 🔢 👐 `OAuth2PasswordBearer`, ✋️ ⚫️ "🇧🇲".
@@ -151,17 +169,20 @@ oauth2_scheme(some, parameters)
🔜 👆 💪 🚶♀️ 👈 `oauth2_scheme` 🔗 ⏮️ `Depends`.
```Python hl_lines="10"
-{!../../../docs_src/security/tutorial001.py!}
+{!../../docs_src/security/tutorial001.py!}
```
👉 🔗 🔜 🚚 `str` 👈 🛠️ 🔢 `token` *➡ 🛠️ 🔢*.
**FastAPI** 🔜 💭 👈 ⚫️ 💪 ⚙️ 👉 🔗 🔬 "💂♂ ⚖" 🗄 🔗 (& 🏧 🛠️ 🩺).
-!!! info "📡 ℹ"
- **FastAPI** 🔜 💭 👈 ⚫️ 💪 ⚙️ 🎓 `OAuth2PasswordBearer` (📣 🔗) 🔬 💂♂ ⚖ 🗄 ↩️ ⚫️ 😖 ⚪️➡️ `fastapi.security.oauth2.OAuth2`, ❔ 🔄 😖 ⚪️➡️ `fastapi.security.base.SecurityBase`.
+/// info | "📡 ℹ"
- 🌐 💂♂ 🚙 👈 🛠️ ⏮️ 🗄 (& 🏧 🛠️ 🩺) 😖 ⚪️➡️ `SecurityBase`, 👈 ❔ **FastAPI** 💪 💭 ❔ 🛠️ 👫 🗄.
+**FastAPI** 🔜 💭 👈 ⚫️ 💪 ⚙️ 🎓 `OAuth2PasswordBearer` (📣 🔗) 🔬 💂♂ ⚖ 🗄 ↩️ ⚫️ 😖 ⚪️➡️ `fastapi.security.oauth2.OAuth2`, ❔ 🔄 😖 ⚪️➡️ `fastapi.security.base.SecurityBase`.
+
+🌐 💂♂ 🚙 👈 🛠️ ⏮️ 🗄 (& 🏧 🛠️ 🩺) 😖 ⚪️➡️ `SecurityBase`, 👈 ❔ **FastAPI** 💪 💭 ❔ 🛠️ 👫 🗄.
+
+///
## ⚫️❔ ⚫️ 🔨
diff --git a/docs/em/docs/tutorial/security/get-current-user.md b/docs/em/docs/tutorial/security/get-current-user.md
index 455cb4f46..4e5b4ebfc 100644
--- a/docs/em/docs/tutorial/security/get-current-user.md
+++ b/docs/em/docs/tutorial/security/get-current-user.md
@@ -3,7 +3,7 @@
⏮️ 📃 💂♂ ⚙️ (❔ 🧢 🔛 🔗 💉 ⚙️) 🤝 *➡ 🛠️ 🔢* `token` `str`:
```Python hl_lines="10"
-{!../../../docs_src/security/tutorial001.py!}
+{!../../docs_src/security/tutorial001.py!}
```
✋️ 👈 🚫 👈 ⚠.
@@ -16,17 +16,21 @@
🎏 🌌 👥 ⚙️ Pydantic 📣 💪, 👥 💪 ⚙️ ⚫️ 🙆 🙆:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="5 12-16"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+```Python hl_lines="5 12-16"
+{!> ../../docs_src/security/tutorial002.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="3 10-14"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="3 10-14"
+{!> ../../docs_src/security/tutorial002_py310.py!}
+```
+
+////
## ✍ `get_current_user` 🔗
@@ -38,63 +42,81 @@
🎏 👥 🔨 ⏭ *➡ 🛠️* 🔗, 👆 🆕 🔗 `get_current_user` 🔜 📨 `token` `str` ⚪️➡️ 🎧-🔗 `oauth2_scheme`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="25"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+```Python hl_lines="25"
+{!> ../../docs_src/security/tutorial002.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="23"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="23"
+{!> ../../docs_src/security/tutorial002_py310.py!}
+```
+
+////
## 🤚 👩💻
`get_current_user` 🔜 ⚙️ (❌) 🚙 🔢 👥 ✍, 👈 ✊ 🤝 `str` & 📨 👆 Pydantic `User` 🏷:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="19-22 26-27"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+```Python hl_lines="19-22 26-27"
+{!> ../../docs_src/security/tutorial002.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="17-20 24-25"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="17-20 24-25"
+{!> ../../docs_src/security/tutorial002_py310.py!}
+```
+
+////
## 💉 ⏮️ 👩💻
🔜 👥 💪 ⚙️ 🎏 `Depends` ⏮️ 👆 `get_current_user` *➡ 🛠️*:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="31"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+```Python hl_lines="31"
+{!> ../../docs_src/security/tutorial002.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="29"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="29"
+{!> ../../docs_src/security/tutorial002_py310.py!}
+```
+
+////
👀 👈 👥 📣 🆎 `current_user` Pydantic 🏷 `User`.
👉 🔜 ℹ 🇺🇲 🔘 🔢 ⏮️ 🌐 🛠️ & 🆎 ✅.
-!!! tip
- 👆 5️⃣📆 💭 👈 📨 💪 📣 ⏮️ Pydantic 🏷.
+/// tip
- 📥 **FastAPI** 🏆 🚫 🤚 😨 ↩️ 👆 ⚙️ `Depends`.
+👆 5️⃣📆 💭 👈 📨 💪 📣 ⏮️ Pydantic 🏷.
-!!! check
- 🌌 👉 🔗 ⚙️ 🏗 ✔ 👥 ✔️ 🎏 🔗 (🎏 "☑") 👈 🌐 📨 `User` 🏷.
+📥 **FastAPI** 🏆 🚫 🤚 😨 ↩️ 👆 ⚙️ `Depends`.
- 👥 🚫 🚫 ✔️ 🕴 1️⃣ 🔗 👈 💪 📨 👈 🆎 💽.
+///
+
+/// check
+
+🌌 👉 🔗 ⚙️ 🏗 ✔ 👥 ✔️ 🎏 🔗 (🎏 "☑") 👈 🌐 📨 `User` 🏷.
+
+👥 🚫 🚫 ✔️ 🕴 1️⃣ 🔗 👈 💪 📨 👈 🆎 💽.
+
+///
## 🎏 🏷
@@ -128,17 +150,21 @@
& 🌐 👉 💯 *➡ 🛠️* 💪 🤪 3️⃣ ⏸:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="30-32"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+```Python hl_lines="30-32"
+{!> ../../docs_src/security/tutorial002.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="28-30"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="28-30"
+{!> ../../docs_src/security/tutorial002_py310.py!}
+```
+
+////
## 🌃
diff --git a/docs/em/docs/tutorial/security/index.md b/docs/em/docs/tutorial/security/index.md
index d76f7203f..1a47e5510 100644
--- a/docs/em/docs/tutorial/security/index.md
+++ b/docs/em/docs/tutorial/security/index.md
@@ -32,9 +32,11 @@ Oauth2️⃣ 🔧 👈 🔬 📚 🌌 🍵 🤝 & ✔.
Oauth2️⃣ 🚫 ✔ ❔ 🗜 📻, ⚫️ ⌛ 👆 ✔️ 👆 🈸 🍦 ⏮️ 🇺🇸🔍.
-!!! tip
- 📄 🔃 **🛠️** 👆 🔜 👀 ❔ ⚒ 🆙 🇺🇸🔍 🆓, ⚙️ Traefik & ➡️ 🗜.
+/// tip
+📄 🔃 **🛠️** 👆 🔜 👀 ❔ ⚒ 🆙 🇺🇸🔍 🆓, ⚙️ Traefik & ➡️ 🗜.
+
+///
## 👩💻 🔗
@@ -87,10 +89,13 @@ Oauth2️⃣ 🚫 ✔ ❔ 🗜 📻, ⚫️ ⌛ 👆 ✔️ 👆 🈸 🍦 ⏮
* 👉 🏧 🔍 ⚫️❔ 🔬 👩💻 🔗 🔧.
-!!! tip
- 🛠️ 🎏 🤝/✔ 🐕🦺 💖 🇺🇸🔍, 👱📔, 👱📔, 📂, ♒️. 💪 & 📶 ⏩.
+/// tip
- 🌅 🏗 ⚠ 🏗 🤝/✔ 🐕🦺 💖 👈, ✋️ **FastAPI** 🤝 👆 🧰 ⚫️ 💪, ⏪ 🔨 🏋️ 🏋♂ 👆.
+🛠️ 🎏 🤝/✔ 🐕🦺 💖 🇺🇸🔍, 👱📔, 👱📔, 📂, ♒️. 💪 & 📶 ⏩.
+
+🌅 🏗 ⚠ 🏗 🤝/✔ 🐕🦺 💖 👈, ✋️ **FastAPI** 🤝 👆 🧰 ⚫️ 💪, ⏪ 🔨 🏋️ 🏋♂ 👆.
+
+///
## **FastAPI** 🚙
diff --git a/docs/em/docs/tutorial/security/oauth2-jwt.md b/docs/em/docs/tutorial/security/oauth2-jwt.md
index bc3c943f8..95fa58f71 100644
--- a/docs/em/docs/tutorial/security/oauth2-jwt.md
+++ b/docs/em/docs/tutorial/security/oauth2-jwt.md
@@ -44,10 +44,13 @@ $ pip install "python-jose[cryptography]"
📥 👥 ⚙️ 👍 1️⃣: )/⚛.
-!!! tip
- 👉 🔰 ⏪ ⚙️ PyJWT.
+/// tip
- ✋️ ⚫️ ℹ ⚙️ 🐍-🇩🇬 ↩️ ⚫️ 🚚 🌐 ⚒ ⚪️➡️ PyJWT ➕ ➕ 👈 👆 💪 💪 ⏪ 🕐❔ 🏗 🛠️ ⏮️ 🎏 🧰.
+👉 🔰 ⏪ ⚙️ PyJWT.
+
+✋️ ⚫️ ℹ ⚙️ 🐍-🇩🇬 ↩️ ⚫️ 🚚 🌐 ⚒ ⚪️➡️ PyJWT ➕ ➕ 👈 👆 💪 💪 ⏪ 🕐❔ 🏗 🛠️ ⏮️ 🎏 🧰.
+
+///
## 🔐 🔁
@@ -83,12 +86,15 @@ $ pip install "passlib[bcrypt]"
-!!! tip
- ⏮️ `passlib`, 👆 💪 🔗 ⚫️ 💪 ✍ 🔐 ✍ **✳**, **🏺** 💂♂ 🔌-⚖️ 📚 🎏.
+/// tip
- , 👆 🔜 💪, 🖼, 💰 🎏 📊 ⚪️➡️ ✳ 🈸 💽 ⏮️ FastAPI 🈸. ⚖️ 📉 ↔ ✳ 🈸 ⚙️ 🎏 💽.
+⏮️ `passlib`, 👆 💪 🔗 ⚫️ 💪 ✍ 🔐 ✍ **✳**, **🏺** 💂♂ 🔌-⚖️ 📚 🎏.
- & 👆 👩💻 🔜 💪 💳 ⚪️➡️ 👆 ✳ 📱 ⚖️ ⚪️➡️ 👆 **FastAPI** 📱, 🎏 🕰.
+, 👆 🔜 💪, 🖼, 💰 🎏 📊 ⚪️➡️ ✳ 🈸 💽 ⏮️ FastAPI 🈸. ⚖️ 📉 ↔ ✳ 🈸 ⚙️ 🎏 💽.
+
+ & 👆 👩💻 🔜 💪 💳 ⚪️➡️ 👆 ✳ 📱 ⚖️ ⚪️➡️ 👆 **FastAPI** 📱, 🎏 🕰.
+
+///
## #️⃣ & ✔ 🔐
@@ -96,12 +102,15 @@ $ pip install "passlib[bcrypt]"
✍ 🇸🇲 "🔑". 👉 ⚫️❔ 🔜 ⚙️ #️⃣ & ✔ 🔐.
-!!! tip
- 🇸🇲 🔑 ✔️ 🛠️ ⚙️ 🎏 🔁 📊, 🔌 😢 🗝 🕐 🕴 ✔ ✔ 👫, ♒️.
+/// tip
- 🖼, 👆 💪 ⚙️ ⚫️ ✍ & ✔ 🔐 🏗 ➕1️⃣ ⚙️ (💖 ✳) ✋️ #️⃣ 🙆 🆕 🔐 ⏮️ 🎏 📊 💖 🐡.
+🇸🇲 🔑 ✔️ 🛠️ ⚙️ 🎏 🔁 📊, 🔌 😢 🗝 🕐 🕴 ✔ ✔ 👫, ♒️.
- & 🔗 ⏮️ 🌐 👫 🎏 🕰.
+🖼, 👆 💪 ⚙️ ⚫️ ✍ & ✔ 🔐 🏗 ➕1️⃣ ⚙️ (💖 ✳) ✋️ #️⃣ 🙆 🆕 🔐 ⏮️ 🎏 📊 💖 🐡.
+
+ & 🔗 ⏮️ 🌐 👫 🎏 🕰.
+
+///
✍ 🚙 🔢 #️⃣ 🔐 👟 ⚪️➡️ 👩💻.
@@ -109,20 +118,27 @@ $ pip install "passlib[bcrypt]"
& ➕1️⃣ 1️⃣ 🔓 & 📨 👩💻.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="7 48 55-56 59-60 69-75"
- {!> ../../../docs_src/security/tutorial004.py!}
- ```
+```Python hl_lines="7 48 55-56 59-60 69-75"
+{!> ../../docs_src/security/tutorial004.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="6 47 54-55 58-59 68-74"
- {!> ../../../docs_src/security/tutorial004_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-!!! note
- 🚥 👆 ✅ 🆕 (❌) 💽 `fake_users_db`, 👆 🔜 👀 ❔ #️⃣ 🔐 👀 💖 🔜: `"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`.
+```Python hl_lines="6 47 54-55 58-59 68-74"
+{!> ../../docs_src/security/tutorial004_py310.py!}
+```
+
+////
+
+/// note
+
+🚥 👆 ✅ 🆕 (❌) 💽 `fake_users_db`, 👆 🔜 👀 ❔ #️⃣ 🔐 👀 💖 🔜: `"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`.
+
+///
## 🍵 🥙 🤝
@@ -152,17 +168,21 @@ $ openssl rand -hex 32
✍ 🚙 🔢 🏗 🆕 🔐 🤝.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="6 12-14 28-30 78-86"
- {!> ../../../docs_src/security/tutorial004.py!}
- ```
+```Python hl_lines="6 12-14 28-30 78-86"
+{!> ../../docs_src/security/tutorial004.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="5 11-13 27-29 77-85"
- {!> ../../../docs_src/security/tutorial004_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="5 11-13 27-29 77-85"
+{!> ../../docs_src/security/tutorial004_py310.py!}
+```
+
+////
## ℹ 🔗
@@ -172,17 +192,21 @@ $ openssl rand -hex 32
🚥 🤝 ❌, 📨 🇺🇸🔍 ❌ ▶️️ ↖️.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="89-106"
- {!> ../../../docs_src/security/tutorial004.py!}
- ```
+```Python hl_lines="89-106"
+{!> ../../docs_src/security/tutorial004.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="88-105"
- {!> ../../../docs_src/security/tutorial004_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="88-105"
+{!> ../../docs_src/security/tutorial004_py310.py!}
+```
+
+////
## ℹ `/token` *➡ 🛠️*
@@ -190,17 +214,21 @@ $ openssl rand -hex 32
✍ 🎰 🥙 🔐 🤝 & 📨 ⚫️.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="115-130"
- {!> ../../../docs_src/security/tutorial004.py!}
- ```
+```Python hl_lines="115-130"
+{!> ../../docs_src/security/tutorial004.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="114-129"
- {!> ../../../docs_src/security/tutorial004_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="114-129"
+{!> ../../docs_src/security/tutorial004_py310.py!}
+```
+
+////
### 📡 ℹ 🔃 🥙 "📄" `sub`
@@ -239,8 +267,11 @@ $ openssl rand -hex 32
🆔: `johndoe`
🔐: `secret`
-!!! check
- 👀 👈 🕳 📟 🔢 🔐 "`secret`", 👥 🕴 ✔️ #️⃣ ⏬.
+/// check
+
+👀 👈 🕳 📟 🔢 🔐 "`secret`", 👥 🕴 ✔️ #️⃣ ⏬.
+
+///
@@ -261,8 +292,11 @@ $ openssl rand -hex 32
-!!! note
- 👀 🎚 `Authorization`, ⏮️ 💲 👈 ▶️ ⏮️ `Bearer `.
+/// note
+
+👀 🎚 `Authorization`, ⏮️ 💲 👈 ▶️ ⏮️ `Bearer `.
+
+///
## 🏧 ⚙️ ⏮️ `scopes`
diff --git a/docs/em/docs/tutorial/security/simple-oauth2.md b/docs/em/docs/tutorial/security/simple-oauth2.md
index b9e3deb3c..43d928ce7 100644
--- a/docs/em/docs/tutorial/security/simple-oauth2.md
+++ b/docs/em/docs/tutorial/security/simple-oauth2.md
@@ -32,14 +32,17 @@ Oauth2️⃣ ✔ 👈 🕐❔ ⚙️ "🔐 💧" (👈 👥 ⚙️) 👩💻/
* `instagram_basic` ⚙️ 👱📔 / 👱📔.
* `https://www.googleapis.com/auth/drive` ⚙️ 🇺🇸🔍.
-!!! info
- Oauth2️⃣ "↔" 🎻 👈 📣 🎯 ✔ ✔.
+/// info
- ⚫️ 🚫 🤔 🚥 ⚫️ ✔️ 🎏 🦹 💖 `:` ⚖️ 🚥 ⚫️ 📛.
+Oauth2️⃣ "↔" 🎻 👈 📣 🎯 ✔ ✔.
- 👈 ℹ 🛠️ 🎯.
+⚫️ 🚫 🤔 🚥 ⚫️ ✔️ 🎏 🦹 💖 `:` ⚖️ 🚥 ⚫️ 📛.
- Oauth2️⃣ 👫 🎻.
+👈 ℹ 🛠️ 🎯.
+
+Oauth2️⃣ 👫 🎻.
+
+///
## 📟 🤚 `username` & `password`
@@ -49,17 +52,21 @@ Oauth2️⃣ ✔ 👈 🕐❔ ⚙️ "🔐 💧" (👈 👥 ⚙️) 👩💻/
🥇, 🗄 `OAuth2PasswordRequestForm`, & ⚙️ ⚫️ 🔗 ⏮️ `Depends` *➡ 🛠️* `/token`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="4 76"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+```Python hl_lines="4 76"
+{!> ../../docs_src/security/tutorial003.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="2 74"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="2 74"
+{!> ../../docs_src/security/tutorial003_py310.py!}
+```
+
+////
`OAuth2PasswordRequestForm` 🎓 🔗 👈 📣 📨 💪 ⏮️:
@@ -68,29 +75,38 @@ Oauth2️⃣ ✔ 👈 🕐❔ ⚙️ "🔐 💧" (👈 👥 ⚙️) 👩💻/
* 📦 `scope` 🏑 🦏 🎻, ✍ 🎻 🎏 🚀.
* 📦 `grant_type`.
-!!! tip
- Oauth2️⃣ 🔌 🤙 *🚚* 🏑 `grant_type` ⏮️ 🔧 💲 `password`, ✋️ `OAuth2PasswordRequestForm` 🚫 🛠️ ⚫️.
+/// tip
- 🚥 👆 💪 🛠️ ⚫️, ⚙️ `OAuth2PasswordRequestFormStrict` ↩️ `OAuth2PasswordRequestForm`.
+Oauth2️⃣ 🔌 🤙 *🚚* 🏑 `grant_type` ⏮️ 🔧 💲 `password`, ✋️ `OAuth2PasswordRequestForm` 🚫 🛠️ ⚫️.
+
+🚥 👆 💪 🛠️ ⚫️, ⚙️ `OAuth2PasswordRequestFormStrict` ↩️ `OAuth2PasswordRequestForm`.
+
+///
* 📦 `client_id` (👥 🚫 💪 ⚫️ 👆 🖼).
* 📦 `client_secret` (👥 🚫 💪 ⚫️ 👆 🖼).
-!!! info
- `OAuth2PasswordRequestForm` 🚫 🎁 🎓 **FastAPI** `OAuth2PasswordBearer`.
+/// info
- `OAuth2PasswordBearer` ⚒ **FastAPI** 💭 👈 ⚫️ 💂♂ ⚖. ⚫️ 🚮 👈 🌌 🗄.
+`OAuth2PasswordRequestForm` 🚫 🎁 🎓 **FastAPI** `OAuth2PasswordBearer`.
- ✋️ `OAuth2PasswordRequestForm` 🎓 🔗 👈 👆 💪 ✔️ ✍ 👆, ⚖️ 👆 💪 ✔️ 📣 `Form` 🔢 🔗.
+`OAuth2PasswordBearer` ⚒ **FastAPI** 💭 👈 ⚫️ 💂♂ ⚖. ⚫️ 🚮 👈 🌌 🗄.
- ✋️ ⚫️ ⚠ ⚙️ 💼, ⚫️ 🚚 **FastAPI** 🔗, ⚒ ⚫️ ⏩.
+✋️ `OAuth2PasswordRequestForm` 🎓 🔗 👈 👆 💪 ✔️ ✍ 👆, ⚖️ 👆 💪 ✔️ 📣 `Form` 🔢 🔗.
+
+✋️ ⚫️ ⚠ ⚙️ 💼, ⚫️ 🚚 **FastAPI** 🔗, ⚒ ⚫️ ⏩.
+
+///
### ⚙️ 📨 💽
-!!! tip
- 👐 🔗 🎓 `OAuth2PasswordRequestForm` 🏆 🚫 ✔️ 🔢 `scope` ⏮️ 📏 🎻 👽 🚀, ↩️, ⚫️ 🔜 ✔️ `scopes` 🔢 ⏮️ ☑ 📇 🎻 🔠 ↔ 📨.
+/// tip
- 👥 🚫 ⚙️ `scopes` 👉 🖼, ✋️ 🛠️ 📤 🚥 👆 💪 ⚫️.
+👐 🔗 🎓 `OAuth2PasswordRequestForm` 🏆 🚫 ✔️ 🔢 `scope` ⏮️ 📏 🎻 👽 🚀, ↩️, ⚫️ 🔜 ✔️ `scopes` 🔢 ⏮️ ☑ 📇 🎻 🔠 ↔ 📨.
+
+👥 🚫 ⚙️ `scopes` 👉 🖼, ✋️ 🛠️ 📤 🚥 👆 💪 ⚫️.
+
+///
🔜, 🤚 👩💻 📊 ⚪️➡️ (❌) 💽, ⚙️ `username` ⚪️➡️ 📨 🏑.
@@ -98,17 +114,21 @@ Oauth2️⃣ ✔ 👈 🕐❔ ⚙️ "🔐 💧" (👈 👥 ⚙️) 👩💻/
❌, 👥 ⚙️ ⚠ `HTTPException`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="3 77-79"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+```Python hl_lines="3 77-79"
+{!> ../../docs_src/security/tutorial003.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="1 75-77"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="1 75-77"
+{!> ../../docs_src/security/tutorial003_py310.py!}
+```
+
+////
### ✅ 🔐
@@ -134,17 +154,21 @@ Oauth2️⃣ ✔ 👈 🕐❔ ⚙️ "🔐 💧" (👈 👥 ⚙️) 👩💻/
, 🧙♀ 🏆 🚫 💪 🔄 ⚙️ 👈 🎏 🔐 ➕1️⃣ ⚙️ (📚 👩💻 ⚙️ 🎏 🔐 🌐, 👉 🔜 ⚠).
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="80-83"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+```Python hl_lines="80-83"
+{!> ../../docs_src/security/tutorial003.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="78-81"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="78-81"
+{!> ../../docs_src/security/tutorial003_py310.py!}
+```
+
+////
#### 🔃 `**user_dict`
@@ -162,8 +186,11 @@ UserInDB(
)
```
-!!! info
- 🌅 🏁 🔑 `**👩💻_ #️⃣ ` ✅ 🔙 [🧾 **➕ 🏷**](../extra-models.md#user_indict){.internal-link target=_blank}.
+/// info
+
+🌅 🏁 🔑 `**👩💻_ #️⃣ ` ✅ 🔙 [🧾 **➕ 🏷**](../extra-models.md#user_indict){.internal-link target=_blank}.
+
+///
## 📨 🤝
@@ -175,31 +202,41 @@ UserInDB(
👉 🙅 🖼, 👥 🔜 🍕 😟 & 📨 🎏 `username` 🤝.
-!!! tip
- ⏭ 📃, 👆 🔜 👀 🎰 🔐 🛠️, ⏮️ 🔐 #️⃣ & 🥙 🤝.
+/// tip
- ✋️ 🔜, ➡️ 🎯 🔛 🎯 ℹ 👥 💪.
+⏭ 📃, 👆 🔜 👀 🎰 🔐 🛠️, ⏮️ 🔐 #️⃣ & 🥙 🤝.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+✋️ 🔜, ➡️ 🎯 🔛 🎯 ℹ 👥 💪.
- ```Python hl_lines="85"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+///
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="83"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+```Python hl_lines="85"
+{!> ../../docs_src/security/tutorial003.py!}
+```
-!!! tip
- 🔌, 👆 🔜 📨 🎻 ⏮️ `access_token` & `token_type`, 🎏 👉 🖼.
+////
- 👉 🕳 👈 👆 ✔️ 👆 👆 📟, & ⚒ 💭 👆 ⚙️ 📚 🎻 🔑.
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
- ⚫️ 🌖 🕴 👜 👈 👆 ✔️ 💭 ☑ 👆, 🛠️ ⏮️ 🔧.
+```Python hl_lines="83"
+{!> ../../docs_src/security/tutorial003_py310.py!}
+```
- 🎂, **FastAPI** 🍵 ⚫️ 👆.
+////
+
+/// tip
+
+🔌, 👆 🔜 📨 🎻 ⏮️ `access_token` & `token_type`, 🎏 👉 🖼.
+
+👉 🕳 👈 👆 ✔️ 👆 👆 📟, & ⚒ 💭 👆 ⚙️ 📚 🎻 🔑.
+
+⚫️ 🌖 🕴 👜 👈 👆 ✔️ 💭 ☑ 👆, 🛠️ ⏮️ 🔧.
+
+🎂, **FastAPI** 🍵 ⚫️ 👆.
+
+///
## ℹ 🔗
@@ -213,32 +250,39 @@ UserInDB(
, 👆 🔗, 👥 🔜 🕴 🤚 👩💻 🚥 👩💻 🔀, ☑ 🔓, & 🦁:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="58-66 69-72 90"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+```Python hl_lines="58-66 69-72 90"
+{!> ../../docs_src/security/tutorial003.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python hl_lines="55-64 67-70 88"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
-!!! info
- 🌖 🎚 `WWW-Authenticate` ⏮️ 💲 `Bearer` 👥 🛬 📥 🍕 🔌.
+```Python hl_lines="55-64 67-70 88"
+{!> ../../docs_src/security/tutorial003_py310.py!}
+```
- 🙆 🇺🇸🔍 (❌) 👔 📟 4️⃣0️⃣1️⃣ "⛔" 🤔 📨 `WWW-Authenticate` 🎚.
+////
- 💼 📨 🤝 (👆 💼), 💲 👈 🎚 🔜 `Bearer`.
+/// info
- 👆 💪 🤙 🚶 👈 ➕ 🎚 & ⚫️ 🔜 👷.
+🌖 🎚 `WWW-Authenticate` ⏮️ 💲 `Bearer` 👥 🛬 📥 🍕 🔌.
- ✋️ ⚫️ 🚚 📥 🛠️ ⏮️ 🔧.
+🙆 🇺🇸🔍 (❌) 👔 📟 4️⃣0️⃣1️⃣ "⛔" 🤔 📨 `WWW-Authenticate` 🎚.
- , 📤 5️⃣📆 🧰 👈 ⌛ & ⚙️ ⚫️ (🔜 ⚖️ 🔮) & 👈 💪 ⚠ 👆 ⚖️ 👆 👩💻, 🔜 ⚖️ 🔮.
+💼 📨 🤝 (👆 💼), 💲 👈 🎚 🔜 `Bearer`.
- 👈 💰 🐩...
+👆 💪 🤙 🚶 👈 ➕ 🎚 & ⚫️ 🔜 👷.
+
+✋️ ⚫️ 🚚 📥 🛠️ ⏮️ 🔧.
+
+, 📤 5️⃣📆 🧰 👈 ⌛ & ⚙️ ⚫️ (🔜 ⚖️ 🔮) & 👈 💪 ⚠ 👆 ⚖️ 👆 👩💻, 🔜 ⚖️ 🔮.
+
+👈 💰 🐩...
+
+///
## 👀 ⚫️ 🎯
diff --git a/docs/em/docs/tutorial/sql-databases.md b/docs/em/docs/tutorial/sql-databases.md
index 5a5227352..c59d8c131 100644
--- a/docs/em/docs/tutorial/sql-databases.md
+++ b/docs/em/docs/tutorial/sql-databases.md
@@ -18,13 +18,19 @@
⏪, 👆 🏭 🈸, 👆 💪 💚 ⚙️ 💽 💽 💖 **✳**.
-!!! tip
- 📤 🛂 🏗 🚂 ⏮️ **FastAPI** & **✳**, 🌐 ⚓️ 🔛 **☁**, 🔌 🕸 & 🌖 🧰: https://github.com/tiangolo/full-stack-fastapi-postgresql
+/// tip
-!!! note
- 👀 👈 📚 📟 🐩 `SQLAlchemy` 📟 👆 🔜 ⚙️ ⏮️ 🙆 🛠️.
+📤 🛂 🏗 🚂 ⏮️ **FastAPI** & **✳**, 🌐 ⚓️ 🔛 **☁**, 🔌 🕸 & 🌖 🧰: https://github.com/tiangolo/full-stack-fastapi-postgresql
- **FastAPI** 🎯 📟 🤪 🕧.
+///
+
+/// note
+
+👀 👈 📚 📟 🐩 `SQLAlchemy` 📟 👆 🔜 ⚙️ ⏮️ 🙆 🛠️.
+
+ **FastAPI** 🎯 📟 🤪 🕧.
+
+///
## 🐜
@@ -58,8 +64,11 @@
🎏 🌌 👆 💪 ⚙️ 🙆 🎏 🐜.
-!!! tip
- 📤 🌓 📄 ⚙️ 🏒 📥 🩺.
+/// tip
+
+📤 🌓 📄 ⚙️ 🏒 📥 🩺.
+
+///
## 📁 📊
@@ -101,13 +110,13 @@ $ pip install sqlalchemy
### 🗄 🇸🇲 🍕
```Python hl_lines="1-3"
-{!../../../docs_src/sql_databases/sql_app/database.py!}
+{!../../docs_src/sql_databases/sql_app/database.py!}
```
### ✍ 💽 📛 🇸🇲
```Python hl_lines="5-6"
-{!../../../docs_src/sql_databases/sql_app/database.py!}
+{!../../docs_src/sql_databases/sql_app/database.py!}
```
👉 🖼, 👥 "🔗" 🗄 💽 (📂 📁 ⏮️ 🗄 💽).
@@ -124,9 +133,11 @@ SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db"
...& 🛠️ ⚫️ ⏮️ 👆 💽 📊 & 🎓 (📊 ✳, ✳ ⚖️ 🙆 🎏).
-!!! tip
+/// tip
- 👉 👑 ⏸ 👈 👆 🔜 ✔️ 🔀 🚥 👆 💚 ⚙️ 🎏 💽.
+👉 👑 ⏸ 👈 👆 🔜 ✔️ 🔀 🚥 👆 💚 ⚙️ 🎏 💽.
+
+///
### ✍ 🇸🇲 `engine`
@@ -135,7 +146,7 @@ SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db"
👥 🔜 ⏪ ⚙️ 👉 `engine` 🎏 🥉.
```Python hl_lines="8-10"
-{!../../../docs_src/sql_databases/sql_app/database.py!}
+{!../../docs_src/sql_databases/sql_app/database.py!}
```
#### 🗒
@@ -148,15 +159,17 @@ connect_args={"check_same_thread": False}
...💪 🕴 `SQLite`. ⚫️ 🚫 💪 🎏 💽.
-!!! info "📡 ℹ"
+/// info | "📡 ℹ"
- 🔢 🗄 🔜 🕴 ✔ 1️⃣ 🧵 🔗 ⏮️ ⚫️, 🤔 👈 🔠 🧵 🔜 🍵 🔬 📨.
+🔢 🗄 🔜 🕴 ✔ 1️⃣ 🧵 🔗 ⏮️ ⚫️, 🤔 👈 🔠 🧵 🔜 🍵 🔬 📨.
- 👉 ❎ 😫 🤝 🎏 🔗 🎏 👜 (🎏 📨).
+👉 ❎ 😫 🤝 🎏 🔗 🎏 👜 (🎏 📨).
- ✋️ FastAPI, ⚙️ 😐 🔢 (`def`) 🌅 🌘 1️⃣ 🧵 💪 🔗 ⏮️ 💽 🎏 📨, 👥 💪 ⚒ 🗄 💭 👈 ⚫️ 🔜 ✔ 👈 ⏮️ `connect_args={"check_same_thread": False}`.
+✋️ FastAPI, ⚙️ 😐 🔢 (`def`) 🌅 🌘 1️⃣ 🧵 💪 🔗 ⏮️ 💽 🎏 📨, 👥 💪 ⚒ 🗄 💭 👈 ⚫️ 🔜 ✔ 👈 ⏮️ `connect_args={"check_same_thread": False}`.
- , 👥 🔜 ⚒ 💭 🔠 📨 🤚 🚮 👍 💽 🔗 🎉 🔗, 📤 🙅♂ 💪 👈 🔢 🛠️.
+, 👥 🔜 ⚒ 💭 🔠 📨 🤚 🚮 👍 💽 🔗 🎉 🔗, 📤 🙅♂ 💪 👈 🔢 🛠️.
+
+///
### ✍ `SessionLocal` 🎓
@@ -171,7 +184,7 @@ connect_args={"check_same_thread": False}
✍ `SessionLocal` 🎓, ⚙️ 🔢 `sessionmaker`:
```Python hl_lines="11"
-{!../../../docs_src/sql_databases/sql_app/database.py!}
+{!../../docs_src/sql_databases/sql_app/database.py!}
```
### ✍ `Base` 🎓
@@ -181,7 +194,7 @@ connect_args={"check_same_thread": False}
⏪ 👥 🔜 😖 ⚪️➡️ 👉 🎓 ✍ 🔠 💽 🏷 ⚖️ 🎓 (🐜 🏷):
```Python hl_lines="13"
-{!../../../docs_src/sql_databases/sql_app/database.py!}
+{!../../docs_src/sql_databases/sql_app/database.py!}
```
## ✍ 💽 🏷
@@ -192,10 +205,13 @@ connect_args={"check_same_thread": False}
👥 🔜 ⚙️ 👉 `Base` 🎓 👥 ✍ ⏭ ✍ 🇸🇲 🏷.
-!!! tip
- 🇸🇲 ⚙️ ⚖ "**🏷**" 🔗 👉 🎓 & 👐 👈 🔗 ⏮️ 💽.
+/// tip
- ✋️ Pydantic ⚙️ ⚖ "**🏷**" 🔗 🕳 🎏, 💽 🔬, 🛠️, & 🧾 🎓 & 👐.
+🇸🇲 ⚙️ ⚖ "**🏷**" 🔗 👉 🎓 & 👐 👈 🔗 ⏮️ 💽.
+
+✋️ Pydantic ⚙️ ⚖ "**🏷**" 🔗 🕳 🎏, 💽 🔬, 🛠️, & 🧾 🎓 & 👐.
+
+///
🗄 `Base` ⚪️➡️ `database` (📁 `database.py` ⚪️➡️ 🔛).
@@ -204,7 +220,7 @@ connect_args={"check_same_thread": False}
👫 🎓 🇸🇲 🏷.
```Python hl_lines="4 7-8 18-19"
-{!../../../docs_src/sql_databases/sql_app/models.py!}
+{!../../docs_src/sql_databases/sql_app/models.py!}
```
`__tablename__` 🔢 💬 🇸🇲 📛 🏓 ⚙️ 💽 🔠 👫 🏷.
@@ -220,7 +236,7 @@ connect_args={"check_same_thread": False}
& 👥 🚶♀️ 🇸🇲 🎓 "🆎", `Integer`, `String`, & `Boolean`, 👈 🔬 🆎 💽, ❌.
```Python hl_lines="1 10-13 21-24"
-{!../../../docs_src/sql_databases/sql_app/models.py!}
+{!../../docs_src/sql_databases/sql_app/models.py!}
```
### ✍ 💛
@@ -232,7 +248,7 @@ connect_args={"check_same_thread": False}
👉 🔜 ▶️️, 🌅 ⚖️ 🌘, "🎱" 🔢 👈 🔜 🔌 💲 ⚪️➡️ 🎏 🏓 🔗 👉 1️⃣.
```Python hl_lines="2 15 26"
-{!../../../docs_src/sql_databases/sql_app/models.py!}
+{!../../docs_src/sql_databases/sql_app/models.py!}
```
🕐❔ 🔐 🔢 `items` `User`, `my_user.items`, ⚫️ 🔜 ✔️ 📇 `Item` 🇸🇲 🏷 (⚪️➡️ `items` 🏓) 👈 ✔️ 💱 🔑 ☝ 👉 ⏺ `users` 🏓.
@@ -245,12 +261,15 @@ connect_args={"check_same_thread": False}
🔜 ➡️ ✅ 📁 `sql_app/schemas.py`.
-!!! tip
- ❎ 😨 🖖 🇸🇲 *🏷* & Pydantic *🏷*, 👥 🔜 ✔️ 📁 `models.py` ⏮️ 🇸🇲 🏷, & 📁 `schemas.py` ⏮️ Pydantic 🏷.
+/// tip
- 👫 Pydantic 🏷 🔬 🌅 ⚖️ 🌘 "🔗" (☑ 📊 💠).
+❎ 😨 🖖 🇸🇲 *🏷* & Pydantic *🏷*, 👥 🔜 ✔️ 📁 `models.py` ⏮️ 🇸🇲 🏷, & 📁 `schemas.py` ⏮️ Pydantic 🏷.
- 👉 🔜 ℹ 👥 ❎ 😨 ⏪ ⚙️ 👯♂️.
+👫 Pydantic 🏷 🔬 🌅 ⚖️ 🌘 "🔗" (☑ 📊 💠).
+
+👉 🔜 ℹ 👥 ❎ 😨 ⏪ ⚙️ 👯♂️.
+
+///
### ✍ ▶️ Pydantic *🏷* / 🔗
@@ -262,23 +281,29 @@ connect_args={"check_same_thread": False}
✋️ 💂♂, `password` 🏆 🚫 🎏 Pydantic *🏷*, 🖼, ⚫️ 🏆 🚫 📨 ⚪️➡️ 🛠️ 🕐❔ 👂 👩💻.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="3 6-8 11-12 23-24 27-28"
- {!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
- ```
+```Python hl_lines="3 6-8 11-12 23-24 27-28"
+{!> ../../docs_src/sql_databases/sql_app/schemas.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="3 6-8 11-12 23-24 27-28"
- {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="3 6-8 11-12 23-24 27-28"
+{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!}
+```
- ```Python hl_lines="1 4-6 9-10 21-22 25-26"
- {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
- ```
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="1 4-6 9-10 21-22 25-26"
+{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!}
+```
+
+////
#### 🇸🇲 👗 & Pydantic 👗
@@ -306,26 +331,35 @@ name: str
🚫 🕴 🆔 📚 🏬, ✋️ 🌐 💽 👈 👥 🔬 Pydantic *🏷* 👂 🏬: `Item`.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="15-17 31-34"
- {!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
- ```
+```Python hl_lines="15-17 31-34"
+{!> ../../docs_src/sql_databases/sql_app/schemas.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="15-17 31-34"
- {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="15-17 31-34"
+{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!}
+```
- ```Python hl_lines="13-15 29-32"
- {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
- ```
+////
-!!! tip
- 👀 👈 `User`, Pydantic *🏷* 👈 🔜 ⚙️ 🕐❔ 👂 👩💻 (🛬 ⚫️ ⚪️➡️ 🛠️) 🚫 🔌 `password`.
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python hl_lines="13-15 29-32"
+{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!}
+```
+
+////
+
+/// tip
+
+👀 👈 `User`, Pydantic *🏷* 👈 🔜 ⚙️ 🕐❔ 👂 👩💻 (🛬 ⚫️ ⚪️➡️ 🛠️) 🚫 🔌 `password`.
+
+///
### ⚙️ Pydantic `orm_mode`
@@ -335,32 +369,41 @@ name: str
`Config` 🎓, ⚒ 🔢 `orm_mode = True`.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="15 19-20 31 36-37"
- {!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
- ```
+```Python hl_lines="15 19-20 31 36-37"
+{!> ../../docs_src/sql_databases/sql_app/schemas.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="15 19-20 31 36-37"
- {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python hl_lines="15 19-20 31 36-37"
+{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!}
+```
- ```Python hl_lines="13 17-18 29 34-35"
- {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
- ```
+////
-!!! tip
- 👀 ⚫️ ⚖ 💲 ⏮️ `=`, 💖:
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
- `orm_mode = True`
+```Python hl_lines="13 17-18 29 34-35"
+{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!}
+```
- ⚫️ 🚫 ⚙️ `:` 🆎 📄 ⏭.
+////
- 👉 ⚒ 📁 💲, 🚫 📣 🆎.
+/// tip
+
+👀 ⚫️ ⚖ 💲 ⏮️ `=`, 💖:
+
+`orm_mode = True`
+
+⚫️ 🚫 ⚙️ `:` 🆎 📄 ⏭.
+
+👉 ⚒ 📁 💲, 🚫 📣 🆎.
+
+///
Pydantic `orm_mode` 🔜 💬 Pydantic *🏷* ✍ 💽 🚥 ⚫️ 🚫 `dict`, ✋️ 🐜 🏷 (⚖️ 🙆 🎏 ❌ 🎚 ⏮️ 🔢).
@@ -423,11 +466,14 @@ current_user.items
* ✍ 💗 🏬.
```Python hl_lines="1 3 6-7 10-11 14-15 27-28"
-{!../../../docs_src/sql_databases/sql_app/crud.py!}
+{!../../docs_src/sql_databases/sql_app/crud.py!}
```
-!!! tip
- 🏗 🔢 👈 🕴 💡 🔗 ⏮️ 💽 (🤚 👩💻 ⚖️ 🏬) 🔬 👆 *➡ 🛠️ 🔢*, 👆 💪 🌖 💪 ♻ 👫 💗 🍕 & 🚮 ⚒ 💯 👫.
+/// tip
+
+🏗 🔢 👈 🕴 💡 🔗 ⏮️ 💽 (🤚 👩💻 ⚖️ 🏬) 🔬 👆 *➡ 🛠️ 🔢*, 👆 💪 🌖 💪 ♻ 👫 💗 🍕 & 🚮 ⚒ 💯 👫.
+
+///
### ✍ 💽
@@ -441,37 +487,46 @@ current_user.items
* `refresh` 👆 👐 (👈 ⚫️ 🔌 🙆 🆕 📊 ⚪️➡️ 💽, 💖 🏗 🆔).
```Python hl_lines="18-24 31-36"
-{!../../../docs_src/sql_databases/sql_app/crud.py!}
+{!../../docs_src/sql_databases/sql_app/crud.py!}
```
-!!! tip
- 🇸🇲 🏷 `User` 🔌 `hashed_password` 👈 🔜 🔌 🔐 #️⃣ ⏬ 🔐.
+/// tip
- ✋️ ⚫️❔ 🛠️ 👩💻 🚚 ⏮️ 🔐, 👆 💪 ⚗ ⚫️ & 🏗 #️⃣ 🔐 👆 🈸.
+🇸🇲 🏷 `User` 🔌 `hashed_password` 👈 🔜 🔌 🔐 #️⃣ ⏬ 🔐.
- & ⤴️ 🚶♀️ `hashed_password` ❌ ⏮️ 💲 🖊.
+✋️ ⚫️❔ 🛠️ 👩💻 🚚 ⏮️ 🔐, 👆 💪 ⚗ ⚫️ & 🏗 #️⃣ 🔐 👆 🈸.
-!!! warning
- 👉 🖼 🚫 🔐, 🔐 🚫#️⃣.
+ & ⤴️ 🚶♀️ `hashed_password` ❌ ⏮️ 💲 🖊.
- 🎰 👨❤👨 🈸 👆 🔜 💪 #️⃣ 🔐 & 🙅 🖊 👫 🔢.
+///
- 🌅 ℹ, 🚶 🔙 💂♂ 📄 🔰.
+/// warning
- 📥 👥 🎯 🕴 🔛 🧰 & 👨🔧 💽.
+👉 🖼 🚫 🔐, 🔐 🚫#️⃣.
-!!! tip
- ↩️ 🚶♀️ 🔠 🇨🇻 ❌ `Item` & 👂 🔠 1️⃣ 👫 ⚪️➡️ Pydantic *🏷*, 👥 🏭 `dict` ⏮️ Pydantic *🏷*'Ⓜ 📊 ⏮️:
+🎰 👨❤👨 🈸 👆 🔜 💪 #️⃣ 🔐 & 🙅 🖊 👫 🔢.
- `item.dict()`
+🌅 ℹ, 🚶 🔙 💂♂ 📄 🔰.
- & ⤴️ 👥 🚶♀️ `dict`'Ⓜ 🔑-💲 👫 🇨🇻 ❌ 🇸🇲 `Item`, ⏮️:
+📥 👥 🎯 🕴 🔛 🧰 & 👨🔧 💽.
- `Item(**item.dict())`
+///
- & ⤴️ 👥 🚶♀️ ➕ 🇨🇻 ❌ `owner_id` 👈 🚫 🚚 Pydantic *🏷*, ⏮️:
+/// tip
- `Item(**item.dict(), owner_id=user_id)`
+↩️ 🚶♀️ 🔠 🇨🇻 ❌ `Item` & 👂 🔠 1️⃣ 👫 ⚪️➡️ Pydantic *🏷*, 👥 🏭 `dict` ⏮️ Pydantic *🏷*'Ⓜ 📊 ⏮️:
+
+`item.dict()`
+
+ & ⤴️ 👥 🚶♀️ `dict`'Ⓜ 🔑-💲 👫 🇨🇻 ❌ 🇸🇲 `Item`, ⏮️:
+
+`Item(**item.dict())`
+
+ & ⤴️ 👥 🚶♀️ ➕ 🇨🇻 ❌ `owner_id` 👈 🚫 🚚 Pydantic *🏷*, ⏮️:
+
+`Item(**item.dict(), owner_id=user_id)`
+
+///
## 👑 **FastAPI** 📱
@@ -481,17 +536,21 @@ current_user.items
📶 🙃 🌌 ✍ 💽 🏓:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="9"
- {!> ../../../docs_src/sql_databases/sql_app/main.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/sql_databases/sql_app/main.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
+
+```Python hl_lines="7"
+{!> ../../docs_src/sql_databases/sql_app_py39/main.py!}
+```
+
+////
#### ⚗ 🗒
@@ -515,63 +574,81 @@ current_user.items
👆 🔗 🔜 ✍ 🆕 🇸🇲 `SessionLocal` 👈 🔜 ⚙️ 👁 📨, & ⤴️ 🔐 ⚫️ 🕐 📨 🏁.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="15-20"
- {!> ../../../docs_src/sql_databases/sql_app/main.py!}
- ```
+```Python hl_lines="15-20"
+{!> ../../docs_src/sql_databases/sql_app/main.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="13-18"
- {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-!!! info
- 👥 🚮 🏗 `SessionLocal()` & 🚚 📨 `try` 🍫.
+```Python hl_lines="13-18"
+{!> ../../docs_src/sql_databases/sql_app_py39/main.py!}
+```
- & ⤴️ 👥 🔐 ⚫️ `finally` 🍫.
+////
- 👉 🌌 👥 ⚒ 💭 💽 🎉 🕧 📪 ⏮️ 📨. 🚥 📤 ⚠ ⏪ 🏭 📨.
+/// info
- ✋️ 👆 💪 🚫 🤚 ➕1️⃣ ⚠ ⚪️➡️ 🚪 📟 (⏮️ `yield`). 👀 🌖 [🔗 ⏮️ `yield` & `HTTPException`](dependencies/dependencies-with-yield.md#yield-httpexception){.internal-link target=_blank}
+👥 🚮 🏗 `SessionLocal()` & 🚚 📨 `try` 🍫.
+
+ & ⤴️ 👥 🔐 ⚫️ `finally` 🍫.
+
+👉 🌌 👥 ⚒ 💭 💽 🎉 🕧 📪 ⏮️ 📨. 🚥 📤 ⚠ ⏪ 🏭 📨.
+
+✋️ 👆 💪 🚫 🤚 ➕1️⃣ ⚠ ⚪️➡️ 🚪 📟 (⏮️ `yield`). 👀 🌖 [🔗 ⏮️ `yield` & `HTTPException`](dependencies/dependencies-with-yield.md#yield-httpexception){.internal-link target=_blank}
+
+///
& ⤴️, 🕐❔ ⚙️ 🔗 *➡ 🛠️ 🔢*, 👥 📣 ⚫️ ⏮️ 🆎 `Session` 👥 🗄 🔗 ⚪️➡️ 🇸🇲.
👉 🔜 ⤴️ 🤝 👥 👍 👨🎨 🐕🦺 🔘 *➡ 🛠️ 🔢*, ↩️ 👨🎨 🔜 💭 👈 `db` 🔢 🆎 `Session`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="24 32 38 47 53"
- {!> ../../../docs_src/sql_databases/sql_app/main.py!}
- ```
+```Python hl_lines="24 32 38 47 53"
+{!> ../../docs_src/sql_databases/sql_app/main.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="22 30 36 45 51"
- {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-!!! info "📡 ℹ"
- 🔢 `db` 🤙 🆎 `SessionLocal`, ✋️ 👉 🎓 (✍ ⏮️ `sessionmaker()`) "🗳" 🇸🇲 `Session`,, 👨🎨 🚫 🤙 💭 ⚫️❔ 👩🔬 🚚.
+```Python hl_lines="22 30 36 45 51"
+{!> ../../docs_src/sql_databases/sql_app_py39/main.py!}
+```
- ✋️ 📣 🆎 `Session`, 👨🎨 🔜 💪 💭 💪 👩🔬 (`.add()`, `.query()`, `.commit()`, ♒️) & 💪 🚚 👍 🐕🦺 (💖 🛠️). 🆎 📄 🚫 📉 ☑ 🎚.
+////
+
+/// info | "📡 ℹ"
+
+🔢 `db` 🤙 🆎 `SessionLocal`, ✋️ 👉 🎓 (✍ ⏮️ `sessionmaker()`) "🗳" 🇸🇲 `Session`,, 👨🎨 🚫 🤙 💭 ⚫️❔ 👩🔬 🚚.
+
+✋️ 📣 🆎 `Session`, 👨🎨 🔜 💪 💭 💪 👩🔬 (`.add()`, `.query()`, `.commit()`, ♒️) & 💪 🚚 👍 🐕🦺 (💖 🛠️). 🆎 📄 🚫 📉 ☑ 🎚.
+
+///
### ✍ 👆 **FastAPI** *➡ 🛠️*
🔜, 😒, 📥 🐩 **FastAPI** *➡ 🛠️* 📟.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="23-28 31-34 37-42 45-49 52-55"
- {!> ../../../docs_src/sql_databases/sql_app/main.py!}
- ```
+```Python hl_lines="23-28 31-34 37-42 45-49 52-55"
+{!> ../../docs_src/sql_databases/sql_app/main.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="21-26 29-32 35-40 43-47 50-53"
- {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
+
+```Python hl_lines="21-26 29-32 35-40 43-47 50-53"
+{!> ../../docs_src/sql_databases/sql_app_py39/main.py!}
+```
+
+////
👥 🏗 💽 🎉 ⏭ 🔠 📨 🔗 ⏮️ `yield`, & ⤴️ 📪 ⚫️ ⏮️.
@@ -579,15 +656,21 @@ current_user.items
⏮️ 👈, 👥 💪 🤙 `crud.get_user` 🔗 ⚪️➡️ 🔘 *➡ 🛠️ 🔢* & ⚙️ 👈 🎉.
-!!! tip
- 👀 👈 💲 👆 📨 🇸🇲 🏷, ⚖️ 📇 🇸🇲 🏷.
+/// tip
- ✋️ 🌐 *➡ 🛠️* ✔️ `response_model` ⏮️ Pydantic *🏷* / 🔗 ⚙️ `orm_mode`, 💽 📣 👆 Pydantic 🏷 🔜 ⚗ ⚪️➡️ 👫 & 📨 👩💻, ⏮️ 🌐 😐 ⛽ & 🔬.
+👀 👈 💲 👆 📨 🇸🇲 🏷, ⚖️ 📇 🇸🇲 🏷.
-!!! tip
- 👀 👈 📤 `response_models` 👈 ✔️ 🐩 🐍 🆎 💖 `List[schemas.Item]`.
+✋️ 🌐 *➡ 🛠️* ✔️ `response_model` ⏮️ Pydantic *🏷* / 🔗 ⚙️ `orm_mode`, 💽 📣 👆 Pydantic 🏷 🔜 ⚗ ⚪️➡️ 👫 & 📨 👩💻, ⏮️ 🌐 😐 ⛽ & 🔬.
- ✋️ 🎚/🔢 👈 `List` Pydantic *🏷* ⏮️ `orm_mode`, 💽 🔜 🗃 & 📨 👩💻 🛎, 🍵 ⚠.
+///
+
+/// tip
+
+👀 👈 📤 `response_models` 👈 ✔️ 🐩 🐍 🆎 💖 `List[schemas.Item]`.
+
+✋️ 🎚/🔢 👈 `List` Pydantic *🏷* ⏮️ `orm_mode`, 💽 🔜 🗃 & 📨 👩💻 🛎, 🍵 ⚠.
+
+///
### 🔃 `def` 🆚 `async def`
@@ -616,11 +699,17 @@ def read_user(user_id: int, db: Session = Depends(get_db)):
...
```
-!!! info
- 🚥 👆 💪 🔗 👆 🔗 💽 🔁, 👀 [🔁 🗄 (🔗) 💽](../advanced/async-sql-databases.md){.internal-link target=_blank}.
+/// info
-!!! note "📶 📡 ℹ"
- 🚥 👆 😟 & ✔️ ⏬ 📡 💡, 👆 💪 ✅ 📶 📡 ℹ ❔ 👉 `async def` 🆚 `def` 🍵 [🔁](../async.md#i_2){.internal-link target=_blank} 🩺.
+🚥 👆 💪 🔗 👆 🔗 💽 🔁, 👀 [🔁 🗄 (🔗) 💽](../advanced/async-sql-databases.md){.internal-link target=_blank}.
+
+///
+
+/// note | "📶 📡 ℹ"
+
+🚥 👆 😟 & ✔️ ⏬ 📡 💡, 👆 💪 ✅ 📶 📡 ℹ ❔ 👉 `async def` 🆚 `def` 🍵 [🔁](../async.md#i_2){.internal-link target=_blank} 🩺.
+
+///
## 🛠️
@@ -643,62 +732,74 @@ def read_user(user_id: int, db: Session = Depends(get_db)):
* `sql_app/database.py`:
```Python
-{!../../../docs_src/sql_databases/sql_app/database.py!}
+{!../../docs_src/sql_databases/sql_app/database.py!}
```
* `sql_app/models.py`:
```Python
-{!../../../docs_src/sql_databases/sql_app/models.py!}
+{!../../docs_src/sql_databases/sql_app/models.py!}
```
* `sql_app/schemas.py`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python
- {!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
- ```
+```Python
+{!> ../../docs_src/sql_databases/sql_app/schemas.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python
- {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+```Python
+{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!}
+```
- ```Python
- {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
- ```
+////
+
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python
+{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!}
+```
+
+////
* `sql_app/crud.py`:
```Python
-{!../../../docs_src/sql_databases/sql_app/crud.py!}
+{!../../docs_src/sql_databases/sql_app/crud.py!}
```
* `sql_app/main.py`:
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python
- {!> ../../../docs_src/sql_databases/sql_app/main.py!}
- ```
+```Python
+{!> ../../docs_src/sql_databases/sql_app/main.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python
- {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
+
+```Python
+{!> ../../docs_src/sql_databases/sql_app_py39/main.py!}
+```
+
+////
## ✅ ⚫️
👆 💪 📁 👉 📟 & ⚙️ ⚫️.
-!!! info
+/// info
- 👐, 📟 🎦 📥 🍕 💯. 🌅 📟 👉 🩺.
+👐, 📟 🎦 📥 🍕 💯. 🌅 📟 👉 🩺.
+
+///
⤴️ 👆 💪 🏃 ⚫️ ⏮️ Uvicorn:
@@ -739,24 +840,31 @@ $ uvicorn sql_app.main:app --reload
🛠️ 👥 🔜 🚮 (🔢) 🔜 ✍ 🆕 🇸🇲 `SessionLocal` 🔠 📨, 🚮 ⚫️ 📨 & ⤴️ 🔐 ⚫️ 🕐 📨 🏁.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python hl_lines="14-22"
- {!> ../../../docs_src/sql_databases/sql_app/alt_main.py!}
- ```
+```Python hl_lines="14-22"
+{!> ../../docs_src/sql_databases/sql_app/alt_main.py!}
+```
-=== "🐍 3️⃣.9️⃣ & 🔛"
+////
- ```Python hl_lines="12-20"
- {!> ../../../docs_src/sql_databases/sql_app_py39/alt_main.py!}
- ```
+//// tab | 🐍 3️⃣.9️⃣ & 🔛
-!!! info
- 👥 🚮 🏗 `SessionLocal()` & 🚚 📨 `try` 🍫.
+```Python hl_lines="12-20"
+{!> ../../docs_src/sql_databases/sql_app_py39/alt_main.py!}
+```
- & ⤴️ 👥 🔐 ⚫️ `finally` 🍫.
+////
- 👉 🌌 👥 ⚒ 💭 💽 🎉 🕧 📪 ⏮️ 📨. 🚥 📤 ⚠ ⏪ 🏭 📨.
+/// info
+
+👥 🚮 🏗 `SessionLocal()` & 🚚 📨 `try` 🍫.
+
+ & ⤴️ 👥 🔐 ⚫️ `finally` 🍫.
+
+👉 🌌 👥 ⚒ 💭 💽 🎉 🕧 📪 ⏮️ 📨. 🚥 📤 ⚠ ⏪ 🏭 📨.
+
+///
### 🔃 `request.state`
@@ -777,10 +885,16 @@ $ uvicorn sql_app.main:app --reload
* , 🔗 🔜 ✍ 🔠 📨.
* 🕐❔ *➡ 🛠️* 👈 🍵 👈 📨 🚫 💪 💽.
-!!! tip
- ⚫️ 🎲 👍 ⚙️ 🔗 ⏮️ `yield` 🕐❔ 👫 🥃 ⚙️ 💼.
+/// tip
-!!! info
- 🔗 ⏮️ `yield` 🚮 ⏳ **FastAPI**.
+⚫️ 🎲 👍 ⚙️ 🔗 ⏮️ `yield` 🕐❔ 👫 🥃 ⚙️ 💼.
- ⏮️ ⏬ 👉 🔰 🕴 ✔️ 🖼 ⏮️ 🛠️ & 📤 🎲 📚 🈸 ⚙️ 🛠️ 💽 🎉 🧾.
+///
+
+/// info
+
+🔗 ⏮️ `yield` 🚮 ⏳ **FastAPI**.
+
+⏮️ ⏬ 👉 🔰 🕴 ✔️ 🖼 ⏮️ 🛠️ & 📤 🎲 📚 🈸 ⚙️ 🛠️ 💽 🎉 🧾.
+
+///
diff --git a/docs/em/docs/tutorial/static-files.md b/docs/em/docs/tutorial/static-files.md
index 6090c5338..0627031b3 100644
--- a/docs/em/docs/tutorial/static-files.md
+++ b/docs/em/docs/tutorial/static-files.md
@@ -8,13 +8,16 @@
* "🗻" `StaticFiles()` 👐 🎯 ➡.
```Python hl_lines="2 6"
-{!../../../docs_src/static_files/tutorial001.py!}
+{!../../docs_src/static_files/tutorial001.py!}
```
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette.staticfiles import StaticFiles`.
+/// note | "📡 ℹ"
- **FastAPI** 🚚 🎏 `starlette.staticfiles` `fastapi.staticfiles` 🏪 👆, 👩💻. ✋️ ⚫️ 🤙 👟 🔗 ⚪️➡️ 💃.
+👆 💪 ⚙️ `from starlette.staticfiles import StaticFiles`.
+
+**FastAPI** 🚚 🎏 `starlette.staticfiles` `fastapi.staticfiles` 🏪 👆, 👩💻. ✋️ ⚫️ 🤙 👟 🔗 ⚪️➡️ 💃.
+
+///
### ⚫️❔ "🗜"
diff --git a/docs/em/docs/tutorial/testing.md b/docs/em/docs/tutorial/testing.md
index 3ae51e298..5f3d5e736 100644
--- a/docs/em/docs/tutorial/testing.md
+++ b/docs/em/docs/tutorial/testing.md
@@ -8,10 +8,13 @@
## ⚙️ `TestClient`
-!!! info
- ⚙️ `TestClient`, 🥇 ❎ `httpx`.
+/// info
- 🤶 Ⓜ. `pip install httpx`.
+⚙️ `TestClient`, 🥇 ❎ `httpx`.
+
+🤶 Ⓜ. `pip install httpx`.
+
+///
🗄 `TestClient`.
@@ -24,23 +27,32 @@
✍ 🙅 `assert` 📄 ⏮️ 🐩 🐍 🧬 👈 👆 💪 ✅ (🔄, 🐩 `pytest`).
```Python hl_lines="2 12 15-18"
-{!../../../docs_src/app_testing/tutorial001.py!}
+{!../../docs_src/app_testing/tutorial001.py!}
```
-!!! tip
- 👀 👈 🔬 🔢 😐 `def`, 🚫 `async def`.
+/// tip
- & 🤙 👩💻 😐 🤙, 🚫 ⚙️ `await`.
+👀 👈 🔬 🔢 😐 `def`, 🚫 `async def`.
- 👉 ✔ 👆 ⚙️ `pytest` 🔗 🍵 🤢.
+ & 🤙 👩💻 😐 🤙, 🚫 ⚙️ `await`.
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette.testclient import TestClient`.
+👉 ✔ 👆 ⚙️ `pytest` 🔗 🍵 🤢.
- **FastAPI** 🚚 🎏 `starlette.testclient` `fastapi.testclient` 🏪 👆, 👩💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃.
+///
-!!! tip
- 🚥 👆 💚 🤙 `async` 🔢 👆 💯 ↖️ ⚪️➡️ 📨 📨 👆 FastAPI 🈸 (✅ 🔁 💽 🔢), ✔️ 👀 [🔁 💯](../advanced/async-tests.md){.internal-link target=_blank} 🏧 🔰.
+/// note | "📡 ℹ"
+
+👆 💪 ⚙️ `from starlette.testclient import TestClient`.
+
+**FastAPI** 🚚 🎏 `starlette.testclient` `fastapi.testclient` 🏪 👆, 👩💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃.
+
+///
+
+/// tip
+
+🚥 👆 💚 🤙 `async` 🔢 👆 💯 ↖️ ⚪️➡️ 📨 📨 👆 FastAPI 🈸 (✅ 🔁 💽 🔢), ✔️ 👀 [🔁 💯](../advanced/async-tests.md){.internal-link target=_blank} 🏧 🔰.
+
+///
## 🎏 💯
@@ -63,7 +75,7 @@
```Python
-{!../../../docs_src/app_testing/main.py!}
+{!../../docs_src/app_testing/main.py!}
```
### 🔬 📁
@@ -81,7 +93,7 @@
↩️ 👉 📁 🎏 📦, 👆 💪 ⚙️ ⚖ 🗄 🗄 🎚 `app` ⚪️➡️ `main` 🕹 (`main.py`):
```Python hl_lines="3"
-{!../../../docs_src/app_testing/test_main.py!}
+{!../../docs_src/app_testing/test_main.py!}
```
...& ✔️ 📟 💯 💖 ⏭.
@@ -110,24 +122,28 @@
👯♂️ *➡ 🛠️* 🚚 `X-Token` 🎚.
-=== "🐍 3️⃣.6️⃣ & 🔛"
+//// tab | 🐍 3️⃣.6️⃣ & 🔛
- ```Python
- {!> ../../../docs_src/app_testing/app_b/main.py!}
- ```
+```Python
+{!> ../../docs_src/app_testing/app_b/main.py!}
+```
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
+////
- ```Python
- {!> ../../../docs_src/app_testing/app_b_py310/main.py!}
- ```
+//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛
+
+```Python
+{!> ../../docs_src/app_testing/app_b_py310/main.py!}
+```
+
+////
### ↔ 🔬 📁
👆 💪 ⤴️ ℹ `test_main.py` ⏮️ ↔ 💯:
```Python
-{!> ../../../docs_src/app_testing/app_b/test_main.py!}
+{!> ../../docs_src/app_testing/app_b/test_main.py!}
```
🕐❔ 👆 💪 👩💻 🚶♀️ ℹ 📨 & 👆 🚫 💭 ❔, 👆 💪 🔎 (🇺🇸🔍) ❔ ⚫️ `httpx`, ⚖️ ❔ ⚫️ ⏮️ `requests`, 🇸🇲 🔧 ⚓️ 🔛 📨' 🔧.
@@ -144,10 +160,13 @@
🌖 ℹ 🔃 ❔ 🚶♀️ 💽 👩💻 (⚙️ `httpx` ⚖️ `TestClient`) ✅ 🇸🇲 🧾.
-!!! info
- 🗒 👈 `TestClient` 📨 💽 👈 💪 🗜 🎻, 🚫 Pydantic 🏷.
+/// info
- 🚥 👆 ✔️ Pydantic 🏷 👆 💯 & 👆 💚 📨 🚮 💽 🈸 ⏮️ 🔬, 👆 💪 ⚙️ `jsonable_encoder` 🔬 [🎻 🔗 🔢](encoder.md){.internal-link target=_blank}.
+🗒 👈 `TestClient` 📨 💽 👈 💪 🗜 🎻, 🚫 Pydantic 🏷.
+
+🚥 👆 ✔️ Pydantic 🏷 👆 💯 & 👆 💚 📨 🚮 💽 🈸 ⏮️ 🔬, 👆 💪 ⚙️ `jsonable_encoder` 🔬 [🎻 🔗 🔢](encoder.md){.internal-link target=_blank}.
+
+///
## 🏃 ⚫️
diff --git a/docs/en/data/external_links.yml b/docs/en/data/external_links.yml
index 15f6169ee..dedbe87f4 100644
--- a/docs/en/data/external_links.yml
+++ b/docs/en/data/external_links.yml
@@ -1,5 +1,9 @@
Articles:
English:
+ - author: Balthazar Rouberol
+ author_link: https://balthazar-rouberol.com
+ link: https://blog.balthazar-rouberol.com/how-to-profile-a-fastapi-asynchronous-request
+ title: How to profile a FastAPI asynchronous request
- author: Stephen Siegert - Neon
link: https://neon.tech/blog/deploy-a-serverless-fastapi-app-with-neon-postgres-and-aws-app-runner-at-any-scale
title: Deploy a Serverless FastAPI App with Neon Postgres and AWS App Runner at any scale
@@ -264,6 +268,14 @@ Articles:
author_link: https://devonray.com
link: https://devonray.com/blog/deploying-a-fastapi-project-using-aws-lambda-aurora-cdk
title: Deployment using Docker, Lambda, Aurora, CDK & GH Actions
+ - author: Shubhendra Kushwaha
+ author_link: https://www.linkedin.com/in/theshubhendra/
+ link: https://theshubhendra.medium.com/mastering-soft-delete-advanced-sqlalchemy-techniques-4678f4738947
+ title: 'Mastering Soft Delete: Advanced SQLAlchemy Techniques'
+ - author: Shubhendra Kushwaha
+ author_link: https://www.linkedin.com/in/theshubhendra/
+ link: https://theshubhendra.medium.com/role-based-row-filtering-advanced-sqlalchemy-techniques-733e6b1328f6
+ title: 'Role based row filtering: Advanced SQLAlchemy Techniques'
German:
- author: Marcel Sander (actidoo)
author_link: https://www.actidoo.com
diff --git a/docs/en/data/members.yml b/docs/en/data/members.yml
index 0b9e7b94c..0069f8c75 100644
--- a/docs/en/data/members.yml
+++ b/docs/en/data/members.yml
@@ -1,19 +1,19 @@
members:
- login: tiangolo
- avatar_url: https://github.com/tiangolo.png
+ avatar_url: https://avatars.githubusercontent.com/u/1326112
url: https://github.com/tiangolo
- login: Kludex
- avatar_url: https://github.com/Kludex.png
+ avatar_url: https://avatars.githubusercontent.com/u/7353520
url: https://github.com/Kludex
- login: alejsdev
- avatar_url: https://github.com/alejsdev.png
+ avatar_url: https://avatars.githubusercontent.com/u/90076947
url: https://github.com/alejsdev
- login: svlandeg
- avatar_url: https://github.com/svlandeg.png
+ avatar_url: https://avatars.githubusercontent.com/u/8796347
url: https://github.com/svlandeg
- login: estebanx64
- avatar_url: https://github.com/estebanx64.png
+ avatar_url: https://avatars.githubusercontent.com/u/10840422
url: https://github.com/estebanx64
- login: patrick91
- avatar_url: https://github.com/patrick91.png
+ avatar_url: https://avatars.githubusercontent.com/u/667029
url: https://github.com/patrick91
diff --git a/docs/en/data/sponsors.yml b/docs/en/data/sponsors.yml
index 8c0956ac5..6db9c509a 100644
--- a/docs/en/data/sponsors.yml
+++ b/docs/en/data/sponsors.yml
@@ -17,21 +17,15 @@ gold:
- url: https://www.propelauth.com/?utm_source=fastapi&utm_campaign=1223&utm_medium=mainbadge
title: Auth, user management and more for your B2B product
img: https://fastapi.tiangolo.com/img/sponsors/propelauth.png
- - url: https://docs.withcoherence.com/configuration/frameworks/?utm_medium=advertising&utm_source=fastapi&utm_campaign=docs#fastapi-example
+ - url: https://www.withcoherence.com/?utm_medium=advertising&utm_source=fastapi&utm_campaign=website
title: Coherence
img: https://fastapi.tiangolo.com/img/sponsors/coherence.png
- url: https://www.mongodb.com/developer/languages/python/python-quickstart-fastapi/?utm_campaign=fastapi_framework&utm_source=fastapi_sponsorship&utm_medium=web_referral
title: Simplify Full Stack Development with FastAPI & MongoDB
img: https://fastapi.tiangolo.com/img/sponsors/mongodb.png
- - url: https://konghq.com/products/kong-konnect?utm_medium=referral&utm_source=github&utm_campaign=platform&utm_content=fast-api
- title: Kong Konnect - API management platform
- img: https://fastapi.tiangolo.com/img/sponsors/kong.png
- url: https://zuplo.link/fastapi-gh
title: 'Zuplo: Scale, Protect, Document, and Monetize your FastAPI'
img: https://fastapi.tiangolo.com/img/sponsors/zuplo.png
- - url: https://fine.dev?ref=fastapibadge
- title: "Fine's AI FastAPI Workflow: Effortlessly Deploy and Integrate FastAPI into Your Project"
- img: https://fastapi.tiangolo.com/img/sponsors/fine.png
- url: https://liblab.com?utm_source=fastapi
title: liblab - Generate SDKs from FastAPI
img: https://fastapi.tiangolo.com/img/sponsors/liblab.png
diff --git a/docs/en/data/sponsors_badge.yml b/docs/en/data/sponsors_badge.yml
index d8a41fbcb..d45028aaa 100644
--- a/docs/en/data/sponsors_badge.yml
+++ b/docs/en/data/sponsors_badge.yml
@@ -30,3 +30,4 @@ logins:
- svix
- zuplo-oss
- Kong
+ - speakeasy-api
diff --git a/docs/en/docs/advanced/additional-responses.md b/docs/en/docs/advanced/additional-responses.md
index 88d27018c..c038096f9 100644
--- a/docs/en/docs/advanced/additional-responses.md
+++ b/docs/en/docs/advanced/additional-responses.md
@@ -1,9 +1,12 @@
# Additional Responses in OpenAPI
-!!! warning
- This is a rather advanced topic.
+/// warning
- If you are starting with **FastAPI**, you might not need this.
+This is a rather advanced topic.
+
+If you are starting with **FastAPI**, you might not need this.
+
+///
You can declare additional responses, with additional status codes, media types, descriptions, etc.
@@ -15,7 +18,7 @@ But for those additional responses you have to make sure you return a `Response`
You can pass to your *path operation decorators* a parameter `responses`.
-It receives a `dict`, the keys are status codes for each response, like `200`, and the values are other `dict`s with the information for each of them.
+It receives a `dict`: the keys are status codes for each response (like `200`), and the values are other `dict`s with the information for each of them.
Each of those response `dict`s can have a key `model`, containing a Pydantic model, just like `response_model`.
@@ -24,23 +27,29 @@ Each of those response `dict`s can have a key `model`, containing a Pydantic mod
For example, to declare another response with a status code `404` and a Pydantic model `Message`, you can write:
```Python hl_lines="18 22"
-{!../../../docs_src/additional_responses/tutorial001.py!}
+{!../../docs_src/additional_responses/tutorial001.py!}
```
-!!! note
- Keep in mind that you have to return the `JSONResponse` directly.
+/// note
-!!! info
- The `model` key is not part of OpenAPI.
+Keep in mind that you have to return the `JSONResponse` directly.
- **FastAPI** will take the Pydantic model from there, generate the `JSON Schema`, and put it in the correct place.
+///
- The correct place is:
+/// info
- * In the key `content`, that has as value another JSON object (`dict`) that contains:
- * A key with the media type, e.g. `application/json`, that contains as value another JSON object, that contains:
- * A key `schema`, that has as the value the JSON Schema from the model, here's the correct place.
- * **FastAPI** adds a reference here to the global JSON Schemas in another place in your OpenAPI instead of including it directly. This way, other applications and clients can use those JSON Schemas directly, provide better code generation tools, etc.
+The `model` key is not part of OpenAPI.
+
+**FastAPI** will take the Pydantic model from there, generate the JSON Schema, and put it in the correct place.
+
+The correct place is:
+
+* In the key `content`, that has as value another JSON object (`dict`) that contains:
+ * A key with the media type, e.g. `application/json`, that contains as value another JSON object, that contains:
+ * A key `schema`, that has as the value the JSON Schema from the model, here's the correct place.
+ * **FastAPI** adds a reference here to the global JSON Schemas in another place in your OpenAPI instead of including it directly. This way, other applications and clients can use those JSON Schemas directly, provide better code generation tools, etc.
+
+///
The generated responses in the OpenAPI for this *path operation* will be:
@@ -169,16 +178,22 @@ You can use this same `responses` parameter to add different media types for the
For example, you can add an additional media type of `image/png`, declaring that your *path operation* can return a JSON object (with media type `application/json`) or a PNG image:
```Python hl_lines="19-24 28"
-{!../../../docs_src/additional_responses/tutorial002.py!}
+{!../../docs_src/additional_responses/tutorial002.py!}
```
-!!! note
- Notice that you have to return the image using a `FileResponse` directly.
+/// note
-!!! info
- Unless you specify a different media type explicitly in your `responses` parameter, FastAPI will assume the response has the same media type as the main response class (default `application/json`).
+Notice that you have to return the image using a `FileResponse` directly.
- But if you have specified a custom response class with `None` as its media type, FastAPI will use `application/json` for any additional response that has an associated model.
+///
+
+/// info
+
+Unless you specify a different media type explicitly in your `responses` parameter, FastAPI will assume the response has the same media type as the main response class (default `application/json`).
+
+But if you have specified a custom response class with `None` as its media type, FastAPI will use `application/json` for any additional response that has an associated model.
+
+///
## Combining information
@@ -193,7 +208,7 @@ For example, you can declare a response with a status code `404` that uses a Pyd
And a response with a status code `200` that uses your `response_model`, but includes a custom `example`:
```Python hl_lines="20-31"
-{!../../../docs_src/additional_responses/tutorial003.py!}
+{!../../docs_src/additional_responses/tutorial003.py!}
```
It will all be combined and included in your OpenAPI, and shown in the API docs:
@@ -229,12 +244,12 @@ You can use that technique to reuse some predefined responses in your *path oper
For example:
```Python hl_lines="13-17 26"
-{!../../../docs_src/additional_responses/tutorial004.py!}
+{!../../docs_src/additional_responses/tutorial004.py!}
```
## More information about OpenAPI responses
To see what exactly you can include in the responses, you can check these sections in the OpenAPI specification:
-* OpenAPI Responses Object, it includes the `Response Object`.
-* OpenAPI Response Object, you can include anything from this directly in each response inside your `responses` parameter. Including `description`, `headers`, `content` (inside of this is that you declare different media types and JSON Schemas), and `links`.
+* OpenAPI Responses Object, it includes the `Response Object`.
+* OpenAPI Response Object, you can include anything from this directly in each response inside your `responses` parameter. Including `description`, `headers`, `content` (inside of this is that you declare different media types and JSON Schemas), and `links`.
diff --git a/docs/en/docs/advanced/additional-status-codes.md b/docs/en/docs/advanced/additional-status-codes.md
index 0ce275343..6105a301c 100644
--- a/docs/en/docs/advanced/additional-status-codes.md
+++ b/docs/en/docs/advanced/additional-status-codes.md
@@ -14,53 +14,75 @@ But you also want it to accept new items. And when the items didn't exist before
To achieve that, import `JSONResponse`, and return your content there directly, setting the `status_code` that you want:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="4 25"
- {!> ../../../docs_src/additional_status_codes/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="4 25"
+{!> ../../docs_src/additional_status_codes/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="4 25"
- {!> ../../../docs_src/additional_status_codes/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="4 25"
+{!> ../../docs_src/additional_status_codes/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="4 26"
- {!> ../../../docs_src/additional_status_codes/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="4 26"
+{!> ../../docs_src/additional_status_codes/tutorial001_an.py!}
+```
- ```Python hl_lines="2 23"
- {!> ../../../docs_src/additional_status_codes/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="4 25"
- {!> ../../../docs_src/additional_status_codes/tutorial001.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-!!! warning
- When you return a `Response` directly, like in the example above, it will be returned directly.
+///
- It won't be serialized with a model, etc.
+```Python hl_lines="2 23"
+{!> ../../docs_src/additional_status_codes/tutorial001_py310.py!}
+```
- Make sure it has the data you want it to have, and that the values are valid JSON (if you are using `JSONResponse`).
+////
-!!! note "Technical Details"
- You could also use `from starlette.responses import JSONResponse`.
+//// tab | Python 3.8+ non-Annotated
- **FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. The same with `status`.
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="4 25"
+{!> ../../docs_src/additional_status_codes/tutorial001.py!}
+```
+
+////
+
+/// warning
+
+When you return a `Response` directly, like in the example above, it will be returned directly.
+
+It won't be serialized with a model, etc.
+
+Make sure it has the data you want it to have, and that the values are valid JSON (if you are using `JSONResponse`).
+
+///
+
+/// note | "Technical Details"
+
+You could also use `from starlette.responses import JSONResponse`.
+
+**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. The same with `status`.
+
+///
## OpenAPI and API docs
diff --git a/docs/en/docs/advanced/advanced-dependencies.md b/docs/en/docs/advanced/advanced-dependencies.md
index 0cffab56d..b15a4fe3d 100644
--- a/docs/en/docs/advanced/advanced-dependencies.md
+++ b/docs/en/docs/advanced/advanced-dependencies.md
@@ -18,26 +18,35 @@ Not the class itself (which is already a callable), but an instance of that clas
To do that, we declare a method `__call__`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="12"
- {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
- ```
+```Python hl_lines="12"
+{!> ../../docs_src/dependencies/tutorial011_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="11"
- {!> ../../../docs_src/dependencies/tutorial011_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="11"
+{!> ../../docs_src/dependencies/tutorial011_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/dependencies/tutorial011.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="10"
+{!> ../../docs_src/dependencies/tutorial011.py!}
+```
+
+////
In this case, this `__call__` is what **FastAPI** will use to check for additional parameters and sub-dependencies, and this is what will be called to pass a value to the parameter in your *path operation function* later.
@@ -45,26 +54,35 @@ In this case, this `__call__` is what **FastAPI** will use to check for addition
And now, we can use `__init__` to declare the parameters of the instance that we can use to "parameterize" the dependency:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="9"
- {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/dependencies/tutorial011_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/dependencies/tutorial011_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="8"
+{!> ../../docs_src/dependencies/tutorial011_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/dependencies/tutorial011.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="7"
+{!> ../../docs_src/dependencies/tutorial011.py!}
+```
+
+////
In this case, **FastAPI** won't ever touch or care about `__init__`, we will use it directly in our code.
@@ -72,26 +90,35 @@ In this case, **FastAPI** won't ever touch or care about `__init__`, we will use
We could create an instance of this class with:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="18"
- {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
- ```
+```Python hl_lines="18"
+{!> ../../docs_src/dependencies/tutorial011_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial011_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="17"
+{!> ../../docs_src/dependencies/tutorial011_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="16"
- {!> ../../../docs_src/dependencies/tutorial011.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="16"
+{!> ../../docs_src/dependencies/tutorial011.py!}
+```
+
+////
And that way we are able to "parameterize" our dependency, that now has `"bar"` inside of it, as the attribute `checker.fixed_content`.
@@ -107,32 +134,44 @@ checker(q="somequery")
...and pass whatever that returns as the value of the dependency in our *path operation function* as the parameter `fixed_content_included`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="22"
- {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
- ```
+```Python hl_lines="22"
+{!> ../../docs_src/dependencies/tutorial011_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="21"
- {!> ../../../docs_src/dependencies/tutorial011_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="21"
+{!> ../../docs_src/dependencies/tutorial011_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="20"
- {!> ../../../docs_src/dependencies/tutorial011.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-!!! tip
- All this might seem contrived. And it might not be very clear how is it useful yet.
+/// tip
- These examples are intentionally simple, but show how it all works.
+Prefer to use the `Annotated` version if possible.
- In the chapters about security, there are utility functions that are implemented in this same way.
+///
- If you understood all this, you already know how those utility tools for security work underneath.
+```Python hl_lines="20"
+{!> ../../docs_src/dependencies/tutorial011.py!}
+```
+
+////
+
+/// tip
+
+All this might seem contrived. And it might not be very clear how is it useful yet.
+
+These examples are intentionally simple, but show how it all works.
+
+In the chapters about security, there are utility functions that are implemented in this same way.
+
+If you understood all this, you already know how those utility tools for security work underneath.
+
+///
diff --git a/docs/en/docs/advanced/async-tests.md b/docs/en/docs/advanced/async-tests.md
index f9c82e6ab..232cd6e57 100644
--- a/docs/en/docs/advanced/async-tests.md
+++ b/docs/en/docs/advanced/async-tests.md
@@ -33,13 +33,13 @@ For a simple example, let's consider a file structure similar to the one describ
The file `main.py` would have:
```Python
-{!../../../docs_src/async_tests/main.py!}
+{!../../docs_src/async_tests/main.py!}
```
The file `test_main.py` would have the tests for `main.py`, it could look like this now:
```Python
-{!../../../docs_src/async_tests/test_main.py!}
+{!../../docs_src/async_tests/test_main.py!}
```
## Run it
@@ -61,16 +61,19 @@ $ pytest
The marker `@pytest.mark.anyio` tells pytest that this test function should be called asynchronously:
```Python hl_lines="7"
-{!../../../docs_src/async_tests/test_main.py!}
+{!../../docs_src/async_tests/test_main.py!}
```
-!!! tip
- Note that the test function is now `async def` instead of just `def` as before when using the `TestClient`.
+/// tip
+
+Note that the test function is now `async def` instead of just `def` as before when using the `TestClient`.
+
+///
Then we can create an `AsyncClient` with the app, and send async requests to it, using `await`.
-```Python hl_lines="9-10"
-{!../../../docs_src/async_tests/test_main.py!}
+```Python hl_lines="9-12"
+{!../../docs_src/async_tests/test_main.py!}
```
This is the equivalent to:
@@ -81,15 +84,24 @@ response = client.get('/')
...that we used to make our requests with the `TestClient`.
-!!! tip
- Note that we're using async/await with the new `AsyncClient` - the request is asynchronous.
+/// tip
-!!! warning
- If your application relies on lifespan events, the `AsyncClient` won't trigger these events. To ensure they are triggered, use `LifespanManager` from florimondmanca/asgi-lifespan.
+Note that we're using async/await with the new `AsyncClient` - the request is asynchronous.
+
+///
+
+/// warning
+
+If your application relies on lifespan events, the `AsyncClient` won't trigger these events. To ensure they are triggered, use `LifespanManager` from florimondmanca/asgi-lifespan.
+
+///
## Other Asynchronous Function Calls
As the testing function is now asynchronous, you can now also call (and `await`) other `async` functions apart from sending requests to your FastAPI application in your tests, exactly as you would call them anywhere else in your code.
-!!! tip
- If you encounter a `RuntimeError: Task attached to a different loop` when integrating asynchronous function calls in your tests (e.g. when using MongoDB's MotorClient) Remember to instantiate objects that need an event loop only within async functions, e.g. an `'@app.on_event("startup")` callback.
+/// tip
+
+If you encounter a `RuntimeError: Task attached to a different loop` when integrating asynchronous function calls in your tests (e.g. when using MongoDB's MotorClient), remember to instantiate objects that need an event loop only within async functions, e.g. an `'@app.on_event("startup")` callback.
+
+///
diff --git a/docs/en/docs/advanced/behind-a-proxy.md b/docs/en/docs/advanced/behind-a-proxy.md
index c17b024f9..67718a27b 100644
--- a/docs/en/docs/advanced/behind-a-proxy.md
+++ b/docs/en/docs/advanced/behind-a-proxy.md
@@ -19,7 +19,7 @@ In this case, the original path `/app` would actually be served at `/api/v1/app`
Even though all your code is written assuming there's just `/app`.
```Python hl_lines="6"
-{!../../../docs_src/behind_a_proxy/tutorial001.py!}
+{!../../docs_src/behind_a_proxy/tutorial001.py!}
```
And the proxy would be **"stripping"** the **path prefix** on the fly before transmitting the request to the app server (probably Uvicorn via FastAPI CLI), keeping your application convinced that it is being served at `/app`, so that you don't have to update all your code to include the prefix `/api/v1`.
@@ -43,8 +43,11 @@ browser --> proxy
proxy --> server
```
-!!! tip
- The IP `0.0.0.0` is commonly used to mean that the program listens on all the IPs available in that machine/server.
+/// tip
+
+The IP `0.0.0.0` is commonly used to mean that the program listens on all the IPs available in that machine/server.
+
+///
The docs UI would also need the OpenAPI schema to declare that this API `server` is located at `/api/v1` (behind the proxy). For example:
@@ -81,10 +84,13 @@ $ fastapi run main.py --root-path /api/v1
If you use Hypercorn, it also has the option `--root-path`.
-!!! note "Technical Details"
- The ASGI specification defines a `root_path` for this use case.
+/// note | "Technical Details"
- And the `--root-path` command line option provides that `root_path`.
+The ASGI specification defines a `root_path` for this use case.
+
+And the `--root-path` command line option provides that `root_path`.
+
+///
### Checking the current `root_path`
@@ -93,7 +99,7 @@ You can get the current `root_path` used by your application for each request, i
Here we are including it in the message just for demonstration purposes.
```Python hl_lines="8"
-{!../../../docs_src/behind_a_proxy/tutorial001.py!}
+{!../../docs_src/behind_a_proxy/tutorial001.py!}
```
Then, if you start Uvicorn with:
@@ -122,7 +128,7 @@ The response would be something like:
Alternatively, if you don't have a way to provide a command line option like `--root-path` or equivalent, you can set the `root_path` parameter when creating your FastAPI app:
```Python hl_lines="3"
-{!../../../docs_src/behind_a_proxy/tutorial002.py!}
+{!../../docs_src/behind_a_proxy/tutorial002.py!}
```
Passing the `root_path` to `FastAPI` would be the equivalent of passing the `--root-path` command line option to Uvicorn or Hypercorn.
@@ -172,8 +178,11 @@ Then create a file `traefik.toml` with:
This tells Traefik to listen on port 9999 and to use another file `routes.toml`.
-!!! tip
- We are using port 9999 instead of the standard HTTP port 80 so that you don't have to run it with admin (`sudo`) privileges.
+/// tip
+
+We are using port 9999 instead of the standard HTTP port 80 so that you don't have to run it with admin (`sudo`) privileges.
+
+///
Now create that other file `routes.toml`:
@@ -202,7 +211,7 @@ Now create that other file `routes.toml`:
This file configures Traefik to use the path prefix `/api/v1`.
-And then it will redirect its requests to your Uvicorn running on `http://127.0.0.1:8000`.
+And then Traefik will redirect its requests to your Uvicorn running on `http://127.0.0.1:8000`.
Now start Traefik:
@@ -239,8 +248,11 @@ Now, if you go to the URL with the port for Uvicorn: http://127.0.0.1:9999/api/v1/app.
@@ -283,19 +295,22 @@ This is because FastAPI uses this `root_path` to create the default `server` in
## Additional servers
-!!! warning
- This is a more advanced use case. Feel free to skip it.
+/// warning
+
+This is a more advanced use case. Feel free to skip it.
+
+///
By default, **FastAPI** will create a `server` in the OpenAPI schema with the URL for the `root_path`.
-But you can also provide other alternative `servers`, for example if you want *the same* docs UI to interact with a staging and production environments.
+But you can also provide other alternative `servers`, for example if you want *the same* docs UI to interact with both a staging and a production environment.
If you pass a custom list of `servers` and there's a `root_path` (because your API lives behind a proxy), **FastAPI** will insert a "server" with this `root_path` at the beginning of the list.
For example:
```Python hl_lines="4-7"
-{!../../../docs_src/behind_a_proxy/tutorial003.py!}
+{!../../docs_src/behind_a_proxy/tutorial003.py!}
```
Will generate an OpenAPI schema like:
@@ -323,22 +338,28 @@ Will generate an OpenAPI schema like:
}
```
-!!! tip
- Notice the auto-generated server with a `url` value of `/api/v1`, taken from the `root_path`.
+/// tip
+
+Notice the auto-generated server with a `url` value of `/api/v1`, taken from the `root_path`.
+
+///
In the docs UI at http://127.0.0.1:9999/api/v1/docs it would look like:
-!!! tip
- The docs UI will interact with the server that you select.
+/// tip
+
+The docs UI will interact with the server that you select.
+
+///
### Disable automatic server from `root_path`
If you don't want **FastAPI** to include an automatic server using the `root_path`, you can use the parameter `root_path_in_servers=False`:
```Python hl_lines="9"
-{!../../../docs_src/behind_a_proxy/tutorial004.py!}
+{!../../docs_src/behind_a_proxy/tutorial004.py!}
```
and then it won't include it in the OpenAPI schema.
diff --git a/docs/en/docs/advanced/custom-response.md b/docs/en/docs/advanced/custom-response.md
index 1d12173a1..1d6dc3f6d 100644
--- a/docs/en/docs/advanced/custom-response.md
+++ b/docs/en/docs/advanced/custom-response.md
@@ -4,16 +4,19 @@ By default, **FastAPI** will return the responses using `JSONResponse`.
You can override it by returning a `Response` directly as seen in [Return a Response directly](response-directly.md){.internal-link target=_blank}.
-But if you return a `Response` directly, the data won't be automatically converted, and the documentation won't be automatically generated (for example, including the specific "media type", in the HTTP header `Content-Type` as part of the generated OpenAPI).
+But if you return a `Response` directly (or any subclass, like `JSONResponse`), the data won't be automatically converted (even if you declare a `response_model`), and the documentation won't be automatically generated (for example, including the specific "media type", in the HTTP header `Content-Type` as part of the generated OpenAPI).
-But you can also declare the `Response` that you want to be used, in the *path operation decorator*.
+But you can also declare the `Response` that you want to be used (e.g. any `Response` subclass), in the *path operation decorator* using the `response_class` parameter.
The contents that you return from your *path operation function* will be put inside of that `Response`.
And if that `Response` has a JSON media type (`application/json`), like is the case with the `JSONResponse` and `UJSONResponse`, the data you return will be automatically converted (and filtered) with any Pydantic `response_model` that you declared in the *path operation decorator*.
-!!! note
- If you use a response class with no media type, FastAPI will expect your response to have no content, so it will not document the response format in its generated OpenAPI docs.
+/// note
+
+If you use a response class with no media type, FastAPI will expect your response to have no content, so it will not document the response format in its generated OpenAPI docs.
+
+///
## Use `ORJSONResponse`
@@ -28,18 +31,24 @@ 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!}
```
-!!! info
- The parameter `response_class` will also be used to define the "media type" of the response.
+/// info
- In this case, the HTTP header `Content-Type` will be set to `application/json`.
+The parameter `response_class` will also be used to define the "media type" of the response.
- And it will be documented as such in OpenAPI.
+In this case, the HTTP header `Content-Type` will be set to `application/json`.
-!!! tip
- The `ORJSONResponse` is only available in FastAPI, not in Starlette.
+And it will be documented as such in OpenAPI.
+
+///
+
+/// tip
+
+The `ORJSONResponse` is only available in FastAPI, not in Starlette.
+
+///
## HTML Response
@@ -49,15 +58,18 @@ To return a response with HTML directly from **FastAPI**, use `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!}
```
-!!! info
- The parameter `response_class` will also be used to define the "media type" of the response.
+/// info
- In this case, the HTTP header `Content-Type` will be set to `text/html`.
+The parameter `response_class` will also be used to define the "media type" of the response.
- And it will be documented as such in OpenAPI.
+In this case, the HTTP header `Content-Type` will be set to `text/html`.
+
+And it will be documented as such in OpenAPI.
+
+///
### Return a `Response`
@@ -66,14 +78,20 @@ 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!}
```
-!!! warning
- A `Response` returned directly by your *path operation function* won't be documented in OpenAPI (for example, the `Content-Type` won't be documented) and won't be visible in the automatic interactive docs.
+/// warning
-!!! info
- Of course, the actual `Content-Type` header, status code, etc, will come from the `Response` object you returned.
+A `Response` returned directly by your *path operation function* won't be documented in OpenAPI (for example, the `Content-Type` won't be documented) and won't be visible in the automatic interactive docs.
+
+///
+
+/// info
+
+Of course, the actual `Content-Type` header, status code, etc, will come from the `Response` object you returned.
+
+///
### Document in OpenAPI and override `Response`
@@ -86,7 +104,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!}
```
In this example, the function `generate_html_response()` already generates and returns a `Response` instead of returning the HTML in a `str`.
@@ -103,10 +121,13 @@ Here are some of the available responses.
Keep in mind that you can use `Response` to return anything else, or even create a custom sub-class.
-!!! note "Technical Details"
- You could also use `from starlette.responses import HTMLResponse`.
+/// note | "Technical Details"
- **FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette.
+You could also use `from starlette.responses import HTMLResponse`.
+
+**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette.
+
+///
### `Response`
@@ -121,10 +142,10 @@ It accepts the following parameters:
* `headers` - A `dict` of strings.
* `media_type` - A `str` giving the media type. E.g. `"text/html"`.
-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.
+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!}
```
### `HTMLResponse`
@@ -133,10 +154,10 @@ Takes some text or bytes and returns an HTML response, as you read above.
### `PlainTextResponse`
-Takes some text or bytes and returns an plain text response.
+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!}
```
### `JSONResponse`
@@ -149,25 +170,37 @@ This is the default response used in **FastAPI**, as you read above.
A fast alternative JSON response using `orjson`, as you read above.
-!!! info
- This requires installing `orjson` for example with `pip install orjson`.
+/// info
+
+This requires installing `orjson` for example with `pip install orjson`.
+
+///
### `UJSONResponse`
An alternative JSON response using `ujson`.
-!!! info
- This requires installing `ujson` for example with `pip install ujson`.
+/// info
-!!! warning
- `ujson` is less careful than Python's built-in implementation in how it handles some edge-cases.
+This requires installing `ujson` for example with `pip install ujson`.
+
+///
+
+/// warning
+
+`ujson` is less careful than Python's built-in implementation in how it handles some edge-cases.
+
+///
```Python hl_lines="2 7"
-{!../../../docs_src/custom_response/tutorial001.py!}
+{!../../docs_src/custom_response/tutorial001.py!}
```
-!!! tip
- It's possible that `ORJSONResponse` might be a faster alternative.
+/// tip
+
+It's possible that `ORJSONResponse` might be a faster alternative.
+
+///
### `RedirectResponse`
@@ -176,7 +209,7 @@ 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!}
```
---
@@ -185,7 +218,7 @@ 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!}
```
If you do that, then you can return the URL directly from your *path operation* function.
@@ -197,7 +230,7 @@ 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!}
```
### `StreamingResponse`
@@ -205,7 +238,7 @@ You can also use the `status_code` parameter combined with the `response_class`
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!}
```
#### Using `StreamingResponse` with file-like objects
@@ -217,19 +250,22 @@ 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!}
```
1. This is the generator function. It's a "generator function" because it contains `yield` statements inside.
2. By using a `with` block, we make sure that the file-like object is closed after the generator function is done. So, after it finishes sending the response.
-3. This `yield from` tells the function to iterate over that thing named `file_like`. And then, for each part iterated, yield that part as coming from this generator function.
+3. This `yield from` tells the function to iterate over that thing named `file_like`. And then, for each part iterated, yield that part as coming from this generator function (`iterfile`).
So, it is a generator function that transfers the "generating" work to something else internally.
- By doing it this way, we can put it in a `with` block, and that way, ensure that it is closed after finishing.
+ By doing it this way, we can put it in a `with` block, and that way, ensure that the file-like object is closed after finishing.
-!!! tip
- Notice that here as we are using standard `open()` that doesn't support `async` and `await`, we declare the path operation with normal `def`.
+/// tip
+
+Notice that here as we are using standard `open()` that doesn't support `async` and `await`, we declare the path operation with normal `def`.
+
+///
### `FileResponse`
@@ -237,7 +273,7 @@ Asynchronously streams a file as the response.
Takes a different set of arguments to instantiate than the other response types:
-* `path` - The filepath to the file to stream.
+* `path` - The file path to the file to stream.
* `headers` - Any custom headers to include, as a dictionary.
* `media_type` - A string giving the media type. If unset, the filename or path will be used to infer a media type.
* `filename` - If set, this will be included in the response `Content-Disposition`.
@@ -245,13 +281,13 @@ 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!}
```
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!}
```
In this case, you can return the file path directly from your *path operation* function.
@@ -267,7 +303,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!}
```
Now instead of returning:
@@ -295,11 +331,14 @@ 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!}
```
-!!! tip
- You can still override `response_class` in *path operations* as before.
+/// tip
+
+You can still override `response_class` in *path operations* as before.
+
+///
## Additional documentation
diff --git a/docs/en/docs/advanced/dataclasses.md b/docs/en/docs/advanced/dataclasses.md
index 286e8f93f..efc07eab2 100644
--- a/docs/en/docs/advanced/dataclasses.md
+++ b/docs/en/docs/advanced/dataclasses.md
@@ -5,7 +5,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!}
```
This is still supported thanks to **Pydantic**, as it has internal support for `dataclasses`.
@@ -20,19 +20,22 @@ And of course, it supports the same:
This works the same way as with Pydantic models. And it is actually achieved in the same way underneath, using Pydantic.
-!!! info
- Keep in mind that dataclasses can't do everything Pydantic models can do.
+/// info
- So, you might still need to use Pydantic models.
+Keep in mind that dataclasses can't do everything Pydantic models can do.
- But if you have a bunch of dataclasses laying around, this is a nice trick to use them to power a web API using FastAPI. 🤓
+So, you might still need to use Pydantic models.
+
+But if you have a bunch of dataclasses laying around, this is a nice trick to use them to power a web API using FastAPI. 🤓
+
+///
## Dataclasses in `response_model`
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!}
```
The dataclass will be automatically converted to a Pydantic dataclass.
@@ -50,7 +53,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!}
```
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 703fcb7ae..efce492f4 100644
--- a/docs/en/docs/advanced/events.md
+++ b/docs/en/docs/advanced/events.md
@@ -31,24 +31,27 @@ 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!}
```
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*.
And then, right after the `yield`, we unload the model. This code will be executed **after** the application **finishes handling requests**, right before the *shutdown*. This could, for example, release resources like memory or a GPU.
-!!! tip
- The `shutdown` would happen when you are **stopping** the application.
+/// tip
- Maybe you need to start a new version, or you just got tired of running it. 🤷
+The `shutdown` would happen when you are **stopping** the application.
+
+Maybe you need to start a new version, or you just got tired of running it. 🤷
+
+///
### Lifespan function
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!}
```
The first part of the function, before the `yield`, will be executed **before** the application starts.
@@ -62,7 +65,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!}
```
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:
@@ -86,15 +89,18 @@ 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!}
```
## Alternative Events (deprecated)
-!!! warning
- The recommended way to handle the *startup* and *shutdown* is using the `lifespan` parameter of the `FastAPI` app as described above. If you provide a `lifespan` parameter, `startup` and `shutdown` event handlers will no longer be called. It's all `lifespan` or all events, not both.
+/// warning
- You can probably skip this part.
+The recommended way to handle the *startup* and *shutdown* is using the `lifespan` parameter of the `FastAPI` app as described above. If you provide a `lifespan` parameter, `startup` and `shutdown` event handlers will no longer be called. It's all `lifespan` or all events, not both.
+
+You can probably skip this part.
+
+///
There's an alternative way to define this logic to be executed during *startup* and during *shutdown*.
@@ -107,7 +113,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!}
```
In this case, the `startup` event handler function will initialize the items "database" (just a `dict`) with some values.
@@ -121,22 +127,28 @@ 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!}
```
Here, the `shutdown` event handler function will write a text line `"Application shutdown"` to a file `log.txt`.
-!!! info
- In the `open()` function, the `mode="a"` means "append", so, the line will be added after whatever is on that file, without overwriting the previous contents.
+/// info
-!!! tip
- Notice that in this case we are using a standard Python `open()` function that interacts with a file.
+In the `open()` function, the `mode="a"` means "append", so, the line will be added after whatever is on that file, without overwriting the previous contents.
- So, it involves I/O (input/output), that requires "waiting" for things to be written to disk.
+///
- But `open()` doesn't use `async` and `await`.
+/// tip
- So, we declare the event handler function with standard `def` instead of `async def`.
+Notice that in this case we are using a standard Python `open()` function that interacts with a file.
+
+So, it involves I/O (input/output), that requires "waiting" for things to be written to disk.
+
+But `open()` doesn't use `async` and `await`.
+
+So, we declare the event handler function with standard `def` instead of `async def`.
+
+///
### `startup` and `shutdown` together
@@ -152,10 +164,13 @@ Just a technical detail for the curious nerds. 🤓
Underneath, in the ASGI technical specification, this is part of the Lifespan Protocol, and it defines events called `startup` and `shutdown`.
-!!! info
- You can read more about the Starlette `lifespan` handlers in Starlette's Lifespan' docs.
+/// info
- Including how to handle lifespan state that can be used in other areas of your code.
+You can read more about the Starlette `lifespan` handlers in Starlette's Lifespan' docs.
+
+Including how to handle lifespan state that can be used in other areas of your code.
+
+///
## Sub Applications
diff --git a/docs/en/docs/advanced/generate-clients.md b/docs/en/docs/advanced/generate-clients.md
index 0053ac9bb..7872103c3 100644
--- a/docs/en/docs/advanced/generate-clients.md
+++ b/docs/en/docs/advanced/generate-clients.md
@@ -32,17 +32,21 @@ There are also several other companies offering similar services that you can se
Let's start with a simple FastAPI application:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="7-9 12-13 16-17 21"
- {!> ../../../docs_src/generate_clients/tutorial001_py39.py!}
- ```
+```Python hl_lines="7-9 12-13 16-17 21"
+{!> ../../docs_src/generate_clients/tutorial001_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9-11 14-15 18 19 23"
- {!> ../../../docs_src/generate_clients/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="9-11 14-15 18 19 23"
+{!> ../../docs_src/generate_clients/tutorial001.py!}
+```
+
+////
Notice that the *path operations* define the models they use for request payload and response payload, using the models `Item` and `ResponseMessage`.
@@ -127,8 +131,11 @@ You will also get autocompletion for the payload to send:
-!!! tip
- Notice the autocompletion for `name` and `price`, that was defined in the FastAPI application, in the `Item` model.
+/// tip
+
+Notice the autocompletion for `name` and `price`, that was defined in the FastAPI application, in the `Item` model.
+
+///
You will have inline errors for the data that you send:
@@ -144,17 +151,21 @@ In many cases your FastAPI app will be bigger, and you will probably use tags to
For example, you could have a section for **items** and another section for **users**, and they could be separated by tags:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="21 26 34"
- {!> ../../../docs_src/generate_clients/tutorial002_py39.py!}
- ```
+```Python hl_lines="21 26 34"
+{!> ../../docs_src/generate_clients/tutorial002_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="23 28 36"
- {!> ../../../docs_src/generate_clients/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="23 28 36"
+{!> ../../docs_src/generate_clients/tutorial002.py!}
+```
+
+////
### Generate a TypeScript Client with Tags
@@ -201,17 +212,21 @@ For example, here it is using the first tag (you will probably have only one tag
You can then pass that custom function to **FastAPI** as the `generate_unique_id_function` parameter:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="6-7 10"
- {!> ../../../docs_src/generate_clients/tutorial003_py39.py!}
- ```
+```Python hl_lines="6-7 10"
+{!> ../../docs_src/generate_clients/tutorial003_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="8-9 12"
- {!> ../../../docs_src/generate_clients/tutorial003.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="8-9 12"
+{!> ../../docs_src/generate_clients/tutorial003.py!}
+```
+
+////
### Generate a TypeScript Client with Custom Operation IDs
@@ -233,17 +248,21 @@ But for the generated client we could **modify** the OpenAPI operation IDs right
We could download the OpenAPI JSON to a file `openapi.json` and then we could **remove that prefixed tag** with a script like this:
-=== "Python"
+//// tab | Python
- ```Python
- {!> ../../../docs_src/generate_clients/tutorial004.py!}
- ```
+```Python
+{!> ../../docs_src/generate_clients/tutorial004.py!}
+```
-=== "Node.js"
+////
- ```Javascript
- {!> ../../../docs_src/generate_clients/tutorial004.js!}
- ```
+//// tab | Node.js
+
+```Javascript
+{!> ../../docs_src/generate_clients/tutorial004.js!}
+```
+
+////
With that, the operation IDs would be renamed from things like `items-get_items` to just `get_items`, that way the client generator can generate simpler method names.
diff --git a/docs/en/docs/advanced/index.md b/docs/en/docs/advanced/index.md
index 86e42fba0..36f0720c0 100644
--- a/docs/en/docs/advanced/index.md
+++ b/docs/en/docs/advanced/index.md
@@ -6,10 +6,13 @@ The main [Tutorial - User Guide](../tutorial/index.md){.internal-link target=_bl
In the next sections you will see other options, configurations, and additional features.
-!!! tip
- The next sections are **not necessarily "advanced"**.
+/// tip
- And it's possible that for your use case, the solution is in one of them.
+The next sections are **not necessarily "advanced"**.
+
+And it's possible that for your use case, the solution is in one of them.
+
+///
## Read the Tutorial first
diff --git a/docs/en/docs/advanced/middleware.md b/docs/en/docs/advanced/middleware.md
index 9219f1d2c..07deac716 100644
--- a/docs/en/docs/advanced/middleware.md
+++ b/docs/en/docs/advanced/middleware.md
@@ -24,7 +24,7 @@ app = SomeASGIApp()
new_app = UnicornMiddleware(app, some_config="rainbow")
```
-But FastAPI (actually Starlette) provides a simpler way to do it that makes sure that the internal middlewares to handle server errors and custom exception handlers work properly.
+But FastAPI (actually Starlette) provides a simpler way to do it that makes sure that the internal middlewares handle server errors and custom exception handlers work properly.
For that, you use `app.add_middleware()` (as in the example for CORS).
@@ -43,19 +43,22 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow")
**FastAPI** includes several middlewares for common use cases, we'll see next how to use them.
-!!! note "Technical Details"
- For the next examples, you could also use `from starlette.middleware.something import SomethingMiddleware`.
+/// note | "Technical Details"
- **FastAPI** provides several middlewares in `fastapi.middleware` just as a convenience for you, the developer. But most of the available middlewares come directly from Starlette.
+For the next examples, you could also use `from starlette.middleware.something import SomethingMiddleware`.
+
+**FastAPI** provides several middlewares in `fastapi.middleware` just as a convenience for you, the developer. But most of the available middlewares come directly from Starlette.
+
+///
## `HTTPSRedirectMiddleware`
Enforces that all incoming requests must either be `https` or `wss`.
-Any incoming requests to `http` or `ws` will be redirected to the secure scheme instead.
+Any incoming request to `http` or `ws` will be redirected to the secure scheme instead.
```Python hl_lines="2 6"
-{!../../../docs_src/advanced_middleware/tutorial001.py!}
+{!../../docs_src/advanced_middleware/tutorial001.py!}
```
## `TrustedHostMiddleware`
@@ -63,7 +66,7 @@ Any incoming requests to `http` or `ws` will be redirected to the secure scheme
Enforces that all incoming requests have a correctly set `Host` header, in order to guard against HTTP Host Header attacks.
```Python hl_lines="2 6-8"
-{!../../../docs_src/advanced_middleware/tutorial002.py!}
+{!../../docs_src/advanced_middleware/tutorial002.py!}
```
The following arguments are supported:
@@ -79,12 +82,13 @@ Handles GZip responses for any request that includes `"gzip"` in the `Accept-Enc
The middleware will handle both standard and streaming responses.
```Python hl_lines="2 6"
-{!../../../docs_src/advanced_middleware/tutorial003.py!}
+{!../../docs_src/advanced_middleware/tutorial003.py!}
```
The following arguments are supported:
* `minimum_size` - Do not GZip responses that are smaller than this minimum size in bytes. Defaults to `500`.
+* `compresslevel` - Used during GZip compression. It is an integer ranging from 1 to 9. Defaults to `9`. Lower value results in faster compression but larger file sizes, while higher value results in slower compression but smaller file sizes.
## Other middlewares
@@ -92,7 +96,6 @@ There are many other ASGI middlewares.
For example:
-* Sentry
* Uvicorn's `ProxyHeadersMiddleware`
* MessagePack
diff --git a/docs/en/docs/advanced/openapi-callbacks.md b/docs/en/docs/advanced/openapi-callbacks.md
index 1ff51f077..82069a950 100644
--- a/docs/en/docs/advanced/openapi-callbacks.md
+++ b/docs/en/docs/advanced/openapi-callbacks.md
@@ -32,11 +32,14 @@ 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!}
```
-!!! tip
- The `callback_url` query parameter uses a Pydantic URL type.
+/// tip
+
+The `callback_url` query parameter uses a Pydantic Url type.
+
+///
The only new thing is the `callbacks=invoices_callback_router.routes` as an argument to the *path operation decorator*. We'll see what that is next.
@@ -61,10 +64,13 @@ That documentation will show up in the Swagger UI at `/docs` in your API, and it
This example doesn't implement the callback itself (that could be just a line of code), only the documentation part.
-!!! tip
- The actual callback is just an HTTP request.
+/// tip
- When implementing the callback yourself, you could use something like HTTPX or Requests.
+The actual callback is just an HTTP request.
+
+When implementing the callback yourself, you could use something like HTTPX or Requests.
+
+///
## Write the callback documentation code
@@ -74,17 +80,20 @@ But, you already know how to easily create automatic documentation for an API wi
So we are going to use that same knowledge to document how the *external API* should look like... by creating the *path operation(s)* that the external API should implement (the ones your API will call).
-!!! tip
- When writing the code to document a callback, it might be useful to imagine that you are that *external developer*. And that you are currently implementing the *external API*, not *your API*.
+/// tip
- Temporarily adopting this point of view (of the *external developer*) can help you feel like it's more obvious where to put the parameters, the Pydantic model for the body, for the response, etc. for that *external API*.
+When writing the code to document a callback, it might be useful to imagine that you are that *external developer*. And that you are currently implementing the *external API*, not *your API*.
+
+Temporarily adopting this point of view (of the *external developer*) can help you feel like it's more obvious where to put the parameters, the Pydantic model for the body, for the response, etc. for that *external API*.
+
+///
### Create a callback `APIRouter`
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!}
```
### Create the callback *path operation*
@@ -97,7 +106,7 @@ It should look just like a normal FastAPI *path operation*:
* 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!}
```
There are 2 main differences from a normal *path operation*:
@@ -154,8 +163,11 @@ and it would expect a response from that *external API* with a JSON body like:
}
```
-!!! tip
- Notice how the callback URL used contains the URL received as a query parameter in `callback_url` (`https://www.external.org/events`) and also the invoice `id` from inside of the JSON body (`2expen51ve`).
+/// tip
+
+Notice how the callback URL used contains the URL received as a query parameter in `callback_url` (`https://www.external.org/events`) and also the invoice `id` from inside of the JSON body (`2expen51ve`).
+
+///
### Add the callback router
@@ -164,11 +176,14 @@ 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!}
```
-!!! tip
- Notice that you are not passing the router itself (`invoices_callback_router`) to `callback=`, but the attribute `.routes`, as in `invoices_callback_router.routes`.
+/// tip
+
+Notice that you are not passing the router itself (`invoices_callback_router`) to `callback=`, but the attribute `.routes`, as in `invoices_callback_router.routes`.
+
+///
### Check the docs
diff --git a/docs/en/docs/advanced/openapi-webhooks.md b/docs/en/docs/advanced/openapi-webhooks.md
index f7f43b357..eaaa48a37 100644
--- a/docs/en/docs/advanced/openapi-webhooks.md
+++ b/docs/en/docs/advanced/openapi-webhooks.md
@@ -22,21 +22,27 @@ With **FastAPI**, using OpenAPI, you can define the names of these webhooks, the
This can make it a lot easier for your users to **implement their APIs** to receive your **webhook** requests, they might even be able to autogenerate some of their own API code.
-!!! info
- Webhooks are available in OpenAPI 3.1.0 and above, supported by FastAPI `0.99.0` and above.
+/// info
+
+Webhooks are available in OpenAPI 3.1.0 and above, supported by FastAPI `0.99.0` and above.
+
+///
## An app with webhooks
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!}
```
The webhooks that you define will end up in the **OpenAPI** schema and the automatic **docs UI**.
-!!! info
- The `app.webhooks` object is actually just an `APIRouter`, the same type you would use when structuring your app with multiple files.
+/// info
+
+The `app.webhooks` object is actually just an `APIRouter`, the same type you would use when structuring your app with multiple files.
+
+///
Notice that with webhooks you are actually not declaring a *path* (like `/items/`), the text you pass there is just an **identifier** of the webhook (the name of the event), for example in `@app.webhooks.post("new-subscription")`, the webhook name is `new-subscription`.
diff --git a/docs/en/docs/advanced/path-operation-advanced-configuration.md b/docs/en/docs/advanced/path-operation-advanced-configuration.md
index 35f7d1b8d..a61e3f19b 100644
--- a/docs/en/docs/advanced/path-operation-advanced-configuration.md
+++ b/docs/en/docs/advanced/path-operation-advanced-configuration.md
@@ -2,15 +2,18 @@
## OpenAPI operationId
-!!! warning
- If you are not an "expert" in OpenAPI, you probably don't need this.
+/// warning
+
+If you are not an "expert" in OpenAPI, you probably don't need this.
+
+///
You can set the OpenAPI `operationId` to be used in your *path operation* with the parameter `operation_id`.
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!}
```
### Using the *path operation function* name as the operationId
@@ -20,23 +23,29 @@ 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!}
```
-!!! tip
- If you manually call `app.openapi()`, you should update the `operationId`s before that.
+/// tip
-!!! warning
- If you do this, you have to make sure each one of your *path operation functions* has a unique name.
+If you manually call `app.openapi()`, you should update the `operationId`s before that.
- Even if they are in different modules (Python files).
+///
+
+/// warning
+
+If you do this, you have to make sure each one of your *path operation functions* has a unique name.
+
+Even if they are in different modules (Python files).
+
+///
## Exclude from OpenAPI
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!}
```
## Advanced description from docstring
@@ -48,7 +57,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!}
```
## Additional Responses
@@ -65,8 +74,11 @@ There's a whole chapter here in the documentation about it, you can read it at [
When you declare a *path operation* in your application, **FastAPI** automatically generates the relevant metadata about that *path operation* to be included in the OpenAPI schema.
-!!! note "Technical details"
- In the OpenAPI specification it is called the Operation Object.
+/// note | "Technical details"
+
+In the OpenAPI specification it is called the Operation Object.
+
+///
It has all the information about the *path operation* and is used to generate the automatic documentation.
@@ -74,10 +86,13 @@ It includes the `tags`, `parameters`, `requestBody`, `responses`, etc.
This *path operation*-specific OpenAPI schema is normally generated automatically by **FastAPI**, but you can also extend it.
-!!! tip
- This is a low level extension point.
+/// tip
- If you only need to declare additional responses, a more convenient way to do it is with [Additional Responses in OpenAPI](additional-responses.md){.internal-link target=_blank}.
+This is a low level extension point.
+
+If you only need to declare additional responses, a more convenient way to do it is with [Additional Responses in OpenAPI](additional-responses.md){.internal-link target=_blank}.
+
+///
You can extend the OpenAPI schema for a *path operation* using the parameter `openapi_extra`.
@@ -86,7 +101,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!}
```
If you open the automatic API docs, your extension will show up at the bottom of the specific *path operation*.
@@ -134,8 +149,8 @@ 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="20-37 39-40"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial006.py!}
+```Python hl_lines="19-36 39-40"
+{!../../docs_src/path_operation_advanced_configuration/tutorial006.py!}
```
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.
@@ -150,20 +165,27 @@ And you could do this even if the data type in the request is not JSON.
For example, in this application we don't use FastAPI's integrated functionality to extract the JSON Schema from Pydantic models nor the automatic validation for JSON. In fact, we are declaring the request content type as YAML, not JSON:
-=== "Pydantic v2"
+//// tab | Pydantic v2
- ```Python hl_lines="17-22 24"
- {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007.py!}
- ```
+```Python hl_lines="17-22 24"
+{!> ../../docs_src/path_operation_advanced_configuration/tutorial007.py!}
+```
-=== "Pydantic v1"
+////
- ```Python hl_lines="17-22 24"
- {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!}
- ```
+//// tab | Pydantic v1
-!!! info
- In Pydantic version 1 the method to get the JSON Schema for a model was called `Item.schema()`, in Pydantic version 2, the method is called `Item.model_json_schema()`.
+```Python hl_lines="17-22 24"
+{!> ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!}
+```
+
+////
+
+/// info
+
+In Pydantic version 1 the method to get the JSON Schema for a model was called `Item.schema()`, in Pydantic version 2, the method is called `Item.model_json_schema()`.
+
+///
Nevertheless, although we are not using the default integrated functionality, we are still using a Pydantic model to manually generate the JSON Schema for the data that we want to receive in YAML.
@@ -171,22 +193,32 @@ Then we use the request directly, and extract the body as `bytes`. This means th
And then in our code, we parse that YAML content directly, and then we are again using the same Pydantic model to validate the YAML content:
-=== "Pydantic v2"
+//// tab | Pydantic v2
- ```Python hl_lines="26-33"
- {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007.py!}
- ```
+```Python hl_lines="26-33"
+{!> ../../docs_src/path_operation_advanced_configuration/tutorial007.py!}
+```
-=== "Pydantic v1"
+////
- ```Python hl_lines="26-33"
- {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!}
- ```
+//// tab | Pydantic v1
-!!! info
- In Pydantic version 1 the method to parse and validate an object was `Item.parse_obj()`, in Pydantic version 2, the method is called `Item.model_validate()`.
+```Python hl_lines="26-33"
+{!> ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!}
+```
-!!! tip
- Here we reuse the same Pydantic model.
+////
- But the same way, we could have validated it in some other way.
+/// info
+
+In Pydantic version 1 the method to parse and validate an object was `Item.parse_obj()`, in Pydantic version 2, the method is called `Item.model_validate()`.
+
+///
+
+/// tip
+
+Here we reuse the same Pydantic model.
+
+But the same way, we could have validated it in some other way.
+
+///
diff --git a/docs/en/docs/advanced/response-change-status-code.md b/docs/en/docs/advanced/response-change-status-code.md
index b88d74a8a..fc041f7de 100644
--- a/docs/en/docs/advanced/response-change-status-code.md
+++ b/docs/en/docs/advanced/response-change-status-code.md
@@ -21,7 +21,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!}
```
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 d53985dbb..4467779ba 100644
--- a/docs/en/docs/advanced/response-cookies.md
+++ b/docs/en/docs/advanced/response-cookies.md
@@ -7,7 +7,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!}
```
And then you can return any object you need, as you normally would (a `dict`, a database model, etc).
@@ -27,23 +27,29 @@ 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!}
```
-!!! tip
- Keep in mind that if you return a response directly instead of using the `Response` parameter, FastAPI will return it directly.
+/// tip
- So, you will have to make sure your data is of the correct type. E.g. it is compatible with JSON, if you are returning a `JSONResponse`.
+Keep in mind that if you return a response directly instead of using the `Response` parameter, FastAPI will return it directly.
- And also that you are not sending any data that should have been filtered by a `response_model`.
+So, you will have to make sure your data is of the correct type. E.g. it is compatible with JSON, if you are returning a `JSONResponse`.
+
+And also that you are not sending any data that should have been filtered by a `response_model`.
+
+///
### More info
-!!! note "Technical Details"
- You could also use `from starlette.responses import Response` or `from starlette.responses import JSONResponse`.
+/// note | "Technical Details"
- **FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette.
+You could also use `from starlette.responses import Response` or `from starlette.responses import JSONResponse`.
- And as the `Response` can be used frequently to set headers and cookies, **FastAPI** also provides it at `fastapi.Response`.
+**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette.
+
+And as the `Response` can be used frequently to set headers and cookies, **FastAPI** also provides it at `fastapi.Response`.
+
+///
To see all the available parameters and options, check the documentation in Starlette.
diff --git a/docs/en/docs/advanced/response-directly.md b/docs/en/docs/advanced/response-directly.md
index 8836140ec..8246b9674 100644
--- a/docs/en/docs/advanced/response-directly.md
+++ b/docs/en/docs/advanced/response-directly.md
@@ -14,8 +14,11 @@ It might be useful, for example, to return custom headers or cookies.
In fact, you can return any `Response` or any sub-class of it.
-!!! tip
- `JSONResponse` itself is a sub-class of `Response`.
+/// tip
+
+`JSONResponse` itself is a sub-class of `Response`.
+
+///
And when you return a `Response`, **FastAPI** will pass it directly.
@@ -25,20 +28,23 @@ This gives you a lot of flexibility. You can return any data type, override any
## Using the `jsonable_encoder` in a `Response`
-Because **FastAPI** doesn't do any change to a `Response` you return, you have to make sure it's contents are ready for it.
+Because **FastAPI** doesn't make any changes to a `Response` you return, you have to make sure its contents are ready for it.
For example, you cannot put a Pydantic model in a `JSONResponse` without first converting it to a `dict` with all the data types (like `datetime`, `UUID`, etc) converted to JSON-compatible types.
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!}
```
-!!! note "Technical Details"
- You could also use `from starlette.responses import JSONResponse`.
+/// note | "Technical Details"
- **FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette.
+You could also use `from starlette.responses import JSONResponse`.
+
+**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette.
+
+///
## Returning a custom `Response`
@@ -48,10 +54,10 @@ Now, let's see how you could use that to return a custom response.
Let's say that you want to return an XML response.
-You could put your XML content in a string, put it in a `Response`, and return it:
+You could put your XML content in a string, put that in a `Response`, and return it:
```Python hl_lines="1 18"
-{!../../../docs_src/response_directly/tutorial002.py!}
+{!../../docs_src/response_directly/tutorial002.py!}
```
## Notes
diff --git a/docs/en/docs/advanced/response-headers.md b/docs/en/docs/advanced/response-headers.md
index 49b5fe476..80c100826 100644
--- a/docs/en/docs/advanced/response-headers.md
+++ b/docs/en/docs/advanced/response-headers.md
@@ -7,7 +7,7 @@ You can declare a parameter of type `Response` in your *path operation function*
And then you can set headers in that *temporal* response object.
```Python hl_lines="1 7-8"
-{!../../../docs_src/response_headers/tutorial002.py!}
+{!../../docs_src/response_headers/tutorial002.py!}
```
And then you can return any object you need, as you normally would (a `dict`, a database model, etc).
@@ -25,15 +25,18 @@ You can also add headers when you return a `Response` directly.
Create a response as described in [Return a Response Directly](response-directly.md){.internal-link target=_blank} and pass the headers as an additional parameter:
```Python hl_lines="10-12"
-{!../../../docs_src/response_headers/tutorial001.py!}
+{!../../docs_src/response_headers/tutorial001.py!}
```
-!!! note "Technical Details"
- You could also use `from starlette.responses import Response` or `from starlette.responses import JSONResponse`.
+/// note | "Technical Details"
- **FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette.
+You could also use `from starlette.responses import Response` or `from starlette.responses import JSONResponse`.
- And as the `Response` can be used frequently to set headers and cookies, **FastAPI** also provides it at `fastapi.Response`.
+**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette.
+
+And as the `Response` can be used frequently to set headers and cookies, **FastAPI** also provides it at `fastapi.Response`.
+
+///
## Custom Headers
diff --git a/docs/en/docs/advanced/security/http-basic-auth.md b/docs/en/docs/advanced/security/http-basic-auth.md
index 680f4dff5..fa652c52b 100644
--- a/docs/en/docs/advanced/security/http-basic-auth.md
+++ b/docs/en/docs/advanced/security/http-basic-auth.md
@@ -20,26 +20,35 @@ Then, when you type that username and password, the browser sends them in the he
* It returns an object of type `HTTPBasicCredentials`:
* It contains the `username` and `password` sent.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="4 8 12"
- {!> ../../../docs_src/security/tutorial006_an_py39.py!}
- ```
+```Python hl_lines="4 8 12"
+{!> ../../docs_src/security/tutorial006_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="2 7 11"
- {!> ../../../docs_src/security/tutorial006_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="2 7 11"
+{!> ../../docs_src/security/tutorial006_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="2 6 10"
- {!> ../../../docs_src/security/tutorial006.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="2 6 10"
+{!> ../../docs_src/security/tutorial006.py!}
+```
+
+////
When you try to open the URL for the first time (or click the "Execute" button in the docs) the browser will ask you for your username and password:
@@ -59,26 +68,35 @@ To handle that, we first convert the `username` and `password` to `bytes` encodi
Then we can use `secrets.compare_digest()` to ensure that `credentials.username` is `"stanleyjobson"`, and that `credentials.password` is `"swordfish"`.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="1 12-24"
- {!> ../../../docs_src/security/tutorial007_an_py39.py!}
- ```
+```Python hl_lines="1 12-24"
+{!> ../../docs_src/security/tutorial007_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1 12-24"
- {!> ../../../docs_src/security/tutorial007_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="1 12-24"
+{!> ../../docs_src/security/tutorial007_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="1 11-21"
- {!> ../../../docs_src/security/tutorial007.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="1 11-21"
+{!> ../../docs_src/security/tutorial007.py!}
+```
+
+////
This would be similar to:
@@ -126,7 +144,7 @@ And then they can try again knowing that it's probably something more similar to
#### A "professional" attack
-Of course, the attackers would not try all this by hand, they would write a program to do it, possibly with thousands or millions of tests per second. And would get just one extra correct letter at a time.
+Of course, the attackers would not try all this by hand, they would write a program to do it, possibly with thousands or millions of tests per second. And they would get just one extra correct letter at a time.
But doing that, in some minutes or hours the attackers would have guessed the correct username and password, with the "help" of our application, just using the time taken to answer.
@@ -142,23 +160,32 @@ That way, using `secrets.compare_digest()` in your application code, it will be
After detecting that the credentials are incorrect, return an `HTTPException` with a status code 401 (the same returned when no credentials are provided) and add the header `WWW-Authenticate` to make the browser show the login prompt again:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="26-30"
- {!> ../../../docs_src/security/tutorial007_an_py39.py!}
- ```
+```Python hl_lines="26-30"
+{!> ../../docs_src/security/tutorial007_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="26-30"
- {!> ../../../docs_src/security/tutorial007_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="26-30"
+{!> ../../docs_src/security/tutorial007_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="23-27"
- {!> ../../../docs_src/security/tutorial007.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="23-27"
+{!> ../../docs_src/security/tutorial007.py!}
+```
+
+////
diff --git a/docs/en/docs/advanced/security/index.md b/docs/en/docs/advanced/security/index.md
index c9ede4231..edb42132e 100644
--- a/docs/en/docs/advanced/security/index.md
+++ b/docs/en/docs/advanced/security/index.md
@@ -4,10 +4,13 @@
There are some extra features to handle security apart from the ones covered in the [Tutorial - User Guide: Security](../../tutorial/security/index.md){.internal-link target=_blank}.
-!!! tip
- The next sections are **not necessarily "advanced"**.
+/// tip
- And it's possible that for your use case, the solution is in one of them.
+The next sections are **not necessarily "advanced"**.
+
+And it's possible that for your use case, the solution is in one of them.
+
+///
## Read the Tutorial first
diff --git a/docs/en/docs/advanced/security/oauth2-scopes.md b/docs/en/docs/advanced/security/oauth2-scopes.md
index 9a9c0dff9..3db284d02 100644
--- a/docs/en/docs/advanced/security/oauth2-scopes.md
+++ b/docs/en/docs/advanced/security/oauth2-scopes.md
@@ -10,18 +10,21 @@ Every time you "log in with" Facebook, Google, GitHub, Microsoft, Twitter, that
In this section you will see how to manage authentication and authorization with the same OAuth2 with scopes in your **FastAPI** application.
-!!! warning
- This is a more or less advanced section. If you are just starting, you can skip it.
+/// warning
- You don't necessarily need OAuth2 scopes, and you can handle authentication and authorization however you want.
+This is a more or less advanced section. If you are just starting, you can skip it.
- But OAuth2 with scopes can be nicely integrated into your API (with OpenAPI) and your API docs.
+You don't necessarily need OAuth2 scopes, and you can handle authentication and authorization however you want.
- Nevertheless, you still enforce those scopes, or any other security/authorization requirement, however you need, in your code.
+But OAuth2 with scopes can be nicely integrated into your API (with OpenAPI) and your API docs.
- In many cases, OAuth2 with scopes can be an overkill.
+Nevertheless, you still enforce those scopes, or any other security/authorization requirement, however you need, in your code.
- But if you know you need it, or you are curious, keep reading.
+In many cases, OAuth2 with scopes can be an overkill.
+
+But if you know you need it, or you are curious, keep reading.
+
+///
## OAuth2 scopes and OpenAPI
@@ -43,63 +46,87 @@ They are normally used to declare specific security permissions, for example:
* `instagram_basic` is used by Facebook / Instagram.
* `https://www.googleapis.com/auth/drive` is used by Google.
-!!! info
- In OAuth2 a "scope" is just a string that declares a specific permission required.
+/// info
- It doesn't matter if it has other characters like `:` or if it is a URL.
+In OAuth2 a "scope" is just a string that declares a specific permission required.
- Those details are implementation specific.
+It doesn't matter if it has other characters like `:` or if it is a URL.
- For OAuth2 they are just strings.
+Those details are implementation specific.
+
+For OAuth2 they are just strings.
+
+///
## Global view
First, let's quickly see the parts that change from the examples in the main **Tutorial - User Guide** for [OAuth2 with Password (and hashing), Bearer with JWT tokens](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. Now using OAuth2 scopes:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="5 9 13 47 65 106 108-116 122-125 129-135 140 156"
- {!> ../../../docs_src/security/tutorial005_an_py310.py!}
- ```
+```Python hl_lines="5 9 13 47 65 106 108-116 122-125 129-135 140 156"
+{!> ../../docs_src/security/tutorial005_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156"
- {!> ../../../docs_src/security/tutorial005_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156"
+{!> ../../docs_src/security/tutorial005_an_py39.py!}
+```
- ```Python hl_lines="2 5 9 13 48 66 107 109-117 123-126 130-136 141 157"
- {!> ../../../docs_src/security/tutorial005_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="2 5 9 13 48 66 107 109-117 123-126 130-136 141 157"
+{!> ../../docs_src/security/tutorial005_an.py!}
+```
- ```Python hl_lines="4 8 12 46 64 105 107-115 121-124 128-134 139 155"
- {!> ../../../docs_src/security/tutorial005_py310.py!}
- ```
+////
-=== "Python 3.9+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156"
- {!> ../../../docs_src/security/tutorial005_py39.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="4 8 12 46 64 105 107-115 121-124 128-134 139 155"
+{!> ../../docs_src/security/tutorial005_py310.py!}
+```
- ```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156"
- {!> ../../../docs_src/security/tutorial005.py!}
- ```
+////
+
+//// tab | Python 3.9+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156"
+{!> ../../docs_src/security/tutorial005_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156"
+{!> ../../docs_src/security/tutorial005.py!}
+```
+
+////
Now let's review those changes step by step.
@@ -109,51 +136,71 @@ The first change is that now we are declaring the OAuth2 security scheme with tw
The `scopes` parameter receives a `dict` with each scope as a key and the description as the value:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="63-66"
- {!> ../../../docs_src/security/tutorial005_an_py310.py!}
- ```
+```Python hl_lines="63-66"
+{!> ../../docs_src/security/tutorial005_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="63-66"
- {!> ../../../docs_src/security/tutorial005_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="63-66"
+{!> ../../docs_src/security/tutorial005_an_py39.py!}
+```
- ```Python hl_lines="64-67"
- {!> ../../../docs_src/security/tutorial005_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="64-67"
+{!> ../../docs_src/security/tutorial005_an.py!}
+```
- ```Python hl_lines="62-65"
- {!> ../../../docs_src/security/tutorial005_py310.py!}
- ```
+////
+//// tab | Python 3.10+ non-Annotated
-=== "Python 3.9+ non-Annotated"
+/// tip
- !!! tip
- Prefer to use the `Annotated` version if possible.
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="63-66"
- {!> ../../../docs_src/security/tutorial005_py39.py!}
- ```
+///
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="62-65"
+{!> ../../docs_src/security/tutorial005_py310.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="63-66"
- {!> ../../../docs_src/security/tutorial005.py!}
- ```
+//// tab | Python 3.9+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="63-66"
+{!> ../../docs_src/security/tutorial005_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="63-66"
+{!> ../../docs_src/security/tutorial005.py!}
+```
+
+////
Because we are now declaring those scopes, they will show up in the API docs when you log-in/authorize.
@@ -171,55 +218,79 @@ We are still using the same `OAuth2PasswordRequestForm`. It includes a property
And we return the scopes as part of the JWT token.
-!!! danger
- For simplicity, here we are just adding the scopes received directly to the token.
+/// danger
- But in your application, for security, you should make sure you only add the scopes that the user is actually able to have, or the ones you have predefined.
+For simplicity, here we are just adding the scopes received directly to the token.
-=== "Python 3.10+"
+But in your application, for security, you should make sure you only add the scopes that the user is actually able to have, or the ones you have predefined.
- ```Python hl_lines="156"
- {!> ../../../docs_src/security/tutorial005_an_py310.py!}
- ```
+///
-=== "Python 3.9+"
+//// tab | Python 3.10+
- ```Python hl_lines="156"
- {!> ../../../docs_src/security/tutorial005_an_py39.py!}
- ```
+```Python hl_lines="156"
+{!> ../../docs_src/security/tutorial005_an_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="157"
- {!> ../../../docs_src/security/tutorial005_an.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.10+ non-Annotated"
+```Python hl_lines="156"
+{!> ../../docs_src/security/tutorial005_an_py39.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="155"
- {!> ../../../docs_src/security/tutorial005_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.9+ non-Annotated"
+```Python hl_lines="157"
+{!> ../../docs_src/security/tutorial005_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="156"
- {!> ../../../docs_src/security/tutorial005_py39.py!}
- ```
+//// tab | Python 3.10+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip
- !!! tip
- Prefer to use the `Annotated` version if possible.
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="156"
- {!> ../../../docs_src/security/tutorial005.py!}
- ```
+///
+
+```Python hl_lines="155"
+{!> ../../docs_src/security/tutorial005_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="156"
+{!> ../../docs_src/security/tutorial005_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="156"
+{!> ../../docs_src/security/tutorial005.py!}
+```
+
+////
## Declare scopes in *path operations* and dependencies
@@ -237,62 +308,89 @@ And the dependency function `get_current_active_user` can also declare sub-depen
In this case, it requires the scope `me` (it could require more than one scope).
-!!! note
- You don't necessarily need to add different scopes in different places.
+/// note
- We are doing it here to demonstrate how **FastAPI** handles scopes declared at different levels.
+You don't necessarily need to add different scopes in different places.
-=== "Python 3.10+"
+We are doing it here to demonstrate how **FastAPI** handles scopes declared at different levels.
- ```Python hl_lines="5 140 171"
- {!> ../../../docs_src/security/tutorial005_an_py310.py!}
- ```
+///
-=== "Python 3.9+"
+//// tab | Python 3.10+
- ```Python hl_lines="5 140 171"
- {!> ../../../docs_src/security/tutorial005_an_py39.py!}
- ```
+```Python hl_lines="5 140 171"
+{!> ../../docs_src/security/tutorial005_an_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="5 141 172"
- {!> ../../../docs_src/security/tutorial005_an.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.10+ non-Annotated"
+```Python hl_lines="5 140 171"
+{!> ../../docs_src/security/tutorial005_an_py39.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="4 139 168"
- {!> ../../../docs_src/security/tutorial005_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.9+ non-Annotated"
+```Python hl_lines="5 141 172"
+{!> ../../docs_src/security/tutorial005_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="5 140 169"
- {!> ../../../docs_src/security/tutorial005_py39.py!}
- ```
+//// tab | Python 3.10+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip
- !!! tip
- Prefer to use the `Annotated` version if possible.
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="5 140 169"
- {!> ../../../docs_src/security/tutorial005.py!}
- ```
+///
-!!! info "Technical Details"
- `Security` is actually a subclass of `Depends`, and it has just one extra parameter that we'll see later.
+```Python hl_lines="4 139 168"
+{!> ../../docs_src/security/tutorial005_py310.py!}
+```
- But by using `Security` instead of `Depends`, **FastAPI** will know that it can declare security scopes, use them internally, and document the API with OpenAPI.
+////
- But when you import `Query`, `Path`, `Depends`, `Security` and others from `fastapi`, those are actually functions that return special classes.
+//// tab | Python 3.9+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="5 140 169"
+{!> ../../docs_src/security/tutorial005_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="5 140 169"
+{!> ../../docs_src/security/tutorial005.py!}
+```
+
+////
+
+/// info | "Technical Details"
+
+`Security` is actually a subclass of `Depends`, and it has just one extra parameter that we'll see later.
+
+But by using `Security` instead of `Depends`, **FastAPI** will know that it can declare security scopes, use them internally, and document the API with OpenAPI.
+
+But when you import `Query`, `Path`, `Depends`, `Security` and others from `fastapi`, those are actually functions that return special classes.
+
+///
## Use `SecurityScopes`
@@ -300,7 +398,7 @@ Now update the dependency `get_current_user`.
This is the one used by the dependencies above.
-Here's were we are using the same OAuth2 scheme we created before, declaring it as a dependency: `oauth2_scheme`.
+Here's where we are using the same OAuth2 scheme we created before, declaring it as a dependency: `oauth2_scheme`.
Because this dependency function doesn't have any scope requirements itself, we can use `Depends` with `oauth2_scheme`, we don't have to use `Security` when we don't need to specify security scopes.
@@ -308,50 +406,71 @@ We also declare a special parameter of type `SecurityScopes`, imported from `fas
This `SecurityScopes` class is similar to `Request` (`Request` was used to get the request object directly).
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9 106"
- {!> ../../../docs_src/security/tutorial005_an_py310.py!}
- ```
+```Python hl_lines="9 106"
+{!> ../../docs_src/security/tutorial005_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="9 106"
- {!> ../../../docs_src/security/tutorial005_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="9 106"
+{!> ../../docs_src/security/tutorial005_an_py39.py!}
+```
- ```Python hl_lines="9 107"
- {!> ../../../docs_src/security/tutorial005_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="9 107"
+{!> ../../docs_src/security/tutorial005_an.py!}
+```
- ```Python hl_lines="8 105"
- {!> ../../../docs_src/security/tutorial005_py310.py!}
- ```
+////
-=== "Python 3.9+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="9 106"
- {!> ../../../docs_src/security/tutorial005_py39.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="8 105"
+{!> ../../docs_src/security/tutorial005_py310.py!}
+```
- ```Python hl_lines="9 106"
- {!> ../../../docs_src/security/tutorial005.py!}
- ```
+////
+
+//// tab | Python 3.9+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="9 106"
+{!> ../../docs_src/security/tutorial005_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="9 106"
+{!> ../../docs_src/security/tutorial005.py!}
+```
+
+////
## Use the `scopes`
@@ -365,50 +484,71 @@ We create an `HTTPException` that we can reuse (`raise`) later at several points
In this exception, we include the scopes required (if any) as a string separated by spaces (using `scope_str`). We put that string containing the scopes in the `WWW-Authenticate` header (this is part of the spec).
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="106 108-116"
- {!> ../../../docs_src/security/tutorial005_an_py310.py!}
- ```
+```Python hl_lines="106 108-116"
+{!> ../../docs_src/security/tutorial005_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="106 108-116"
- {!> ../../../docs_src/security/tutorial005_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="106 108-116"
+{!> ../../docs_src/security/tutorial005_an_py39.py!}
+```
- ```Python hl_lines="107 109-117"
- {!> ../../../docs_src/security/tutorial005_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="107 109-117"
+{!> ../../docs_src/security/tutorial005_an.py!}
+```
- ```Python hl_lines="105 107-115"
- {!> ../../../docs_src/security/tutorial005_py310.py!}
- ```
+////
-=== "Python 3.9+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="106 108-116"
- {!> ../../../docs_src/security/tutorial005_py39.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="105 107-115"
+{!> ../../docs_src/security/tutorial005_py310.py!}
+```
- ```Python hl_lines="106 108-116"
- {!> ../../../docs_src/security/tutorial005.py!}
- ```
+////
+
+//// tab | Python 3.9+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="106 108-116"
+{!> ../../docs_src/security/tutorial005_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="106 108-116"
+{!> ../../docs_src/security/tutorial005.py!}
+```
+
+////
## Verify the `username` and data shape
@@ -424,50 +564,71 @@ Instead of, for example, a `dict`, or something else, as it could break the appl
We also verify that we have a user with that username, and if not, we raise that same exception we created before.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="47 117-128"
- {!> ../../../docs_src/security/tutorial005_an_py310.py!}
- ```
+```Python hl_lines="47 117-128"
+{!> ../../docs_src/security/tutorial005_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="47 117-128"
- {!> ../../../docs_src/security/tutorial005_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="47 117-128"
+{!> ../../docs_src/security/tutorial005_an_py39.py!}
+```
- ```Python hl_lines="48 118-129"
- {!> ../../../docs_src/security/tutorial005_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="48 118-129"
+{!> ../../docs_src/security/tutorial005_an.py!}
+```
- ```Python hl_lines="46 116-127"
- {!> ../../../docs_src/security/tutorial005_py310.py!}
- ```
+////
-=== "Python 3.9+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="47 117-128"
- {!> ../../../docs_src/security/tutorial005_py39.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="46 116-127"
+{!> ../../docs_src/security/tutorial005_py310.py!}
+```
- ```Python hl_lines="47 117-128"
- {!> ../../../docs_src/security/tutorial005.py!}
- ```
+////
+
+//// tab | Python 3.9+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="47 117-128"
+{!> ../../docs_src/security/tutorial005_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="47 117-128"
+{!> ../../docs_src/security/tutorial005.py!}
+```
+
+////
## Verify the `scopes`
@@ -475,50 +636,71 @@ We now verify that all the scopes required, by this dependency and all the depen
For this, we use `security_scopes.scopes`, that contains a `list` with all these scopes as `str`.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="129-135"
- {!> ../../../docs_src/security/tutorial005_an_py310.py!}
- ```
+```Python hl_lines="129-135"
+{!> ../../docs_src/security/tutorial005_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="129-135"
- {!> ../../../docs_src/security/tutorial005_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="129-135"
+{!> ../../docs_src/security/tutorial005_an_py39.py!}
+```
- ```Python hl_lines="130-136"
- {!> ../../../docs_src/security/tutorial005_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="130-136"
+{!> ../../docs_src/security/tutorial005_an.py!}
+```
- ```Python hl_lines="128-134"
- {!> ../../../docs_src/security/tutorial005_py310.py!}
- ```
+////
-=== "Python 3.9+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="129-135"
- {!> ../../../docs_src/security/tutorial005_py39.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="128-134"
+{!> ../../docs_src/security/tutorial005_py310.py!}
+```
- ```Python hl_lines="129-135"
- {!> ../../../docs_src/security/tutorial005.py!}
- ```
+////
+
+//// tab | Python 3.9+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="129-135"
+{!> ../../docs_src/security/tutorial005_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="129-135"
+{!> ../../docs_src/security/tutorial005.py!}
+```
+
+////
## Dependency tree and scopes
@@ -543,12 +725,15 @@ Here's how the hierarchy of dependencies and scopes looks like:
* This `security_scopes` parameter has a property `scopes` with a `list` containing all these scopes declared above, so:
* `security_scopes.scopes` will contain `["me", "items"]` for the *path operation* `read_own_items`.
* `security_scopes.scopes` will contain `["me"]` for the *path operation* `read_users_me`, because it is declared in the dependency `get_current_active_user`.
- * `security_scopes.scopes` will contain `[]` (nothing) for the *path operation* `read_system_status`, because it didn't declare any `Security` with `scopes`, and its dependency, `get_current_user`, doesn't declare any `scope` either.
+ * `security_scopes.scopes` will contain `[]` (nothing) for the *path operation* `read_system_status`, because it didn't declare any `Security` with `scopes`, and its dependency, `get_current_user`, doesn't declare any `scopes` either.
-!!! tip
- The important and "magic" thing here is that `get_current_user` will have a different list of `scopes` to check for each *path operation*.
+/// tip
- All depending on the `scopes` declared in each *path operation* and each dependency in the dependency tree for that specific *path operation*.
+The important and "magic" thing here is that `get_current_user` will have a different list of `scopes` to check for each *path operation*.
+
+All depending on the `scopes` declared in each *path operation* and each dependency in the dependency tree for that specific *path operation*.
+
+///
## More details about `SecurityScopes`
@@ -584,12 +769,15 @@ But if you are building an OAuth2 application that others would connect to (i.e.
The most common is the implicit flow.
-The most secure is the code flow, but is more complex to implement as it requires more steps. As it is more complex, many providers end up suggesting the implicit flow.
+The most secure is the code flow, but it's more complex to implement as it requires more steps. As it is more complex, many providers end up suggesting the implicit flow.
-!!! note
- It's common that each authentication provider names their flows in a different way, to make it part of their brand.
+/// note
- But in the end, they are implementing the same OAuth2 standard.
+It's common that each authentication provider names their flows in a different way, to make it part of their brand.
+
+But in the end, they are implementing the same OAuth2 standard.
+
+///
**FastAPI** includes utilities for all these OAuth2 authentication flows in `fastapi.security.oauth2`.
diff --git a/docs/en/docs/advanced/settings.md b/docs/en/docs/advanced/settings.md
index 56af4f441..01810c438 100644
--- a/docs/en/docs/advanced/settings.md
+++ b/docs/en/docs/advanced/settings.md
@@ -6,130 +6,25 @@ Most of these settings are variable (can change), like database URLs. And many c
For this reason it's common to provide them in environment variables that are read by the application.
-## Environment Variables
+/// tip
-!!! tip
- If you already know what "environment variables" are and how to use them, feel free to skip to the next section below.
+To understand environment variables you can read [Environment Variables](../environment-variables.md){.internal-link target=_blank}.
-An environment variable (also known as "env var") is a variable that lives outside of the Python code, in the operating system, and could be read by your Python code (or by other programs as well).
+///
-You can create and use environment variables in the shell, without needing Python:
-
-=== "Linux, macOS, Windows Bash"
-
-
-!!! info
- Beautiful illustrations by Ketrina Thompson. 🎨
+/// info
+
+Beautiful illustrations by Ketrina Thompson. 🎨
+
+///
---
@@ -199,8 +205,11 @@ You just eat them, and you are done. ⏹
There was not much talk or flirting as most of the time was spent waiting 🕙 in front of the counter. 😞
-!!! info
- Beautiful illustrations by Ketrina Thompson. 🎨
+/// info
+
+Beautiful illustrations by Ketrina Thompson. 🎨
+
+///
---
@@ -283,7 +292,7 @@ For example:
### Concurrency + Parallelism: Web + Machine Learning
-With **FastAPI** you can take the advantage of concurrency that is very common for web development (the same main attraction of NodeJS).
+With **FastAPI** you can take advantage of concurrency that is very common for web development (the same main attraction of NodeJS).
But you can also exploit the benefits of parallelism and multiprocessing (having multiple processes running in parallel) for **CPU bound** workloads like those in Machine Learning systems.
@@ -360,6 +369,8 @@ In particular, you can directly use AnyIO to be highly compatible and get its benefits (e.g. *structured concurrency*).
+I created another library on top of AnyIO, as a thin layer on top, to improve a bit the type annotations and get better **autocompletion**, **inline errors**, etc. It also has a friendly introduction and tutorial to help you **understand** and write **your own async code**: Asyncer. It would be particularly useful if you need to **combine async code with regular** (blocking/synchronous) code.
+
### Other forms of asynchronous code
This style of using `async` and `await` is relatively new in the language.
@@ -376,7 +387,7 @@ In previous versions of NodeJS / Browser JavaScript, you would have used "callba
## Coroutines
-**Coroutine** is just the very fancy term for the thing returned by an `async def` function. Python knows that it is something like a function that it can start and that it will end at some point, but that it might be paused ⏸ internally too, whenever there is an `await` inside of it.
+**Coroutine** is just the very fancy term for the thing returned by an `async def` function. Python knows that it is something like a function, that it can start and that it will end at some point, but that it might be paused ⏸ internally too, whenever there is an `await` inside of it.
But all this functionality of using asynchronous code with `async` and `await` is many times summarized as using "coroutines". It is comparable to the main key feature of Go, the "Goroutines".
@@ -392,12 +403,15 @@ All that is what powers FastAPI (through Starlette) and what makes it have such
## Very Technical Details
-!!! warning
- You can probably skip this.
+/// warning
- These are very technical details of how **FastAPI** works underneath.
+You can probably skip this.
- If you have quite some technical knowledge (coroutines, threads, blocking, etc.) and are curious about how FastAPI handles `async def` vs normal `def`, go ahead.
+These are very technical details of how **FastAPI** works underneath.
+
+If you have quite some technical knowledge (coroutines, threads, blocking, etc.) and are curious about how FastAPI handles `async def` vs normal `def`, go ahead.
+
+///
### Path operation functions
diff --git a/docs/en/docs/contributing.md b/docs/en/docs/contributing.md
index d7ec25dea..0dc07b89b 100644
--- a/docs/en/docs/contributing.md
+++ b/docs/en/docs/contributing.md
@@ -6,104 +6,13 @@ First, you might want to see the basic ways to [help FastAPI and get help](help-
If you already cloned the fastapi repository and you want to deep dive in the code, here are some guidelines to set up your environment.
-### Virtual environment with `venv`
+### Virtual environment
-You can create an isolated virtual local environment in a directory using Python's `venv` module. Let's do this in the cloned repository (where the `requirements.txt` is):
-
-fastapi run --workers 4 main.py +INFO Using path main.py +INFO Resolved absolute path /home/user/code/awesomeapp/main.py +INFO Searching for package file structure from directories with __init__.py files +INFO Importing from /home/user/code/awesomeapp ----> 100% + ╭─ Python module file ─╮ + │ │ + │ 🐍 main.py │ + │ │ + ╰──────────────────────╯ + +INFO Importing module main +INFO Found importable FastAPI app + + ╭─ Importable FastAPI app ─╮ + │ │ + │ from main import app │ + │ │ + ╰──────────────────────────╯ + +INFO Using import string main:app + + ╭─────────── FastAPI CLI - Production mode ───────────╮ + │ │ + │ Serving at: http://0.0.0.0:8000 │ + │ │ + │ API docs: http://0.0.0.0:8000/docs │ + │ │ + │ Running in production mode, for development use: │ + │ │ + │ fastapi dev │ + │ │ + ╰─────────────────────────────────────────────────────╯ + +INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit) +INFO: Started parent process [27365] +INFO: Started server process [27368] +INFO: Waiting for application startup. +INFO: Application startup complete. +INFO: Started server process [27369] +INFO: Waiting for application startup. +INFO: Application startup complete. +INFO: Started server process [27370] +INFO: Waiting for application startup. +INFO: Application startup complete. +INFO: Started server process [27367] +INFO: Waiting for application startup. +INFO: Application startup complete. +```
-
-## More info
-
-You can read more about `encode/databases` at its GitHub page.
diff --git a/docs/en/docs/how-to/conditional-openapi.md b/docs/en/docs/how-to/conditional-openapi.md
index add16fbec..6cd0385a2 100644
--- a/docs/en/docs/how-to/conditional-openapi.md
+++ b/docs/en/docs/how-to/conditional-openapi.md
@@ -30,7 +30,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!}
```
Here we declare the setting `openapi_url` with the same default of `"/openapi.json"`.
diff --git a/docs/en/docs/how-to/configure-swagger-ui.md b/docs/en/docs/how-to/configure-swagger-ui.md
index 108afb929..2c649c152 100644
--- a/docs/en/docs/how-to/configure-swagger-ui.md
+++ b/docs/en/docs/how-to/configure-swagger-ui.md
@@ -1,6 +1,6 @@
# Configure Swagger UI
-You can configure some extra Swagger UI parameters.
+You can configure some extra Swagger UI parameters.
To configure them, pass the `swagger_ui_parameters` argument when creating the `FastAPI()` app object or to the `get_swagger_ui_html()` function.
@@ -19,7 +19,7 @@ Without changing the settings, syntax highlighting is enabled by default:
But you can disable it by setting `syntaxHighlight` to `False`:
```Python hl_lines="3"
-{!../../../docs_src/configure_swagger_ui/tutorial001.py!}
+{!../../docs_src/configure_swagger_ui/tutorial001.py!}
```
...and then Swagger UI won't show the syntax highlighting anymore:
@@ -31,7 +31,7 @@ But you can disable it by setting `syntaxHighlight` to `False`:
The same way you could set the syntax highlighting theme with the key `"syntaxHighlight.theme"` (notice that it has a dot in the middle):
```Python hl_lines="3"
-{!../../../docs_src/configure_swagger_ui/tutorial002.py!}
+{!../../docs_src/configure_swagger_ui/tutorial002.py!}
```
That configuration would change the syntax highlighting color theme:
@@ -45,7 +45,7 @@ FastAPI includes some default configuration parameters appropriate for most of t
It includes these default configurations:
```Python
-{!../../../fastapi/openapi/docs.py[ln:7-23]!}
+{!../../fastapi/openapi/docs.py[ln:7-23]!}
```
You can override any of them by setting a different value in the argument `swagger_ui_parameters`.
@@ -53,12 +53,12 @@ You can override any of them by setting a different value in the argument `swagg
For example, to disable `deepLinking` you could pass these settings to `swagger_ui_parameters`:
```Python hl_lines="3"
-{!../../../docs_src/configure_swagger_ui/tutorial003.py!}
+{!../../docs_src/configure_swagger_ui/tutorial003.py!}
```
## Other Swagger UI Parameters
-To see all the other possible configurations you can use, read the official docs for Swagger UI parameters.
+To see all the other possible configurations you can use, read the official docs for Swagger UI parameters.
## JavaScript-only settings
diff --git a/docs/en/docs/how-to/custom-docs-ui-assets.md b/docs/en/docs/how-to/custom-docs-ui-assets.md
index 053e5eacd..16c873d11 100644
--- a/docs/en/docs/how-to/custom-docs-ui-assets.md
+++ b/docs/en/docs/how-to/custom-docs-ui-assets.md
@@ -19,7 +19,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!}
```
### Include the custom docs
@@ -37,22 +37,25 @@ 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!}
```
-!!! tip
- The *path operation* for `swagger_ui_redirect` is a helper for when you use OAuth2.
+/// tip
- If you integrate your API with an OAuth2 provider, you will be able to authenticate and come back to the API docs with the acquired credentials. And interact with it using the real OAuth2 authentication.
+The *path operation* for `swagger_ui_redirect` is a helper for when you use OAuth2.
- Swagger UI will handle it behind the scenes for you, but it needs this "redirect" helper.
+If you integrate your API with an OAuth2 provider, you will be able to authenticate and come back to the API docs with the acquired credentials. And interact with it using the real OAuth2 authentication.
+
+Swagger UI will handle it behind the scenes for you, but it needs this "redirect" helper.
+
+///
### Create a *path operation* to test it
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!}
```
### Test it
@@ -122,7 +125,7 @@ After that, your file structure could look like:
* "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!}
```
### Test the static files
@@ -156,7 +159,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!}
```
### Include the custom docs for static files
@@ -174,22 +177,25 @@ 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!}
```
-!!! tip
- The *path operation* for `swagger_ui_redirect` is a helper for when you use OAuth2.
+/// tip
- If you integrate your API with an OAuth2 provider, you will be able to authenticate and come back to the API docs with the acquired credentials. And interact with it using the real OAuth2 authentication.
+The *path operation* for `swagger_ui_redirect` is a helper for when you use OAuth2.
- Swagger UI will handle it behind the scenes for you, but it needs this "redirect" helper.
+If you integrate your API with an OAuth2 provider, you will be able to authenticate and come back to the API docs with the acquired credentials. And interact with it using the real OAuth2 authentication.
+
+Swagger UI will handle it behind the scenes for you, but it needs this "redirect" helper.
+
+///
### Create a *path operation* to test static files
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!}
```
### 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 3b9435004..a62ebf1d5 100644
--- a/docs/en/docs/how-to/custom-request-and-route.md
+++ b/docs/en/docs/how-to/custom-request-and-route.md
@@ -6,10 +6,13 @@ In particular, this may be a good alternative to logic in a middleware.
For example, if you want to read or manipulate the request body before it is processed by your application.
-!!! danger
- This is an "advanced" feature.
+/// danger
- If you are just starting with **FastAPI** you might want to skip this section.
+This is an "advanced" feature.
+
+If you are just starting with **FastAPI** you might want to skip this section.
+
+///
## Use cases
@@ -27,8 +30,11 @@ And an `APIRoute` subclass to use that custom request class.
### Create a custom `GzipRequest` class
-!!! tip
- This is a toy example to demonstrate how it works, if you need Gzip support, you can use the provided [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware){.internal-link target=_blank}.
+/// tip
+
+This is a toy example to demonstrate how it works, if you need Gzip support, you can use the provided [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware){.internal-link target=_blank}.
+
+///
First, we create a `GzipRequest` class, which will overwrite the `Request.body()` method to decompress the body in the presence of an appropriate header.
@@ -37,7 +43,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!}
```
### Create a custom `GzipRoute` class
@@ -51,19 +57,22 @@ 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!}
```
-!!! note "Technical Details"
- A `Request` has a `request.scope` attribute, that's just a Python `dict` containing the metadata related to the request.
+/// note | "Technical Details"
- A `Request` also has a `request.receive`, that's a function to "receive" the body of the request.
+A `Request` has a `request.scope` attribute, that's just a Python `dict` containing the metadata related to the request.
- The `scope` `dict` and `receive` function are both part of the ASGI specification.
+A `Request` also has a `request.receive`, that's a function to "receive" the body of the request.
- And those two things, `scope` and `receive`, are what is needed to create a new `Request` instance.
+The `scope` `dict` and `receive` function are both part of the ASGI specification.
- To learn more about the `Request` check Starlette's docs about Requests.
+And those two things, `scope` and `receive`, are what is needed to create a new `Request` instance.
+
+To learn more about the `Request` check Starlette's docs about Requests.
+
+///
The only thing the function returned by `GzipRequest.get_route_handler` does differently is convert the `Request` to a `GzipRequest`.
@@ -75,23 +84,26 @@ But because of our changes in `GzipRequest.body`, the request body will be autom
## Accessing the request body in an exception handler
-!!! tip
- To solve this same problem, it's probably a lot easier to use the `body` in a custom handler for `RequestValidationError` ([Handling Errors](../tutorial/handling-errors.md#use-the-requestvalidationerror-body){.internal-link target=_blank}).
+/// tip
- But this example is still valid and it shows how to interact with the internal components.
+To solve this same problem, it's probably a lot easier to use the `body` in a custom handler for `RequestValidationError` ([Handling Errors](../tutorial/handling-errors.md#use-the-requestvalidationerror-body){.internal-link target=_blank}).
+
+But this example is still valid and it shows how to interact with the internal components.
+
+///
We can also use this same approach to access the request body in an exception handler.
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!}
```
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!}
```
## Custom `APIRoute` class in a router
@@ -99,11 +111,11 @@ If an exception occurs, the`Request` instance will still be in scope, so we can
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!}
```
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!}
```
diff --git a/docs/en/docs/how-to/extending-openapi.md b/docs/en/docs/how-to/extending-openapi.md
index a18fd737e..2b0367952 100644
--- a/docs/en/docs/how-to/extending-openapi.md
+++ b/docs/en/docs/how-to/extending-openapi.md
@@ -27,8 +27,11 @@ And that function `get_openapi()` receives as parameters:
* `description`: The description of your API, this can include markdown and will be shown in the docs.
* `routes`: A list of routes, these are each of the registered *path operations*. They are taken from `app.routes`.
-!!! info
- The parameter `summary` is available in OpenAPI 3.1.0 and above, supported by FastAPI 0.99.0 and above.
+/// info
+
+The parameter `summary` is available in OpenAPI 3.1.0 and above, supported by FastAPI 0.99.0 and above.
+
+///
## Overriding the defaults
@@ -41,7 +44,7 @@ For example, let's add Strawberry documentation.
@@ -46,8 +49,11 @@ Previous versions of Starlette included a `GraphQLApp` class to integrate with <
It was deprecated from Starlette, but if you have code that used it, you can easily **migrate** to starlette-graphene3, that covers the same use case and has an **almost identical interface**.
-!!! tip
- If you need GraphQL, I still would recommend you check out Strawberry, as it's based on type annotations instead of custom classes and types.
+/// tip
+
+If you need GraphQL, I still would recommend you check out Strawberry, as it's based on type annotations instead of custom classes and types.
+
+///
## Learn More
diff --git a/docs/en/docs/how-to/index.md b/docs/en/docs/how-to/index.md
index ec7fd38f8..730dce5d5 100644
--- a/docs/en/docs/how-to/index.md
+++ b/docs/en/docs/how-to/index.md
@@ -6,6 +6,8 @@ Most of these ideas would be more or less **independent**, and in most cases you
If something seems interesting and useful to your project, go ahead and check it, but otherwise, you might probably just skip them.
-!!! tip
+/// tip
- If you want to **learn FastAPI** in a structured way (recommended), go and read the [Tutorial - User Guide](../tutorial/index.md){.internal-link target=_blank} chapter by chapter instead.
+If you want to **learn FastAPI** in a structured way (recommended), go and read the [Tutorial - User Guide](../tutorial/index.md){.internal-link target=_blank} chapter by chapter instead.
+
+///
diff --git a/docs/en/docs/how-to/nosql-databases-couchbase.md b/docs/en/docs/how-to/nosql-databases-couchbase.md
deleted file mode 100644
index 18e3f4b7e..000000000
--- a/docs/en/docs/how-to/nosql-databases-couchbase.md
+++ /dev/null
@@ -1,166 +0,0 @@
-# ~~NoSQL (Distributed / Big Data) Databases with Couchbase~~ (deprecated)
-
-!!! info
- These docs are about to be updated. 🎉
-
- The current version assumes Pydantic v1.
-
- The new docs will hopefully use Pydantic v2 and will use ODMantic with MongoDB.
-
-!!! warning "Deprecated"
- This tutorial is deprecated and will be removed in a future version.
-
-**FastAPI** can also be integrated with any NoSQL.
-
-Here we'll see an example using **Couchbase**, a document based NoSQL database.
-
-You can adapt it to any other NoSQL database like:
-
-* **MongoDB**
-* **Cassandra**
-* **CouchDB**
-* **ArangoDB**
-* **ElasticSearch**, etc.
-
-!!! tip
- There is an official project generator with **FastAPI** and **Couchbase**, all based on **Docker**, including a frontend and more tools: https://github.com/tiangolo/full-stack-fastapi-couchbase
-
-## Import Couchbase components
-
-For now, don't pay attention to the rest, only the imports:
-
-```Python hl_lines="3-5"
-{!../../../docs_src/nosql_databases/tutorial001.py!}
-```
-
-## Define a constant to use as a "document type"
-
-We will use it later as a fixed field `type` in our documents.
-
-This is not required by Couchbase, but is a good practice that will help you afterwards.
-
-```Python hl_lines="9"
-{!../../../docs_src/nosql_databases/tutorial001.py!}
-```
-
-## Add a function to get a `Bucket`
-
-In **Couchbase**, a bucket is a set of documents, that can be of different types.
-
-They are generally all related to the same application.
-
-The analogy in the relational database world would be a "database" (a specific database, not the database server).
-
-The analogy in **MongoDB** would be a "collection".
-
-In the code, a `Bucket` represents the main entrypoint of communication with the database.
-
-This utility function will:
-
-* Connect to a **Couchbase** cluster (that might be a single machine).
- * Set defaults for timeouts.
-* Authenticate in the cluster.
-* Get a `Bucket` instance.
- * Set defaults for timeouts.
-* Return it.
-
-```Python hl_lines="12-21"
-{!../../../docs_src/nosql_databases/tutorial001.py!}
-```
-
-## Create Pydantic models
-
-As **Couchbase** "documents" are actually just "JSON objects", we can model them with Pydantic.
-
-### `User` model
-
-First, let's create a `User` model:
-
-```Python hl_lines="24-28"
-{!../../../docs_src/nosql_databases/tutorial001.py!}
-```
-
-We will use this model in our *path operation function*, so, we don't include in it the `hashed_password`.
-
-### `UserInDB` model
-
-Now, let's create a `UserInDB` model.
-
-This will have the data that is actually stored in the database.
-
-We don't create it as a subclass of Pydantic's `BaseModel` but as a subclass of our own `User`, because it will have all the attributes in `User` plus a couple more:
-
-```Python hl_lines="31-33"
-{!../../../docs_src/nosql_databases/tutorial001.py!}
-```
-
-!!! note
- Notice that we have a `hashed_password` and a `type` field that will be stored in the database.
-
- But it is not part of the general `User` model (the one we will return in the *path operation*).
-
-## Get the user
-
-Now create a function that will:
-
-* Take a username.
-* Generate a document ID from it.
-* Get the document with that ID.
-* Put the contents of the document in a `UserInDB` model.
-
-By creating a function that is only dedicated to getting your user from a `username` (or any other parameter) independent of your *path operation function*, you can more easily reuse it in multiple parts and also add unit tests for it:
-
-```Python hl_lines="36-42"
-{!../../../docs_src/nosql_databases/tutorial001.py!}
-```
-
-### f-strings
-
-If you are not familiar with the `f"userprofile::{username}"`, it is a Python "f-string".
-
-Any variable that is put inside of `{}` in an f-string will be expanded / injected in the string.
-
-### `dict` unpacking
-
-If you are not familiar with the `UserInDB(**result.value)`, it is using `dict` "unpacking".
-
-It will take the `dict` at `result.value`, and take each of its keys and values and pass them as key-values to `UserInDB` as keyword arguments.
-
-So, if the `dict` contains:
-
-```Python
-{
- "username": "johndoe",
- "hashed_password": "some_hash",
-}
-```
-
-It will be passed to `UserInDB` as:
-
-```Python
-UserInDB(username="johndoe", hashed_password="some_hash")
-```
-
-## Create your **FastAPI** code
-
-### Create the `FastAPI` app
-
-```Python hl_lines="46"
-{!../../../docs_src/nosql_databases/tutorial001.py!}
-```
-
-### Create the *path operation function*
-
-As our code is calling Couchbase and we are not using the experimental Python await support, we should declare our function with normal `def` instead of `async def`.
-
-Also, Couchbase recommends not using a single `Bucket` object in multiple "threads", so, we can just get the bucket directly and pass it to our utility functions:
-
-```Python hl_lines="49-53"
-{!../../../docs_src/nosql_databases/tutorial001.py!}
-```
-
-## Recap
-
-You can integrate any third party NoSQL database, just using their standard packages.
-
-The same applies to any other external tool, system or API.
diff --git a/docs/en/docs/how-to/separate-openapi-schemas.md b/docs/en/docs/how-to/separate-openapi-schemas.md
index 10be1071a..75fd3f9b6 100644
--- a/docs/en/docs/how-to/separate-openapi-schemas.md
+++ b/docs/en/docs/how-to/separate-openapi-schemas.md
@@ -10,111 +10,123 @@ Let's see how that works and how to change it if you need to do that.
Let's say you have a Pydantic model with default values, like this one:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7"
- {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-7]!}
+```Python hl_lines="7"
+{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-7]!}
- # Code below omitted 👇
- ```
+# Code below omitted 👇
+```
- email_validator - for email validation.
+* email-validator - for email validation.
Used by Starlette:
diff --git a/docs/en/docs/js/custom.js b/docs/en/docs/js/custom.js
index b7e5236f3..ff17710e2 100644
--- a/docs/en/docs/js/custom.js
+++ b/docs/en/docs/js/custom.js
@@ -147,7 +147,7 @@ async function showRandomAnnouncement(groupId, timeInterval) {
children = shuffle(children)
let index = 0
const announceRandom = () => {
- children.forEach((el, i) => {el.style.display = "none"});
+ children.forEach((el, i) => { el.style.display = "none" });
children[index].style.display = "block"
index = (index + 1) % children.length
}
@@ -176,5 +176,6 @@ async function main() {
showRandomAnnouncement('announce-left', 5000)
showRandomAnnouncement('announce-right', 10000)
}
-
-main()
+document$.subscribe(() => {
+ main()
+})
diff --git a/docs/en/docs/management-tasks.md b/docs/en/docs/management-tasks.md
index efda1a703..7e7aa3baf 100644
--- a/docs/en/docs/management-tasks.md
+++ b/docs/en/docs/management-tasks.md
@@ -2,8 +2,11 @@
These are the tasks that can be performed to manage the FastAPI repository by [team members](./fastapi-people.md#team){.internal-link target=_blank}.
-!!! tip
- This section is useful only to a handful of people, team members with permissions to manage the repository. You can probably skip it. 😉
+/// tip
+
+This section is useful only to a handful of people, team members with permissions to manage the repository. You can probably skip it. 😉
+
+///
...so, you are a [team member of FastAPI](./fastapi-people.md#team){.internal-link target=_blank}? Wow, you are so cool! 😎
@@ -80,8 +83,11 @@ Make sure you use a supported label from the `Questions` that are `Unanswered`.
diff --git a/docs/en/docs/newsletter.md b/docs/en/docs/newsletter.md
index 782db1353..29b777a67 100644
--- a/docs/en/docs/newsletter.md
+++ b/docs/en/docs/newsletter.md
@@ -1,5 +1,5 @@
# FastAPI and friends newsletter
-
+
diff --git a/docs/en/docs/project-generation.md b/docs/en/docs/project-generation.md
index d142862ee..665bc54f9 100644
--- a/docs/en/docs/project-generation.md
+++ b/docs/en/docs/project-generation.md
@@ -13,9 +13,10 @@ GitHub Repository: Concatenates them with a space in the middle.
```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial001.py!}
+{!../../docs_src/python_types/tutorial001.py!}
```
### Edit it
@@ -80,7 +83,7 @@ That's it.
Those are the "type hints":
```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial002.py!}
+{!../../docs_src/python_types/tutorial002.py!}
```
That is not the same as declaring default values like would be with:
@@ -110,7 +113,7 @@ With that, you can scroll, seeing the options, until you find the one that "ring
Check this function, it already has type hints:
```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial003.py!}
+{!../../docs_src/python_types/tutorial003.py!}
```
Because the editor knows the types of the variables, you don't only get completion, you also get error checks:
@@ -120,7 +123,7 @@ Because the editor knows the types of the variables, you don't only get completi
Now you know that you have to fix it, convert `age` to a string with `str(age)`:
```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial004.py!}
+{!../../docs_src/python_types/tutorial004.py!}
```
## Declaring types
@@ -141,7 +144,7 @@ You can use, for example:
* `bytes`
```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial005.py!}
+{!../../docs_src/python_types/tutorial005.py!}
```
### Generic types with type parameters
@@ -170,45 +173,55 @@ If you can use the **latest versions of Python**, use the examples for the lates
For example, let's define a variable to be a `list` of `str`.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- Declare the variable, with the same colon (`:`) syntax.
+Declare the variable, with the same colon (`:`) syntax.
- As the type, put `list`.
+As the type, put `list`.
- As the list is a type that contains some internal types, you put them in square brackets:
+As the list is a type that contains some internal types, you put them in square brackets:
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial006_py39.py!}
- ```
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial006_py39.py!}
+```
-=== "Python 3.8+"
+////
- From `typing`, import `List` (with a capital `L`):
+//// tab | Python 3.8+
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial006.py!}
- ```
+From `typing`, import `List` (with a capital `L`):
- Declare the variable, with the same colon (`:`) syntax.
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial006.py!}
+```
- As the type, put the `List` that you imported from `typing`.
+Declare the variable, with the same colon (`:`) syntax.
- As the list is a type that contains some internal types, you put them in square brackets:
+As the type, put the `List` that you imported from `typing`.
- ```Python hl_lines="4"
- {!> ../../../docs_src/python_types/tutorial006.py!}
- ```
+As the list is a type that contains some internal types, you put them in square brackets:
-!!! info
- Those internal types in the square brackets are called "type parameters".
+```Python hl_lines="4"
+{!> ../../docs_src/python_types/tutorial006.py!}
+```
- In this case, `str` is the type parameter passed to `List` (or `list` in Python 3.9 and above).
+////
+
+/// info
+
+Those internal types in the square brackets are called "type parameters".
+
+In this case, `str` is the type parameter passed to `List` (or `list` in Python 3.9 and above).
+
+///
That means: "the variable `items` is a `list`, and each of the items in this list is a `str`".
-!!! tip
- If you use Python 3.9 or above, you don't have to import `List` from `typing`, you can use the same regular `list` type instead.
+/// tip
+
+If you use Python 3.9 or above, you don't have to import `List` from `typing`, you can use the same regular `list` type instead.
+
+///
By doing that, your editor can provide support even while processing items from the list:
@@ -224,17 +237,21 @@ And still, the editor knows it is a `str`, and provides support for that.
You would do the same to declare `tuple`s and `set`s:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial007_py39.py!}
- ```
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial007_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial007.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial007.py!}
+```
+
+////
This means:
@@ -249,17 +266,21 @@ The first type parameter is for the keys of the `dict`.
The second type parameter is for the values of the `dict`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial008_py39.py!}
- ```
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial008_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial008.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial008.py!}
+```
+
+////
This means:
@@ -275,17 +296,21 @@ In Python 3.6 and above (including Python 3.10) you can use the `Union` type fro
In Python 3.10 there's also a **new syntax** where you can put the possible types separated by a vertical bar (`|`).
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial008b_py310.py!}
- ```
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial008b_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial008b.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial008b.py!}
+```
+
+////
In both cases this means that `item` could be an `int` or a `str`.
@@ -296,32 +321,38 @@ You can declare that a value could have a type, like `str`, but that it could al
In Python 3.6 and above (including Python 3.10) you can declare it by importing and using `Optional` from the `typing` module.
```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009.py!}
+{!../../docs_src/python_types/tutorial009.py!}
```
-Using `Optional[str]` instead of just `str` will let the editor help you detecting errors where you could be assuming that a value is always a `str`, when it could actually be `None` too.
+Using `Optional[str]` instead of just `str` will let the editor help you detect errors where you could be assuming that a value is always a `str`, when it could actually be `None` too.
`Optional[Something]` is actually a shortcut for `Union[Something, None]`, they are equivalent.
This also means that in Python 3.10, you can use `Something | None`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial009_py310.py!}
- ```
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial009_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial009.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ alternative"
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial009.py!}
+```
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial009b.py!}
- ```
+////
+
+//// tab | Python 3.8+ alternative
+
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial009b.py!}
+```
+
+////
#### Using `Union` or `Optional`
@@ -339,7 +370,7 @@ It's just about the words and names. But those words can affect how you and your
As an example, let's take this function:
```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009c.py!}
+{!../../docs_src/python_types/tutorial009c.py!}
```
The parameter `name` is defined as `Optional[str]`, but it is **not optional**, you cannot call the function without the parameter:
@@ -357,7 +388,7 @@ say_hi(name=None) # This works, None is valid 🎉
The good news is, once you are on Python 3.10 you won't have to worry about that, as you will be able to simply use `|` to define unions of types:
```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009c_py310.py!}
+{!../../docs_src/python_types/tutorial009c_py310.py!}
```
And then you won't have to worry about names like `Optional` and `Union`. 😎
@@ -366,47 +397,53 @@ And then you won't have to worry about names like `Optional` and `Union`. 😎
These types that take type parameters in square brackets are called **Generic types** or **Generics**, for example:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- You can use the same builtin types as generics (with square brackets and types inside):
+You can use the same builtin types as generics (with square brackets and types inside):
- * `list`
- * `tuple`
- * `set`
- * `dict`
+* `list`
+* `tuple`
+* `set`
+* `dict`
- And the same as with Python 3.8, from the `typing` module:
+And the same as with Python 3.8, from the `typing` module:
- * `Union`
- * `Optional` (the same as with Python 3.8)
- * ...and others.
+* `Union`
+* `Optional` (the same as with Python 3.8)
+* ...and others.
- In Python 3.10, as an alternative to using the generics `Union` and `Optional`, you can use the vertical bar (`|`) to declare unions of types, that's a lot better and simpler.
+In Python 3.10, as an alternative to using the generics `Union` and `Optional`, you can use the vertical bar (`|`) to declare unions of types, that's a lot better and simpler.
-=== "Python 3.9+"
+////
- You can use the same builtin types as generics (with square brackets and types inside):
+//// tab | Python 3.9+
- * `list`
- * `tuple`
- * `set`
- * `dict`
+You can use the same builtin types as generics (with square brackets and types inside):
- And the same as with Python 3.8, from the `typing` module:
+* `list`
+* `tuple`
+* `set`
+* `dict`
- * `Union`
- * `Optional`
- * ...and others.
+And the same as with Python 3.8, from the `typing` module:
-=== "Python 3.8+"
+* `Union`
+* `Optional`
+* ...and others.
- * `List`
- * `Tuple`
- * `Set`
- * `Dict`
- * `Union`
- * `Optional`
- * ...and others.
+////
+
+//// tab | Python 3.8+
+
+* `List`
+* `Tuple`
+* `Set`
+* `Dict`
+* `Union`
+* `Optional`
+* ...and others.
+
+////
### Classes as types
@@ -415,13 +452,13 @@ You can also declare a class as the type of a variable.
Let's say you have a class `Person`, with a name:
```Python hl_lines="1-3"
-{!../../../docs_src/python_types/tutorial010.py!}
+{!../../docs_src/python_types/tutorial010.py!}
```
Then you can declare a variable to be of type `Person`:
```Python hl_lines="6"
-{!../../../docs_src/python_types/tutorial010.py!}
+{!../../docs_src/python_types/tutorial010.py!}
```
And then, again, you get all the editor support:
@@ -446,55 +483,71 @@ And you get all the editor support with that resulting object.
An example from the official Pydantic docs:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python
- {!> ../../../docs_src/python_types/tutorial011_py310.py!}
- ```
+```Python
+{!> ../../docs_src/python_types/tutorial011_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python
- {!> ../../../docs_src/python_types/tutorial011_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python
+{!> ../../docs_src/python_types/tutorial011_py39.py!}
+```
- ```Python
- {!> ../../../docs_src/python_types/tutorial011.py!}
- ```
+////
-!!! info
- To learn more about Pydantic, check its docs.
+//// tab | Python 3.8+
+
+```Python
+{!> ../../docs_src/python_types/tutorial011.py!}
+```
+
+////
+
+/// info
+
+To learn more about Pydantic, check its docs.
+
+///
**FastAPI** is all based on Pydantic.
You will see a lot more of all this in practice in the [Tutorial - User Guide](tutorial/index.md){.internal-link target=_blank}.
-!!! tip
- Pydantic has a special behavior when you use `Optional` or `Union[Something, None]` without a default value, you can read more about it in the Pydantic docs about Required Optional fields.
+/// tip
+
+Pydantic has a special behavior when you use `Optional` or `Union[Something, None]` without a default value, you can read more about it in the Pydantic docs about Required Optional fields.
+
+///
## Type Hints with Metadata Annotations
Python also has a feature that allows putting **additional metadata** in these type hints using `Annotated`.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- In Python 3.9, `Annotated` is part of the standard library, so you can import it from `typing`.
+In Python 3.9, `Annotated` is part of the standard library, so you can import it from `typing`.
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial013_py39.py!}
- ```
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial013_py39.py!}
+```
-=== "Python 3.8+"
+////
- In versions below Python 3.9, you import `Annotated` from `typing_extensions`.
+//// tab | Python 3.8+
- It will already be installed with **FastAPI**.
+In versions below Python 3.9, you import `Annotated` from `typing_extensions`.
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial013.py!}
- ```
+It will already be installed with **FastAPI**.
+
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial013.py!}
+```
+
+////
Python itself doesn't do anything with this `Annotated`. And for editors and other tools, the type is still `str`.
@@ -506,10 +559,13 @@ For now, you just need to know that `Annotated` exists, and that it's standard P
Later you will see how **powerful** it can be.
-!!! tip
- The fact that this is **standard Python** means that you will still get the **best possible developer experience** in your editor, with the tools you use to analyze and refactor your code, etc. ✨
+/// tip
- And also that your code will be very compatible with many other Python tools and libraries. 🚀
+The fact that this is **standard Python** means that you will still get the **best possible developer experience** in your editor, with the tools you use to analyze and refactor your code, etc. ✨
+
+And also that your code will be very compatible with many other Python tools and libraries. 🚀
+
+///
## Type hints in **FastAPI**
@@ -533,5 +589,8 @@ This might all sound abstract. Don't worry. You'll see all this in action in the
The important thing is that by using standard Python types, in a single place (instead of adding more classes, decorators, etc), **FastAPI** will do a lot of the work for you.
-!!! info
- If you already went through all the tutorial and came back to see more about types, a good resource is the "cheat sheet" from `mypy`.
+/// info
+
+If you already went through all the tutorial and came back to see more about types, a good resource is the "cheat sheet" from `mypy`.
+
+///
diff --git a/docs/en/docs/reference/request.md b/docs/en/docs/reference/request.md
index 0326f3fc7..f1de21642 100644
--- a/docs/en/docs/reference/request.md
+++ b/docs/en/docs/reference/request.md
@@ -8,7 +8,10 @@ You can import it directly from `fastapi`:
from fastapi import Request
```
-!!! tip
- When you want to define dependencies that should be compatible with both HTTP and WebSockets, you can define a parameter that takes an `HTTPConnection` instead of a `Request` or a `WebSocket`.
+/// tip
+
+When you want to define dependencies that should be compatible with both HTTP and WebSockets, you can define a parameter that takes an `HTTPConnection` instead of a `Request` or a `WebSocket`.
+
+///
::: fastapi.Request
diff --git a/docs/en/docs/reference/websockets.md b/docs/en/docs/reference/websockets.md
index d21e81a07..4b7244e08 100644
--- a/docs/en/docs/reference/websockets.md
+++ b/docs/en/docs/reference/websockets.md
@@ -8,8 +8,11 @@ It is provided directly by Starlette, but you can import it from `fastapi`:
from fastapi import WebSocket
```
-!!! tip
- When you want to define dependencies that should be compatible with both HTTP and WebSockets, you can define a parameter that takes an `HTTPConnection` instead of a `Request` or a `WebSocket`.
+/// tip
+
+When you want to define dependencies that should be compatible with both HTTP and WebSockets, you can define a parameter that takes an `HTTPConnection` instead of a `Request` or a `WebSocket`.
+
+///
::: fastapi.WebSocket
options:
diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md
index f7a3cbe55..90e45367b 100644
--- a/docs/en/docs/release-notes.md
+++ b/docs/en/docs/release-notes.md
@@ -7,12 +7,484 @@ hide:
## Latest Changes
+### Internal
+
+* ⬆ Update httpx requirement from <0.25.0,>=0.23.0 to >=0.23.0,<0.28.0. PR [#11509](https://github.com/fastapi/fastapi/pull/11509) by [@dependabot[bot]](https://github.com/apps/dependabot).
+
+## 0.115.2
+
+### Upgrades
+
+* ⬆️ Upgrade Starlette to `>=0.37.2,<0.41.0`. PR [#12431](https://github.com/fastapi/fastapi/pull/12431) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.115.1
+
+### Fixes
+
+* 🐛 Fix openapi generation with responses kwarg. PR [#10895](https://github.com/fastapi/fastapi/pull/10895) by [@flxdot](https://github.com/flxdot).
+* 🐛 Remove `Required` shadowing from fastapi using Pydantic v2. PR [#12197](https://github.com/fastapi/fastapi/pull/12197) by [@pachewise](https://github.com/pachewise).
+
+### Refactors
+
+* ♻️ Update type annotations for improved `python-multipart`. PR [#12407](https://github.com/fastapi/fastapi/pull/12407) by [@tiangolo](https://github.com/tiangolo).
+
+### Docs
+
+* ✨ Add new tutorial for SQL databases with SQLModel. PR [#12285](https://github.com/fastapi/fastapi/pull/12285) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Add External Link: How to profile a FastAPI asynchronous request. PR [#12389](https://github.com/fastapi/fastapi/pull/12389) by [@brouberol](https://github.com/brouberol).
+* 🔧 Remove `base_path` for `mdx_include` Markdown extension in MkDocs. PR [#12391](https://github.com/fastapi/fastapi/pull/12391) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Update link to Swagger UI configuration docs. PR [#12264](https://github.com/fastapi/fastapi/pull/12264) by [@makisukurisu](https://github.com/makisukurisu).
+* 📝 Adding links for Playwright and Vite in `docs/project-generation.md`. PR [#12274](https://github.com/fastapi/fastapi/pull/12274) by [@kayqueGovetri](https://github.com/kayqueGovetri).
+* 📝 Fix small typos in the documentation. PR [#12213](https://github.com/fastapi/fastapi/pull/12213) by [@svlandeg](https://github.com/svlandeg).
+
### Translations
+* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/cookie-param-models.md`. PR [#12298](https://github.com/fastapi/fastapi/pull/12298) by [@ceb10n](https://github.com/ceb10n).
+* 🌐 Add Portuguese translation for `docs/pt/docs/how-to/graphql.md`. PR [#12215](https://github.com/fastapi/fastapi/pull/12215) by [@AnandaCampelo](https://github.com/AnandaCampelo).
+* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/security/oauth2-scopes.md`. PR [#12263](https://github.com/fastapi/fastapi/pull/12263) by [@ceb10n](https://github.com/ceb10n).
+* 🌐 Add Portuguese translation for `docs/pt/docs/deployment/concepts.md`. PR [#12219](https://github.com/fastapi/fastapi/pull/12219) by [@marcelomarkus](https://github.com/marcelomarkus).
+* 🌐 Add Portuguese translation for `docs/pt/docs/how-to/conditional-openapi.md`. PR [#12221](https://github.com/fastapi/fastapi/pull/12221) by [@marcelomarkus](https://github.com/marcelomarkus).
+* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/response-directly.md`. PR [#12266](https://github.com/fastapi/fastapi/pull/12266) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda).
+* 🌐 Update Portuguese translation for `docs/pt/docs/tutorial/cookie-params.md`. PR [#12297](https://github.com/fastapi/fastapi/pull/12297) by [@ceb10n](https://github.com/ceb10n).
+* 🌐 Fix Korean translation for `docs/ko/docs/tutorial/index.md`. PR [#12278](https://github.com/fastapi/fastapi/pull/12278) by [@kkotipy](https://github.com/kkotipy).
+* 🌐 Update Portuguese translation for `docs/pt/docs/advanced/security/http-basic-auth.md`. PR [#12275](https://github.com/fastapi/fastapi/pull/12275) by [@andersonrocha0](https://github.com/andersonrocha0).
+* 🌐 Add Portuguese translation for `docs/pt/docs/deployment/cloud.md`. PR [#12217](https://github.com/fastapi/fastapi/pull/12217) by [@marcelomarkus](https://github.com/marcelomarkus).
+* ✏️ Fix typo in `docs/es/docs/python-types.md`. PR [#12235](https://github.com/fastapi/fastapi/pull/12235) by [@JavierSanchezCastro](https://github.com/JavierSanchezCastro).
+* 🌐 Add Dutch translation for `docs/nl/docs/environment-variables.md`. PR [#12200](https://github.com/fastapi/fastapi/pull/12200) by [@maxscheijen](https://github.com/maxscheijen).
+* 🌐 Add Portuguese translation for `docs/pt/docs/deployment/manually.md`. PR [#12210](https://github.com/fastapi/fastapi/pull/12210) by [@JoaoGustavoRogel](https://github.com/JoaoGustavoRogel).
+* 🌐 Add Portuguese translation for `docs/pt/docs/deployment/server-workers.md`. PR [#12220](https://github.com/fastapi/fastapi/pull/12220) by [@marcelomarkus](https://github.com/marcelomarkus).
+* 🌐 Add Portuguese translation for `docs/pt/docs/how-to/configure-swagger-ui.md`. PR [#12222](https://github.com/fastapi/fastapi/pull/12222) by [@marcelomarkus](https://github.com/marcelomarkus).
+
+### Internal
+
+* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12396](https://github.com/fastapi/fastapi/pull/12396) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
+* 🔨 Add script to generate variants of files. PR [#12405](https://github.com/fastapi/fastapi/pull/12405) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Add speakeasy-api to `sponsors_badge.yml`. PR [#12404](https://github.com/fastapi/fastapi/pull/12404) by [@tiangolo](https://github.com/tiangolo).
+* ➕ Add docs dependency: markdown-include-variants. PR [#12399](https://github.com/fastapi/fastapi/pull/12399) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Fix extra mdx-base-path paths. PR [#12397](https://github.com/fastapi/fastapi/pull/12397) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Tweak labeler to not override custom labels. PR [#12398](https://github.com/fastapi/fastapi/pull/12398) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Update worfkow deploy-docs-notify URL. PR [#12392](https://github.com/fastapi/fastapi/pull/12392) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Update Cloudflare GitHub Action. PR [#12387](https://github.com/fastapi/fastapi/pull/12387) by [@tiangolo](https://github.com/tiangolo).
+* ⬆ Bump pypa/gh-action-pypi-publish from 1.10.1 to 1.10.3. PR [#12386](https://github.com/fastapi/fastapi/pull/12386) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump mkdocstrings[python] from 0.25.1 to 0.26.1. PR [#12371](https://github.com/fastapi/fastapi/pull/12371) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump griffe-typingdoc from 0.2.6 to 0.2.7. PR [#12370](https://github.com/fastapi/fastapi/pull/12370) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12331](https://github.com/fastapi/fastapi/pull/12331) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
+* 🔧 Update sponsors, remove Fine.dev. PR [#12271](https://github.com/fastapi/fastapi/pull/12271) by [@tiangolo](https://github.com/tiangolo).
+* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12253](https://github.com/fastapi/fastapi/pull/12253) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
+* ✏️ Fix docstring typos in http security. PR [#12223](https://github.com/fastapi/fastapi/pull/12223) by [@albertvillanova](https://github.com/albertvillanova).
+
+## 0.115.0
+
+### Highlights
+
+Now you can declare `Query`, `Header`, and `Cookie` parameters with Pydantic models. 🎉
+
+#### `Query` Parameter Models
+
+Use Pydantic models for `Query` parameters:
+
+```python
+from typing import Annotated, Literal
+
+from fastapi import FastAPI, Query
+from pydantic import BaseModel, Field
+
+app = FastAPI()
+
+
+class FilterParams(BaseModel):
+ limit: int = Field(100, gt=0, le=100)
+ offset: int = Field(0, ge=0)
+ order_by: Literal["created_at", "updated_at"] = "created_at"
+ tags: list[str] = []
+
+
+@app.get("/items/")
+async def read_items(filter_query: Annotated[FilterParams, Query()]):
+ return filter_query
+```
+
+Read the new docs: [Query Parameter Models](https://fastapi.tiangolo.com/tutorial/query-param-models/).
+
+#### `Header` Parameter Models
+
+Use Pydantic models for `Header` parameters:
+
+```python
+from typing import Annotated
+
+from fastapi import FastAPI, Header
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class CommonHeaders(BaseModel):
+ host: str
+ save_data: bool
+ if_modified_since: str | None = None
+ traceparent: str | None = None
+ x_tag: list[str] = []
+
+
+@app.get("/items/")
+async def read_items(headers: Annotated[CommonHeaders, Header()]):
+ return headers
+```
+
+Read the new docs: [Header Parameter Models](https://fastapi.tiangolo.com/tutorial/header-param-models/).
+
+#### `Cookie` Parameter Models
+
+Use Pydantic models for `Cookie` parameters:
+
+```python
+from typing import Annotated
+
+from fastapi import Cookie, FastAPI
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class Cookies(BaseModel):
+ session_id: str
+ fatebook_tracker: str | None = None
+ googall_tracker: str | None = None
+
+
+@app.get("/items/")
+async def read_items(cookies: Annotated[Cookies, Cookie()]):
+ return cookies
+```
+
+Read the new docs: [Cookie Parameter Models](https://fastapi.tiangolo.com/tutorial/cookie-param-models/).
+
+#### Forbid Extra Query (Cookie, Header) Parameters
+
+Use Pydantic models to restrict extra values for `Query` parameters (also applies to `Header` and `Cookie` parameters).
+
+To achieve it, use Pydantic's `model_config = {"extra": "forbid"}`:
+
+```python
+from typing import Annotated, Literal
+
+from fastapi import FastAPI, Query
+from pydantic import BaseModel, Field
+
+app = FastAPI()
+
+
+class FilterParams(BaseModel):
+ model_config = {"extra": "forbid"}
+
+ limit: int = Field(100, gt=0, le=100)
+ offset: int = Field(0, ge=0)
+ order_by: Literal["created_at", "updated_at"] = "created_at"
+ tags: list[str] = []
+
+
+@app.get("/items/")
+async def read_items(filter_query: Annotated[FilterParams, Query()]):
+ return filter_query
+```
+
+This applies to `Query`, `Header`, and `Cookie` parameters, read the new docs:
+
+* [Forbid Extra Query Parameters](https://fastapi.tiangolo.com/tutorial/query-param-models/#forbid-extra-query-parameters)
+* [Forbid Extra Headers](https://fastapi.tiangolo.com/tutorial/header-param-models/#forbid-extra-headers)
+* [Forbid Extra Cookies](https://fastapi.tiangolo.com/tutorial/cookie-param-models/#forbid-extra-cookies)
+
+### Features
+
+* ✨ Add support for Pydantic models for parameters using `Query`, `Cookie`, `Header`. PR [#12199](https://github.com/fastapi/fastapi/pull/12199) by [@tiangolo](https://github.com/tiangolo).
+
+### Translations
+
+* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/security/http-basic-auth.md`. PR [#12195](https://github.com/fastapi/fastapi/pull/12195) by [@ceb10n](https://github.com/ceb10n).
+
+### Internal
+
+* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12204](https://github.com/fastapi/fastapi/pull/12204) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
+
+## 0.114.2
+
+### Fixes
+
+* 🐛 Fix form field regression with `alias`. PR [#12194](https://github.com/fastapi/fastapi/pull/12194) by [@Wurstnase](https://github.com/Wurstnase).
+
+### Translations
+
+* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/request-form-models.md`. PR [#12175](https://github.com/fastapi/fastapi/pull/12175) by [@ceb10n](https://github.com/ceb10n).
+* 🌐 Add Chinese translation for `docs/zh/docs/project-generation.md`. PR [#12170](https://github.com/fastapi/fastapi/pull/12170) by [@waketzheng](https://github.com/waketzheng).
+* 🌐 Add Dutch translation for `docs/nl/docs/python-types.md`. PR [#12158](https://github.com/fastapi/fastapi/pull/12158) by [@maxscheijen](https://github.com/maxscheijen).
+
+### Internal
+
+* 💡 Add comments with instructions for Playwright screenshot scripts. PR [#12193](https://github.com/fastapi/fastapi/pull/12193) by [@tiangolo](https://github.com/tiangolo).
+* ➕ Add inline-snapshot for tests. PR [#12189](https://github.com/fastapi/fastapi/pull/12189) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.114.1
+
+### Refactors
+
+* ⚡️ Improve performance in request body parsing with a cache for internal model fields. PR [#12184](https://github.com/fastapi/fastapi/pull/12184) by [@tiangolo](https://github.com/tiangolo).
+
+### Docs
+
+* 📝 Remove duplicate line in docs for `docs/en/docs/environment-variables.md`. PR [#12169](https://github.com/fastapi/fastapi/pull/12169) by [@prometek](https://github.com/prometek).
+
+### Translations
+
+* 🌐 Add Portuguese translation for `docs/pt/docs/virtual-environments.md`. PR [#12163](https://github.com/fastapi/fastapi/pull/12163) by [@marcelomarkus](https://github.com/marcelomarkus).
+* 🌐 Add Portuguese translation for `docs/pt/docs/environment-variables.md`. PR [#12162](https://github.com/fastapi/fastapi/pull/12162) by [@marcelomarkus](https://github.com/marcelomarkus).
+* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/testing.md`. PR [#12164](https://github.com/fastapi/fastapi/pull/12164) by [@marcelomarkus](https://github.com/marcelomarkus).
+* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/debugging.md`. PR [#12165](https://github.com/fastapi/fastapi/pull/12165) by [@marcelomarkus](https://github.com/marcelomarkus).
+* 🌐 Add Korean translation for `docs/ko/docs/project-generation.md`. PR [#12157](https://github.com/fastapi/fastapi/pull/12157) by [@BORA040126](https://github.com/BORA040126).
+
+### Internal
+
+* ⬆ Bump tiangolo/issue-manager from 0.5.0 to 0.5.1. PR [#12173](https://github.com/fastapi/fastapi/pull/12173) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12176](https://github.com/fastapi/fastapi/pull/12176) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
+* 👷 Update `issue-manager.yml`. PR [#12159](https://github.com/fastapi/fastapi/pull/12159) by [@tiangolo](https://github.com/tiangolo).
+* ✏️ Fix typo in `fastapi/params.py`. PR [#12143](https://github.com/fastapi/fastapi/pull/12143) by [@surreal30](https://github.com/surreal30).
+
+## 0.114.0
+
+You can restrict form fields to only include those declared in a Pydantic model and forbid any extra field sent in the request using Pydantic's `model_config = {"extra": "forbid"}`:
+
+```python
+from typing import Annotated
+
+from fastapi import FastAPI, Form
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class FormData(BaseModel):
+ username: str
+ password: str
+ model_config = {"extra": "forbid"}
+
+
+@app.post("/login/")
+async def login(data: Annotated[FormData, Form()]):
+ return data
+```
+
+Read the new docs: [Form Models - Forbid Extra Form Fields](https://fastapi.tiangolo.com/tutorial/request-form-models/#forbid-extra-form-fields).
+
+### Features
+
+* ✨ Add support for forbidding extra form fields with Pydantic models. PR [#12134](https://github.com/fastapi/fastapi/pull/12134) by [@tiangolo](https://github.com/tiangolo).
+
+### Docs
+
+* 📝 Update docs, Form Models section title, to match config name. PR [#12152](https://github.com/fastapi/fastapi/pull/12152) by [@tiangolo](https://github.com/tiangolo).
+
+### Internal
+
+* ✅ Update internal tests for latest Pydantic, including CI tweaks to install the latest Pydantic. PR [#12147](https://github.com/fastapi/fastapi/pull/12147) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.113.0
+
+Now you can declare form fields with Pydantic models:
+
+```python
+from typing import Annotated
+
+from fastapi import FastAPI, Form
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class FormData(BaseModel):
+ username: str
+ password: str
+
+
+@app.post("/login/")
+async def login(data: Annotated[FormData, Form()]):
+ return data
+```
+
+Read the new docs: [Form Models](https://fastapi.tiangolo.com/tutorial/request-form-models/).
+
+### Features
+
+* ✨ Add support for Pydantic models in `Form` parameters. PR [#12129](https://github.com/fastapi/fastapi/pull/12129) by [@tiangolo](https://github.com/tiangolo).
+
+### Internal
+
+* 🔧 Update sponsors: Coherence link. PR [#12130](https://github.com/fastapi/fastapi/pull/12130) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.112.4
+
+This release is mainly a big internal refactor to enable adding support for Pydantic models for `Form` fields, but that feature comes in the next release.
+
+This release shouldn't affect apps using FastAPI in any way. You don't even have to upgrade to this version yet. It's just a checkpoint. 🤓
+
+### Refactors
+
+* ♻️ Refactor deciding if `embed` body fields, do not overwrite fields, compute once per router, refactor internals in preparation for Pydantic models in `Form`, `Query` and others. PR [#12117](https://github.com/fastapi/fastapi/pull/12117) by [@tiangolo](https://github.com/tiangolo).
+
+### Internal
+
+* ⏪️ Temporarily revert "✨ Add support for Pydantic models in `Form` parameters" to make a checkpoint release. PR [#12128](https://github.com/fastapi/fastapi/pull/12128) by [@tiangolo](https://github.com/tiangolo). Restored by PR [#12129](https://github.com/fastapi/fastapi/pull/12129).
+* ✨ Add support for Pydantic models in `Form` parameters. PR [#12127](https://github.com/fastapi/fastapi/pull/12127) by [@tiangolo](https://github.com/tiangolo). Reverted by PR [#12128](https://github.com/fastapi/fastapi/pull/12128) to make a checkpoint release with only refactors. Restored by PR [#12129](https://github.com/fastapi/fastapi/pull/12129).
+
+## 0.112.3
+
+This release is mainly internal refactors, it shouldn't affect apps using FastAPI in any way. You don't even have to upgrade to this version yet. There are a few bigger releases coming right after. 🚀
+
+### Refactors
+
+* ♻️ Refactor internal `check_file_field()`, rename to `ensure_multipart_is_installed()` to clarify its purpose. PR [#12106](https://github.com/fastapi/fastapi/pull/12106) by [@tiangolo](https://github.com/tiangolo).
+* ♻️ Rename internal `create_response_field()` to `create_model_field()` as it's used for more than response models. PR [#12103](https://github.com/fastapi/fastapi/pull/12103) by [@tiangolo](https://github.com/tiangolo).
+* ♻️ Refactor and simplify internal data from `solve_dependencies()` using dataclasses. PR [#12100](https://github.com/fastapi/fastapi/pull/12100) by [@tiangolo](https://github.com/tiangolo).
+* ♻️ Refactor and simplify internal `analyze_param()` to structure data with dataclasses instead of tuple. PR [#12099](https://github.com/fastapi/fastapi/pull/12099) by [@tiangolo](https://github.com/tiangolo).
+* ♻️ Refactor and simplify dependencies data structures with dataclasses. PR [#12098](https://github.com/fastapi/fastapi/pull/12098) by [@tiangolo](https://github.com/tiangolo).
+
+### Docs
+
+* 📝 Add External Link: Techniques and applications of SQLAlchemy global filters in FastAPI. PR [#12109](https://github.com/fastapi/fastapi/pull/12109) by [@TheShubhendra](https://github.com/TheShubhendra).
+* 📝 Add note about `time.perf_counter()` in middlewares. PR [#12095](https://github.com/fastapi/fastapi/pull/12095) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Tweak middleware code sample `time.time()` to `time.perf_counter()`. PR [#11957](https://github.com/fastapi/fastapi/pull/11957) by [@domdent](https://github.com/domdent).
+* 🔧 Update sponsors: Coherence. PR [#12093](https://github.com/fastapi/fastapi/pull/12093) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Fix async test example not to trigger DeprecationWarning. PR [#12084](https://github.com/fastapi/fastapi/pull/12084) by [@marcinsulikowski](https://github.com/marcinsulikowski).
+* 📝 Update `docs_src/path_params_numeric_validations/tutorial006.py`. PR [#11478](https://github.com/fastapi/fastapi/pull/11478) by [@MuhammadAshiqAmeer](https://github.com/MuhammadAshiqAmeer).
+* 📝 Update comma in `docs/en/docs/async.md`. PR [#12062](https://github.com/fastapi/fastapi/pull/12062) by [@Alec-Gillis](https://github.com/Alec-Gillis).
+* 📝 Update docs about serving FastAPI: ASGI servers, Docker containers, etc.. PR [#12069](https://github.com/fastapi/fastapi/pull/12069) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Clarify `response_class` parameter, validations, and returning a response directly. PR [#12067](https://github.com/fastapi/fastapi/pull/12067) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Fix minor typos and issues in the documentation. PR [#12063](https://github.com/fastapi/fastapi/pull/12063) by [@svlandeg](https://github.com/svlandeg).
+* 📝 Add note in Docker docs about ensuring graceful shutdowns and lifespan events with `CMD` exec form. PR [#11960](https://github.com/fastapi/fastapi/pull/11960) by [@GPla](https://github.com/GPla).
+
+### Translations
+
+* 🌐 Add Dutch translation for `docs/nl/docs/features.md`. PR [#12101](https://github.com/fastapi/fastapi/pull/12101) by [@maxscheijen](https://github.com/maxscheijen).
+* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/testing-events.md`. PR [#12108](https://github.com/fastapi/fastapi/pull/12108) by [@ceb10n](https://github.com/ceb10n).
+* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/security/index.md`. PR [#12114](https://github.com/fastapi/fastapi/pull/12114) by [@ceb10n](https://github.com/ceb10n).
+* 🌐 Add Dutch translation for `docs/nl/docs/index.md`. PR [#12042](https://github.com/fastapi/fastapi/pull/12042) by [@svlandeg](https://github.com/svlandeg).
+* 🌐 Update Chinese translation for `docs/zh/docs/how-to/index.md`. PR [#12070](https://github.com/fastapi/fastapi/pull/12070) by [@synthpop123](https://github.com/synthpop123).
+
+### Internal
+
+* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12115](https://github.com/fastapi/fastapi/pull/12115) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
+* ⬆ Bump pypa/gh-action-pypi-publish from 1.10.0 to 1.10.1. PR [#12120](https://github.com/fastapi/fastapi/pull/12120) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump pillow from 10.3.0 to 10.4.0. PR [#12105](https://github.com/fastapi/fastapi/pull/12105) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* 💚 Set `include-hidden-files` to `True` when using the `upload-artifact` GH action. PR [#12118](https://github.com/fastapi/fastapi/pull/12118) by [@svlandeg](https://github.com/svlandeg).
+* ⬆ Bump pypa/gh-action-pypi-publish from 1.9.0 to 1.10.0. PR [#12112](https://github.com/fastapi/fastapi/pull/12112) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* 🔧 Update sponsors link: Coherence. PR [#12097](https://github.com/fastapi/fastapi/pull/12097) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update labeler config to handle sponsorships data. PR [#12096](https://github.com/fastapi/fastapi/pull/12096) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update sponsors, remove Kong. PR [#12085](https://github.com/fastapi/fastapi/pull/12085) by [@tiangolo](https://github.com/tiangolo).
+* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12076](https://github.com/fastapi/fastapi/pull/12076) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
+* 👷 Update `latest-changes` GitHub Action. PR [#12073](https://github.com/fastapi/fastapi/pull/12073) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.112.2
+
+### Fixes
+
+* 🐛 Fix `allow_inf_nan` option for Param and Body classes. PR [#11867](https://github.com/fastapi/fastapi/pull/11867) by [@giunio-prc](https://github.com/giunio-prc).
+* 🐛 Ensure that `app.include_router` merges nested lifespans. PR [#9630](https://github.com/fastapi/fastapi/pull/9630) by [@Lancetnik](https://github.com/Lancetnik).
+
+### Refactors
+
+* 🎨 Fix typing annotation for semi-internal `FastAPI.add_api_route()`. PR [#10240](https://github.com/fastapi/fastapi/pull/10240) by [@ordinary-jamie](https://github.com/ordinary-jamie).
+* ⬆️ Upgrade version of Ruff and reformat. PR [#12032](https://github.com/fastapi/fastapi/pull/12032) by [@tiangolo](https://github.com/tiangolo).
+
+### Docs
+
+* 📝 Fix a typo in `docs/en/docs/virtual-environments.md`. PR [#12064](https://github.com/fastapi/fastapi/pull/12064) by [@aymenkrifa](https://github.com/aymenkrifa).
+* 📝 Add docs about Environment Variables and Virtual Environments. PR [#12054](https://github.com/fastapi/fastapi/pull/12054) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Add Asyncer mention in async docs. PR [#12037](https://github.com/fastapi/fastapi/pull/12037) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Move the Features docs to the top level to improve the main page menu. PR [#12036](https://github.com/fastapi/fastapi/pull/12036) by [@tiangolo](https://github.com/tiangolo).
+* ✏️ Fix import typo in reference example for `Security`. PR [#11168](https://github.com/fastapi/fastapi/pull/11168) by [@0shah0](https://github.com/0shah0).
+* 📝 Highlight correct line in tutorial `docs/en/docs/tutorial/body-multiple-params.md`. PR [#11978](https://github.com/fastapi/fastapi/pull/11978) by [@svlandeg](https://github.com/svlandeg).
+* 🔥 Remove Sentry link from Advanced Middleware docs. PR [#12031](https://github.com/fastapi/fastapi/pull/12031) by [@alejsdev](https://github.com/alejsdev).
+* 📝 Clarify management tasks for translations, multiples files in one PR. PR [#12030](https://github.com/fastapi/fastapi/pull/12030) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Edit the link to the OpenAPI "Responses Object" and "Response Object" sections in the "Additional Responses in OpenAPI" section. PR [#11996](https://github.com/fastapi/fastapi/pull/11996) by [@VaitoSoi](https://github.com/VaitoSoi).
+* 🔨 Specify `email-validator` dependency with dash. PR [#11515](https://github.com/fastapi/fastapi/pull/11515) by [@jirikuncar](https://github.com/jirikuncar).
+* 🌐 Add Spanish translation for `docs/es/docs/project-generation.md`. PR [#11947](https://github.com/fastapi/fastapi/pull/11947) by [@alejsdev](https://github.com/alejsdev).
+* 📝 Fix minor typo. PR [#12026](https://github.com/fastapi/fastapi/pull/12026) by [@MicaelJarniac](https://github.com/MicaelJarniac).
+* 📝 Several docs improvements, tweaks, and clarifications. PR [#11390](https://github.com/fastapi/fastapi/pull/11390) by [@nilslindemann](https://github.com/nilslindemann).
+* 📝 Add missing `compresslevel` parameter on docs for `GZipMiddleware`. PR [#11350](https://github.com/fastapi/fastapi/pull/11350) by [@junah201](https://github.com/junah201).
+* 📝 Fix inconsistent response code when item already exists in docs for testing. PR [#11818](https://github.com/fastapi/fastapi/pull/11818) by [@lokomilo](https://github.com/lokomilo).
+* 📝 Update `docs/en/docs/tutorial/body.md` with Python 3.10 union type example. PR [#11415](https://github.com/fastapi/fastapi/pull/11415) by [@rangzen](https://github.com/rangzen).
+
+### Translations
+
+* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/request_file.md`. PR [#12018](https://github.com/fastapi/fastapi/pull/12018) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda).
+* 🌐 Add Japanese translation for `docs/ja/docs/learn/index.md`. PR [#11592](https://github.com/fastapi/fastapi/pull/11592) by [@ukwhatn](https://github.com/ukwhatn).
+* 📝 Update Spanish translation docs for consistency. PR [#12044](https://github.com/fastapi/fastapi/pull/12044) by [@alejsdev](https://github.com/alejsdev).
+* 🌐 Update Chinese translation for `docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md`. PR [#12028](https://github.com/fastapi/fastapi/pull/12028) by [@xuvjso](https://github.com/xuvjso).
+* 📝 Update FastAPI People, do not translate to have the most recent info. PR [#12034](https://github.com/fastapi/fastapi/pull/12034) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Update Urdu translation for `docs/ur/docs/benchmarks.md`. PR [#10046](https://github.com/fastapi/fastapi/pull/10046) by [@AhsanSheraz](https://github.com/AhsanSheraz).
+
+### Internal
+
+* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12046](https://github.com/fastapi/fastapi/pull/12046) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
+* 🔧 Update coverage config files. PR [#12035](https://github.com/fastapi/fastapi/pull/12035) by [@tiangolo](https://github.com/tiangolo).
+* 🔨 Standardize shebang across shell scripts. PR [#11942](https://github.com/fastapi/fastapi/pull/11942) by [@gitworkflows](https://github.com/gitworkflows).
+* ⬆ Update sqlalchemy requirement from <1.4.43,>=1.3.18 to >=1.3.18,<2.0.33. PR [#11979](https://github.com/fastapi/fastapi/pull/11979) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* 🔊 Remove old ignore warnings. PR [#11950](https://github.com/fastapi/fastapi/pull/11950) by [@tiangolo](https://github.com/tiangolo).
+* ⬆️ Upgrade griffe-typingdoc for the docs. PR [#12029](https://github.com/fastapi/fastapi/pull/12029) by [@tiangolo](https://github.com/tiangolo).
+* 🙈 Add .coverage* to `.gitignore`. PR [#11940](https://github.com/fastapi/fastapi/pull/11940) by [@gitworkflows](https://github.com/gitworkflows).
+* ⚙️ Record and show test coverage contexts (what test covers which line). PR [#11518](https://github.com/fastapi/fastapi/pull/11518) by [@slafs](https://github.com/slafs).
+
+## 0.112.1
+
+### Upgrades
+
+* ⬆️ Allow Starlette 0.38.x, update the pin to `>=0.37.2,<0.39.0`. PR [#11876](https://github.com/fastapi/fastapi/pull/11876) by [@musicinmybrain](https://github.com/musicinmybrain).
+
+### Docs
+
+* 📝 Update docs section about "Don't Translate these Pages". PR [#12022](https://github.com/fastapi/fastapi/pull/12022) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Add documentation for non-translated pages and scripts to verify them. PR [#12020](https://github.com/fastapi/fastapi/pull/12020) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Update docs about discussions questions. PR [#11985](https://github.com/fastapi/fastapi/pull/11985) by [@tiangolo](https://github.com/tiangolo).
+
+### Translations
+
+* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/bigger-applications.md`. PR [#11971](https://github.com/fastapi/fastapi/pull/11971) by [@marcelomarkus](https://github.com/marcelomarkus).
+* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/testing-websockets.md`. PR [#11994](https://github.com/fastapi/fastapi/pull/11994) by [@ceb10n](https://github.com/ceb10n).
+* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/testing-dependencies.md`. PR [#11995](https://github.com/fastapi/fastapi/pull/11995) by [@ceb10n](https://github.com/ceb10n).
+* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/using-request-directly.md`. PR [#11956](https://github.com/fastapi/fastapi/pull/11956) by [@ceb10n](https://github.com/ceb10n).
+* 🌐 Add French translation for `docs/fr/docs/tutorial/body-multiple-params.md`. PR [#11796](https://github.com/fastapi/fastapi/pull/11796) by [@pe-brian](https://github.com/pe-brian).
+* 🌐 Update Chinese translation for `docs/zh/docs/tutorial/query-params.md`. PR [#11557](https://github.com/fastapi/fastapi/pull/11557) by [@caomingpei](https://github.com/caomingpei).
+* 🌐 Update typo in Chinese translation for `docs/zh/docs/advanced/testing-dependencies.md`. PR [#11944](https://github.com/fastapi/fastapi/pull/11944) by [@bestony](https://github.com/bestony).
* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/sub-applications.md` and `docs/pt/docs/advanced/behind-a-proxy.md`. PR [#11856](https://github.com/fastapi/fastapi/pull/11856) by [@marcelomarkus](https://github.com/marcelomarkus).
* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/cors.md` and `docs/pt/docs/tutorial/middleware.md`. PR [#11916](https://github.com/fastapi/fastapi/pull/11916) by [@wesinalves](https://github.com/wesinalves).
* 🌐 Add French translation for `docs/fr/docs/tutorial/path-params-numeric-validations.md`. PR [#11788](https://github.com/fastapi/fastapi/pull/11788) by [@pe-brian](https://github.com/pe-brian).
+### Internal
+
+* ⬆ Bump pypa/gh-action-pypi-publish from 1.8.14 to 1.9.0. PR [#11727](https://github.com/fastapi/fastapi/pull/11727) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* 🔧 Add changelog URL to `pyproject.toml`, shows in PyPI. PR [#11152](https://github.com/fastapi/fastapi/pull/11152) by [@Pierre-VF](https://github.com/Pierre-VF).
+* 👷 Do not sync labels as it overrides manually added labels. PR [#12024](https://github.com/fastapi/fastapi/pull/12024) by [@tiangolo](https://github.com/tiangolo).
+* 👷🏻 Update Labeler GitHub Actions. PR [#12019](https://github.com/fastapi/fastapi/pull/12019) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update configs for MkDocs for languages and social cards. PR [#12016](https://github.com/fastapi/fastapi/pull/12016) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Update permissions and config for labeler GitHub Action. PR [#12008](https://github.com/fastapi/fastapi/pull/12008) by [@tiangolo](https://github.com/tiangolo).
+* 👷🏻 Add GitHub Action label-checker. PR [#12005](https://github.com/fastapi/fastapi/pull/12005) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Add label checker GitHub Action. PR [#12004](https://github.com/fastapi/fastapi/pull/12004) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Update GitHub Action add-to-project. PR [#12002](https://github.com/fastapi/fastapi/pull/12002) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update labeler GitHub Action. PR [#12001](https://github.com/fastapi/fastapi/pull/12001) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Add GitHub Action labeler. PR [#12000](https://github.com/fastapi/fastapi/pull/12000) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Add GitHub Action add-to-project. PR [#11999](https://github.com/fastapi/fastapi/pull/11999) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Update admonitions in docs missing. PR [#11998](https://github.com/fastapi/fastapi/pull/11998) by [@tiangolo](https://github.com/tiangolo).
+* 🔨 Update docs.py script to enable dirty reload conditionally. PR [#11986](https://github.com/fastapi/fastapi/pull/11986) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update MkDocs instant previews. PR [#11982](https://github.com/fastapi/fastapi/pull/11982) by [@tiangolo](https://github.com/tiangolo).
+* 🐛 Fix deploy docs previews script to handle mkdocs.yml files. PR [#11984](https://github.com/fastapi/fastapi/pull/11984) by [@tiangolo](https://github.com/tiangolo).
+* 💡 Add comment about custom Termynal line-height. PR [#11976](https://github.com/fastapi/fastapi/pull/11976) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Add alls-green for test-redistribute. PR [#11974](https://github.com/fastapi/fastapi/pull/11974) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Update docs-previews to handle no docs changes. PR [#11975](https://github.com/fastapi/fastapi/pull/11975) by [@tiangolo](https://github.com/tiangolo).
+* 🔨 Refactor script `deploy_docs_status.py` to account for deploy URLs with or without trailing slash. PR [#11965](https://github.com/fastapi/fastapi/pull/11965) by [@tiangolo](https://github.com/tiangolo).
+* 🔒️ Update permissions for deploy-docs action. PR [#11964](https://github.com/fastapi/fastapi/pull/11964) by [@tiangolo](https://github.com/tiangolo).
+* 👷🏻 Add deploy docs status and preview links to PRs. PR [#11961](https://github.com/fastapi/fastapi/pull/11961) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update docs setup with latest configs and plugins. PR [#11953](https://github.com/fastapi/fastapi/pull/11953) by [@tiangolo](https://github.com/tiangolo).
+* 🔇 Ignore warning from attrs in Trio. PR [#11949](https://github.com/fastapi/fastapi/pull/11949) by [@tiangolo](https://github.com/tiangolo).
+
## 0.112.0
### Breaking Changes
@@ -32,7 +504,7 @@ pip install "fastapi[standard]"
* This adds support for calling the CLI as:
```bash
-python -m python
+python -m fastapi
```
* And it upgrades `fastapi-cli[standard] >=0.0.5`.
@@ -88,7 +560,7 @@ Discussed here: [#11522](https://github.com/fastapi/fastapi/pull/11522) and here
### Upgrades
* ➖ Remove `orjson` and `ujson` from default dependencies. PR [#11842](https://github.com/tiangolo/fastapi/pull/11842) by [@tiangolo](https://github.com/tiangolo).
- * These dependencies are still installed when you install with `pip install "fastapi[all]"`. But they not included in `pip install fastapi`.
+ * These dependencies are still installed when you install with `pip install "fastapi[all]"`. But they are not included in `pip install fastapi`.
* 📝 Restored Swagger-UI links to use the latest version possible. PR [#11459](https://github.com/tiangolo/fastapi/pull/11459) by [@UltimateLobster](https://github.com/UltimateLobster).
### Docs
diff --git a/docs/en/docs/tutorial/background-tasks.md b/docs/en/docs/tutorial/background-tasks.md
index bcfadc8b8..1cd460b07 100644
--- a/docs/en/docs/tutorial/background-tasks.md
+++ b/docs/en/docs/tutorial/background-tasks.md
@@ -9,14 +9,14 @@ This includes, for example:
* Email notifications sent after performing an action:
* As connecting to an email server and sending an email tends to be "slow" (several seconds), you can return the response right away and send the email notification in the background.
* Processing data:
- * For example, let's say you receive a file that must go through a slow process, you can return a response of "Accepted" (HTTP 202) and process it in the background.
+ * For example, let's say you receive a file that must go through a slow process, you can return a response of "Accepted" (HTTP 202) and process the file in the background.
## Using `BackgroundTasks`
First, import `BackgroundTasks` and define a parameter in your *path operation function* with a type declaration of `BackgroundTasks`:
```Python hl_lines="1 13"
-{!../../../docs_src/background_tasks/tutorial001.py!}
+{!../../docs_src/background_tasks/tutorial001.py!}
```
**FastAPI** will create the object of type `BackgroundTasks` for you and pass it as that parameter.
@@ -34,7 +34,7 @@ In this case, the task function will write to a file (simulating sending an emai
And as the write operation doesn't use `async` and `await`, we define the function with normal `def`:
```Python hl_lines="6-9"
-{!../../../docs_src/background_tasks/tutorial001.py!}
+{!../../docs_src/background_tasks/tutorial001.py!}
```
## Add the background task
@@ -42,7 +42,7 @@ And as the write operation doesn't use `async` and `await`, we define the functi
Inside of your *path operation function*, pass your task function to the *background tasks* object with the method `.add_task()`:
```Python hl_lines="14"
-{!../../../docs_src/background_tasks/tutorial001.py!}
+{!../../docs_src/background_tasks/tutorial001.py!}
```
`.add_task()` receives as arguments:
@@ -57,41 +57,57 @@ Using `BackgroundTasks` also works with the dependency injection system, you can
**FastAPI** knows what to do in each case and how to reuse the same object, so that all the background tasks are merged together and are run in the background afterwards:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="13 15 22 25"
- {!> ../../../docs_src/background_tasks/tutorial002_an_py310.py!}
- ```
+```Python hl_lines="13 15 22 25"
+{!> ../../docs_src/background_tasks/tutorial002_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="13 15 22 25"
- {!> ../../../docs_src/background_tasks/tutorial002_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="13 15 22 25"
+{!> ../../docs_src/background_tasks/tutorial002_an_py39.py!}
+```
- ```Python hl_lines="14 16 23 26"
- {!> ../../../docs_src/background_tasks/tutorial002_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="14 16 23 26"
+{!> ../../docs_src/background_tasks/tutorial002_an.py!}
+```
- ```Python hl_lines="11 13 20 23"
- {!> ../../../docs_src/background_tasks/tutorial002_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="13 15 22 25"
- {!> ../../../docs_src/background_tasks/tutorial002.py!}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="11 13 20 23"
+{!> ../../docs_src/background_tasks/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="13 15 22 25"
+{!> ../../docs_src/background_tasks/tutorial002.py!}
+```
+
+////
In this example, the messages will be written to the `log.txt` file *after* the response is sent.
diff --git a/docs/en/docs/tutorial/bigger-applications.md b/docs/en/docs/tutorial/bigger-applications.md
index eccdd8aeb..4ec9b15bd 100644
--- a/docs/en/docs/tutorial/bigger-applications.md
+++ b/docs/en/docs/tutorial/bigger-applications.md
@@ -1,11 +1,14 @@
# Bigger Applications - Multiple Files
-If you are building an application or a web API, it's rarely the case that you can put everything on a single file.
+If you are building an application or a web API, it's rarely the case that you can put everything in a single file.
**FastAPI** provides a convenience tool to structure your application while keeping all the flexibility.
-!!! info
- If you come from Flask, this would be the equivalent of Flask's Blueprints.
+/// info
+
+If you come from Flask, this would be the equivalent of Flask's Blueprints.
+
+///
## An example file structure
@@ -26,16 +29,19 @@ Let's say you have a file structure like this:
│ └── admin.py
```
-!!! tip
- There are several `__init__.py` files: one in each directory or subdirectory.
+/// tip
- This is what allows importing code from one file into another.
+There are several `__init__.py` files: one in each directory or subdirectory.
- For example, in `app/main.py` you could have a line like:
+This is what allows importing code from one file into another.
- ```
- from app.routers import items
- ```
+For example, in `app/main.py` you could have a line like:
+
+```
+from app.routers import items
+```
+
+///
* The `app` directory contains everything. And it has an empty file `app/__init__.py`, so it is a "Python package" (a collection of "Python modules"): `app`.
* It contains an `app/main.py` file. As it is inside a Python package (a directory with a file `__init__.py`), it is a "module" of that package: `app.main`.
@@ -80,7 +86,7 @@ You can create the *path operations* for that module using `APIRouter`.
You import it and create an "instance" the same way you would with the class `FastAPI`:
```Python hl_lines="1 3" title="app/routers/users.py"
-{!../../../docs_src/bigger_applications/app/routers/users.py!}
+{!../../docs_src/bigger_applications/app/routers/users.py!}
```
### *Path operations* with `APIRouter`
@@ -90,7 +96,7 @@ And then you use it to declare your *path operations*.
Use it the same way you would use the `FastAPI` class:
```Python hl_lines="6 11 16" title="app/routers/users.py"
-{!../../../docs_src/bigger_applications/app/routers/users.py!}
+{!../../docs_src/bigger_applications/app/routers/users.py!}
```
You can think of `APIRouter` as a "mini `FastAPI`" class.
@@ -99,8 +105,11 @@ All the same options are supported.
All the same `parameters`, `responses`, `dependencies`, `tags`, etc.
-!!! tip
- In this example, the variable is called `router`, but you can name it however you want.
+/// tip
+
+In this example, the variable is called `router`, but you can name it however you want.
+
+///
We are going to include this `APIRouter` in the main `FastAPI` app, but first, let's check the dependencies and another `APIRouter`.
@@ -112,31 +121,43 @@ So we put them in their own `dependencies` module (`app/dependencies.py`).
We will now use a simple dependency to read a custom `X-Token` header:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="3 6-8" title="app/dependencies.py"
- {!> ../../../docs_src/bigger_applications/app_an_py39/dependencies.py!}
- ```
+```Python hl_lines="3 6-8" title="app/dependencies.py"
+{!> ../../docs_src/bigger_applications/app_an_py39/dependencies.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1 5-7" title="app/dependencies.py"
- {!> ../../../docs_src/bigger_applications/app_an/dependencies.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="1 5-7" title="app/dependencies.py"
+{!> ../../docs_src/bigger_applications/app_an/dependencies.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="1 4-6" title="app/dependencies.py"
- {!> ../../../docs_src/bigger_applications/app/dependencies.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-!!! tip
- We are using an invented header to simplify this example.
+/// tip
- But in real cases you will get better results using the integrated [Security utilities](security/index.md){.internal-link target=_blank}.
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="1 4-6" title="app/dependencies.py"
+{!> ../../docs_src/bigger_applications/app/dependencies.py!}
+```
+
+////
+
+/// tip
+
+We are using an invented header to simplify this example.
+
+But in real cases you will get better results using the integrated [Security utilities](security/index.md){.internal-link target=_blank}.
+
+///
## Another module with `APIRouter`
@@ -161,7 +182,7 @@ We know all the *path operations* in this module have the same:
So, instead of adding all that to each *path operation*, we can add it to the `APIRouter`.
```Python hl_lines="5-10 16 21" title="app/routers/items.py"
-{!../../../docs_src/bigger_applications/app/routers/items.py!}
+{!../../docs_src/bigger_applications/app/routers/items.py!}
```
As the path of each *path operation* has to start with `/`, like in:
@@ -180,8 +201,11 @@ We can also add a list of `tags` and extra `responses` that will be applied to a
And we can add a list of `dependencies` that will be added to all the *path operations* in the router and will be executed/solved for each request made to them.
-!!! tip
- Note that, much like [dependencies in *path operation decorators*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, no value will be passed to your *path operation function*.
+/// tip
+
+Note that, much like [dependencies in *path operation decorators*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, no value will be passed to your *path operation function*.
+
+///
The end result is that the item paths are now:
@@ -198,11 +222,17 @@ The end result is that the item paths are now:
* The router dependencies are executed first, then the [`dependencies` in the decorator](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, and then the normal parameter dependencies.
* You can also add [`Security` dependencies with `scopes`](../advanced/security/oauth2-scopes.md){.internal-link target=_blank}.
-!!! tip
- Having `dependencies` in the `APIRouter` can be used, for example, to require authentication for a whole group of *path operations*. Even if the dependencies are not added individually to each one of them.
+/// tip
-!!! check
- The `prefix`, `tags`, `responses`, and `dependencies` parameters are (as in many other cases) just a feature from **FastAPI** to help you avoid code duplication.
+Having `dependencies` in the `APIRouter` can be used, for example, to require authentication for a whole group of *path operations*. Even if the dependencies are not added individually to each one of them.
+
+///
+
+/// check
+
+The `prefix`, `tags`, `responses`, and `dependencies` parameters are (as in many other cases) just a feature from **FastAPI** to help you avoid code duplication.
+
+///
### Import the dependencies
@@ -213,13 +243,16 @@ And we need to get the dependency function from the module `app.dependencies`, t
So we use a relative import with `..` for the dependencies:
```Python hl_lines="3" title="app/routers/items.py"
-{!../../../docs_src/bigger_applications/app/routers/items.py!}
+{!../../docs_src/bigger_applications/app/routers/items.py!}
```
#### How relative imports work
-!!! tip
- If you know perfectly how imports work, continue to the next section below.
+/// tip
+
+If you know perfectly how imports work, continue to the next section below.
+
+///
A single dot `.`, like in:
@@ -283,13 +316,16 @@ We are not adding the prefix `/items` nor the `tags=["items"]` to each *path ope
But we can still add _more_ `tags` that will be applied to a specific *path operation*, and also some extra `responses` specific to that *path operation*:
```Python hl_lines="30-31" title="app/routers/items.py"
-{!../../../docs_src/bigger_applications/app/routers/items.py!}
+{!../../docs_src/bigger_applications/app/routers/items.py!}
```
-!!! tip
- This last path operation will have the combination of tags: `["items", "custom"]`.
+/// tip
- And it will also have both responses in the documentation, one for `404` and one for `403`.
+This last path operation will have the combination of tags: `["items", "custom"]`.
+
+And it will also have both responses in the documentation, one for `404` and one for `403`.
+
+///
## The main `FastAPI`
@@ -308,7 +344,7 @@ You import and create a `FastAPI` class as normally.
And we can even declare [global dependencies](dependencies/global-dependencies.md){.internal-link target=_blank} that will be combined with the dependencies for each `APIRouter`:
```Python hl_lines="1 3 7" title="app/main.py"
-{!../../../docs_src/bigger_applications/app/main.py!}
+{!../../docs_src/bigger_applications/app/main.py!}
```
### Import the `APIRouter`
@@ -316,7 +352,7 @@ And we can even declare [global dependencies](dependencies/global-dependencies.m
Now we import the other submodules that have `APIRouter`s:
```Python hl_lines="4-5" title="app/main.py"
-{!../../../docs_src/bigger_applications/app/main.py!}
+{!../../docs_src/bigger_applications/app/main.py!}
```
As the files `app/routers/users.py` and `app/routers/items.py` are submodules that are part of the same Python package `app`, we can use a single dot `.` to import them using "relative imports".
@@ -345,20 +381,23 @@ We could also import them like:
from app.routers import items, users
```
-!!! info
- The first version is a "relative import":
+/// info
- ```Python
- from .routers import items, users
- ```
+The first version is a "relative import":
- The second version is an "absolute import":
+```Python
+from .routers import items, users
+```
- ```Python
- from app.routers import items, users
- ```
+The second version is an "absolute import":
- To learn more about Python Packages and Modules, read the official Python documentation about Modules.
+```Python
+from app.routers import items, users
+```
+
+To learn more about Python Packages and Modules, read the official Python documentation about Modules.
+
+///
### Avoid name collisions
@@ -378,7 +417,7 @@ the `router` from `users` would overwrite the one from `items` and we wouldn't b
So, to be able to use both of them in the same file, we import the submodules directly:
```Python hl_lines="5" title="app/main.py"
-{!../../../docs_src/bigger_applications/app/main.py!}
+{!../../docs_src/bigger_applications/app/main.py!}
```
### Include the `APIRouter`s for `users` and `items`
@@ -386,29 +425,38 @@ So, to be able to use both of them in the same file, we import the submodules di
Now, let's include the `router`s from the submodules `users` and `items`:
```Python hl_lines="10-11" title="app/main.py"
-{!../../../docs_src/bigger_applications/app/main.py!}
+{!../../docs_src/bigger_applications/app/main.py!}
```
-!!! info
- `users.router` contains the `APIRouter` inside of the file `app/routers/users.py`.
+/// info
- And `items.router` contains the `APIRouter` inside of the file `app/routers/items.py`.
+`users.router` contains the `APIRouter` inside of the file `app/routers/users.py`.
+
+And `items.router` contains the `APIRouter` inside of the file `app/routers/items.py`.
+
+///
With `app.include_router()` we can add each `APIRouter` to the main `FastAPI` application.
It will include all the routes from that router as part of it.
-!!! note "Technical Details"
- It will actually internally create a *path operation* for each *path operation* that was declared in the `APIRouter`.
+/// note | "Technical Details"
- So, behind the scenes, it will actually work as if everything was the same single app.
+It will actually internally create a *path operation* for each *path operation* that was declared in the `APIRouter`.
-!!! check
- You don't have to worry about performance when including routers.
+So, behind the scenes, it will actually work as if everything was the same single app.
- This will take microseconds and will only happen at startup.
+///
- So it won't affect performance. ⚡
+/// check
+
+You don't have to worry about performance when including routers.
+
+This will take microseconds and will only happen at startup.
+
+So it won't affect performance. ⚡
+
+///
### Include an `APIRouter` with a custom `prefix`, `tags`, `responses`, and `dependencies`
@@ -419,7 +467,7 @@ It contains an `APIRouter` with some admin *path operations* that your organizat
For this example it will be super simple. But let's say that because it is shared with other projects in the organization, we cannot modify it and add a `prefix`, `dependencies`, `tags`, etc. directly to the `APIRouter`:
```Python hl_lines="3" title="app/internal/admin.py"
-{!../../../docs_src/bigger_applications/app/internal/admin.py!}
+{!../../docs_src/bigger_applications/app/internal/admin.py!}
```
But we still want to set a custom `prefix` when including the `APIRouter` so that all its *path operations* start with `/admin`, we want to secure it with the `dependencies` we already have for this project, and we want to include `tags` and `responses`.
@@ -427,10 +475,10 @@ But we still want to set a custom `prefix` when including the `APIRouter` so tha
We can declare all that without having to modify the original `APIRouter` by passing those parameters to `app.include_router()`:
```Python hl_lines="14-17" title="app/main.py"
-{!../../../docs_src/bigger_applications/app/main.py!}
+{!../../docs_src/bigger_applications/app/main.py!}
```
-That way, the original `APIRouter` will keep unmodified, so we can still share that same `app/internal/admin.py` file with other projects in the organization.
+That way, the original `APIRouter` will stay unmodified, so we can still share that same `app/internal/admin.py` file with other projects in the organization.
The result is that in our app, each of the *path operations* from the `admin` module will have:
@@ -450,30 +498,33 @@ We can also add *path operations* directly to the `FastAPI` app.
Here we do it... just to show that we can 🤷:
```Python hl_lines="21-23" title="app/main.py"
-{!../../../docs_src/bigger_applications/app/main.py!}
+{!../../docs_src/bigger_applications/app/main.py!}
```
and it will work correctly, together with all the other *path operations* added with `app.include_router()`.
-!!! info "Very Technical Details"
- **Note**: this is a very technical detail that you probably can **just skip**.
+/// info | "Very Technical Details"
- ---
+**Note**: this is a very technical detail that you probably can **just skip**.
- The `APIRouter`s are not "mounted", they are not isolated from the rest of the application.
+---
- This is because we want to include their *path operations* in the OpenAPI schema and the user interfaces.
+The `APIRouter`s are not "mounted", they are not isolated from the rest of the application.
- As we cannot just isolate them and "mount" them independently of the rest, the *path operations* are "cloned" (re-created), not included directly.
+This is because we want to include their *path operations* in the OpenAPI schema and the user interfaces.
+
+As we cannot just isolate them and "mount" them independently of the rest, the *path operations* are "cloned" (re-created), not included directly.
+
+///
## Check the automatic API docs
-Now, run `uvicorn`, using the module `app.main` and the variable `app`:
+Now, run your app:
-And will be also used in the API docs inside each *path operation* that needs them:
+And will also be used in the API docs inside each *path operation* that needs them:
@@ -134,32 +149,39 @@ But you would get the same editor support with
-!!! tip
- If you use PyCharm as your editor, you can use the Pydantic PyCharm Plugin.
+/// tip
- It improves editor support for Pydantic models, with:
+If you use PyCharm as your editor, you can use the Pydantic PyCharm Plugin.
- * auto-completion
- * type checks
- * refactoring
- * searching
- * inspections
+It improves editor support for Pydantic models, with:
+
+* auto-completion
+* type checks
+* refactoring
+* searching
+* inspections
+
+///
## Use the model
Inside of the function, you can access all the attributes of the model object directly:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="19"
- {!> ../../../docs_src/body/tutorial002_py310.py!}
- ```
+```Python hl_lines="19"
+{!> ../../docs_src/body/tutorial002_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="21"
- {!> ../../../docs_src/body/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="21"
+{!> ../../docs_src/body/tutorial002.py!}
+```
+
+////
## Request body + path parameters
@@ -167,17 +189,21 @@ You can declare path parameters and request body at the same time.
**FastAPI** will recognize that the function parameters that match path parameters should be **taken from the path**, and that function parameters that are declared to be Pydantic models should be **taken from the request body**.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="15-16"
- {!> ../../../docs_src/body/tutorial003_py310.py!}
- ```
+```Python hl_lines="15-16"
+{!> ../../docs_src/body/tutorial003_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="17-18"
- {!> ../../../docs_src/body/tutorial003.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="17-18"
+{!> ../../docs_src/body/tutorial003.py!}
+```
+
+////
## Request body + path + query parameters
@@ -185,17 +211,21 @@ You can also declare **body**, **path** and **query** parameters, all at the sam
**FastAPI** will recognize each of them and take the data from the correct place.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="16"
- {!> ../../../docs_src/body/tutorial004_py310.py!}
- ```
+```Python hl_lines="16"
+{!> ../../docs_src/body/tutorial004_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="18"
- {!> ../../../docs_src/body/tutorial004.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="18"
+{!> ../../docs_src/body/tutorial004.py!}
+```
+
+////
The function parameters will be recognized as follows:
@@ -203,10 +233,15 @@ The function parameters will be recognized as follows:
* If the parameter is of a **singular type** (like `int`, `float`, `str`, `bool`, etc) it will be interpreted as a **query** parameter.
* If the parameter is declared to be of the type of a **Pydantic model**, it will be interpreted as a request **body**.
-!!! note
- FastAPI will know that the value of `q` is not required because of the default value `= None`.
+/// note
- The `Union` in `Union[str, None]` is not used by FastAPI, but will allow your editor to give you better support and detect errors.
+FastAPI will know that the value of `q` is not required because of the default value `= None`.
+
+The `str | None` (Python 3.10+) or `Union` in `Union[str, None]` (Python 3.8+) is not used by FastAPI to determine that the value is not required, it will know it's not required because it has a default value of `= None`.
+
+But adding the type annotations will allow your editor to give you better support and detect errors.
+
+///
## Without Pydantic
diff --git a/docs/en/docs/tutorial/cookie-param-models.md b/docs/en/docs/tutorial/cookie-param-models.md
new file mode 100644
index 000000000..62cafbb23
--- /dev/null
+++ b/docs/en/docs/tutorial/cookie-param-models.md
@@ -0,0 +1,154 @@
+# Cookie Parameter Models
+
+If you have a group of **cookies** that are related, you can create a **Pydantic model** to declare them. 🍪
+
+This would allow you to **re-use the model** in **multiple places** and also to declare validations and metadata for all the parameters at once. 😎
+
+/// note
+
+This is supported since FastAPI version `0.115.0`. 🤓
+
+///
+
+/// tip
+
+This same technique applies to `Query`, `Cookie`, and `Header`. 😎
+
+///
+
+## Cookies with a Pydantic Model
+
+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!}
+```
+
+////
+
+**FastAPI** will **extract** the data for **each field** from the **cookies** received in the request and give you the Pydantic model you defined.
+
+## Check the Docs
+
+You can see the defined cookies in the docs UI at `/docs`:
+
+
+get operation
-!!! info "`@decorator` Info"
- That `@something` syntax in Python is called a "decorator".
+/// info | "`@decorator` Info"
- You put it on top of a function. Like a pretty decorative hat (I guess that's where the term came from).
+That `@something` syntax in Python is called a "decorator".
- A "decorator" takes the function below and does something with it.
+You put it on top of a function. Like a pretty decorative hat (I guess that's where the term came from).
- In our case, this decorator tells **FastAPI** that the function below corresponds to the **path** `/` with an **operation** `get`.
+A "decorator" takes the function below and does something with it.
- It is the "**path operation decorator**".
+In our case, this decorator tells **FastAPI** that the function below corresponds to the **path** `/` with an **operation** `get`.
+
+It is the "**path operation decorator**".
+
+///
You can also use the other operations:
@@ -271,14 +280,17 @@ And the more exotic ones:
* `@app.patch()`
* `@app.trace()`
-!!! tip
- You are free to use each operation (HTTP method) as you wish.
+/// tip
- **FastAPI** doesn't enforce any specific meaning.
+You are free to use each operation (HTTP method) as you wish.
- The information here is presented as a guideline, not a requirement.
+**FastAPI** doesn't enforce any specific meaning.
- For example, when using GraphQL you normally perform all the actions using only `POST` operations.
+The information here is presented as a guideline, not a requirement.
+
+For example, when using GraphQL you normally perform all the actions using only `POST` operations.
+
+///
### Step 4: define the **path operation function**
@@ -289,7 +301,7 @@ This is our "**path operation function**":
* **function**: is the function below the "decorator" (below `@app.get("/")`).
```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial001.py!}
+{!../../docs_src/first_steps/tutorial001.py!}
```
This is a Python function.
@@ -303,16 +315,19 @@ In this case, it is an `async` function.
You could also define it as a normal function instead of `async def`:
```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial003.py!}
+{!../../docs_src/first_steps/tutorial003.py!}
```
-!!! note
- If you don't know the difference, check the [Async: *"In a hurry?"*](../async.md#in-a-hurry){.internal-link target=_blank}.
+/// note
+
+If you don't know the difference, check the [Async: *"In a hurry?"*](../async.md#in-a-hurry){.internal-link target=_blank}.
+
+///
### Step 5: return the content
```Python hl_lines="8"
-{!../../../docs_src/first_steps/tutorial001.py!}
+{!../../docs_src/first_steps/tutorial001.py!}
```
You can return a `dict`, `list`, singular values as `str`, `int`, etc.
diff --git a/docs/en/docs/tutorial/handling-errors.md b/docs/en/docs/tutorial/handling-errors.md
index 6133898e4..38c15761b 100644
--- a/docs/en/docs/tutorial/handling-errors.md
+++ b/docs/en/docs/tutorial/handling-errors.md
@@ -26,7 +26,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!}
```
### Raise an `HTTPException` in your code
@@ -42,7 +42,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!}
```
### The resulting response
@@ -63,12 +63,15 @@ But if the client requests `http://example.com/items/bar` (a non-existent `item_
}
```
-!!! tip
- When raising an `HTTPException`, you can pass any value that can be converted to JSON as the parameter `detail`, not only `str`.
+/// tip
- You could pass a `dict`, a `list`, etc.
+When raising an `HTTPException`, you can pass any value that can be converted to JSON as the parameter `detail`, not only `str`.
- They are handled automatically by **FastAPI** and converted to JSON.
+You could pass a `dict`, a `list`, etc.
+
+They are handled automatically by **FastAPI** and converted to JSON.
+
+///
## Add custom headers
@@ -79,7 +82,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!}
```
## Install custom exception handlers
@@ -93,7 +96,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!}
```
Here, if you request `/unicorns/yolo`, the *path operation* will `raise` a `UnicornException`.
@@ -106,10 +109,13 @@ So, you will receive a clean error, with an HTTP status code of `418` and a JSON
{"message": "Oops! yolo did something. There goes a rainbow..."}
```
-!!! note "Technical Details"
- You could also use `from starlette.requests import Request` and `from starlette.responses import JSONResponse`.
+/// note | "Technical Details"
- **FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. The same with `Request`.
+You could also use `from starlette.requests import Request` and `from starlette.responses import JSONResponse`.
+
+**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. The same with `Request`.
+
+///
## Override the default exception handlers
@@ -130,7 +136,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!}
```
Now, if you go to `/items/foo`, instead of getting the default JSON error with:
@@ -160,14 +166,17 @@ path -> item_id
#### `RequestValidationError` vs `ValidationError`
-!!! warning
- These are technical details that you might skip if it's not important for you now.
+/// warning
+
+These are technical details that you might skip if it's not important for you now.
+
+///
`RequestValidationError` is a sub-class of Pydantic's `ValidationError`.
**FastAPI** uses it so that, if you use a Pydantic model in `response_model`, and your data has an error, you will see the error in your log.
-But the client/user will not see it. Instead, the client will receive an "Internal Server Error" with a HTTP status code `500`.
+But the client/user will not see it. Instead, the client will receive an "Internal Server Error" with an HTTP status code `500`.
It should be this way because if you have a Pydantic `ValidationError` in your *response* or anywhere in your code (not in the client's *request*), it's actually a bug in your code.
@@ -180,13 +189,16 @@ 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!}
```
-!!! note "Technical Details"
- You could also use `from starlette.responses import PlainTextResponse`.
+/// note | "Technical Details"
- **FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette.
+You could also use `from starlette.responses import PlainTextResponse`.
+
+**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette.
+
+///
### Use the `RequestValidationError` body
@@ -195,7 +207,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!}
```
Now try sending an invalid item like:
@@ -250,10 +262,10 @@ from starlette.exceptions import HTTPException as StarletteHTTPException
### Reuse **FastAPI**'s exception handlers
-If you want to use the exception along with the same default exception handlers from **FastAPI**, You can import and reuse the default exception handlers from `fastapi.exception_handlers`:
+If you want to use the exception along with the same default exception handlers from **FastAPI**, you can import and reuse the default exception handlers from `fastapi.exception_handlers`:
```Python hl_lines="2-5 15 21"
-{!../../../docs_src/handling_errors/tutorial006.py!}
+{!../../docs_src/handling_errors/tutorial006.py!}
```
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
new file mode 100644
index 000000000..78517e498
--- /dev/null
+++ b/docs/en/docs/tutorial/header-param-models.md
@@ -0,0 +1,184 @@
+# Header Parameter Models
+
+If you have a group of related **header parameters**, you can create a **Pydantic model** to declare them.
+
+This would allow you to **re-use the model** in **multiple places** and also to declare validations and metadata for all the parameters at once. 😎
+
+/// note
+
+This is supported since FastAPI version `0.115.0`. 🤓
+
+///
+
+## Header Parameters with a Pydantic Model
+
+Declare the **header parameters** that you need in a **Pydantic model**, and then declare the parameter as `Header`:
+
+//// 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!}
+```
+
+////
+
+**FastAPI** will **extract** the data for **each field** from the **headers** in the request and give you the Pydantic model you defined.
+
+## Check the Docs
+
+You can see the required headers in the docs UI at `/docs`:
+
+
+
@@ -163,7 +205,7 @@ You can specify the response description with the parameter `response_descriptio
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!}
```
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 ca86ad226..9ddf49ea9 100644
--- a/docs/en/docs/tutorial/path-params-numeric-validations.md
+++ b/docs/en/docs/tutorial/path-params-numeric-validations.md
@@ -6,48 +6,67 @@ In the same way that you can declare more validations and metadata for query par
First, import `Path` from `fastapi`, and import `Annotated`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="1 3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="1 3"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="1 3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="1 3"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="3-4"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="3-4"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
+```
- ```Python hl_lines="1"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-!!! info
- FastAPI added support for `Annotated` (and started recommending it) in version 0.95.0.
+///
- If you have an older version, you would get errors when trying to use `Annotated`.
+```Python hl_lines="1"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
+```
- Make sure you [Upgrade the FastAPI version](../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} to at least 0.95.1 before using `Annotated`.
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="3"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!}
+```
+
+////
+
+/// info
+
+FastAPI added support for `Annotated` (and started recommending it) in version 0.95.0.
+
+If you have an older version, you would get errors when trying to use `Annotated`.
+
+Make sure you [Upgrade the FastAPI version](../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} to at least 0.95.1 before using `Annotated`.
+
+///
## Declare metadata
@@ -55,49 +74,71 @@ You can declare all the same parameters as for `Query`.
For example, to declare a `title` metadata value for the path parameter `item_id` you can type:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="10"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="10"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="11"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="11"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
+```
- ```Python hl_lines="8"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-!!! note
- A path parameter is always required as it has to be part of the path. Even if you declared it with `None` or set a default value, it would not affect anything, it would still be always required.
+///
+
+```Python hl_lines="8"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="10"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!}
+```
+
+////
+
+/// note
+
+A path parameter is always required as it has to be part of the path. Even if you declared it with `None` or set a default value, it would not affect anything, it would still be always required.
+
+///
## Order the parameters as you need
-!!! tip
- This is probably not as important or necessary if you use `Annotated`.
+/// tip
+
+This is probably not as important or necessary if you use `Annotated`.
+
+///
Let's say that you want to declare the query parameter `q` as a required `str`.
@@ -113,33 +154,45 @@ It doesn't matter for **FastAPI**. It will detect the parameters by their names,
So, you can declare your function as:
-=== "Python 3.8 non-Annotated"
+//// tab | Python 3.8 non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="7"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="7"
+{!> ../../docs_src/path_params_numeric_validations/tutorial002.py!}
+```
+
+////
But keep in mind that if you use `Annotated`, you won't have this problem, it won't matter as you're not using the function parameter default values for `Query()` or `Path()`.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!}
- ```
+```Python hl_lines="10"
+{!> ../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../docs_src/path_params_numeric_validations/tutorial002_an.py!}
+```
+
+////
## Order the parameters as you need, tricks
-!!! tip
- This is probably not as important or necessary if you use `Annotated`.
+/// tip
+
+This is probably not as important or necessary if you use `Annotated`.
+
+///
Here's a **small trick** that can be handy, but you won't need it often.
@@ -157,24 +210,28 @@ 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!}
```
### Better with `Annotated`
Keep in mind that if you use `Annotated`, as you are not using function parameter default values, you won't have this problem, and you probably won't need to use `*`.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!}
- ```
+```Python hl_lines="10"
+{!> ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../docs_src/path_params_numeric_validations/tutorial003_an.py!}
+```
+
+////
## Number validations: greater than or equal
@@ -182,26 +239,35 @@ With `Query` and `Path` (and others you'll see later) you can declare number con
Here, with `ge=1`, `item_id` will need to be an integer number "`g`reater than or `e`qual" to `1`.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!}
- ```
+```Python hl_lines="10"
+{!> ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="9"
+{!> ../../docs_src/path_params_numeric_validations/tutorial004_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="8"
+{!> ../../docs_src/path_params_numeric_validations/tutorial004.py!}
+```
+
+////
## Number validations: greater than and less than or equal
@@ -210,26 +276,35 @@ The same applies for:
* `gt`: `g`reater `t`han
* `le`: `l`ess than or `e`qual
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!}
- ```
+```Python hl_lines="10"
+{!> ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="9"
+{!> ../../docs_src/path_params_numeric_validations/tutorial005_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="9"
+{!> ../../docs_src/path_params_numeric_validations/tutorial005.py!}
+```
+
+////
## Number validations: floats, greater than and less than
@@ -241,26 +316,35 @@ So, `0.5` would be a valid value. But `0.0` or `0` would not.
And the same for lt.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="13"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!}
- ```
+```Python hl_lines="13"
+{!> ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="12"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="12"
+{!> ../../docs_src/path_params_numeric_validations/tutorial006_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="11"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="11"
+{!> ../../docs_src/path_params_numeric_validations/tutorial006.py!}
+```
+
+////
## Recap
@@ -273,18 +357,24 @@ And you can also declare numeric validations:
* `lt`: `l`ess `t`han
* `le`: `l`ess than or `e`qual
-!!! info
- `Query`, `Path`, and other classes you will see later are subclasses of a common `Param` class.
+/// info
- All of them share the same parameters for additional validation and metadata you have seen.
+`Query`, `Path`, and other classes you will see later are subclasses of a common `Param` class.
-!!! note "Technical Details"
- When you import `Query`, `Path` and others from `fastapi`, they are actually functions.
+All of them share the same parameters for additional validation and metadata you have seen.
- That when called, return instances of classes of the same name.
+///
- So, you import `Query`, which is a function. And when you call it, it returns an instance of a class also named `Query`.
+/// note | "Technical Details"
- These functions are there (instead of just using the classes directly) so that your editor doesn't mark errors about their types.
+When you import `Query`, `Path` and others from `fastapi`, they are actually functions.
- That way you can use your normal editor and coding tools without having to add custom configurations to disregard those errors.
+That when called, return instances of classes of the same name.
+
+So, you import `Query`, which is a function. And when you call it, it returns an instance of a class also named `Query`.
+
+These functions are there (instead of just using the classes directly) so that your editor doesn't mark errors about their types.
+
+That way you can use your normal editor and coding tools without having to add custom configurations to disregard those errors.
+
+///
diff --git a/docs/en/docs/tutorial/path-params.md b/docs/en/docs/tutorial/path-params.md
index 6246d6680..fd9e74585 100644
--- a/docs/en/docs/tutorial/path-params.md
+++ b/docs/en/docs/tutorial/path-params.md
@@ -3,7 +3,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!}
```
The value of the path parameter `item_id` will be passed to your function as the argument `item_id`.
@@ -19,13 +19,16 @@ So, if you run this example and go to conversion
@@ -35,10 +38,13 @@ If you run this example and open your browser at "parsing".
+Notice that the value your function received (and returned) is `3`, as a Python `int`, not a string `"3"`.
+
+So, with that type declaration, **FastAPI** gives you automatic request "parsing".
+
+///
## Data validation
@@ -65,12 +71,15 @@ because the path parameter `item_id` had a value of `"foo"`, which is not an `in
The same error would appear if you provided a `float` instead of an `int`, as in: http://127.0.0.1:8000/items/4.2
-!!! check
- So, with the same Python type declaration, **FastAPI** gives you data validation.
+/// check
- Notice that the error also clearly states exactly the point where the validation didn't pass.
+So, with the same Python type declaration, **FastAPI** gives you data validation.
- This is incredibly helpful while developing and debugging code that interacts with your API.
+Notice that the error also clearly states exactly the point where the validation didn't pass.
+
+This is incredibly helpful while developing and debugging code that interacts with your API.
+
+///
## Documentation
@@ -78,10 +87,13 @@ And when you open your browser at
-!!! check
- Again, just with that same Python type declaration, **FastAPI** gives you automatic, interactive documentation (integrating Swagger UI).
+/// check
- Notice that the path parameter is declared to be an integer.
+Again, just with that same Python type declaration, **FastAPI** gives you automatic, interactive documentation (integrating Swagger UI).
+
+Notice that the path parameter is declared to be an integer.
+
+///
## Standards-based benefits, alternative documentation
@@ -112,7 +124,7 @@ And then you can also have a path `/users/{user_id}` to get data about a specifi
Because *path operations* are evaluated in order, you need to make sure that the path for `/users/me` is declared before the one for `/users/{user_id}`:
```Python hl_lines="6 11"
-{!../../../docs_src/path_params/tutorial003.py!}
+{!../../docs_src/path_params/tutorial003.py!}
```
Otherwise, the path for `/users/{user_id}` would match also for `/users/me`, "thinking" that it's receiving a parameter `user_id` with a value of `"me"`.
@@ -120,7 +132,7 @@ Otherwise, the path for `/users/{user_id}` would match also for `/users/me`, "th
Similarly, you cannot redefine a path operation:
```Python hl_lines="6 11"
-{!../../../docs_src/path_params/tutorial003b.py!}
+{!../../docs_src/path_params/tutorial003b.py!}
```
The first one will always be used since the path matches first.
@@ -138,21 +150,27 @@ By inheriting from `str` the API docs will be able to know that the values must
Then create class attributes with fixed values, which will be the available valid values:
```Python hl_lines="1 6-9"
-{!../../../docs_src/path_params/tutorial005.py!}
+{!../../docs_src/path_params/tutorial005.py!}
```
-!!! info
- Enumerations (or enums) are available in Python since version 3.4.
+/// info
-!!! tip
- If you are wondering, "AlexNet", "ResNet", and "LeNet" are just names of Machine Learning models.
+Enumerations (or enums) are available in Python since version 3.4.
+
+///
+
+/// tip
+
+If you are wondering, "AlexNet", "ResNet", and "LeNet" are just names of Machine Learning models.
+
+///
### Declare a *path parameter*
Then create a *path parameter* with a type annotation using the enum class you created (`ModelName`):
```Python hl_lines="16"
-{!../../../docs_src/path_params/tutorial005.py!}
+{!../../docs_src/path_params/tutorial005.py!}
```
### Check the docs
@@ -170,7 +188,7 @@ The value of the *path parameter* will be an *enumeration member*.
You can compare it with the *enumeration member* in your created enum `ModelName`:
```Python hl_lines="17"
-{!../../../docs_src/path_params/tutorial005.py!}
+{!../../docs_src/path_params/tutorial005.py!}
```
#### Get the *enumeration value*
@@ -178,11 +196,14 @@ You can compare it with the *enumeration member* in your created enum `ModelName
You can get the actual value (a `str` in this case) using `model_name.value`, or in general, `your_enum_member.value`:
```Python hl_lines="20"
-{!../../../docs_src/path_params/tutorial005.py!}
+{!../../docs_src/path_params/tutorial005.py!}
```
-!!! tip
- You could also access the value `"lenet"` with `ModelName.lenet.value`.
+/// tip
+
+You could also access the value `"lenet"` with `ModelName.lenet.value`.
+
+///
#### Return *enumeration members*
@@ -191,7 +212,7 @@ You can return *enum members* from your *path operation*, even nested in a JSON
They will be converted to their corresponding values (strings in this case) before returning them to the client:
```Python hl_lines="18 21 23"
-{!../../../docs_src/path_params/tutorial005.py!}
+{!../../docs_src/path_params/tutorial005.py!}
```
In your client you will get a JSON response like:
@@ -232,13 +253,16 @@ In this case, the name of the parameter is `file_path`, and the last part, `:pat
So, you can use it with:
```Python hl_lines="6"
-{!../../../docs_src/path_params/tutorial004.py!}
+{!../../docs_src/path_params/tutorial004.py!}
```
-!!! tip
- You could need the parameter to contain `/home/johndoe/myfile.txt`, with a leading slash (`/`).
+/// tip
- In that case, the URL would be: `/files//home/johndoe/myfile.txt`, with a double slash (`//`) between `files` and `home`.
+You could need the parameter to contain `/home/johndoe/myfile.txt`, with a leading slash (`/`).
+
+In that case, the URL would be: `/files//home/johndoe/myfile.txt`, with a double slash (`//`) between `files` and `home`.
+
+///
## Recap
diff --git a/docs/en/docs/tutorial/query-param-models.md b/docs/en/docs/tutorial/query-param-models.md
new file mode 100644
index 000000000..f7ce345b2
--- /dev/null
+++ b/docs/en/docs/tutorial/query-param-models.md
@@ -0,0 +1,196 @@
+# Query Parameter Models
+
+If you have a group of **query parameters** that are related, you can create a **Pydantic model** to declare them.
+
+This would allow you to **re-use the model** in **multiple places** and also to declare validations and metadata for all the parameters at once. 😎
+
+/// note
+
+This is supported since FastAPI version `0.115.0`. 🤓
+
+///
+
+## Query Parameters with a Pydantic Model
+
+Declare the **query parameters** that you need in a **Pydantic model**, and then declare the parameter as `Query`:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="9-13 17"
+{!> ../../docs_src/query_param_models/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="8-12 16"
+{!> ../../docs_src/query_param_models/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="10-14 18"
+{!> ../../docs_src/query_param_models/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="9-13 17"
+{!> ../../docs_src/query_param_models/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="8-12 16"
+{!> ../../docs_src/query_param_models/tutorial001_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="9-13 17"
+{!> ../../docs_src/query_param_models/tutorial001_py310.py!}
+```
+
+////
+
+**FastAPI** will **extract** the data for **each field** from the **query parameters** in the request and give you the Pydantic model you defined.
+
+## Check the Docs
+
+You can see the query parameters in the docs UI at `/docs`:
+
+
+
-## Exclude from OpenAPI
+## Exclude parameters from OpenAPI
To exclude a query parameter from the generated OpenAPI schema (and thus, from the automatic documentation systems), set the parameter `include_in_schema` of `Query` to `False`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial014_an_py310.py!}
- ```
+```Python hl_lines="10"
+{!> ../../docs_src/query_params_str_validations/tutorial014_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial014_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="10"
+{!> ../../docs_src/query_params_str_validations/tutorial014_an_py39.py!}
+```
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial014_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="11"
+{!> ../../docs_src/query_params_str_validations/tutorial014_an.py!}
+```
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial014.py!}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="8"
+{!> ../../docs_src/query_params_str_validations/tutorial014_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="10"
+{!> ../../docs_src/query_params_str_validations/tutorial014.py!}
+```
+
+////
## Recap
@@ -915,4 +1182,4 @@ Validations specific for strings:
In these examples you saw how to declare validations for `str` values.
-See the next chapters to see how to declare validations for other types, like numbers.
+See the next chapters to learn how to declare validations for other types, like numbers.
diff --git a/docs/en/docs/tutorial/query-params.md b/docs/en/docs/tutorial/query-params.md
index bc3b11948..0d31d453d 100644
--- a/docs/en/docs/tutorial/query-params.md
+++ b/docs/en/docs/tutorial/query-params.md
@@ -3,7 +3,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!}
```
The query is the set of key-value pairs that go after the `?` in a URL, separated by `&` characters.
@@ -63,38 +63,49 @@ The parameter values in your function will be:
The same way, you can declare optional query parameters, by setting their default to `None`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params/tutorial002_py310.py!}
- ```
+```Python hl_lines="7"
+{!> ../../docs_src/query_params/tutorial002_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../docs_src/query_params/tutorial002.py!}
+```
+
+////
In this case, the function parameter `q` will be optional, and will be `None` by default.
-!!! check
- Also notice that **FastAPI** is smart enough to notice that the path parameter `item_id` is a path parameter and `q` is not, so, it's a query parameter.
+/// check
+
+Also notice that **FastAPI** is smart enough to notice that the path parameter `item_id` is a path parameter and `q` is not, so, it's a query parameter.
+
+///
## Query parameter type conversion
You can also declare `bool` types, and they will be converted:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params/tutorial003_py310.py!}
- ```
+```Python hl_lines="7"
+{!> ../../docs_src/query_params/tutorial003_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params/tutorial003.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../docs_src/query_params/tutorial003.py!}
+```
+
+////
In this case, if you go to:
@@ -137,17 +148,21 @@ And you don't have to declare them in any specific order.
They will be detected by name:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="6 8"
- {!> ../../../docs_src/query_params/tutorial004_py310.py!}
- ```
+```Python hl_lines="6 8"
+{!> ../../docs_src/query_params/tutorial004_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="8 10"
- {!> ../../../docs_src/query_params/tutorial004.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="8 10"
+{!> ../../docs_src/query_params/tutorial004.py!}
+```
+
+////
## Required query parameters
@@ -158,7 +173,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!}
```
Here the query parameter `needy` is a required query parameter of type `str`.
@@ -205,17 +220,21 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
And of course, you can define some parameters as required, some as having a default value, and some entirely optional:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params/tutorial006_py310.py!}
- ```
+```Python hl_lines="8"
+{!> ../../docs_src/query_params/tutorial006_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params/tutorial006.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="10"
+{!> ../../docs_src/query_params/tutorial006.py!}
+```
+
+////
In this case, there are 3 query parameters:
@@ -223,5 +242,8 @@ In this case, there are 3 query parameters:
* `skip`, an `int` with a default value of `0`.
* `limit`, an optional `int`.
-!!! tip
- You could also use `Enum`s the same way as with [Path Parameters](path-params.md#predefined-values){.internal-link target=_blank}.
+/// tip
+
+You could also use `Enum`s the same way as with [Path Parameters](path-params.md#predefined-values){.internal-link target=_blank}.
+
+///
diff --git a/docs/en/docs/tutorial/request-files.md b/docs/en/docs/tutorial/request-files.md
index 17ac3b25d..f3f1eb103 100644
--- a/docs/en/docs/tutorial/request-files.md
+++ b/docs/en/docs/tutorial/request-files.md
@@ -2,70 +2,101 @@
You can define files to be uploaded by the client using `File`.
-!!! info
- To receive uploaded files, first install `python-multipart`.
+/// info
- E.g. `pip install python-multipart`.
+To receive uploaded files, first install `python-multipart`.
- This is because uploaded files are sent as "form data".
+Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install it, for example:
+
+```console
+$ pip install python-multipart
+```
+
+This is because uploaded files are sent as "form data".
+
+///
## Import `File`
Import `File` and `UploadFile` from `fastapi`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="3"
- {!> ../../../docs_src/request_files/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="3"
+{!> ../../docs_src/request_files/tutorial001_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/request_files/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="1"
+{!> ../../docs_src/request_files/tutorial001_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/request_files/tutorial001.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="1"
+{!> ../../docs_src/request_files/tutorial001.py!}
+```
+
+////
## Define `File` Parameters
Create file parameters the same way you would for `Body` or `Form`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="9"
- {!> ../../../docs_src/request_files/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/request_files/tutorial001_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/request_files/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="8"
+{!> ../../docs_src/request_files/tutorial001_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/request_files/tutorial001.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-!!! info
- `File` is a class that inherits directly from `Form`.
+/// tip
- But remember that when you import `Query`, `Path`, `File` and others from `fastapi`, those are actually functions that return special classes.
+Prefer to use the `Annotated` version if possible.
-!!! tip
- To declare File bodies, you need to use `File`, because otherwise the parameters would be interpreted as query parameters or body (JSON) parameters.
+///
+
+```Python hl_lines="7"
+{!> ../../docs_src/request_files/tutorial001.py!}
+```
+
+////
+
+/// info
+
+`File` is a class that inherits directly from `Form`.
+
+But remember that when you import `Query`, `Path`, `File` and others from `fastapi`, those are actually functions that return special classes.
+
+///
+
+/// tip
+
+To declare File bodies, you need to use `File`, because otherwise the parameters would be interpreted as query parameters or body (JSON) parameters.
+
+///
The files will be uploaded as "form data".
@@ -79,26 +110,35 @@ But there are several cases in which you might benefit from using `UploadFile`.
Define a file parameter with a type of `UploadFile`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="14"
- {!> ../../../docs_src/request_files/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="14"
+{!> ../../docs_src/request_files/tutorial001_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="13"
- {!> ../../../docs_src/request_files/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="13"
+{!> ../../docs_src/request_files/tutorial001_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="12"
- {!> ../../../docs_src/request_files/tutorial001.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="12"
+{!> ../../docs_src/request_files/tutorial001.py!}
+```
+
+////
Using `UploadFile` has several advantages over `bytes`:
@@ -116,7 +156,7 @@ Using `UploadFile` has several advantages over `bytes`:
* `filename`: A `str` with the original file name that was uploaded (e.g. `myimage.jpg`).
* `content_type`: A `str` with the content type (MIME type / media type) (e.g. `image/jpeg`).
-* `file`: A `SpooledTemporaryFile` (a file-like object). This is the actual Python file that you can pass directly to other functions or libraries that expect a "file-like" object.
+* `file`: A `SpooledTemporaryFile` (a file-like object). This is the actual Python file object that you can pass directly to other functions or libraries that expect a "file-like" object.
`UploadFile` has the following `async` methods. They all call the corresponding file methods underneath (using the internal `SpooledTemporaryFile`).
@@ -141,11 +181,17 @@ If you are inside of a normal `def` *path operation function*, you can access th
contents = myfile.file.read()
```
-!!! note "`async` Technical Details"
- When you use the `async` methods, **FastAPI** runs the file methods in a threadpool and awaits for them.
+/// note | "`async` Technical Details"
-!!! note "Starlette Technical Details"
- **FastAPI**'s `UploadFile` inherits directly from **Starlette**'s `UploadFile`, but adds some necessary parts to make it compatible with **Pydantic** and the other parts of FastAPI.
+When you use the `async` methods, **FastAPI** runs the file methods in a threadpool and awaits for them.
+
+///
+
+/// note | "Starlette Technical Details"
+
+**FastAPI**'s `UploadFile` inherits directly from **Starlette**'s `UploadFile`, but adds some necessary parts to make it compatible with **Pydantic** and the other parts of FastAPI.
+
+///
## What is "Form Data"
@@ -153,82 +199,113 @@ The way HTML forms (``) sends the data to the server normally uses
**FastAPI** will make sure to read that data from the right place instead of JSON.
-!!! note "Technical Details"
- Data from forms is normally encoded using the "media type" `application/x-www-form-urlencoded` when it doesn't include files.
+/// note | "Technical Details"
- But when the form includes files, it is encoded as `multipart/form-data`. If you use `File`, **FastAPI** will know it has to get the files from the correct part of the body.
+Data from forms is normally encoded using the "media type" `application/x-www-form-urlencoded` when it doesn't include files.
- If you want to read more about these encodings and form fields, head to the MDN web docs for POST.
+But when the form includes files, it is encoded as `multipart/form-data`. If you use `File`, **FastAPI** will know it has to get the files from the correct part of the body.
-!!! warning
- You can declare multiple `File` and `Form` parameters in a *path operation*, but you can't also declare `Body` fields that you expect to receive as JSON, as the request will have the body encoded using `multipart/form-data` instead of `application/json`.
+If you want to read more about these encodings and form fields, head to the MDN web docs for POST.
- This is not a limitation of **FastAPI**, it's part of the HTTP protocol.
+///
+
+/// warning
+
+You can declare multiple `File` and `Form` parameters in a *path operation*, but you can't also declare `Body` fields that you expect to receive as JSON, as the request will have the body encoded using `multipart/form-data` instead of `application/json`.
+
+This is not a limitation of **FastAPI**, it's part of the HTTP protocol.
+
+///
## Optional File Upload
You can make a file optional by using standard type annotations and setting a default value of `None`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9 17"
- {!> ../../../docs_src/request_files/tutorial001_02_an_py310.py!}
- ```
+```Python hl_lines="9 17"
+{!> ../../docs_src/request_files/tutorial001_02_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="9 17"
- {!> ../../../docs_src/request_files/tutorial001_02_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="9 17"
+{!> ../../docs_src/request_files/tutorial001_02_an_py39.py!}
+```
- ```Python hl_lines="10 18"
- {!> ../../../docs_src/request_files/tutorial001_02_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="10 18"
+{!> ../../docs_src/request_files/tutorial001_02_an.py!}
+```
- ```Python hl_lines="7 15"
- {!> ../../../docs_src/request_files/tutorial001_02_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="9 17"
- {!> ../../../docs_src/request_files/tutorial001_02.py!}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="7 15"
+{!> ../../docs_src/request_files/tutorial001_02_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="9 17"
+{!> ../../docs_src/request_files/tutorial001_02.py!}
+```
+
+////
## `UploadFile` with Additional Metadata
You can also use `File()` with `UploadFile`, for example, to set additional metadata:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="9 15"
- {!> ../../../docs_src/request_files/tutorial001_03_an_py39.py!}
- ```
+```Python hl_lines="9 15"
+{!> ../../docs_src/request_files/tutorial001_03_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="8 14"
- {!> ../../../docs_src/request_files/tutorial001_03_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="8 14"
+{!> ../../docs_src/request_files/tutorial001_03_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="7 13"
- {!> ../../../docs_src/request_files/tutorial001_03.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="7 13"
+{!> ../../docs_src/request_files/tutorial001_03.py!}
+```
+
+////
## Multiple File Uploads
@@ -238,76 +315,107 @@ They would be associated to the same "form field" sent using "form data".
To use that, declare a list of `bytes` or `UploadFile`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="10 15"
- {!> ../../../docs_src/request_files/tutorial002_an_py39.py!}
- ```
+```Python hl_lines="10 15"
+{!> ../../docs_src/request_files/tutorial002_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="11 16"
- {!> ../../../docs_src/request_files/tutorial002_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.9+ non-Annotated"
+```Python hl_lines="11 16"
+{!> ../../docs_src/request_files/tutorial002_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="8 13"
- {!> ../../../docs_src/request_files/tutorial002_py39.py!}
- ```
+//// tab | Python 3.9+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip
- !!! tip
- Prefer to use the `Annotated` version if possible.
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="10 15"
- {!> ../../../docs_src/request_files/tutorial002.py!}
- ```
+///
+
+```Python hl_lines="8 13"
+{!> ../../docs_src/request_files/tutorial002_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="10 15"
+{!> ../../docs_src/request_files/tutorial002.py!}
+```
+
+////
You will receive, as declared, a `list` of `bytes` or `UploadFile`s.
-!!! note "Technical Details"
- You could also use `from starlette.responses import HTMLResponse`.
+/// note | "Technical Details"
- **FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette.
+You could also use `from starlette.responses import HTMLResponse`.
+
+**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette.
+
+///
### Multiple File Uploads with Additional Metadata
And the same way as before, you can use `File()` to set additional parameters, even for `UploadFile`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="11 18-20"
- {!> ../../../docs_src/request_files/tutorial003_an_py39.py!}
- ```
+```Python hl_lines="11 18-20"
+{!> ../../docs_src/request_files/tutorial003_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="12 19-21"
- {!> ../../../docs_src/request_files/tutorial003_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.9+ non-Annotated"
+```Python hl_lines="12 19-21"
+{!> ../../docs_src/request_files/tutorial003_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="9 16"
- {!> ../../../docs_src/request_files/tutorial003_py39.py!}
- ```
+//// tab | Python 3.9+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip
- !!! tip
- Prefer to use the `Annotated` version if possible.
+Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="11 18"
- {!> ../../../docs_src/request_files/tutorial003.py!}
- ```
+///
+
+```Python hl_lines="9 16"
+{!> ../../docs_src/request_files/tutorial003_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="11 18"
+{!> ../../docs_src/request_files/tutorial003.py!}
+```
+
+////
## Recap
diff --git a/docs/en/docs/tutorial/request-form-models.md b/docs/en/docs/tutorial/request-form-models.md
new file mode 100644
index 000000000..f1142877a
--- /dev/null
+++ b/docs/en/docs/tutorial/request-form-models.md
@@ -0,0 +1,134 @@
+# Form Models
+
+You can use **Pydantic models** to declare **form fields** in FastAPI.
+
+/// info
+
+To use forms, first install `python-multipart`.
+
+Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install it, for example:
+
+```console
+$ pip install python-multipart
+```
+
+///
+
+/// note
+
+This is supported since FastAPI version `0.113.0`. 🤓
+
+///
+
+## Pydantic Models for Forms
+
+You just need to declare a **Pydantic model** with the fields you want to receive as **form fields**, and then declare the parameter as `Form`:
+
+//// 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!}
+```
+
+////
+
+**FastAPI** will **extract** the data for **each field** from the **form data** in the request and give you the Pydantic model you defined.
+
+## Check the Docs
+
+You can verify it in the docs UI at `/docs`:
+
+
+POST.
+But when the form includes files, it is encoded as `multipart/form-data`. You'll read about handling files in the next chapter.
-!!! warning
- You can declare multiple `Form` parameters in a *path operation*, but you can't also declare `Body` fields that you expect to receive as JSON, as the request will have the body encoded using `application/x-www-form-urlencoded` instead of `application/json`.
+If you want to read more about these encodings and form fields, head to the MDN web docs for POST.
- This is not a limitation of **FastAPI**, it's part of the HTTP protocol.
+///
+
+/// warning
+
+You can declare multiple `Form` parameters in a *path operation*, but you can't also declare `Body` fields that you expect to receive as JSON, as the request will have the body encoded using `application/x-www-form-urlencoded` instead of `application/json`.
+
+This is not a limitation of **FastAPI**, it's part of the HTTP protocol.
+
+///
## Recap
diff --git a/docs/en/docs/tutorial/response-model.md b/docs/en/docs/tutorial/response-model.md
index 75d5df106..36ccfc4ce 100644
--- a/docs/en/docs/tutorial/response-model.md
+++ b/docs/en/docs/tutorial/response-model.md
@@ -4,23 +4,29 @@ You can declare the type used for the response by annotating the *path operation
You can use **type annotations** the same way you would for input data in function **parameters**, you can use Pydantic models, lists, dictionaries, scalar values like integers, booleans, etc.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="16 21"
- {!> ../../../docs_src/response_model/tutorial001_01_py310.py!}
- ```
+```Python hl_lines="16 21"
+{!> ../../docs_src/response_model/tutorial001_01_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="18 23"
- {!> ../../../docs_src/response_model/tutorial001_01_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="18 23"
+{!> ../../docs_src/response_model/tutorial001_01_py39.py!}
+```
- ```Python hl_lines="18 23"
- {!> ../../../docs_src/response_model/tutorial001_01.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="18 23"
+{!> ../../docs_src/response_model/tutorial001_01.py!}
+```
+
+////
FastAPI will use this return type to:
@@ -53,35 +59,47 @@ You can use the `response_model` parameter in any of the *path operations*:
* `@app.delete()`
* etc.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001_py310.py!}
- ```
+```Python hl_lines="17 22 24-27"
+{!> ../../docs_src/response_model/tutorial001_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="17 22 24-27"
+{!> ../../docs_src/response_model/tutorial001_py39.py!}
+```
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001.py!}
- ```
+////
-!!! note
- Notice that `response_model` is a parameter of the "decorator" method (`get`, `post`, etc). Not of your *path operation function*, like all the parameters and body.
+//// tab | Python 3.8+
+
+```Python hl_lines="17 22 24-27"
+{!> ../../docs_src/response_model/tutorial001.py!}
+```
+
+////
+
+/// note
+
+Notice that `response_model` is a parameter of the "decorator" method (`get`, `post`, etc). Not of your *path operation function*, like all the parameters and body.
+
+///
`response_model` receives the same type you would declare for a Pydantic model field, so, it can be a Pydantic model, but it can also be, e.g. a `list` of Pydantic models, like `List[Item]`.
FastAPI will use this `response_model` to do all the data documentation, validation, etc. and also to **convert and filter the output data** to its type declaration.
-!!! tip
- If you have strict type checks in your editor, mypy, etc, you can declare the function return type as `Any`.
+/// tip
- That way you tell the editor that you are intentionally returning anything. But FastAPI will still do the data documentation, validation, filtering, etc. with the `response_model`.
+If you have strict type checks in your editor, mypy, etc, you can declare the function return type as `Any`.
+
+That way you tell the editor that you are intentionally returning anything. But FastAPI will still do the data documentation, validation, filtering, etc. with the `response_model`.
+
+///
### `response_model` Priority
@@ -95,37 +113,57 @@ You can also use `response_model=None` to disable creating a response model for
Here we are declaring a `UserIn` model, it will contain a plaintext password:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7 9"
- {!> ../../../docs_src/response_model/tutorial002_py310.py!}
- ```
+```Python hl_lines="7 9"
+{!> ../../docs_src/response_model/tutorial002_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9 11"
- {!> ../../../docs_src/response_model/tutorial002.py!}
- ```
+//// tab | Python 3.8+
-!!! info
- To use `EmailStr`, first install `email_validator`.
+```Python hl_lines="9 11"
+{!> ../../docs_src/response_model/tutorial002.py!}
+```
- E.g. `pip install email-validator`
- or `pip install pydantic[email]`.
+////
+
+/// info
+
+To use `EmailStr`, first install `email-validator`.
+
+Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install it, for example:
+
+```console
+$ pip install email-validator
+```
+
+or with:
+
+```console
+$ pip install "pydantic[email]"
+```
+
+///
And we are using this model to declare our input and the same model to declare our output:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="16"
- {!> ../../../docs_src/response_model/tutorial002_py310.py!}
- ```
+```Python hl_lines="16"
+{!> ../../docs_src/response_model/tutorial002_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="18"
- {!> ../../../docs_src/response_model/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="18"
+{!> ../../docs_src/response_model/tutorial002.py!}
+```
+
+////
Now, whenever a browser is creating a user with a password, the API will return the same password in the response.
@@ -133,52 +171,67 @@ In this case, it might not be a problem, because it's the same user sending the
But if we use the same model for another *path operation*, we could be sending our user's passwords to every client.
-!!! danger
- Never store the plain password of a user or send it in a response like this, unless you know all the caveats and you know what you are doing.
+/// danger
+
+Never store the plain password of a user or send it in a response like this, unless you know all the caveats and you know what you are doing.
+
+///
## Add an output model
We can instead create an input model with the plaintext password and an output model without it:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9 11 16"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
+```Python hl_lines="9 11 16"
+{!> ../../docs_src/response_model/tutorial003_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9 11 16"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="9 11 16"
+{!> ../../docs_src/response_model/tutorial003.py!}
+```
+
+////
Here, even though our *path operation function* is returning the same input user that contains the password:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
+```Python hl_lines="24"
+{!> ../../docs_src/response_model/tutorial003_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="24"
+{!> ../../docs_src/response_model/tutorial003.py!}
+```
+
+////
...we declared the `response_model` to be our model `UserOut`, that doesn't include the password:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
+```Python hl_lines="22"
+{!> ../../docs_src/response_model/tutorial003_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="22"
+{!> ../../docs_src/response_model/tutorial003.py!}
+```
+
+////
So, **FastAPI** will take care of filtering out all the data that is not declared in the output model (using Pydantic).
@@ -192,9 +245,9 @@ That's why in this example we have to declare it in the `response_model` paramet
## Return Type and Data Filtering
-Let's continue from the previous example. We wanted to **annotate the function with one type** but return something that includes **more data**.
+Let's continue from the previous example. We wanted to **annotate the function with one type**, but we wanted to be able to return from the function something that actually includes **more data**.
-We want FastAPI to keep **filtering** the data using the response model.
+We want FastAPI to keep **filtering** the data using the response model. So that even though the function returns more data, the response will only include the fields declared in the response model.
In the previous example, because the classes were different, we had to use the `response_model` parameter. But that also means that we don't get the support from the editor and tools checking the function return type.
@@ -202,17 +255,21 @@ But in most of the cases where we need to do something like this, we want the mo
And in those cases, we can use classes and inheritance to take advantage of function **type annotations** to get better support in the editor and tools, and still get the FastAPI **data filtering**.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7-10 13-14 18"
- {!> ../../../docs_src/response_model/tutorial003_01_py310.py!}
- ```
+```Python hl_lines="7-10 13-14 18"
+{!> ../../docs_src/response_model/tutorial003_01_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9-13 15-16 20"
- {!> ../../../docs_src/response_model/tutorial003_01.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="9-13 15-16 20"
+{!> ../../docs_src/response_model/tutorial003_01.py!}
+```
+
+////
With this, we get tooling support, from editors and mypy as this code is correct in terms of types, but we also get the data filtering from FastAPI.
@@ -255,10 +312,10 @@ 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!}
```
-This simple case is handled automatically by FastAPI because the return type annotation is the class (or a subclass) of `Response`.
+This simple case is handled automatically by FastAPI because the return type annotation is the class (or a subclass of) `Response`.
And tools will also be happy because both `RedirectResponse` and `JSONResponse` are subclasses of `Response`, so the type annotation is correct.
@@ -267,7 +324,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!}
```
This will also work because `RedirectResponse` is a subclass of `Response`, and FastAPI will automatically handle this simple case.
@@ -278,17 +335,21 @@ But when you return some other arbitrary object that is not a valid Pydantic typ
The same would happen if you had something like a union between different types where one or more of them are not valid Pydantic types, for example this would fail 💥:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="8"
- {!> ../../../docs_src/response_model/tutorial003_04_py310.py!}
- ```
+```Python hl_lines="8"
+{!> ../../docs_src/response_model/tutorial003_04_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/response_model/tutorial003_04.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="10"
+{!> ../../docs_src/response_model/tutorial003_04.py!}
+```
+
+////
...this fails because the type annotation is not a Pydantic type and is not just a single `Response` class or subclass, it's a union (any of the two) between a `Response` and a `dict`.
@@ -300,17 +361,21 @@ But you might want to still keep the return type annotation in the function to g
In this case, you can disable the response model generation by setting `response_model=None`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7"
- {!> ../../../docs_src/response_model/tutorial003_05_py310.py!}
- ```
+```Python hl_lines="7"
+{!> ../../docs_src/response_model/tutorial003_05_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/response_model/tutorial003_05.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../docs_src/response_model/tutorial003_05.py!}
+```
+
+////
This will make FastAPI skip the response model generation and that way you can have any return type annotations you need without it affecting your FastAPI application. 🤓
@@ -318,23 +383,29 @@ This will make FastAPI skip the response model generation and that way you can h
Your response model could have default values, like:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9 11-12"
- {!> ../../../docs_src/response_model/tutorial004_py310.py!}
- ```
+```Python hl_lines="9 11-12"
+{!> ../../docs_src/response_model/tutorial004_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="11 13-14"
- {!> ../../../docs_src/response_model/tutorial004_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="11 13-14"
+{!> ../../docs_src/response_model/tutorial004_py39.py!}
+```
- ```Python hl_lines="11 13-14"
- {!> ../../../docs_src/response_model/tutorial004.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="11 13-14"
+{!> ../../docs_src/response_model/tutorial004.py!}
+```
+
+////
* `description: Union[str, None] = None` (or `str | None = None` in Python 3.10) has a default of `None`.
* `tax: float = 10.5` has a default of `10.5`.
@@ -348,23 +419,29 @@ For example, if you have models with many optional attributes in a NoSQL databas
You can set the *path operation decorator* parameter `response_model_exclude_unset=True`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial004_py310.py!}
- ```
+```Python hl_lines="22"
+{!> ../../docs_src/response_model/tutorial004_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial004_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="24"
+{!> ../../docs_src/response_model/tutorial004_py39.py!}
+```
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial004.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="24"
+{!> ../../docs_src/response_model/tutorial004.py!}
+```
+
+////
and those default values won't be included in the response, only the values actually set.
@@ -377,21 +454,30 @@ So, if you send a request to that *path operation* for the item with ID `foo`, t
}
```
-!!! info
- In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`.
+/// info
- The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2.
+In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`.
-!!! info
- FastAPI uses Pydantic model's `.dict()` with its `exclude_unset` parameter to achieve this.
+The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2.
-!!! info
- You can also use:
+///
- * `response_model_exclude_defaults=True`
- * `response_model_exclude_none=True`
+/// info
- as described in the Pydantic docs for `exclude_defaults` and `exclude_none`.
+FastAPI uses Pydantic model's `.dict()` with its `exclude_unset` parameter to achieve this.
+
+///
+
+/// info
+
+You can also use:
+
+* `response_model_exclude_defaults=True`
+* `response_model_exclude_none=True`
+
+as described in the Pydantic docs for `exclude_defaults` and `exclude_none`.
+
+///
#### Data with values for fields with defaults
@@ -426,10 +512,13 @@ FastAPI is smart enough (actually, Pydantic is smart enough) to realize that, ev
So, they will be included in the JSON response.
-!!! tip
- Notice that the default values can be anything, not only `None`.
+/// tip
- They can be a list (`[]`), a `float` of `10.5`, etc.
+Notice that the default values can be anything, not only `None`.
+
+They can be a list (`[]`), a `float` of `10.5`, etc.
+
+///
### `response_model_include` and `response_model_exclude`
@@ -439,45 +528,59 @@ They take a `set` of `str` with the name of the attributes to include (omitting
This can be used as a quick shortcut if you have only one Pydantic model and want to remove some data from the output.
-!!! tip
- But it is still recommended to use the ideas above, using multiple classes, instead of these parameters.
+/// tip
- This is because the JSON Schema generated in your app's OpenAPI (and the docs) will still be the one for the complete model, even if you use `response_model_include` or `response_model_exclude` to omit some attributes.
+But it is still recommended to use the ideas above, using multiple classes, instead of these parameters.
- This also applies to `response_model_by_alias` that works similarly.
+This is because the JSON Schema generated in your app's OpenAPI (and the docs) will still be the one for the complete model, even if you use `response_model_include` or `response_model_exclude` to omit some attributes.
-=== "Python 3.10+"
+This also applies to `response_model_by_alias` that works similarly.
- ```Python hl_lines="29 35"
- {!> ../../../docs_src/response_model/tutorial005_py310.py!}
- ```
+///
-=== "Python 3.8+"
+//// tab | Python 3.10+
- ```Python hl_lines="31 37"
- {!> ../../../docs_src/response_model/tutorial005.py!}
- ```
+```Python hl_lines="29 35"
+{!> ../../docs_src/response_model/tutorial005_py310.py!}
+```
-!!! tip
- The syntax `{"name", "description"}` creates a `set` with those two values.
+////
- It is equivalent to `set(["name", "description"])`.
+//// tab | Python 3.8+
+
+```Python hl_lines="31 37"
+{!> ../../docs_src/response_model/tutorial005.py!}
+```
+
+////
+
+/// tip
+
+The syntax `{"name", "description"}` creates a `set` with those two values.
+
+It is equivalent to `set(["name", "description"])`.
+
+///
#### Using `list`s instead of `set`s
If you forget to use a `set` and use a `list` or `tuple` instead, FastAPI will still convert it to a `set` and it will work correctly:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="29 35"
- {!> ../../../docs_src/response_model/tutorial006_py310.py!}
- ```
+```Python hl_lines="29 35"
+{!> ../../docs_src/response_model/tutorial006_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="31 37"
- {!> ../../../docs_src/response_model/tutorial006.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="31 37"
+{!> ../../docs_src/response_model/tutorial006.py!}
+```
+
+////
## Recap
diff --git a/docs/en/docs/tutorial/response-status-code.md b/docs/en/docs/tutorial/response-status-code.md
index 646378aa1..73af62aed 100644
--- a/docs/en/docs/tutorial/response-status-code.md
+++ b/docs/en/docs/tutorial/response-status-code.md
@@ -9,16 +9,22 @@ The same way you can specify a response model, you can also declare the HTTP sta
* etc.
```Python hl_lines="6"
-{!../../../docs_src/response_status_code/tutorial001.py!}
+{!../../docs_src/response_status_code/tutorial001.py!}
```
-!!! note
- Notice that `status_code` is a parameter of the "decorator" method (`get`, `post`, etc). Not of your *path operation function*, like all the parameters and body.
+/// note
+
+Notice that `status_code` is a parameter of the "decorator" method (`get`, `post`, etc). Not of your *path operation function*, like all the parameters and body.
+
+///
The `status_code` parameter receives a number with the HTTP status code.
-!!! info
- `status_code` can alternatively also receive an `IntEnum`, such as Python's `http.HTTPStatus`.
+/// info
+
+`status_code` can alternatively also receive an `IntEnum`, such as Python's `http.HTTPStatus`.
+
+///
It will:
@@ -27,15 +33,21 @@ It will:
-!!! note
- Some response codes (see the next section) indicate that the response does not have a body.
+/// note
- FastAPI knows this, and will produce OpenAPI docs that state there is no response body.
+Some response codes (see the next section) indicate that the response does not have a body.
+
+FastAPI knows this, and will produce OpenAPI docs that state there is no response body.
+
+///
## About HTTP status codes
-!!! note
- If you already know what HTTP status codes are, skip to the next section.
+/// note
+
+If you already know what HTTP status codes are, skip to the next section.
+
+///
In HTTP, you send a numeric status code of 3 digits as part of the response.
@@ -54,15 +66,18 @@ In short:
* For generic errors from the client, you can just use `400`.
* `500` and above are for server errors. You almost never use them directly. When something goes wrong at some part in your application code, or server, it will automatically return one of these status codes.
-!!! tip
- To know more about each status code and which code is for what, check the MDN documentation about HTTP status codes.
+/// tip
+
+To know more about each status code and which code is for what, check the MDN documentation about HTTP status codes.
+
+///
## Shortcut to remember the names
Let's see the previous example again:
```Python hl_lines="6"
-{!../../../docs_src/response_status_code/tutorial001.py!}
+{!../../docs_src/response_status_code/tutorial001.py!}
```
`201` is the status code for "Created".
@@ -72,17 +87,20 @@ But you don't have to memorize what each of these codes mean.
You can use the convenience variables from `fastapi.status`.
```Python hl_lines="1 6"
-{!../../../docs_src/response_status_code/tutorial002.py!}
+{!../../docs_src/response_status_code/tutorial002.py!}
```
They are just a convenience, they hold the same number, but that way you can use the editor's autocomplete to find them:
-!!! note "Technical Details"
- You could also use `from starlette import status`.
+/// note | "Technical Details"
- **FastAPI** provides the same `starlette.status` as `fastapi.status` just as a convenience for you, the developer. But it comes directly from Starlette.
+You could also use `from starlette import status`.
+
+**FastAPI** provides the same `starlette.status` as `fastapi.status` just as a convenience for you, the developer. But it comes directly from Starlette.
+
+///
## Changing the default
diff --git a/docs/en/docs/tutorial/schema-extra-example.md b/docs/en/docs/tutorial/schema-extra-example.md
index 40231dc0b..5896b54d9 100644
--- a/docs/en/docs/tutorial/schema-extra-example.md
+++ b/docs/en/docs/tutorial/schema-extra-example.md
@@ -8,71 +8,93 @@ Here are several ways to do it.
You can declare `examples` for a Pydantic model that will be added to the generated JSON Schema.
-=== "Python 3.10+ Pydantic v2"
+//// tab | Python 3.10+ Pydantic v2
- ```Python hl_lines="13-24"
- {!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!}
- ```
+```Python hl_lines="13-24"
+{!> ../../docs_src/schema_extra_example/tutorial001_py310.py!}
+```
-=== "Python 3.10+ Pydantic v1"
+////
- ```Python hl_lines="13-23"
- {!> ../../../docs_src/schema_extra_example/tutorial001_py310_pv1.py!}
- ```
+//// tab | Python 3.10+ Pydantic v1
-=== "Python 3.8+ Pydantic v2"
+```Python hl_lines="13-23"
+{!> ../../docs_src/schema_extra_example/tutorial001_py310_pv1.py!}
+```
- ```Python hl_lines="15-26"
- {!> ../../../docs_src/schema_extra_example/tutorial001.py!}
- ```
+////
-=== "Python 3.8+ Pydantic v1"
+//// tab | Python 3.8+ Pydantic v2
- ```Python hl_lines="15-25"
- {!> ../../../docs_src/schema_extra_example/tutorial001_pv1.py!}
- ```
+```Python hl_lines="15-26"
+{!> ../../docs_src/schema_extra_example/tutorial001.py!}
+```
+
+////
+
+//// tab | Python 3.8+ Pydantic v1
+
+```Python hl_lines="15-25"
+{!> ../../docs_src/schema_extra_example/tutorial001_pv1.py!}
+```
+
+////
That extra info will be added as-is to the output **JSON Schema** for that model, and it will be used in the API docs.
-=== "Pydantic v2"
+//// tab | Pydantic v2
- In Pydantic version 2, you would use the attribute `model_config`, that takes a `dict` as described in Pydantic's docs: Model Config.
+In Pydantic version 2, you would use the attribute `model_config`, that takes a `dict` as described in Pydantic's docs: Configuration.
- You can set `"json_schema_extra"` with a `dict` containing any additional data you would like to show up in the generated JSON Schema, including `examples`.
+You can set `"json_schema_extra"` with a `dict` containing any additional data you would like to show up in the generated JSON Schema, including `examples`.
-=== "Pydantic v1"
+////
- In Pydantic version 1, you would use an internal class `Config` and `schema_extra`, as described in Pydantic's docs: Schema customization.
+//// tab | Pydantic v1
- You can set `schema_extra` with a `dict` containing any additional data you would like to show up in the generated JSON Schema, including `examples`.
+In Pydantic version 1, you would use an internal class `Config` and `schema_extra`, as described in Pydantic's docs: Schema customization.
-!!! tip
- You could use the same technique to extend the JSON Schema and add your own custom extra info.
+You can set `schema_extra` with a `dict` containing any additional data you would like to show up in the generated JSON Schema, including `examples`.
- For example you could use it to add metadata for a frontend user interface, etc.
+////
-!!! info
- OpenAPI 3.1.0 (used since FastAPI 0.99.0) added support for `examples`, which is part of the **JSON Schema** standard.
+/// tip
- Before that, it only supported the keyword `example` with a single example. That is still supported by OpenAPI 3.1.0, but is deprecated and is not part of the JSON Schema standard. So you are encouraged to migrate `example` to `examples`. 🤓
+You could use the same technique to extend the JSON Schema and add your own custom extra info.
- You can read more at the end of this page.
+For example you could use it to add metadata for a frontend user interface, etc.
+
+///
+
+/// info
+
+OpenAPI 3.1.0 (used since FastAPI 0.99.0) added support for `examples`, which is part of the **JSON Schema** standard.
+
+Before that, it only supported the keyword `example` with a single example. That is still supported by OpenAPI 3.1.0, but is deprecated and is not part of the JSON Schema standard. So you are encouraged to migrate `example` to `examples`. 🤓
+
+You can read more at the end of this page.
+
+///
## `Field` additional arguments
When using `Field()` with Pydantic models, you can also declare additional `examples`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="2 8-11"
- {!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!}
- ```
+```Python hl_lines="2 8-11"
+{!> ../../docs_src/schema_extra_example/tutorial002_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="4 10-13"
- {!> ../../../docs_src/schema_extra_example/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="4 10-13"
+{!> ../../docs_src/schema_extra_example/tutorial002.py!}
+```
+
+////
## `examples` in JSON Schema - OpenAPI
@@ -92,41 +114,57 @@ you can also declare a group of `examples` with additional information that will
Here we pass `examples` containing one example of the data expected in `Body()`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="22-29"
- {!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!}
- ```
+```Python hl_lines="22-29"
+{!> ../../docs_src/schema_extra_example/tutorial003_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="22-29"
- {!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="22-29"
+{!> ../../docs_src/schema_extra_example/tutorial003_an_py39.py!}
+```
- ```Python hl_lines="23-30"
- {!> ../../../docs_src/schema_extra_example/tutorial003_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="23-30"
+{!> ../../docs_src/schema_extra_example/tutorial003_an.py!}
+```
- ```Python hl_lines="18-25"
- {!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="20-27"
- {!> ../../../docs_src/schema_extra_example/tutorial003.py!}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="18-25"
+{!> ../../docs_src/schema_extra_example/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="20-27"
+{!> ../../docs_src/schema_extra_example/tutorial003.py!}
+```
+
+////
### Example in the docs UI
@@ -138,41 +176,57 @@ With any of the methods above it would look like this in the `/docs`:
You can of course also pass multiple `examples`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="23-38"
- {!> ../../../docs_src/schema_extra_example/tutorial004_an_py310.py!}
- ```
+```Python hl_lines="23-38"
+{!> ../../docs_src/schema_extra_example/tutorial004_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="23-38"
- {!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="23-38"
+{!> ../../docs_src/schema_extra_example/tutorial004_an_py39.py!}
+```
- ```Python hl_lines="24-39"
- {!> ../../../docs_src/schema_extra_example/tutorial004_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="24-39"
+{!> ../../docs_src/schema_extra_example/tutorial004_an.py!}
+```
- ```Python hl_lines="19-34"
- {!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="21-36"
- {!> ../../../docs_src/schema_extra_example/tutorial004.py!}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="19-34"
+{!> ../../docs_src/schema_extra_example/tutorial004_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="21-36"
+{!> ../../docs_src/schema_extra_example/tutorial004.py!}
+```
+
+////
When you do this, the examples will be part of the internal **JSON Schema** for that body data.
@@ -213,41 +267,57 @@ Each specific example `dict` in the `examples` can contain:
You can use it like this:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="23-49"
- {!> ../../../docs_src/schema_extra_example/tutorial005_an_py310.py!}
- ```
+```Python hl_lines="23-49"
+{!> ../../docs_src/schema_extra_example/tutorial005_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="23-49"
- {!> ../../../docs_src/schema_extra_example/tutorial005_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="23-49"
+{!> ../../docs_src/schema_extra_example/tutorial005_an_py39.py!}
+```
- ```Python hl_lines="24-50"
- {!> ../../../docs_src/schema_extra_example/tutorial005_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="24-50"
+{!> ../../docs_src/schema_extra_example/tutorial005_an.py!}
+```
- ```Python hl_lines="19-45"
- {!> ../../../docs_src/schema_extra_example/tutorial005_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="21-47"
- {!> ../../../docs_src/schema_extra_example/tutorial005.py!}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="19-45"
+{!> ../../docs_src/schema_extra_example/tutorial005_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="21-47"
+{!> ../../docs_src/schema_extra_example/tutorial005.py!}
+```
+
+////
### OpenAPI Examples in the Docs UI
@@ -257,21 +327,27 @@ With `openapi_examples` added to `Body()` the `/docs` would look like:
## Technical Details
-!!! tip
- If you are already using **FastAPI** version **0.99.0 or above**, you can probably **skip** these details.
+/// tip
- They are more relevant for older versions, before OpenAPI 3.1.0 was available.
+If you are already using **FastAPI** version **0.99.0 or above**, you can probably **skip** these details.
- You can consider this a brief OpenAPI and JSON Schema **history lesson**. 🤓
+They are more relevant for older versions, before OpenAPI 3.1.0 was available.
-!!! warning
- These are very technical details about the standards **JSON Schema** and **OpenAPI**.
+You can consider this a brief OpenAPI and JSON Schema **history lesson**. 🤓
- If the ideas above already work for you, that might be enough, and you probably don't need these details, feel free to skip them.
+///
+
+/// warning
+
+These are very technical details about the standards **JSON Schema** and **OpenAPI**.
+
+If the ideas above already work for you, that might be enough, and you probably don't need these details, feel free to skip them.
+
+///
Before OpenAPI 3.1.0, OpenAPI used an older and modified version of **JSON Schema**.
-JSON Schema didn't have `examples`, so OpenAPI added it's own `example` field to its own modified version.
+JSON Schema didn't have `examples`, so OpenAPI added its own `example` field to its own modified version.
OpenAPI also added `example` and `examples` fields to other parts of the specification:
@@ -285,8 +361,11 @@ OpenAPI also added `example` and `examples` fields to other parts of the specifi
* `File()`
* `Form()`
-!!! info
- This old OpenAPI-specific `examples` parameter is now `openapi_examples` since FastAPI `0.103.0`.
+/// info
+
+This old OpenAPI-specific `examples` parameter is now `openapi_examples` since FastAPI `0.103.0`.
+
+///
### JSON Schema's `examples` field
@@ -298,10 +377,13 @@ And now this new `examples` field takes precedence over the old single (and cust
This new `examples` field in JSON Schema is **just a `list`** of examples, not a dict with extra metadata as in the other places in OpenAPI (described above).
-!!! info
- Even after OpenAPI 3.1.0 was released with this new simpler integration with JSON Schema, for a while, Swagger UI, the tool that provides the automatic docs, didn't support OpenAPI 3.1.0 (it does since version 5.0.0 🎉).
+/// info
- Because of that, versions of FastAPI previous to 0.99.0 still used versions of OpenAPI lower than 3.1.0.
+Even after OpenAPI 3.1.0 was released with this new simpler integration with JSON Schema, for a while, Swagger UI, the tool that provides the automatic docs, didn't support OpenAPI 3.1.0 (it does since version 5.0.0 🎉).
+
+Because of that, versions of FastAPI previous to 0.99.0 still used versions of OpenAPI lower than 3.1.0.
+
+///
### Pydantic and FastAPI `examples`
diff --git a/docs/en/docs/tutorial/security/first-steps.md b/docs/en/docs/tutorial/security/first-steps.md
index d8682a054..ead2aa799 100644
--- a/docs/en/docs/tutorial/security/first-steps.md
+++ b/docs/en/docs/tutorial/security/first-steps.md
@@ -20,38 +20,53 @@ Let's first just use the code and see how it works, and then we'll come back to
Copy the example in a file `main.py`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python
- {!> ../../../docs_src/security/tutorial001_an_py39.py!}
- ```
+```Python
+{!> ../../docs_src/security/tutorial001_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python
- {!> ../../../docs_src/security/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python
+{!> ../../docs_src/security/tutorial001_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python
- {!> ../../../docs_src/security/tutorial001.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python
+{!> ../../docs_src/security/tutorial001.py!}
+```
+
+////
## Run it
-!!! info
- The `python-multipart` package is automatically installed with **FastAPI** when you run the `pip install "fastapi[standard]"` command.
+/// info
- However, if you use the `pip install fastapi` command, the `python-multipart` package is not included by default. To install it manually, use the following command:
+The `python-multipart` package is automatically installed with **FastAPI** when you run the `pip install "fastapi[standard]"` command.
- `pip install python-multipart`
+However, if you use the `pip install fastapi` command, the `python-multipart` package is not included by default.
- This is because **OAuth2** uses "form data" for sending the `username` and `password`.
+To install it manually, make sure you create a [virtual environment](../../virtual-environments.md){.internal-link target=_blank}, activate it, and then install it with:
+
+```console
+$ pip install python-multipart
+```
+
+This is because **OAuth2** uses "form data" for sending the `username` and `password`.
+
+///
Run the example with:
@@ -73,17 +88,23 @@ You will see something like this:
-!!! check "Authorize button!"
- You already have a shiny new "Authorize" button.
+/// check | "Authorize button!"
- And your *path operation* has a little lock in the top-right corner that you can click.
+You already have a shiny new "Authorize" button.
+
+And your *path operation* has a little lock in the top-right corner that you can click.
+
+///
And if you click it, you have a little authorization form to type a `username` and `password` (and other optional fields):
-!!! note
- It doesn't matter what you type in the form, it won't work yet. But we'll get there.
+/// note
+
+It doesn't matter what you type in the form, it won't work yet. But we'll get there.
+
+///
This is of course not the frontend for the final users, but it's a great automatic tool to document interactively all your API.
@@ -125,53 +146,71 @@ So, let's review it from that simplified point of view:
In this example we are going to use **OAuth2**, with the **Password** flow, using a **Bearer** token. We do that using the `OAuth2PasswordBearer` class.
-!!! info
- A "bearer" token is not the only option.
+/// info
- But it's the best one for our use case.
+A "bearer" token is not the only option.
- And it might be the best for most use cases, unless you are an OAuth2 expert and know exactly why there's another option that suits better your needs.
+But it's the best one for our use case.
- In that case, **FastAPI** also provides you with the tools to build it.
+And it might be the best for most use cases, unless you are an OAuth2 expert and know exactly why there's another option that better suits your needs.
+
+In that case, **FastAPI** also provides you with the tools to build it.
+
+///
When we create an instance of the `OAuth2PasswordBearer` class we pass in the `tokenUrl` parameter. This parameter contains the URL that the client (the frontend running in the user's browser) will use to send the `username` and `password` in order to get a token.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="8"
- {!> ../../../docs_src/security/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="8"
+{!> ../../docs_src/security/tutorial001_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/security/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="7"
+{!> ../../docs_src/security/tutorial001_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="6"
- {!> ../../../docs_src/security/tutorial001.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-!!! tip
- Here `tokenUrl="token"` refers to a relative URL `token` that we haven't created yet. As it's a relative URL, it's equivalent to `./token`.
+/// tip
- Because we are using a relative URL, if your API was located at `https://example.com/`, then it would refer to `https://example.com/token`. But if your API was located at `https://example.com/api/v1/`, then it would refer to `https://example.com/api/v1/token`.
+Prefer to use the `Annotated` version if possible.
- Using a relative URL is important to make sure your application keeps working even in an advanced use case like [Behind a Proxy](../../advanced/behind-a-proxy.md){.internal-link target=_blank}.
+///
+
+```Python hl_lines="6"
+{!> ../../docs_src/security/tutorial001.py!}
+```
+
+////
+
+/// tip
+
+Here `tokenUrl="token"` refers to a relative URL `token` that we haven't created yet. As it's a relative URL, it's equivalent to `./token`.
+
+Because we are using a relative URL, if your API was located at `https://example.com/`, then it would refer to `https://example.com/token`. But if your API was located at `https://example.com/api/v1/`, then it would refer to `https://example.com/api/v1/token`.
+
+Using a relative URL is important to make sure your application keeps working even in an advanced use case like [Behind a Proxy](../../advanced/behind-a-proxy.md){.internal-link target=_blank}.
+
+///
This parameter doesn't create that endpoint / *path operation*, but declares that the URL `/token` will be the one that the client should use to get the token. That information is used in OpenAPI, and then in the interactive API documentation systems.
We will soon also create the actual path operation.
-!!! info
- If you are a very strict "Pythonista" you might dislike the style of the parameter name `tokenUrl` instead of `token_url`.
+/// info
- That's because it is using the same name as in the OpenAPI spec. So that if you need to investigate more about any of these security schemes you can just copy and paste it to find more information about it.
+If you are a very strict "Pythonista" you might dislike the style of the parameter name `tokenUrl` instead of `token_url`.
+
+That's because it is using the same name as in the OpenAPI spec. So that if you need to investigate more about any of these security schemes you can just copy and paste it to find more information about it.
+
+///
The `oauth2_scheme` variable is an instance of `OAuth2PasswordBearer`, but it is also a "callable".
@@ -187,35 +226,47 @@ So, it can be used with `Depends`.
Now you can pass that `oauth2_scheme` in a dependency with `Depends`.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="12"
- {!> ../../../docs_src/security/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="12"
+{!> ../../docs_src/security/tutorial001_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="11"
- {!> ../../../docs_src/security/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="11"
+{!> ../../docs_src/security/tutorial001_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/security/tutorial001.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="10"
+{!> ../../docs_src/security/tutorial001.py!}
+```
+
+////
This dependency will provide a `str` that is assigned to the parameter `token` of the *path operation function*.
**FastAPI** will know that it can use this dependency to define a "security scheme" in the OpenAPI schema (and the automatic API docs).
-!!! info "Technical Details"
- **FastAPI** will know that it can use the class `OAuth2PasswordBearer` (declared in a dependency) to define the security scheme in OpenAPI because it inherits from `fastapi.security.oauth2.OAuth2`, which in turn inherits from `fastapi.security.base.SecurityBase`.
+/// info | "Technical Details"
- All the security utilities that integrate with OpenAPI (and the automatic API docs) inherit from `SecurityBase`, that's how **FastAPI** can know how to integrate them in OpenAPI.
+**FastAPI** will know that it can use the class `OAuth2PasswordBearer` (declared in a dependency) to define the security scheme in OpenAPI because it inherits from `fastapi.security.oauth2.OAuth2`, which in turn inherits from `fastapi.security.base.SecurityBase`.
+
+All the security utilities that integrate with OpenAPI (and the automatic API docs) inherit from `SecurityBase`, that's how **FastAPI** can know how to integrate them in OpenAPI.
+
+///
## What it does
diff --git a/docs/en/docs/tutorial/security/get-current-user.md b/docs/en/docs/tutorial/security/get-current-user.md
index dc6d87c9c..069806621 100644
--- a/docs/en/docs/tutorial/security/get-current-user.md
+++ b/docs/en/docs/tutorial/security/get-current-user.md
@@ -2,26 +2,35 @@
In the previous chapter the security system (which is based on the dependency injection system) was giving the *path operation function* a `token` as a `str`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="12"
- {!> ../../../docs_src/security/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="12"
+{!> ../../docs_src/security/tutorial001_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="11"
- {!> ../../../docs_src/security/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="11"
+{!> ../../docs_src/security/tutorial001_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/security/tutorial001.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="10"
+{!> ../../docs_src/security/tutorial001.py!}
+```
+
+////
But that is still not that useful.
@@ -33,41 +42,57 @@ First, let's create a Pydantic user model.
The same way we use Pydantic to declare bodies, we can use it anywhere else:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="5 12-16"
- {!> ../../../docs_src/security/tutorial002_an_py310.py!}
- ```
+```Python hl_lines="5 12-16"
+{!> ../../docs_src/security/tutorial002_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="5 12-16"
- {!> ../../../docs_src/security/tutorial002_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="5 12-16"
+{!> ../../docs_src/security/tutorial002_an_py39.py!}
+```
- ```Python hl_lines="5 13-17"
- {!> ../../../docs_src/security/tutorial002_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="5 13-17"
+{!> ../../docs_src/security/tutorial002_an.py!}
+```
- ```Python hl_lines="3 10-14"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="5 12-16"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="3 10-14"
+{!> ../../docs_src/security/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="5 12-16"
+{!> ../../docs_src/security/tutorial002.py!}
+```
+
+////
## Create a `get_current_user` dependency
@@ -79,135 +104,189 @@ Remember that dependencies can have sub-dependencies?
The same as we were doing before in the *path operation* directly, our new dependency `get_current_user` will receive a `token` as a `str` from the sub-dependency `oauth2_scheme`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="25"
- {!> ../../../docs_src/security/tutorial002_an_py310.py!}
- ```
+```Python hl_lines="25"
+{!> ../../docs_src/security/tutorial002_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="25"
- {!> ../../../docs_src/security/tutorial002_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="25"
+{!> ../../docs_src/security/tutorial002_an_py39.py!}
+```
- ```Python hl_lines="26"
- {!> ../../../docs_src/security/tutorial002_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="26"
+{!> ../../docs_src/security/tutorial002_an.py!}
+```
- ```Python hl_lines="23"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="25"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="23"
+{!> ../../docs_src/security/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="25"
+{!> ../../docs_src/security/tutorial002.py!}
+```
+
+////
## Get the user
`get_current_user` will use a (fake) utility function we created, that takes a token as a `str` and returns our Pydantic `User` model:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="19-22 26-27"
- {!> ../../../docs_src/security/tutorial002_an_py310.py!}
- ```
+```Python hl_lines="19-22 26-27"
+{!> ../../docs_src/security/tutorial002_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="19-22 26-27"
- {!> ../../../docs_src/security/tutorial002_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="19-22 26-27"
+{!> ../../docs_src/security/tutorial002_an_py39.py!}
+```
- ```Python hl_lines="20-23 27-28"
- {!> ../../../docs_src/security/tutorial002_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="20-23 27-28"
+{!> ../../docs_src/security/tutorial002_an.py!}
+```
- ```Python hl_lines="17-20 24-25"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="19-22 26-27"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="17-20 24-25"
+{!> ../../docs_src/security/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="19-22 26-27"
+{!> ../../docs_src/security/tutorial002.py!}
+```
+
+////
## Inject the current user
So now we can use the same `Depends` with our `get_current_user` in the *path operation*:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="31"
- {!> ../../../docs_src/security/tutorial002_an_py310.py!}
- ```
+```Python hl_lines="31"
+{!> ../../docs_src/security/tutorial002_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="31"
- {!> ../../../docs_src/security/tutorial002_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="31"
+{!> ../../docs_src/security/tutorial002_an_py39.py!}
+```
- ```Python hl_lines="32"
- {!> ../../../docs_src/security/tutorial002_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="32"
+{!> ../../docs_src/security/tutorial002_an.py!}
+```
- ```Python hl_lines="29"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="31"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="29"
+{!> ../../docs_src/security/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="31"
+{!> ../../docs_src/security/tutorial002.py!}
+```
+
+////
Notice that we declare the type of `current_user` as the Pydantic model `User`.
This will help us inside of the function with all the completion and type checks.
-!!! tip
- You might remember that request bodies are also declared with Pydantic models.
+/// tip
- Here **FastAPI** won't get confused because you are using `Depends`.
+You might remember that request bodies are also declared with Pydantic models.
-!!! check
- The way this dependency system is designed allows us to have different dependencies (different "dependables") that all return a `User` model.
+Here **FastAPI** won't get confused because you are using `Depends`.
- We are not restricted to having only one dependency that can return that type of data.
+///
+
+/// check
+
+The way this dependency system is designed allows us to have different dependencies (different "dependables") that all return a `User` model.
+
+We are not restricted to having only one dependency that can return that type of data.
+
+///
## Other models
@@ -237,45 +316,61 @@ And you can make it as complex as you want. And still, have it written only once
But you can have thousands of endpoints (*path operations*) using the same security system.
-And all of them (or any portion of them that you want) can take the advantage of re-using these dependencies or any other dependencies you create.
+And all of them (or any portion of them that you want) can take advantage of re-using these dependencies or any other dependencies you create.
And all these thousands of *path operations* can be as small as 3 lines:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="30-32"
- {!> ../../../docs_src/security/tutorial002_an_py310.py!}
- ```
+```Python hl_lines="30-32"
+{!> ../../docs_src/security/tutorial002_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="30-32"
- {!> ../../../docs_src/security/tutorial002_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="30-32"
+{!> ../../docs_src/security/tutorial002_an_py39.py!}
+```
- ```Python hl_lines="31-33"
- {!> ../../../docs_src/security/tutorial002_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="31-33"
+{!> ../../docs_src/security/tutorial002_an.py!}
+```
- ```Python hl_lines="28-30"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="30-32"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="28-30"
+{!> ../../docs_src/security/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="30-32"
+{!> ../../docs_src/security/tutorial002.py!}
+```
+
+////
## Recap
diff --git a/docs/en/docs/tutorial/security/index.md b/docs/en/docs/tutorial/security/index.md
index 659a94dc3..d33a2b14d 100644
--- a/docs/en/docs/tutorial/security/index.md
+++ b/docs/en/docs/tutorial/security/index.md
@@ -32,9 +32,11 @@ It is not very popular or used nowadays.
OAuth2 doesn't specify how to encrypt the communication, it expects you to have your application served with HTTPS.
-!!! tip
- In the section about **deployment** you will see how to set up HTTPS for free, using Traefik and Let's Encrypt.
+/// tip
+In the section about **deployment** you will see how to set up HTTPS for free, using Traefik and Let's Encrypt.
+
+///
## OpenID Connect
@@ -87,10 +89,13 @@ OpenAPI defines the following security schemes:
* This automatic discovery is what is defined in the OpenID Connect specification.
-!!! tip
- Integrating other authentication/authorization providers like Google, Facebook, Twitter, GitHub, etc. is also possible and relatively easy.
+/// tip
- The most complex problem is building an authentication/authorization provider like those, but **FastAPI** gives you the tools to do it easily, while doing the heavy lifting for you.
+Integrating other authentication/authorization providers like Google, Facebook, Twitter, GitHub, etc. is also possible and relatively easy.
+
+The most complex problem is building an authentication/authorization provider like those, but **FastAPI** gives you the tools to do it easily, while doing the heavy lifting for you.
+
+///
## **FastAPI** utilities
diff --git a/docs/en/docs/tutorial/security/oauth2-jwt.md b/docs/en/docs/tutorial/security/oauth2-jwt.md
index b011db67a..f454a8b28 100644
--- a/docs/en/docs/tutorial/security/oauth2-jwt.md
+++ b/docs/en/docs/tutorial/security/oauth2-jwt.md
@@ -28,7 +28,9 @@ If you want to play with JWT tokens and see how they work, check
@@ -40,10 +42,13 @@ $ pip install pyjwt
@@ -353,8 +434,11 @@ If you open the developer tools, you could see how the data sent only includes t
-!!! note
- Notice the header `Authorization`, with a value that starts with `Bearer `.
+/// note
+
+Notice the header `Authorization`, with a value that starts with `Bearer `.
+
+///
## Advanced usage with `scopes`
diff --git a/docs/en/docs/tutorial/security/simple-oauth2.md b/docs/en/docs/tutorial/security/simple-oauth2.md
index 6f40531d7..dc15bef20 100644
--- a/docs/en/docs/tutorial/security/simple-oauth2.md
+++ b/docs/en/docs/tutorial/security/simple-oauth2.md
@@ -32,14 +32,17 @@ They are normally used to declare specific security permissions, for example:
* `instagram_basic` is used by Facebook / Instagram.
* `https://www.googleapis.com/auth/drive` is used by Google.
-!!! info
- In OAuth2 a "scope" is just a string that declares a specific permission required.
+/// info
- It doesn't matter if it has other characters like `:` or if it is a URL.
+In OAuth2 a "scope" is just a string that declares a specific permission required.
- Those details are implementation specific.
+It doesn't matter if it has other characters like `:` or if it is a URL.
- For OAuth2 they are just strings.
+Those details are implementation specific.
+
+For OAuth2 they are just strings.
+
+///
## Code to get the `username` and `password`
@@ -49,41 +52,57 @@ Now let's use the utilities provided by **FastAPI** to handle this.
First, import `OAuth2PasswordRequestForm`, and use it as a dependency with `Depends` in the *path operation* for `/token`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="4 78"
- {!> ../../../docs_src/security/tutorial003_an_py310.py!}
- ```
+```Python hl_lines="4 78"
+{!> ../../docs_src/security/tutorial003_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="4 78"
- {!> ../../../docs_src/security/tutorial003_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="4 78"
+{!> ../../docs_src/security/tutorial003_an_py39.py!}
+```
- ```Python hl_lines="4 79"
- {!> ../../../docs_src/security/tutorial003_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="4 79"
+{!> ../../docs_src/security/tutorial003_an.py!}
+```
- ```Python hl_lines="2 74"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="4 76"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="2 74"
+{!> ../../docs_src/security/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="4 76"
+{!> ../../docs_src/security/tutorial003.py!}
+```
+
+////
`OAuth2PasswordRequestForm` is a class dependency that declares a form body with:
@@ -92,29 +111,38 @@ First, import `OAuth2PasswordRequestForm`, and use it as a dependency with `Depe
* An optional `scope` field as a big string, composed of strings separated by spaces.
* An optional `grant_type`.
-!!! tip
- The OAuth2 spec actually *requires* a field `grant_type` with a fixed value of `password`, but `OAuth2PasswordRequestForm` doesn't enforce it.
+/// tip
- If you need to enforce it, use `OAuth2PasswordRequestFormStrict` instead of `OAuth2PasswordRequestForm`.
+The OAuth2 spec actually *requires* a field `grant_type` with a fixed value of `password`, but `OAuth2PasswordRequestForm` doesn't enforce it.
+
+If you need to enforce it, use `OAuth2PasswordRequestFormStrict` instead of `OAuth2PasswordRequestForm`.
+
+///
* An optional `client_id` (we don't need it for our example).
* An optional `client_secret` (we don't need it for our example).
-!!! info
- The `OAuth2PasswordRequestForm` is not a special class for **FastAPI** as is `OAuth2PasswordBearer`.
+/// info
- `OAuth2PasswordBearer` makes **FastAPI** know that it is a security scheme. So it is added that way to OpenAPI.
+The `OAuth2PasswordRequestForm` is not a special class for **FastAPI** as is `OAuth2PasswordBearer`.
- But `OAuth2PasswordRequestForm` is just a class dependency that you could have written yourself, or you could have declared `Form` parameters directly.
+`OAuth2PasswordBearer` makes **FastAPI** know that it is a security scheme. So it is added that way to OpenAPI.
- But as it's a common use case, it is provided by **FastAPI** directly, just to make it easier.
+But `OAuth2PasswordRequestForm` is just a class dependency that you could have written yourself, or you could have declared `Form` parameters directly.
+
+But as it's a common use case, it is provided by **FastAPI** directly, just to make it easier.
+
+///
### Use the form data
-!!! tip
- The instance of the dependency class `OAuth2PasswordRequestForm` won't have an attribute `scope` with the long string separated by spaces, instead, it will have a `scopes` attribute with the actual list of strings for each scope sent.
+/// tip
- We are not using `scopes` in this example, but the functionality is there if you need it.
+The instance of the dependency class `OAuth2PasswordRequestForm` won't have an attribute `scope` with the long string separated by spaces, instead, it will have a `scopes` attribute with the actual list of strings for each scope sent.
+
+We are not using `scopes` in this example, but the functionality is there if you need it.
+
+///
Now, get the user data from the (fake) database, using the `username` from the form field.
@@ -122,41 +150,57 @@ If there is no such user, we return an error saying "Incorrect username or passw
For the error, we use the exception `HTTPException`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="3 79-81"
- {!> ../../../docs_src/security/tutorial003_an_py310.py!}
- ```
+```Python hl_lines="3 79-81"
+{!> ../../docs_src/security/tutorial003_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="3 79-81"
- {!> ../../../docs_src/security/tutorial003_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="3 79-81"
+{!> ../../docs_src/security/tutorial003_an_py39.py!}
+```
- ```Python hl_lines="3 80-82"
- {!> ../../../docs_src/security/tutorial003_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="3 80-82"
+{!> ../../docs_src/security/tutorial003_an.py!}
+```
- ```Python hl_lines="1 75-77"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="3 77-79"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="1 75-77"
+{!> ../../docs_src/security/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="3 77-79"
+{!> ../../docs_src/security/tutorial003.py!}
+```
+
+////
### Check the password
@@ -182,41 +226,57 @@ If your database is stolen, the thief won't have your users' plaintext passwords
So, the thief won't be able to try to use those same passwords in another system (as many users use the same password everywhere, this would be dangerous).
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="82-85"
- {!> ../../../docs_src/security/tutorial003_an_py310.py!}
- ```
+```Python hl_lines="82-85"
+{!> ../../docs_src/security/tutorial003_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="82-85"
- {!> ../../../docs_src/security/tutorial003_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="82-85"
+{!> ../../docs_src/security/tutorial003_an_py39.py!}
+```
- ```Python hl_lines="83-86"
- {!> ../../../docs_src/security/tutorial003_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="83-86"
+{!> ../../docs_src/security/tutorial003_an.py!}
+```
- ```Python hl_lines="78-81"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="80-83"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="78-81"
+{!> ../../docs_src/security/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="80-83"
+{!> ../../docs_src/security/tutorial003.py!}
+```
+
+////
#### About `**user_dict`
@@ -234,8 +294,11 @@ UserInDB(
)
```
-!!! info
- For a more complete explanation of `**user_dict` check back in [the documentation for **Extra Models**](../extra-models.md#about-user_indict){.internal-link target=_blank}.
+/// info
+
+For a more complete explanation of `**user_dict` check back in [the documentation for **Extra Models**](../extra-models.md#about-user_indict){.internal-link target=_blank}.
+
+///
## Return the token
@@ -247,55 +310,77 @@ And it should have an `access_token`, with a string containing our access token.
For this simple example, we are going to just be completely insecure and return the same `username` as the token.
-!!! tip
- In the next chapter, you will see a real secure implementation, with password hashing and JWT tokens.
+/// tip
- But for now, let's focus on the specific details we need.
+In the next chapter, you will see a real secure implementation, with password hashing and JWT tokens.
-=== "Python 3.10+"
+But for now, let's focus on the specific details we need.
- ```Python hl_lines="87"
- {!> ../../../docs_src/security/tutorial003_an_py310.py!}
- ```
+///
-=== "Python 3.9+"
+//// tab | Python 3.10+
- ```Python hl_lines="87"
- {!> ../../../docs_src/security/tutorial003_an_py39.py!}
- ```
+```Python hl_lines="87"
+{!> ../../docs_src/security/tutorial003_an_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="88"
- {!> ../../../docs_src/security/tutorial003_an.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.10+ non-Annotated"
+```Python hl_lines="87"
+{!> ../../docs_src/security/tutorial003_an_py39.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="83"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="88"
+{!> ../../docs_src/security/tutorial003_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="85"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+//// tab | Python 3.10+ non-Annotated
-!!! tip
- By the spec, you should return a JSON with an `access_token` and a `token_type`, the same as in this example.
+/// tip
- This is something that you have to do yourself in your code, and make sure you use those JSON keys.
+Prefer to use the `Annotated` version if possible.
- It's almost the only thing that you have to remember to do correctly yourself, to be compliant with the specifications.
+///
- For the rest, **FastAPI** handles it for you.
+```Python hl_lines="83"
+{!> ../../docs_src/security/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="85"
+{!> ../../docs_src/security/tutorial003.py!}
+```
+
+////
+
+/// tip
+
+By the spec, you should return a JSON with an `access_token` and a `token_type`, the same as in this example.
+
+This is something that you have to do yourself in your code, and make sure you use those JSON keys.
+
+It's almost the only thing that you have to remember to do correctly yourself, to be compliant with the specifications.
+
+For the rest, **FastAPI** handles it for you.
+
+///
## Update the dependencies
@@ -309,56 +394,75 @@ Both of these dependencies will just return an HTTP error if the user doesn't ex
So, in our endpoint, we will only get a user if the user exists, was correctly authenticated, and is active:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="58-66 69-74 94"
- {!> ../../../docs_src/security/tutorial003_an_py310.py!}
- ```
+```Python hl_lines="58-66 69-74 94"
+{!> ../../docs_src/security/tutorial003_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="58-66 69-74 94"
- {!> ../../../docs_src/security/tutorial003_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="58-66 69-74 94"
+{!> ../../docs_src/security/tutorial003_an_py39.py!}
+```
- ```Python hl_lines="59-67 70-75 95"
- {!> ../../../docs_src/security/tutorial003_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="59-67 70-75 95"
+{!> ../../docs_src/security/tutorial003_an.py!}
+```
- ```Python hl_lines="56-64 67-70 88"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="58-66 69-72 90"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-!!! info
- The additional header `WWW-Authenticate` with value `Bearer` we are returning here is also part of the spec.
+///
- Any HTTP (error) status code 401 "UNAUTHORIZED" is supposed to also return a `WWW-Authenticate` header.
+```Python hl_lines="56-64 67-70 88"
+{!> ../../docs_src/security/tutorial003_py310.py!}
+```
- In the case of bearer tokens (our case), the value of that header should be `Bearer`.
+////
- You can actually skip that extra header and it would still work.
+//// tab | Python 3.8+ non-Annotated
- But it's provided here to be compliant with the specifications.
+/// tip
- Also, there might be tools that expect and use it (now or in the future) and that might be useful for you or your users, now or in the future.
+Prefer to use the `Annotated` version if possible.
- That's the benefit of standards...
+///
+
+```Python hl_lines="58-66 69-72 90"
+{!> ../../docs_src/security/tutorial003.py!}
+```
+
+////
+
+/// info
+
+The additional header `WWW-Authenticate` with value `Bearer` we are returning here is also part of the spec.
+
+Any HTTP (error) status code 401 "UNAUTHORIZED" is supposed to also return a `WWW-Authenticate` header.
+
+In the case of bearer tokens (our case), the value of that header should be `Bearer`.
+
+You can actually skip that extra header and it would still work.
+
+But it's provided here to be compliant with the specifications.
+
+Also, there might be tools that expect and use it (now or in the future) and that might be useful for you or your users, now or in the future.
+
+That's the benefit of standards...
+
+///
## See it in action
diff --git a/docs/en/docs/tutorial/sql-databases.md b/docs/en/docs/tutorial/sql-databases.md
index 1f0ebc08b..972eb9308 100644
--- a/docs/en/docs/tutorial/sql-databases.md
+++ b/docs/en/docs/tutorial/sql-databases.md
@@ -1,19 +1,18 @@
# SQL (Relational) Databases
-!!! info
- These docs are about to be updated. 🎉
+**FastAPI** doesn't require you to use a SQL (relational) database. But you can use **any database** that you want.
- The current version assumes Pydantic v1, and SQLAlchemy versions less than 2.0.
+Here we'll see an example using SQLModel.
- The new docs will include Pydantic v2 and will use SQLModel (which is also based on SQLAlchemy) once it is updated to use Pydantic v2 as well.
+**SQLModel** is built on top of SQLAlchemy and Pydantic. It was made by the same author of **FastAPI** to be the perfect match for FastAPI applications that need to use **SQL databases**.
-**FastAPI** doesn't require you to use a SQL (relational) database.
+/// tip
-But you can use any relational database that you want.
+You could use any other SQL or NoSQL database library you want (in some cases called "ORMs"), FastAPI doesn't force you to use anything. 😎
-Here we'll see an example using SQLAlchemy.
+///
-You can easily adapt it to any database supported by SQLAlchemy, like:
+As SQLModel is based on SQLAlchemy, you can easily use **any database supported** by SQLAlchemy (which makes them also supported by SQLModel), like:
* PostgreSQL
* MySQL
@@ -25,774 +24,337 @@ In this example, we'll use **SQLite**, because it uses a single file and Python
Later, for your production application, you might want to use a database server like **PostgreSQL**.
-!!! tip
- There is an official project generator with **FastAPI** and **PostgreSQL**, all based on **Docker**, including a frontend and more tools: https://github.com/tiangolo/full-stack-fastapi-postgresql
+/// tip
-!!! note
- Notice that most of the code is the standard `SQLAlchemy` code you would use with any framework.
+There is an official project generator with **FastAPI** and **PostgreSQL** including a frontend and more tools: https://github.com/fastapi/full-stack-fastapi-template
- The **FastAPI** specific code is as small as always.
+///
-## ORMs
+This is a very simple and short tutorial, if you want to learn about databases in general, about SQL, or more advanced features, go to the SQLModel docs.
-**FastAPI** works with any database and any style of library to talk to the database.
+## Install `SQLModel`
-A common pattern is to use an "ORM": an "object-relational mapping" library.
-
-An ORM has tools to convert ("*map*") between *objects* in code and database tables ("*relations*").
-
-With an ORM, you normally create a class that represents a table in a SQL database, each attribute of the class represents a column, with a name and a type.
-
-For example a class `Pet` could represent a SQL table `pets`.
-
-And each *instance* object of that class represents a row in the database.
-
-For example an object `orion_cat` (an instance of `Pet`) could have an attribute `orion_cat.type`, for the column `type`. And the value of that attribute could be, e.g. `"cat"`.
-
-These ORMs also have tools to make the connections or relations between tables or entities.
-
-This way, you could also have an attribute `orion_cat.owner` and the owner would contain the data for this pet's owner, taken from the table *owners*.
-
-So, `orion_cat.owner.name` could be the name (from the `name` column in the `owners` table) of this pet's owner.
-
-It could have a value like `"Arquilian"`.
-
-And the ORM will do all the work to get the information from the corresponding table *owners* when you try to access it from your pet object.
-
-Common ORMs are for example: Django-ORM (part of the Django framework), SQLAlchemy ORM (part of SQLAlchemy, independent of framework) and Peewee (independent of framework), among others.
-
-Here we will see how to work with **SQLAlchemy ORM**.
-
-In a similar way you could use any other ORM.
-
-!!! tip
- There's an equivalent article using Peewee here in the docs.
-
-## File structure
-
-For these examples, let's say you have a directory named `my_super_project` that contains a sub-directory called `sql_app` with a structure like this:
-
-```
-.
-└── sql_app
- ├── __init__.py
- ├── crud.py
- ├── database.py
- ├── main.py
- ├── models.py
- └── schemas.py
-```
-
-The file `__init__.py` is just an empty file, but it tells Python that `sql_app` with all its modules (Python files) is a package.
-
-Now let's see what each file/module does.
-
-## Install `SQLAlchemy`
-
-First you need to install `SQLAlchemy`:
+First, make sure you create your [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install `sqlmodel`:
+
+
-
-
-
- email_validator - para validación de emails.
+* email-validator - para validación de emails.
Usados por Starlette:
diff --git a/docs/es/docs/newsletter.md b/docs/es/docs/newsletter.md
deleted file mode 100644
index f4dcfe155..000000000
--- a/docs/es/docs/newsletter.md
+++ /dev/null
@@ -1,5 +0,0 @@
-# Boletín de Noticias de FastAPI y amigos
-
-
-
-
diff --git a/docs/es/docs/project-generation.md b/docs/es/docs/project-generation.md
new file mode 100644
index 000000000..6aa570397
--- /dev/null
+++ b/docs/es/docs/project-generation.md
@@ -0,0 +1,28 @@
+# Plantilla de FastAPI Full Stack
+
+Las plantillas, aunque típicamente vienen con una configuración específica, están diseñadas para ser flexibles y personalizables. Esto te permite modificarlas y adaptarlas a los requisitos de tu proyecto, lo que las convierte en un excelente punto de partida. 🏁
+
+Puedes utilizar esta plantilla para comenzar, ya que incluye gran parte de la configuración inicial, seguridad, base de datos y algunos endpoints de API ya realizados.
+
+Repositorio en GitHub: [Full Stack FastAPI Template](https://github.com/tiangolo/full-stack-fastapi-template)
+
+## Plantilla de FastAPI Full Stack - Tecnología y Características
+
+- ⚡ [**FastAPI**](https://fastapi.tiangolo.com) para el backend API en Python.
+ - 🧰 [SQLModel](https://sqlmodel.tiangolo.com) para las interacciones con la base de datos SQL en Python (ORM).
+ - 🔍 [Pydantic](https://docs.pydantic.dev), utilizado por FastAPI, para la validación de datos y la gestión de configuraciones.
+ - 💾 [PostgreSQL](https://www.postgresql.org) como la base de datos SQL.
+- 🚀 [React](https://react.dev) para el frontend.
+ - 💃 Usando TypeScript, hooks, [Vite](https://vitejs.dev) y otras partes de un stack de frontend moderno.
+ - 🎨 [Chakra UI](https://chakra-ui.com) para los componentes del frontend.
+ - 🤖 Un cliente frontend generado automáticamente.
+ - 🧪 [Playwright](https://playwright.dev) para pruebas End-to-End.
+ - 🦇 Soporte para modo oscuro.
+- 🐋 [Docker Compose](https://www.docker.com) para desarrollo y producción.
+- 🔒 Hashing seguro de contraseñas por defecto.
+- 🔑 Autenticación con token JWT.
+- 📫 Recuperación de contraseñas basada en email.
+- ✅ Tests con [Pytest](https://pytest.org).
+- 📞 [Traefik](https://traefik.io) como proxy inverso / balanceador de carga.
+- 🚢 Instrucciones de despliegue utilizando Docker Compose, incluyendo cómo configurar un proxy frontend Traefik para manejar certificados HTTPS automáticos.
+- 🏭 CI (integración continua) y CD (despliegue continuo) basados en GitHub Actions.
diff --git a/docs/es/docs/python-types.md b/docs/es/docs/python-types.md
index 89edbb31e..156907ad1 100644
--- a/docs/es/docs/python-types.md
+++ b/docs/es/docs/python-types.md
@@ -12,15 +12,18 @@ Todo **FastAPI** está basado en estos type hints, lo que le da muchas ventajas
Pero, así nunca uses **FastAPI** te beneficiarás de aprender un poco sobre los type hints.
-!!! note "Nota"
- Si eres un experto en Python y ya lo sabes todo sobre los type hints, salta al siguiente capítulo.
+/// note | Nota
+
+Si eres un experto en Python y ya lo sabes todo sobre los type hints, salta al siguiente capítulo.
+
+///
## Motivación
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:
@@ -36,14 +39,14 @@ La función hace lo siguiente:
* Las concatena con un espacio en la mitad.
```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial001.py!}
+{!../../docs_src/python_types/tutorial001.py!}
```
### Edítalo
Es un programa muy simple.
-Ahora, imagina que lo estás escribiendo desde ceros.
+Ahora, imagina que lo estás escribiendo desde cero.
En algún punto habrías comenzado con la definición de la función, tenías los parámetros listos...
@@ -80,7 +83,7 @@ Eso es todo.
Esos son los "type hints":
```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial002.py!}
+{!../../docs_src/python_types/tutorial002.py!}
```
No es lo mismo a declarar valores por defecto, como sería con:
@@ -110,7 +113,7 @@ 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!}
```
Como el editor conoce el tipo de las variables no solo obtienes auto-completado, si no que también obtienes chequeo de errores:
@@ -120,7 +123,7 @@ 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!}
```
## Declarando tipos
@@ -141,7 +144,7 @@ Por ejemplo, puedes usar:
* `bytes`
```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial005.py!}
+{!../../docs_src/python_types/tutorial005.py!}
```
### Tipos con sub-tipos
@@ -159,7 +162,7 @@ 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!}
```
Declara la variable con la misma sintaxis de los dos puntos (`:`).
@@ -169,7 +172,7 @@ 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!}
```
Esto significa: la variable `items` es una `list` y cada uno de los ítems en esta lista es un `str`.
@@ -189,7 +192,7 @@ 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!}
```
Esto significa:
@@ -206,7 +209,7 @@ 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!}
```
Esto significa:
@@ -222,13 +225,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!}
```
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!}
```
Una vez más tendrás todo el soporte del editor:
@@ -250,11 +253,14 @@ 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"
- Para aprender más sobre Pydantic mira su documentación.
+/// info | Información
+
+Para aprender más sobre Pydantic mira su documentación.
+
+///
**FastAPI** está todo basado en Pydantic.
@@ -282,5 +288,8 @@ Puede que todo esto suene abstracto. Pero no te preocupes que todo lo verás en
Lo importante es que usando los tipos de Python estándar en un único lugar (en vez de añadir más clases, decorator, etc.) **FastAPI** hará mucho del trabajo por ti.
-!!! info "Información"
- Si ya pasaste por todo el tutorial y volviste a la sección de los tipos, una buena referencia es la "cheat sheet" de `mypy`.
+/// info | Información
+
+Si ya pasaste por todo el tutorial y volviste a la sección de los tipos, una buena referencia es la "cheat sheet" de `mypy`.
+
+///
diff --git a/docs/es/docs/tutorial/cookie-params.md b/docs/es/docs/tutorial/cookie-params.md
index 9f736575d..e858e34e8 100644
--- a/docs/es/docs/tutorial/cookie-params.md
+++ b/docs/es/docs/tutorial/cookie-params.md
@@ -6,41 +6,57 @@ Puedes definir parámetros de Cookie de la misma manera que defines parámetros
Primero importa `Cookie`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="3"
+{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="3"
+{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="3"
+{!> ../../docs_src/cookie_params/tutorial001_an.py!}
+```
- ```Python hl_lines="1"
- {!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip | Consejo
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001.py!}
- ```
+Es preferible utilizar la versión `Annotated` si es posible.
+
+///
+
+```Python hl_lines="1"
+{!> ../../docs_src/cookie_params/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | Consejo
+
+Es preferible utilizar la versión `Annotated` si es posible.
+
+///
+
+```Python hl_lines="3"
+{!> ../../docs_src/cookie_params/tutorial001.py!}
+```
+
+////
## Declarar parámetros de `Cookie`
@@ -48,49 +64,71 @@ Luego declara los parámetros de cookie usando la misma estructura que con `Path
El primer valor es el valor por defecto, puedes pasar todos los parámetros adicionales de validación o anotación:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="9"
+{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/cookie_params/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="10"
+{!> ../../docs_src/cookie_params/tutorial001_an.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip | Consejo
- ```Python hl_lines="9"
- {!> ../../../docs_src/cookie_params/tutorial001.py!}
- ```
+Es preferible utilizar la versión `Annotated` si es posible.
-!!! note "Detalles Técnicos"
- `Cookie` es una clase "hermana" de `Path` y `Query`. También hereda de la misma clase común `Param`.
+///
- Pero recuerda que cuando importas `Query`, `Path`, `Cookie` y otros de `fastapi`, en realidad son funciones que devuelven clases especiales.
+```Python hl_lines="7"
+{!> ../../docs_src/cookie_params/tutorial001_py310.py!}
+```
-!!! info
- Para declarar cookies, necesitas usar `Cookie`, porque de lo contrario los parámetros serían interpretados como parámetros de query.
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | Consejo
+
+Es preferible utilizar la versión `Annotated` si es posible.
+
+///
+
+```Python hl_lines="9"
+{!> ../../docs_src/cookie_params/tutorial001.py!}
+```
+
+////
+
+/// note | "Detalles Técnicos"
+
+`Cookie` es una clase "hermana" de `Path` y `Query`. También hereda de la misma clase común `Param`.
+
+Pero recuerda que cuando importas `Query`, `Path`, `Cookie` y otros de `fastapi`, en realidad son funciones que devuelven clases especiales.
+
+///
+
+/// info
+
+Para declarar cookies, necesitas usar `Cookie`, porque de lo contrario los parámetros serían interpretados como parámetros de query.
+
+///
## Resumen
diff --git a/docs/es/docs/tutorial/first-steps.md b/docs/es/docs/tutorial/first-steps.md
index c37ce00fb..68df00e64 100644
--- a/docs/es/docs/tutorial/first-steps.md
+++ b/docs/es/docs/tutorial/first-steps.md
@@ -3,7 +3,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`.
@@ -24,12 +24,15 @@ $ uvicorn main:app --reload
get
-!!! info "Información sobre `@decorator`"
- Esa sintaxis `@algo` se llama un "decorador" en Python.
+/// info | Información sobre `@decorator`
- Lo pones encima de una función. Es como un lindo sombrero decorado (creo que de ahí salió el concepto).
+Esa sintaxis `@algo` se llama un "decorador" en Python.
- Un "decorador" toma la función que tiene debajo y hace algo con ella.
+Lo pones encima de una función. Es como un lindo sombrero decorado (creo que de ahí salió el concepto).
- En nuestro caso, este decorador le dice a **FastAPI** que la función que está debajo corresponde al **path** `/` con una **operación** `get`.
+Un "decorador" toma la función que tiene debajo y hace algo con ella.
- Es el "**decorador de operaciones de path**".
+En nuestro caso, este decorador le dice a **FastAPI** que la función que está debajo corresponde al **path** `/` con una **operación** `get`.
+
+Es el "**decorador de operaciones de path**".
+
+///
También puedes usar las otras operaciones:
@@ -274,14 +286,17 @@ y las más exóticas:
* `@app.patch()`
* `@app.trace()`
-!!! tip "Consejo"
- Tienes la libertad de usar cada operación (método de HTTP) como quieras.
+/// tip | Consejo
- **FastAPI** no impone ningún significado específico.
+Tienes la libertad de usar cada operación (método de HTTP) como quieras.
- La información que está presentada aquí es una guía, no un requerimiento.
+**FastAPI** no impone ningún significado específico.
- Por ejemplo, cuando usas GraphQL normalmente realizas todas las acciones usando únicamente operaciones `POST`.
+La información que está presentada aquí es una guía, no un requerimiento.
+
+Por ejemplo, cuando usas GraphQL normalmente realizas todas las acciones usando únicamente operaciones `POST`.
+
+///
### Paso 4: define la **función de la operación de path**
@@ -292,7 +307,7 @@ Esta es nuestra "**función de la operación de path**":
* **función**: es la función debajo del "decorador" (debajo de `@app.get("/")`).
```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial001.py!}
+{!../../docs_src/first_steps/tutorial001.py!}
```
Esto es una función de Python.
@@ -306,16 +321,19 @@ En este caso es una función `async`.
También podrías definirla como una función estándar en lugar de `async def`:
```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial003.py!}
+{!../../docs_src/first_steps/tutorial003.py!}
```
-!!! note "Nota"
- Si no sabes la diferencia, revisa el [Async: *"¿Tienes prisa?"*](../async.md#tienes-prisa){.internal-link target=_blank}.
+/// note | Nota
+
+Si no sabes la diferencia, revisa el [Async: *"¿Tienes prisa?"*](../async.md#tienes-prisa){.internal-link target=_blank}.
+
+///
### Paso 5: devuelve el contenido
```Python hl_lines="8"
-{!../../../docs_src/first_steps/tutorial001.py!}
+{!../../docs_src/first_steps/tutorial001.py!}
```
Puedes devolver `dict`, `list`, valores singulares como un `str`, `int`, etc.
diff --git a/docs/es/docs/tutorial/index.md b/docs/es/docs/tutorial/index.md
index f11820ef2..46c57c4c3 100644
--- a/docs/es/docs/tutorial/index.md
+++ b/docs/es/docs/tutorial/index.md
@@ -50,22 +50,25 @@ $ pip install "fastapi[all]"
...eso también incluye `uvicorn` que puedes usar como el servidor que ejecuta tu código.
-!!! note "Nota"
- También puedes instalarlo parte por parte.
+/// note | "Nota"
- Esto es lo que probablemente harías una vez que desees implementar tu aplicación en producción:
+También puedes instalarlo parte por parte.
- ```
- pip install fastapi
- ```
+Esto es lo que probablemente harías una vez que desees implementar tu aplicación en producción:
- También debes instalar `uvicorn` para que funcione como tu servidor:
+```
+pip install fastapi
+```
- ```
- pip install "uvicorn[standard]"
- ```
+También debes instalar `uvicorn` para que funcione como tu servidor:
- Y lo mismo para cada una de las dependencias opcionales que quieras utilizar.
+```
+pip install "uvicorn[standard]"
+```
+
+Y lo mismo para cada una de las dependencias opcionales que quieras utilizar.
+
+///
## Guía Avanzada de Usuario
diff --git a/docs/es/docs/tutorial/path-params.md b/docs/es/docs/tutorial/path-params.md
index 7faa92f51..167c88659 100644
--- a/docs/es/docs/tutorial/path-params.md
+++ b/docs/es/docs/tutorial/path-params.md
@@ -3,7 +3,7 @@
Puedes declarar los "parámetros" o "variables" con la misma sintaxis que usan los format strings de Python:
```Python hl_lines="6-7"
-{!../../../docs_src/path_params/tutorial001.py!}
+{!../../docs_src/path_params/tutorial001.py!}
```
El valor del parámetro de path `item_id` será pasado a tu función como el argumento `item_id`.
@@ -19,13 +19,16 @@ Entonces, si corres este ejemplo y vas a Conversión de datos
@@ -35,10 +38,13 @@ Si corres este ejemplo y abres tu navegador en "parsing" automático del request.
+Observa que el valor que recibió (y devolvió) tu función es `3`, como un Python `int`, y no un string `"3"`.
+
+Entonces, con esa declaración de tipos **FastAPI** te da "parsing" automático del request.
+
+///
## Validación de datos
@@ -63,12 +69,15 @@ debido a que el parámetro de path `item_id` tenía el valor `"foo"`, que no es
El mismo error aparecería si pasaras un `float` en vez de un `int` como en: http://127.0.0.1:8000/items/4.2
-!!! check "Revisa"
- Así, con la misma declaración de tipo de Python, **FastAPI** te da validación de datos.
+/// check | Revisa
- Observa que el error también muestra claramente el punto exacto en el que no pasó la validación.
+Así, con la misma declaración de tipo de Python, **FastAPI** te da validación de datos.
- Esto es increíblemente útil cuando estás desarrollando y debugging código que interactúa con tu API.
+Observa que el error también muestra claramente el punto exacto en el que no pasó la validación.
+
+Esto es increíblemente útil cuando estás desarrollando y debugging código que interactúa con tu API.
+
+///
## Documentación
@@ -76,10 +85,13 @@ Cuando abras tu navegador en
-!!! check "Revisa"
- Nuevamente, con la misma declaración de tipo de Python, **FastAPI** te da documentación automática e interactiva (integrándose con Swagger UI)
+/// check | Revisa
- Observa que el parámetro de path está declarado como un integer.
+Nuevamente, con la misma declaración de tipo de Python, **FastAPI** te da documentación automática e interactiva (integrándose con Swagger UI)
+
+Observa que el parámetro de path está declarado como un integer.
+
+///
## Beneficios basados en estándares, documentación alternativa
@@ -110,7 +122,7 @@ Digamos algo como `/users/me` que sea para obtener datos del usuario actual.
Porque las *operaciones de path* son evaluadas en orden, tienes que asegurarte de que el path para `/users/me` sea declarado antes que el path para `/users/{user_id}`:
```Python hl_lines="6 11"
-{!../../../docs_src/path_params/tutorial003.py!}
+{!../../docs_src/path_params/tutorial003.py!}
```
De otra manera el path para `/users/{user_id}` coincidiría también con `/users/me` "pensando" que está recibiendo el parámetro `user_id` con el valor `"me"`.
@@ -128,21 +140,27 @@ Al heredar desde `str` la documentación de la API podrá saber que los valores
Luego crea atributos de clase con valores fijos, que serán los valores disponibles válidos:
```Python hl_lines="1 6-9"
-{!../../../docs_src/path_params/tutorial005.py!}
+{!../../docs_src/path_params/tutorial005.py!}
```
-!!! info "Información"
- Las Enumerations (o enums) están disponibles en Python desde la versión 3.4.
+/// info | Información
-!!! tip "Consejo"
- Si lo estás dudando, "AlexNet", "ResNet", y "LeNet" son solo nombres de modelos de Machine Learning.
+Las Enumerations (o enums) están disponibles en Python desde la versión 3.4.
+
+///
+
+/// tip | Consejo
+
+Si lo estás dudando, "AlexNet", "ResNet", y "LeNet" son solo nombres de modelos de Machine Learning.
+
+///
### Declara un *parámetro de path*
Luego, crea un *parámetro de path* con anotaciones de tipos usando la clase enum que creaste (`ModelName`):
```Python hl_lines="16"
-{!../../../docs_src/path_params/tutorial005.py!}
+{!../../docs_src/path_params/tutorial005.py!}
```
### Revisa la documentación
@@ -160,7 +178,7 @@ El valor del *parámetro de path* será un *enumeration member*.
Puedes compararlo con el *enumeration member* en el enum (`ModelName`) que creaste:
```Python hl_lines="17"
-{!../../../docs_src/path_params/tutorial005.py!}
+{!../../docs_src/path_params/tutorial005.py!}
```
#### Obtén el *enumeration value*
@@ -168,11 +186,14 @@ Puedes compararlo con el *enumeration member* en el enum (`ModelName`) que creas
Puedes obtener el valor exacto (un `str` en este caso) usando `model_name.value`, o en general, `your_enum_member.value`:
```Python hl_lines="20"
-{!../../../docs_src/path_params/tutorial005.py!}
+{!../../docs_src/path_params/tutorial005.py!}
```
-!!! tip "Consejo"
- También podrías obtener el valor `"lenet"` con `ModelName.lenet.value`.
+/// tip | Consejo
+
+También podrías obtener el valor `"lenet"` con `ModelName.lenet.value`.
+
+///
#### Devuelve *enumeration members*
@@ -181,7 +202,7 @@ Puedes devolver *enum members* desde tu *operación de path* inclusive en un bod
Ellos serán convertidos a sus valores correspondientes (strings en este caso) antes de devolverlos al cliente:
```Python hl_lines="18 21 23"
-{!../../../docs_src/path_params/tutorial005.py!}
+{!../../docs_src/path_params/tutorial005.py!}
```
En tu cliente obtendrás una respuesta en JSON como:
@@ -222,13 +243,16 @@ En este caso el nombre del parámetro es `file_path` y la última parte, `:path`
Entonces lo puedes usar con:
```Python hl_lines="6"
-{!../../../docs_src/path_params/tutorial004.py!}
+{!../../docs_src/path_params/tutorial004.py!}
```
-!!! tip "Consejo"
- Podrías necesitar que el parámetro contenga `/home/johndoe/myfile.txt` con un slash inicial (`/`).
+/// tip | Consejo
- En este caso la URL sería `/files//home/johndoe/myfile.txt` con un slash doble (`//`) entre `files` y `home`.
+Podrías necesitar que el parámetro contenga `/home/johndoe/myfile.txt` con un slash inicial (`/`).
+
+En este caso la URL sería `/files//home/johndoe/myfile.txt` con un slash doble (`//`) entre `files` y `home`.
+
+///
## Repaso
diff --git a/docs/es/docs/tutorial/query-params.md b/docs/es/docs/tutorial/query-params.md
index 76dc331a9..f9b5cf69d 100644
--- a/docs/es/docs/tutorial/query-params.md
+++ b/docs/es/docs/tutorial/query-params.md
@@ -3,7 +3,7 @@
Cuando declaras otros parámetros de la función que no hacen parte de los parámetros de path estos se interpretan automáticamente como parámetros de "query".
```Python hl_lines="9"
-{!../../../docs_src/query_params/tutorial001.py!}
+{!../../docs_src/query_params/tutorial001.py!}
```
El query es el conjunto de pares de key-value que van después del `?` en la URL, separados por caracteres `&`.
@@ -64,25 +64,31 @@ Los valores de los parámetros en tu función serán:
Del mismo modo puedes declarar parámetros de query opcionales definiendo el valor por defecto como `None`:
```Python hl_lines="9"
-{!../../../docs_src/query_params/tutorial002.py!}
+{!../../docs_src/query_params/tutorial002.py!}
```
En este caso el parámetro de la función `q` será opcional y será `None` por defecto.
-!!! check "Revisa"
- También puedes notar que **FastAPI** es lo suficientemente inteligente para darse cuenta de que el parámetro de path `item_id` es un parámetro de path y que `q` no lo es, y por lo tanto es un parámetro de query.
+/// check | Revisa
-!!! note "Nota"
- FastAPI sabrá que `q` es opcional por el `= None`.
+También puedes notar que **FastAPI** es lo suficientemente inteligente para darse cuenta de que el parámetro de path `item_id` es un parámetro de path y que `q` no lo es, y por lo tanto es un parámetro de query.
- El `Union` en `Union[str, None]` no es usado por FastAPI (FastAPI solo usará la parte `str`), pero el `Union[str, None]` le permitirá a tu editor ayudarte a encontrar errores en tu código.
+///
+
+/// note | Nota
+
+FastAPI sabrá que `q` es opcional por el `= None`.
+
+El `Union` en `Union[str, None]` no es usado por FastAPI (FastAPI solo usará la parte `str`), pero el `Union[str, None]` le permitirá a tu editor ayudarte a encontrar errores en tu código.
+
+///
## Conversión de tipos de parámetros de query
También puedes declarar tipos `bool` y serán convertidos:
```Python hl_lines="9"
-{!../../../docs_src/query_params/tutorial003.py!}
+{!../../docs_src/query_params/tutorial003.py!}
```
En este caso, si vas a:
@@ -126,7 +132,7 @@ No los tienes que declarar en un orden específico.
Serán detectados por nombre:
```Python hl_lines="8 10"
-{!../../../docs_src/query_params/tutorial004.py!}
+{!../../docs_src/query_params/tutorial004.py!}
```
## Parámetros de query requeridos
@@ -138,7 +144,7 @@ Si no quieres añadir un valor específico sino solo hacerlo opcional, pon el va
Pero cuando quieres hacer que un parámetro de query sea requerido, puedes simplemente no declararle un valor por defecto:
```Python hl_lines="6-7"
-{!../../../docs_src/query_params/tutorial005.py!}
+{!../../docs_src/query_params/tutorial005.py!}
```
Aquí el parámetro de query `needy` es un parámetro de query requerido, del tipo `str`.
@@ -184,7 +190,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
Por supuesto que también puedes definir algunos parámetros como requeridos, con un valor por defecto y otros completamente opcionales:
```Python hl_lines="10"
-{!../../../docs_src/query_params/tutorial006.py!}
+{!../../docs_src/query_params/tutorial006.py!}
```
En este caso hay 3 parámetros de query:
@@ -193,5 +199,8 @@ En este caso hay 3 parámetros de query:
* `skip`, un `int` con un valor por defecto de `0`.
* `limit`, un `int` opcional.
-!!! tip "Consejo"
- También podrías usar los `Enum`s de la misma manera que con los [Parámetros de path](path-params.md#valores-predefinidos){.internal-link target=_blank}.
+/// tip | Consejo
+
+También podrías usar los `Enum`s de la misma manera que con los [Parámetros de path](path-params.md#valores-predefinidos){.internal-link target=_blank}.
+
+///
diff --git a/docs/fa/docs/advanced/sub-applications.md b/docs/fa/docs/advanced/sub-applications.md
index 6f2359b94..5e4326776 100644
--- a/docs/fa/docs/advanced/sub-applications.md
+++ b/docs/fa/docs/advanced/sub-applications.md
@@ -13,7 +13,7 @@
```Python hl_lines="3 6-8"
-{!../../../docs_src/sub_applications/tutorial001.py!}
+{!../../docs_src/sub_applications/tutorial001.py!}
```
### زیر برنامه
@@ -23,7 +23,7 @@
این زیر برنامه فقط یکی دیگر از برنامه های استاندارد FastAPI است، اما این برنامه ای است که متصل می شود:
```Python hl_lines="11 14-16"
-{!../../../docs_src/sub_applications/tutorial001.py!}
+{!../../docs_src/sub_applications/tutorial001.py!}
```
### اتصال زیر برنامه
@@ -31,7 +31,7 @@
در برنامه سطح بالا `app` اتصال زیر برنامه `subapi` در این نمونه `/subapi` در مسیر قرار میدهد و میشود:
```Python hl_lines="11 19"
-{!../../../docs_src/sub_applications/tutorial001.py!}
+{!../../docs_src/sub_applications/tutorial001.py!}
```
### اسناد API خودکار را بررسی کنید
diff --git a/docs/fa/docs/features.md b/docs/fa/docs/features.md
index 58c34b7fc..a5ab1597e 100644
--- a/docs/fa/docs/features.md
+++ b/docs/fa/docs/features.md
@@ -63,10 +63,13 @@ second_user_data = {
my_second_user: User = User(**second_user_data)
```
-!!! info
- `**second_user_data` یعنی:
+/// info
- کلید ها و مقادیر دیکشنری `second_user_data` را مستقیما به عنوان ارگومان های key-value بفرست، که معادل است با : `User(id=4, name="Mary", joined="2018-11-30")`
+`**second_user_data` یعنی:
+
+کلید ها و مقادیر دیکشنری `second_user_data` را مستقیما به عنوان ارگومان های key-value بفرست، که معادل است با : `User(id=4, name="Mary", joined="2018-11-30")`
+
+///
### پشتیبانی ویرایشگر
diff --git a/docs/fa/docs/index.md b/docs/fa/docs/index.md
index bc8b77941..1ae566a9f 100644
--- a/docs/fa/docs/index.md
+++ b/docs/fa/docs/index.md
@@ -442,7 +442,7 @@ item: Item
استفاده شده توسط Pydantic:
-* email_validator - برای اعتبارسنجی آدرسهای ایمیل.
+* email-validator - برای اعتبارسنجی آدرسهای ایمیل.
استفاده شده توسط Starlette:
diff --git a/docs/fa/docs/tutorial/middleware.md b/docs/fa/docs/tutorial/middleware.md
index c5752a4b5..ca631d507 100644
--- a/docs/fa/docs/tutorial/middleware.md
+++ b/docs/fa/docs/tutorial/middleware.md
@@ -11,10 +11,13 @@
* می تواند کاری با **پاسخ** انجام دهید یا هر کد مورد نیازتان را اجرا کند.
* سپس **پاسخ** را برمی گرداند.
-!!! توجه "جزئیات فنی"
- در صورت وجود وابستگی هایی با `yield`، کد خروجی **پس از** اجرای میانافزار اجرا خواهد شد.
+/// توجه | "جزئیات فنی"
- در صورت وجود هر گونه وظایف پس زمینه (که در ادامه توضیح داده میشوند)، تمام میانافزارها *پس از آن* اجرا خواهند شد.
+در صورت وجود وابستگی هایی با `yield`، کد خروجی **پس از** اجرای میانافزار اجرا خواهد شد.
+
+در صورت وجود هر گونه وظایف پس زمینه (که در ادامه توضیح داده میشوند)، تمام میانافزارها *پس از آن* اجرا خواهند شد.
+
+///
## ساخت یک میان افزار
@@ -28,17 +31,22 @@
* شما میتوانید سپس `پاسخ` را تغییر داده و پس از آن را برگردانید.
```Python hl_lines="8-9 11 14"
-{!../../../docs_src/middleware/tutorial001.py!}
+{!../../docs_src/middleware/tutorial001.py!}
```
-!!! نکته به خاطر داشته باشید که هدرهای اختصاصی سفارشی را می توان با استفاده از پیشوند "X-" اضافه کرد.
+/// نکته | به خاطر داشته باشید که هدرهای اختصاصی سفارشی را می توان با استفاده از پیشوند "X-" اضافه کرد.
- اما اگر هدرهای سفارشی دارید که میخواهید مرورگر کاربر بتواند آنها را ببیند، باید آنها را با استفاده از پارامتر `expose_headers` که در مستندات CORS از Starlette توضیح داده شده است، به پیکربندی CORS خود اضافه کنید.
+اما اگر هدرهای سفارشی دارید که میخواهید مرورگر کاربر بتواند آنها را ببیند، باید آنها را با استفاده از پارامتر `expose_headers` که در مستندات CORS از Starlette توضیح داده شده است، به پیکربندی CORS خود اضافه کنید.
-!!! توجه "جزئیات فنی"
- شما همچنین میتوانید از `from starlette.requests import Request` استفاده کنید.
+///
- **FastAPI** این را به عنوان یک سهولت برای شما به عنوان برنامهنویس فراهم میکند. اما این مستقیما از Starlette به دست میآید.
+/// توجه | "جزئیات فنی"
+
+شما همچنین میتوانید از `from starlette.requests import Request` استفاده کنید.
+
+**FastAPI** این را به عنوان یک سهولت برای شما به عنوان برنامهنویس فراهم میکند. اما این مستقیما از Starlette به دست میآید.
+
+///
### قبل و بعد از `پاسخ`
@@ -49,7 +57,7 @@
به عنوان مثال، میتوانید یک هدر سفارشی به نام `X-Process-Time` که شامل زمان پردازش درخواست و تولید پاسخ به صورت ثانیه است، اضافه کنید.
```Python hl_lines="10 12-13"
-{!../../../docs_src/middleware/tutorial001.py!}
+{!../../docs_src/middleware/tutorial001.py!}
```
## سایر میان افزار
diff --git a/docs/fa/docs/tutorial/security/index.md b/docs/fa/docs/tutorial/security/index.md
index 4e68ba961..c0827a8b3 100644
--- a/docs/fa/docs/tutorial/security/index.md
+++ b/docs/fa/docs/tutorial/security/index.md
@@ -33,8 +33,11 @@
پروتکل استاندارد OAuth2 روش رمزگذاری ارتباط را مشخص نمی کند، بلکه انتظار دارد که برنامه شما با HTTPS سرویس دهی شود.
-!!! نکته
- در بخش در مورد **استقرار** ، شما یاد خواهید گرفت که چگونه با استفاده از Traefik و Let's Encrypt رایگان HTTPS را راه اندازی کنید.
+/// نکته
+
+در بخش در مورد **استقرار** ، شما یاد خواهید گرفت که چگونه با استفاده از Traefik و Let's Encrypt رایگان HTTPS را راه اندازی کنید.
+
+///
## استاندارد OpenID Connect
@@ -86,10 +89,13 @@
* شیوه `openIdConnect`: یک روش برای تعریف نحوه کشف دادههای احراز هویت OAuth2 به صورت خودکار.
* کشف خودکار این موضوع را که در مشخصه OpenID Connect تعریف شده است، مشخص میکند.
-!!! نکته
- ادغام سایر ارائهدهندگان احراز هویت/اجازهدهی مانند گوگل، فیسبوک، توییتر، گیتهاب و غیره نیز امکانپذیر و نسبتاً آسان است.
+/// نکته
- مشکل پیچیدهترین مسئله، ساخت یک ارائهدهنده احراز هویت/اجازهدهی مانند آنها است، اما **FastAPI** ابزارهای لازم برای انجام این کار را با سهولت به شما میدهد و همه کارهای سنگین را برای شما انجام میدهد.
+ادغام سایر ارائهدهندگان احراز هویت/اجازهدهی مانند گوگل، فیسبوک، توییتر، گیتهاب و غیره نیز امکانپذیر و نسبتاً آسان است.
+
+مشکل پیچیدهترین مسئله، ساخت یک ارائهدهنده احراز هویت/اجازهدهی مانند آنها است، اما **FastAPI** ابزارهای لازم برای انجام این کار را با سهولت به شما میدهد و همه کارهای سنگین را برای شما انجام میدهد.
+
+///
## ابزارهای **FastAPI**
diff --git a/docs/fr/docs/advanced/additional-responses.md b/docs/fr/docs/advanced/additional-responses.md
index 685a054ad..52a0a0792 100644
--- a/docs/fr/docs/advanced/additional-responses.md
+++ b/docs/fr/docs/advanced/additional-responses.md
@@ -1,9 +1,12 @@
# Réponses supplémentaires dans OpenAPI
-!!! warning "Attention"
- Ceci concerne un sujet plutôt avancé.
+/// warning | "Attention"
- Si vous débutez avec **FastAPI**, vous n'en aurez peut-être pas besoin.
+Ceci concerne un sujet plutôt avancé.
+
+Si vous débutez avec **FastAPI**, vous n'en aurez peut-être pas besoin.
+
+///
Vous pouvez déclarer des réponses supplémentaires, avec des codes HTTP, des types de médias, des descriptions, etc.
@@ -24,23 +27,29 @@ Chacun de ces `dict` de réponse peut avoir une clé `model`, contenant un modè
Par exemple, pour déclarer une autre réponse avec un code HTTP `404` et un modèle Pydantic `Message`, vous pouvez écrire :
```Python hl_lines="18 22"
-{!../../../docs_src/additional_responses/tutorial001.py!}
+{!../../docs_src/additional_responses/tutorial001.py!}
```
-!!! note "Remarque"
- Gardez à l'esprit que vous devez renvoyer directement `JSONResponse`.
+/// note | "Remarque"
-!!! info
- La clé `model` ne fait pas partie d'OpenAPI.
+Gardez à l'esprit que vous devez renvoyer directement `JSONResponse`.
- **FastAPI** prendra le modèle Pydantic à partir de là, générera le `JSON Schema` et le placera au bon endroit.
+///
- Le bon endroit est :
+/// info
- * Dans la clé `content`, qui a pour valeur un autre objet JSON (`dict`) qui contient :
- * Une clé avec le type de support, par ex. `application/json`, qui contient comme valeur un autre objet JSON, qui contient :
- * Une clé `schema`, qui a pour valeur le schéma JSON du modèle, voici le bon endroit.
- * **FastAPI** ajoute ici une référence aux schémas JSON globaux à un autre endroit de votre OpenAPI au lieu de l'inclure directement. De cette façon, d'autres applications et clients peuvent utiliser ces schémas JSON directement, fournir de meilleurs outils de génération de code, etc.
+La clé `model` ne fait pas partie d'OpenAPI.
+
+**FastAPI** prendra le modèle Pydantic à partir de là, générera le `JSON Schema` et le placera au bon endroit.
+
+Le bon endroit est :
+
+* Dans la clé `content`, qui a pour valeur un autre objet JSON (`dict`) qui contient :
+ * Une clé avec le type de support, par ex. `application/json`, qui contient comme valeur un autre objet JSON, qui contient :
+ * Une clé `schema`, qui a pour valeur le schéma JSON du modèle, voici le bon endroit.
+ * **FastAPI** ajoute ici une référence aux schémas JSON globaux à un autre endroit de votre OpenAPI au lieu de l'inclure directement. De cette façon, d'autres applications et clients peuvent utiliser ces schémas JSON directement, fournir de meilleurs outils de génération de code, etc.
+
+///
Les réponses générées au format OpenAPI pour cette *opération de chemin* seront :
@@ -169,16 +178,22 @@ Vous pouvez utiliser ce même paramètre `responses` pour ajouter différents ty
Par exemple, vous pouvez ajouter un type de média supplémentaire `image/png`, en déclarant que votre *opération de chemin* peut renvoyer un objet JSON (avec le type de média `application/json`) ou une image PNG :
```Python hl_lines="19-24 28"
-{!../../../docs_src/additional_responses/tutorial002.py!}
+{!../../docs_src/additional_responses/tutorial002.py!}
```
-!!! note "Remarque"
- Notez que vous devez retourner l'image en utilisant directement un `FileResponse`.
+/// note | "Remarque"
-!!! info
- À moins que vous ne spécifiiez explicitement un type de média différent dans votre paramètre `responses`, FastAPI supposera que la réponse a le même type de média que la classe de réponse principale (par défaut `application/json`).
+Notez que vous devez retourner l'image en utilisant directement un `FileResponse`.
- Mais si vous avez spécifié une classe de réponse personnalisée avec `None` comme type de média, FastAPI utilisera `application/json` pour toute réponse supplémentaire associée à un modèle.
+///
+
+/// info
+
+À moins que vous ne spécifiiez explicitement un type de média différent dans votre paramètre `responses`, FastAPI supposera que la réponse a le même type de média que la classe de réponse principale (par défaut `application/json`).
+
+Mais si vous avez spécifié une classe de réponse personnalisée avec `None` comme type de média, FastAPI utilisera `application/json` pour toute réponse supplémentaire associée à un modèle.
+
+///
## Combinaison d'informations
@@ -193,7 +208,7 @@ Par exemple, vous pouvez déclarer une réponse avec un code HTTP `404` qui util
Et une réponse avec un code HTTP `200` qui utilise votre `response_model`, mais inclut un `example` personnalisé :
```Python hl_lines="20-31"
-{!../../../docs_src/additional_responses/tutorial003.py!}
+{!../../docs_src/additional_responses/tutorial003.py!}
```
Tout sera combiné et inclus dans votre OpenAPI, et affiché dans la documentation de l'API :
@@ -229,7 +244,7 @@ Vous pouvez utiliser cette technique pour réutiliser certaines réponses préd
Par exemple:
```Python hl_lines="13-17 26"
-{!../../../docs_src/additional_responses/tutorial004.py!}
+{!../../docs_src/additional_responses/tutorial004.py!}
```
## Plus d'informations sur les réponses OpenAPI
diff --git a/docs/fr/docs/advanced/additional-status-codes.md b/docs/fr/docs/advanced/additional-status-codes.md
index 51f0db737..06a8043ea 100644
--- a/docs/fr/docs/advanced/additional-status-codes.md
+++ b/docs/fr/docs/advanced/additional-status-codes.md
@@ -15,20 +15,26 @@ Mais vous voulez aussi qu'il accepte de nouveaux éléments. Et lorsque les él
Pour y parvenir, importez `JSONResponse` et renvoyez-y directement votre contenu, en définissant le `status_code` que vous souhaitez :
```Python hl_lines="4 25"
-{!../../../docs_src/additional_status_codes/tutorial001.py!}
+{!../../docs_src/additional_status_codes/tutorial001.py!}
```
-!!! warning "Attention"
- Lorsque vous renvoyez une `Response` directement, comme dans l'exemple ci-dessus, elle sera renvoyée directement.
+/// warning | "Attention"
- Elle ne sera pas sérialisée avec un modèle.
+Lorsque vous renvoyez une `Response` directement, comme dans l'exemple ci-dessus, elle sera renvoyée directement.
- Assurez-vous qu'il contient les données souhaitées et que les valeurs soient dans un format JSON valides (si vous utilisez une `JSONResponse`).
+Elle ne sera pas sérialisée avec un modèle.
-!!! note "Détails techniques"
- Vous pouvez également utiliser `from starlette.responses import JSONResponse`.
+Assurez-vous qu'il contient les données souhaitées et que les valeurs soient dans un format JSON valides (si vous utilisez une `JSONResponse`).
- Pour plus de commodités, **FastAPI** fournit les objets `starlette.responses` sous forme d'un alias accessible par `fastapi.responses`. Mais la plupart des réponses disponibles proviennent directement de Starlette. Il en est de même avec l'objet `statut`.
+///
+
+/// note | "Détails techniques"
+
+Vous pouvez également utiliser `from starlette.responses import JSONResponse`.
+
+Pour plus de commodités, **FastAPI** fournit les objets `starlette.responses` sous forme d'un alias accessible par `fastapi.responses`. Mais la plupart des réponses disponibles proviennent directement de Starlette. Il en est de même avec l'objet `statut`.
+
+///
## Documents OpenAPI et API
diff --git a/docs/fr/docs/advanced/index.md b/docs/fr/docs/advanced/index.md
index 4599bcb6f..198fa8c30 100644
--- a/docs/fr/docs/advanced/index.md
+++ b/docs/fr/docs/advanced/index.md
@@ -6,10 +6,13 @@ Le [Tutoriel - Guide de l'utilisateur](../tutorial/index.md){.internal-link targ
Dans les sections suivantes, vous verrez des options, configurations et fonctionnalités supplémentaires.
-!!! note "Remarque"
- Les sections de ce chapitre ne sont **pas nécessairement "avancées"**.
+/// note | "Remarque"
- Et il est possible que pour votre cas d'utilisation, la solution se trouve dans l'un d'entre eux.
+Les sections de ce chapitre ne sont **pas nécessairement "avancées"**.
+
+Et il est possible que pour votre cas d'utilisation, la solution se trouve dans l'un d'entre eux.
+
+///
## Lisez d'abord le didacticiel
diff --git a/docs/fr/docs/advanced/path-operation-advanced-configuration.md b/docs/fr/docs/advanced/path-operation-advanced-configuration.md
index 77f551aea..94b20b0f3 100644
--- a/docs/fr/docs/advanced/path-operation-advanced-configuration.md
+++ b/docs/fr/docs/advanced/path-operation-advanced-configuration.md
@@ -2,15 +2,18 @@
## ID d'opération OpenAPI
-!!! warning "Attention"
- Si vous n'êtes pas un "expert" en OpenAPI, vous n'en avez probablement pas besoin.
+/// warning | "Attention"
+
+Si vous n'êtes pas un "expert" en OpenAPI, vous n'en avez probablement pas besoin.
+
+///
Dans OpenAPI, les chemins sont des ressources, tels que /users/ ou /items/, exposées par votre API, et les opérations sont les méthodes HTTP utilisées pour manipuler ces chemins, telles que GET, POST ou DELETE. Les operationId sont des chaînes uniques facultatives utilisées pour identifier une opération d'un chemin. Vous pouvez définir l'OpenAPI `operationId` à utiliser dans votre *opération de chemin* avec le paramètre `operation_id`.
Vous devez vous assurer qu'il est unique pour chaque opération.
```Python hl_lines="6"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial001.py!}
+{!../../docs_src/path_operation_advanced_configuration/tutorial001.py!}
```
### Utilisation du nom *path operation function* comme operationId
@@ -20,23 +23,29 @@ Si vous souhaitez utiliser les noms de fonction de vos API comme `operationId`,
Vous devriez le faire après avoir ajouté toutes vos *paramètres de chemin*.
```Python hl_lines="2 12-21 24"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!}
+{!../../docs_src/path_operation_advanced_configuration/tutorial002.py!}
```
-!!! tip "Astuce"
- Si vous appelez manuellement `app.openapi()`, vous devez mettre à jour les `operationId` avant.
+/// tip | "Astuce"
-!!! warning "Attention"
- Pour faire cela, vous devez vous assurer que chacun de vos *chemin* ait un nom unique.
+Si vous appelez manuellement `app.openapi()`, vous devez mettre à jour les `operationId` avant.
- Même s'ils se trouvent dans des modules différents (fichiers Python).
+///
+
+/// warning | "Attention"
+
+Pour faire cela, vous devez vous assurer que chacun de vos *chemin* ait un nom unique.
+
+Même s'ils se trouvent dans des modules différents (fichiers Python).
+
+///
## Exclusion d'OpenAPI
Pour exclure un *chemin* du schéma OpenAPI généré (et donc des systèmes de documentation automatiques), utilisez le paramètre `include_in_schema` et assignez-lui la valeur `False` :
```Python hl_lines="6"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial003.py!}
+{!../../docs_src/path_operation_advanced_configuration/tutorial003.py!}
```
## Description avancée de docstring
@@ -48,7 +57,7 @@ L'ajout d'un `\f` (un caractère d'échappement "form feed") va permettre à **F
Il n'apparaîtra pas dans la documentation, mais d'autres outils (tel que Sphinx) pourront utiliser le reste.
```Python hl_lines="19-29"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial004.py!}
+{!../../docs_src/path_operation_advanced_configuration/tutorial004.py!}
```
## Réponses supplémentaires
@@ -65,8 +74,11 @@ Il y a un chapitre entier ici dans la documentation à ce sujet, vous pouvez le
Lorsque vous déclarez un *chemin* dans votre application, **FastAPI** génère automatiquement les métadonnées concernant ce *chemin* à inclure dans le schéma OpenAPI.
-!!! note "Détails techniques"
- La spécification OpenAPI appelle ces métadonnées des Objets d'opération.
+/// note | "Détails techniques"
+
+La spécification OpenAPI appelle ces métadonnées des Objets d'opération.
+
+///
Il contient toutes les informations sur le *chemin* et est utilisé pour générer automatiquement la documentation.
@@ -74,8 +86,11 @@ Il inclut les `tags`, `parameters`, `requestBody`, `responses`, etc.
Ce schéma OpenAPI spécifique aux *operations* est normalement généré automatiquement par **FastAPI**, mais vous pouvez également l'étendre.
-!!! tip "Astuce"
- Si vous avez seulement besoin de déclarer des réponses supplémentaires, un moyen plus pratique de le faire est d'utiliser les [réponses supplémentaires dans OpenAPI](additional-responses.md){.internal-link target=_blank}.
+/// tip | "Astuce"
+
+Si vous avez seulement besoin de déclarer des réponses supplémentaires, un moyen plus pratique de le faire est d'utiliser les [réponses supplémentaires dans OpenAPI](additional-responses.md){.internal-link target=_blank}.
+
+///
Vous pouvez étendre le schéma OpenAPI pour une *opération de chemin* en utilisant le paramètre `openapi_extra`.
@@ -84,7 +99,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!}
```
Si vous ouvrez la documentation automatique de l'API, votre extension apparaîtra au bas du *chemin* spécifique.
@@ -133,7 +148,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 !}
```
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.
@@ -149,7 +164,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!}
```
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.
@@ -159,10 +174,13 @@ 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!}
```
-!!! tip "Astuce"
- Ici, nous réutilisons le même modèle Pydantic.
+/// tip | "Astuce"
- Mais nous aurions pu tout aussi bien pu le valider d'une autre manière.
+Ici, nous réutilisons le même modèle Pydantic.
+
+Mais nous aurions pu tout aussi bien pu le valider d'une autre manière.
+
+///
diff --git a/docs/fr/docs/advanced/response-directly.md b/docs/fr/docs/advanced/response-directly.md
index ed29446d4..80876bc18 100644
--- a/docs/fr/docs/advanced/response-directly.md
+++ b/docs/fr/docs/advanced/response-directly.md
@@ -14,8 +14,11 @@ Cela peut être utile, par exemple, pour retourner des en-têtes personnalisés
En fait, vous pouvez retourner n'importe quelle `Response` ou n'importe quelle sous-classe de celle-ci.
-!!! note "Remarque"
- `JSONResponse` est elle-même une sous-classe de `Response`.
+/// note | "Remarque"
+
+`JSONResponse` est elle-même une sous-classe de `Response`.
+
+///
Et quand vous retournez une `Response`, **FastAPI** la transmet directement.
@@ -32,13 +35,16 @@ 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!}
```
-!!! note "Détails techniques"
- Vous pouvez aussi utiliser `from starlette.responses import JSONResponse`.
+/// note | "Détails techniques"
- **FastAPI** fournit le même objet `starlette.responses` que `fastapi.responses` juste par commodité pour le développeur. Mais la plupart des réponses disponibles proviennent directement de Starlette.
+Vous pouvez aussi utiliser `from starlette.responses import JSONResponse`.
+
+**FastAPI** fournit le même objet `starlette.responses` que `fastapi.responses` juste par commodité pour le développeur. Mais la plupart des réponses disponibles proviennent directement de Starlette.
+
+///
## Renvoyer une `Response` personnalisée
@@ -51,7 +57,7 @@ Disons que vous voulez retourner une réponse Flask
Flask est un "micro-framework", il ne comprend pas d'intégrations de bases de données ni beaucoup de choses qui sont fournies par défaut dans Django.
@@ -59,11 +65,14 @@ qui est nécessaire, était une caractéristique clé que je voulais conserver.
Compte tenu de la simplicité de Flask, il semblait bien adapté à la création d'API. La prochaine chose à trouver était un "Django REST Framework" pour Flask.
-!!! check "A inspiré **FastAPI** à"
+/// check | "A inspiré **FastAPI** à"
+
Être un micro-framework. Il est donc facile de combiner les outils et les pièces nécessaires.
Proposer un système de routage simple et facile à utiliser.
+///
+
### Requests
**FastAPI** n'est pas réellement une alternative à **Requests**. Leur cadre est très différent.
@@ -98,9 +107,13 @@ def read_url():
Notez les similitudes entre `requests.get(...)` et `@app.get(...)`.
-!!! check "A inspiré **FastAPI** à"
-_ Avoir une API simple et intuitive.
-_ Utiliser les noms de méthodes HTTP (opérations) directement, de manière simple et intuitive. \* Avoir des valeurs par défaut raisonnables, mais des personnalisations puissantes.
+/// check | "A inspiré **FastAPI** à"
+
+Avoir une API simple et intuitive.
+
+Utiliser les noms de méthodes HTTP (opérations) directement, de manière simple et intuitive. \* Avoir des valeurs par défaut raisonnables, mais des personnalisations puissantes.
+
+///
### Swagger / OpenAPI
@@ -115,15 +128,18 @@ Swagger pour une API permettrait d'utiliser cette interface utilisateur web auto
C'est pourquoi, lorsqu'on parle de la version 2.0, il est courant de dire "Swagger", et pour la version 3+ "OpenAPI".
-!!! check "A inspiré **FastAPI** à"
+/// check | "A inspiré **FastAPI** à"
+
Adopter et utiliser une norme ouverte pour les spécifications des API, au lieu d'un schéma personnalisé.
- Intégrer des outils d'interface utilisateur basés sur des normes :
+Intégrer des outils d'interface utilisateur basés sur des normes :
- * Swagger UI
- * ReDoc
+* Swagger UI
+* ReDoc
- Ces deux-là ont été choisis parce qu'ils sont populaires et stables, mais en faisant une recherche rapide, vous pourriez trouver des dizaines d'alternatives supplémentaires pour OpenAPI (que vous pouvez utiliser avec **FastAPI**).
+Ces deux-là ont été choisis parce qu'ils sont populaires et stables, mais en faisant une recherche rapide, vous pourriez trouver des dizaines d'alternatives supplémentaires pour OpenAPI (que vous pouvez utiliser avec **FastAPI**).
+
+///
### Frameworks REST pour Flask
@@ -150,9 +166,12 @@ Ces fonctionnalités sont ce pourquoi Marshmallow a été construit. C'est une e
Mais elle a été créée avant que les type hints n'existent en Python. Ainsi, pour définir chaque schéma, vous devez utiliser des utilitaires et des classes spécifiques fournies par Marshmallow.
-!!! check "A inspiré **FastAPI** à"
+/// check | "A inspiré **FastAPI** à"
+
Utilisez du code pour définir des "schémas" qui fournissent automatiquement les types de données et la validation.
+///
+
### Webargs
Une autre grande fonctionnalité requise par les API est le APISpec
Marshmallow et Webargs fournissent la validation, l'analyse et la sérialisation en tant que plug-ins.
@@ -188,12 +213,18 @@ Mais alors, nous avons à nouveau le problème d'avoir une micro-syntaxe, dans u
L'éditeur ne peut guère aider en la matière. Et si nous modifions les paramètres ou les schémas Marshmallow et que nous oublions de modifier également cette docstring YAML, le schéma généré deviendrait obsolète.
-!!! info
+/// info
+
APISpec a été créé par les développeurs de Marshmallow.
-!!! check "A inspiré **FastAPI** à"
+///
+
+/// check | "A inspiré **FastAPI** à"
+
Supporter la norme ouverte pour les API, OpenAPI.
+///
+
### Flask-apispec
C'est un plug-in pour Flask, qui relie Webargs, Marshmallow et APISpec.
@@ -215,12 +246,18 @@ j'ai (ainsi que plusieurs équipes externes) utilisées jusqu'à présent :
Ces mêmes générateurs full-stack ont servi de base aux [Générateurs de projets pour **FastAPI**](project-generation.md){.internal-link target=\_blank}.
-!!! info
+/// info
+
Flask-apispec a été créé par les développeurs de Marshmallow.
-!!! check "A inspiré **FastAPI** à"
+///
+
+/// check | "A inspiré **FastAPI** à"
+
Générer le schéma OpenAPI automatiquement, à partir du même code qui définit la sérialisation et la validation.
+///
+
### NestJS (et Angular)
Ce n'est même pas du Python, NestJS est un framework JavaScript (TypeScript) NodeJS inspiré d'Angular.
@@ -236,24 +273,33 @@ Mais comme les données TypeScript ne sont pas préservées après la compilatio
Il ne peut pas très bien gérer les modèles imbriqués. Ainsi, si le corps JSON de la requête est un objet JSON comportant des champs internes qui sont à leur tour des objets JSON imbriqués, il ne peut pas être correctement documenté et validé.
-!!! check "A inspiré **FastAPI** à"
+/// check | "A inspiré **FastAPI** à"
+
Utiliser les types Python pour bénéficier d'un excellent support de l'éditeur.
- Disposer d'un puissant système d'injection de dépendances. Trouver un moyen de minimiser la répétition du code.
+Disposer d'un puissant système d'injection de dépendances. Trouver un moyen de minimiser la répétition du code.
+
+///
### Sanic
C'était l'un des premiers frameworks Python extrêmement rapides basés sur `asyncio`. Il a été conçu pour être très similaire à Flask.
-!!! note "Détails techniques"
+/// note | "Détails techniques"
+
Il utilisait `uvloop` au lieu du système par défaut de Python `asyncio`. C'est ce qui l'a rendu si rapide.
- Il a clairement inspiré Uvicorn et Starlette, qui sont actuellement plus rapides que Sanic dans les benchmarks.
+Il a clairement inspiré Uvicorn et Starlette, qui sont actuellement plus rapides que Sanic dans les benchmarks.
+
+///
+
+/// check | "A inspiré **FastAPI** à"
-!!! check "A inspiré **FastAPI** à"
Trouvez un moyen d'avoir une performance folle.
- C'est pourquoi **FastAPI** est basé sur Starlette, car il s'agit du framework le plus rapide disponible (testé par des benchmarks tiers).
+C'est pourquoi **FastAPI** est basé sur Starlette, car il s'agit du framework le plus rapide disponible (testé par des benchmarks tiers).
+
+///
### Falcon
@@ -267,12 +313,15 @@ pas possible de déclarer des paramètres de requête et des corps avec des indi
Ainsi, la validation, la sérialisation et la documentation des données doivent être effectuées dans le code, et non pas automatiquement. Ou bien elles doivent être implémentées comme un framework au-dessus de Falcon, comme Hug. Cette même distinction se retrouve dans d'autres frameworks qui s'inspirent de la conception de Falcon, qui consiste à avoir un objet de requête et un objet de réponse comme paramètres.
-!!! check "A inspiré **FastAPI** à"
+/// check | "A inspiré **FastAPI** à"
+
Trouver des moyens d'obtenir de bonnes performances.
- Avec Hug (puisque Hug est basé sur Falcon), **FastAPI** a inspiré la déclaration d'un paramètre `response` dans les fonctions.
+Avec Hug (puisque Hug est basé sur Falcon), **FastAPI** a inspiré la déclaration d'un paramètre `response` dans les fonctions.
- Bien que dans FastAPI, il est facultatif, et est utilisé principalement pour définir les en-têtes, les cookies, et les codes de statut alternatifs.
+Bien que dans FastAPI, il est facultatif, et est utilisé principalement pour définir les en-têtes, les cookies, et les codes de statut alternatifs.
+
+///
### Molten
@@ -294,10 +343,13 @@ d'utiliser des décorateurs qui peuvent être placés juste au-dessus de la fonc
méthode est plus proche de celle de Django que de celle de Flask (et Starlette). Il sépare dans le code des choses
qui sont relativement fortement couplées.
-!!! check "A inspiré **FastAPI** à"
+/// check | "A inspiré **FastAPI** à"
+
Définir des validations supplémentaires pour les types de données utilisant la valeur "par défaut" des attributs du modèle. Ceci améliore le support de l'éditeur, et n'était pas disponible dans Pydantic auparavant.
- Cela a en fait inspiré la mise à jour de certaines parties de Pydantic, afin de supporter le même style de déclaration de validation (toute cette fonctionnalité est maintenant déjà disponible dans Pydantic).
+Cela a en fait inspiré la mise à jour de certaines parties de Pydantic, afin de supporter le même style de déclaration de validation (toute cette fonctionnalité est maintenant déjà disponible dans Pydantic).
+
+///
### Hug
@@ -314,16 +366,22 @@ API et des CLI.
Comme il est basé sur l'ancienne norme pour les frameworks web Python synchrones (WSGI), il ne peut pas gérer les Websockets et autres, bien qu'il soit également très performant.
-!!! info
+/// info
+
Hug a été créé par Timothy Crosley, le créateur de `isort`, un excellent outil pour trier automatiquement les imports dans les fichiers Python.
-!!! check "A inspiré **FastAPI** à"
+///
+
+/// check | "A inspiré **FastAPI** à"
+
Hug a inspiré certaines parties d'APIStar, et était l'un des outils que je trouvais les plus prometteurs, à côté d'APIStar.
- Hug a contribué à inspirer **FastAPI** pour utiliser les type hints Python
- pour déclarer les paramètres, et pour générer automatiquement un schéma définissant l'API.
+Hug a contribué à inspirer **FastAPI** pour utiliser les type hints Python
+pour déclarer les paramètres, et pour générer automatiquement un schéma définissant l'API.
- Hug a inspiré **FastAPI** pour déclarer un paramètre `response` dans les fonctions pour définir les en-têtes et les cookies.
+Hug a inspiré **FastAPI** pour déclarer un paramètre `response` dans les fonctions pour définir les en-têtes et les cookies.
+
+///
### APIStar (<= 0.5)
@@ -351,23 +409,29 @@ Il ne s'agissait plus d'un framework web API, le créateur devant se concentrer
Maintenant, APIStar est un ensemble d'outils pour valider les spécifications OpenAPI, et non un framework web.
-!!! info
+/// info
+
APIStar a été créé par Tom Christie. Le même gars qui a créé :
- * Django REST Framework
- * Starlette (sur lequel **FastAPI** est basé)
- * Uvicorn (utilisé par Starlette et **FastAPI**)
+* Django REST Framework
+* Starlette (sur lequel **FastAPI** est basé)
+* Uvicorn (utilisé par Starlette et **FastAPI**)
+
+///
+
+/// check | "A inspiré **FastAPI** à"
-!!! check "A inspiré **FastAPI** à"
Exister.
- L'idée de déclarer plusieurs choses (validation des données, sérialisation et documentation) avec les mêmes types Python, tout en offrant un excellent support pour les éditeurs, était pour moi une idée brillante.
+L'idée de déclarer plusieurs choses (validation des données, sérialisation et documentation) avec les mêmes types Python, tout en offrant un excellent support pour les éditeurs, était pour moi une idée brillante.
- Et après avoir longtemps cherché un framework similaire et testé de nombreuses alternatives, APIStar était la meilleure option disponible.
+Et après avoir longtemps cherché un framework similaire et testé de nombreuses alternatives, APIStar était la meilleure option disponible.
- Puis APIStar a cessé d'exister en tant que serveur et Starlette a été créé, et a constitué une meilleure base pour un tel système. Ce fut l'inspiration finale pour construire **FastAPI**.
+Puis APIStar a cessé d'exister en tant que serveur et Starlette a été créé, et a constitué une meilleure base pour un tel système. Ce fut l'inspiration finale pour construire **FastAPI**.
- Je considère **FastAPI** comme un "successeur spirituel" d'APIStar, tout en améliorant et en augmentant les fonctionnalités, le système de typage et d'autres parties, sur la base des enseignements tirés de tous ces outils précédents.
+Je considère **FastAPI** comme un "successeur spirituel" d'APIStar, tout en améliorant et en augmentant les fonctionnalités, le système de typage et d'autres parties, sur la base des enseignements tirés de tous ces outils précédents.
+
+///
## Utilisés par **FastAPI**
@@ -380,10 +444,13 @@ Cela le rend extrêmement intuitif.
Il est comparable à Marshmallow. Bien qu'il soit plus rapide que Marshmallow dans les benchmarks. Et comme il est
basé sur les mêmes type hints Python, le support de l'éditeur est grand.
-!!! check "**FastAPI** l'utilise pour"
+/// check | "**FastAPI** l'utilise pour"
+
Gérer toute la validation des données, leur sérialisation et la documentation automatique du modèle (basée sur le schéma JSON).
- **FastAPI** prend ensuite ces données JSON Schema et les place dans OpenAPI, en plus de toutes les autres choses qu'il fait.
+**FastAPI** prend ensuite ces données JSON Schema et les place dans OpenAPI, en plus de toutes les autres choses qu'il fait.
+
+///
### Starlette
@@ -413,17 +480,23 @@ Mais il ne fournit pas de validation automatique des données, de sérialisation
C'est l'une des principales choses que **FastAPI** ajoute par-dessus, le tout basé sur les type hints Python (en utilisant Pydantic). Cela, plus le système d'injection de dépendances, les utilitaires de sécurité, la génération de schémas OpenAPI, etc.
-!!! note "Détails techniques"
+/// note | "Détails techniques"
+
ASGI est une nouvelle "norme" développée par les membres de l'équipe principale de Django. Il ne s'agit pas encore d'une "norme Python" (un PEP), bien qu'ils soient en train de le faire.
- Néanmoins, il est déjà utilisé comme "standard" par plusieurs outils. Cela améliore grandement l'interopérabilité, puisque vous pouvez remplacer Uvicorn par n'importe quel autre serveur ASGI (comme Daphne ou Hypercorn), ou vous pouvez ajouter des outils compatibles ASGI, comme `python-socketio`.
+Néanmoins, il est déjà utilisé comme "standard" par plusieurs outils. Cela améliore grandement l'interopérabilité, puisque vous pouvez remplacer Uvicorn par n'importe quel autre serveur ASGI (comme Daphne ou Hypercorn), ou vous pouvez ajouter des outils compatibles ASGI, comme `python-socketio`.
+
+///
+
+/// check | "**FastAPI** l'utilise pour"
-!!! check "**FastAPI** l'utilise pour"
Gérer toutes les parties web de base. Ajouter des fonctionnalités par-dessus.
- La classe `FastAPI` elle-même hérite directement de la classe `Starlette`.
+La classe `FastAPI` elle-même hérite directement de la classe `Starlette`.
- Ainsi, tout ce que vous pouvez faire avec Starlette, vous pouvez le faire directement avec **FastAPI**, car il s'agit en fait de Starlette sous stéroïdes.
+Ainsi, tout ce que vous pouvez faire avec Starlette, vous pouvez le faire directement avec **FastAPI**, car il s'agit en fait de Starlette sous stéroïdes.
+
+///
### Uvicorn
@@ -434,12 +507,15 @@ quelque chose qu'un framework comme Starlette (ou **FastAPI**) fournirait par-de
C'est le serveur recommandé pour Starlette et **FastAPI**.
-!!! check "**FastAPI** le recommande comme"
+/// check | "**FastAPI** le recommande comme"
+
Le serveur web principal pour exécuter les applications **FastAPI**.
- Vous pouvez le combiner avec Gunicorn, pour avoir un serveur multi-processus asynchrone.
+Vous pouvez le combiner avec Gunicorn, pour avoir un serveur multi-processus asynchrone.
- Pour plus de détails, consultez la section [Déploiement](deployment/index.md){.internal-link target=_blank}.
+Pour plus de détails, consultez la section [Déploiement](deployment/index.md){.internal-link target=_blank}.
+
+///
## Benchmarks et vitesse
diff --git a/docs/fr/docs/async.md b/docs/fr/docs/async.md
index eabd9686a..0f8f34e65 100644
--- a/docs/fr/docs/async.md
+++ b/docs/fr/docs/async.md
@@ -20,8 +20,11 @@ async def read_results():
return results
```
-!!! note
- Vous pouvez uniquement utiliser `await` dans les fonctions créées avec `async def`.
+/// note
+
+Vous pouvez uniquement utiliser `await` dans les fonctions créées avec `async def`.
+
+///
---
@@ -135,8 +138,11 @@ Vous et votre crush 😍 mangez les burgers 🍔 et passez un bon moment ✨.
-!!! info
- Illustrations proposées par Ketrina Thompson. 🎨
+/// info
+
+Illustrations proposées par Ketrina Thompson. 🎨
+
+///
---
@@ -198,8 +204,11 @@ Vous les mangez, et vous avez terminé 🍔 ⏹.
Durant tout ce processus, il n'y a presque pas eu de discussions ou de flirts car la plupart de votre temps à été passé à attendre 🕙 devant le comptoir 😞.
-!!! info
- Illustrations proposées par Ketrina Thompson. 🎨
+/// info
+
+Illustrations proposées par Ketrina Thompson. 🎨
+
+///
---
@@ -384,12 +393,15 @@ Tout ceci est donc ce qui donne sa force à **FastAPI** (à travers Starlette) e
## Détails très techniques
-!!! warning "Attention !"
- Vous pouvez probablement ignorer cela.
+/// warning | "Attention !"
- Ce sont des détails très poussés sur comment **FastAPI** fonctionne en arrière-plan.
+Vous pouvez probablement ignorer cela.
- Si vous avez de bonnes connaissances techniques (coroutines, threads, code bloquant, etc.) et êtes curieux de comment **FastAPI** gère `async def` versus le `def` classique, cette partie est faite pour vous.
+Ce sont des détails très poussés sur comment **FastAPI** fonctionne en arrière-plan.
+
+Si vous avez de bonnes connaissances techniques (coroutines, threads, code bloquant, etc.) et êtes curieux de comment **FastAPI** gère `async def` versus le `def` classique, cette partie est faite pour vous.
+
+///
### Fonctions de chemin
diff --git a/docs/fr/docs/contributing.md b/docs/fr/docs/contributing.md
index ed4d32f5a..408958339 100644
--- a/docs/fr/docs/contributing.md
+++ b/docs/fr/docs/contributing.md
@@ -24,72 +24,85 @@ Cela va créer un répertoire `./env/` avec les binaires Python et vous pourrez
Activez le nouvel environnement avec :
-=== "Linux, macOS"
+//// tab | Linux, macOS
- email_validator - pour la validation des adresses email.
+* email-validator - pour la validation des adresses email.
Utilisées par Starlette :
diff --git a/docs/fr/docs/python-types.md b/docs/fr/docs/python-types.md
index 4232633e3..2992347be 100644
--- a/docs/fr/docs/python-types.md
+++ b/docs/fr/docs/python-types.md
@@ -13,15 +13,18 @@ Seulement le minimum nécessaire pour les utiliser avec **FastAPI** sera couvert
Mais même si vous n'utilisez pas ou n'utiliserez jamais **FastAPI**, vous pourriez bénéficier d'apprendre quelques choses sur ces dernières.
-!!! note
- Si vous êtes un expert Python, et que vous savez déjà **tout** sur les annotations de type, passez au chapitre suivant.
+/// note
+
+Si vous êtes un expert Python, et que vous savez déjà **tout** sur les annotations de type, passez au chapitre suivant.
+
+///
## Motivations
Prenons un exemple simple :
```Python
-{!../../../docs_src/python_types/tutorial001.py!}
+{!../../docs_src/python_types/tutorial001.py!}
```
Exécuter ce programe affiche :
@@ -37,7 +40,7 @@ La fonction :
* Concatène les résultats avec un espace entre les deux.
```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial001.py!}
+{!../../docs_src/python_types/tutorial001.py!}
```
### Limitations
@@ -82,7 +85,7 @@ C'est tout.
Ce sont des annotations de types :
```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial002.py!}
+{!../../docs_src/python_types/tutorial002.py!}
```
À ne pas confondre avec la déclaration de valeurs par défaut comme ici :
@@ -112,7 +115,7 @@ Vous pouvez donc dérouler les options jusqu'à trouver la méthode à laquelle
Cette fonction possède déjà des annotations de type :
```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial003.py!}
+{!../../docs_src/python_types/tutorial003.py!}
```
Comme l'éditeur connaît le type des variables, vous n'avez pas seulement l'auto-complétion, mais aussi de la détection d'erreurs :
@@ -122,7 +125,7 @@ Comme l'éditeur connaît le type des variables, vous n'avez pas seulement l'aut
Maintenant que vous avez connaissance du problème, convertissez `age` en chaîne de caractères grâce à `str(age)` :
```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial004.py!}
+{!../../docs_src/python_types/tutorial004.py!}
```
## Déclarer des types
@@ -143,7 +146,7 @@ Comme par exemple :
* `bytes`
```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial005.py!}
+{!../../docs_src/python_types/tutorial005.py!}
```
### Types génériques avec des paramètres de types
@@ -161,7 +164,7 @@ Par exemple, définissons une variable comme `list` de `str`.
Importez `List` (avec un `L` majuscule) depuis `typing`.
```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial006.py!}
+{!../../docs_src/python_types/tutorial006.py!}
```
Déclarez la variable, en utilisant la syntaxe des deux-points (`:`).
@@ -171,13 +174,16 @@ Et comme type, mettez `List`.
Les listes étant un type contenant des types internes, mettez ces derniers entre crochets (`[`, `]`) :
```Python hl_lines="4"
-{!../../../docs_src/python_types/tutorial006.py!}
+{!../../docs_src/python_types/tutorial006.py!}
```
-!!! tip "Astuce"
- Ces types internes entre crochets sont appelés des "paramètres de type".
+/// tip | "Astuce"
- Ici, `str` est un paramètre de type passé à `List`.
+Ces types internes entre crochets sont appelés des "paramètres de type".
+
+Ici, `str` est un paramètre de type passé à `List`.
+
+///
Ce qui signifie : "la variable `items` est une `list`, et chacun de ses éléments a pour type `str`.
@@ -196,7 +202,7 @@ Et pourtant, l'éditeur sait qu'elle est de type `str` et pourra donc vous aider
C'est le même fonctionnement pour déclarer un `tuple` ou un `set` :
```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial007.py!}
+{!../../docs_src/python_types/tutorial007.py!}
```
Dans cet exemple :
@@ -211,7 +217,7 @@ Pour définir un `dict`, il faut lui passer 2 paramètres, séparés par une vir
Le premier paramètre de type est pour les clés et le second pour les valeurs du dictionnaire (`dict`).
```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial008.py!}
+{!../../docs_src/python_types/tutorial008.py!}
```
Dans cet exemple :
@@ -225,7 +231,7 @@ Dans cet exemple :
Vous pouvez aussi utiliser `Optional` pour déclarer qu'une variable a un type, comme `str` mais qu'il est "optionnel" signifiant qu'il pourrait aussi être `None`.
```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009.py!}
+{!../../docs_src/python_types/tutorial009.py!}
```
Utiliser `Optional[str]` plutôt que `str` permettra à l'éditeur de vous aider à détecter les erreurs où vous supposeriez qu'une valeur est toujours de type `str`, alors qu'elle pourrait aussi être `None`.
@@ -250,13 +256,13 @@ Vous pouvez aussi déclarer une classe comme type d'une variable.
Disons que vous avez une classe `Person`, avec une variable `name` :
```Python hl_lines="1-3"
-{!../../../docs_src/python_types/tutorial010.py!}
+{!../../docs_src/python_types/tutorial010.py!}
```
Vous pouvez ensuite déclarer une variable de type `Person` :
```Python hl_lines="6"
-{!../../../docs_src/python_types/tutorial010.py!}
+{!../../docs_src/python_types/tutorial010.py!}
```
Et vous aurez accès, encore une fois, au support complet offert par l'éditeur :
@@ -278,11 +284,14 @@ Ainsi, votre éditeur vous offrira un support adapté pour l'objet résultant.
Extrait de la documentation officielle de **Pydantic** :
```Python
-{!../../../docs_src/python_types/tutorial011.py!}
+{!../../docs_src/python_types/tutorial011.py!}
```
-!!! info
- Pour en savoir plus à propos de Pydantic, allez jeter un coup d'oeil à sa documentation.
+/// info
+
+Pour en savoir plus à propos de Pydantic, allez jeter un coup d'oeil à sa documentation.
+
+///
**FastAPI** est basé entièrement sur **Pydantic**.
@@ -310,5 +319,8 @@ Tout cela peut paraître bien abstrait, mais ne vous inquiétez pas, vous verrez
Ce qu'il faut retenir c'est qu'en utilisant les types standard de Python, à un seul endroit (plutôt que d'ajouter plus de classes, de décorateurs, etc.), **FastAPI** fera une grande partie du travail pour vous.
-!!! info
- Si vous avez déjà lu le tutoriel et êtes revenus ici pour voir plus sur les types, une bonne ressource est la "cheat sheet" de `mypy`.
+/// info
+
+Si vous avez déjà lu le tutoriel et êtes revenus ici pour voir plus sur les types, une bonne ressource est la "cheat sheet" de `mypy`.
+
+///
diff --git a/docs/fr/docs/tutorial/background-tasks.md b/docs/fr/docs/tutorial/background-tasks.md
index f7cf1a6cc..d971d293d 100644
--- a/docs/fr/docs/tutorial/background-tasks.md
+++ b/docs/fr/docs/tutorial/background-tasks.md
@@ -17,7 +17,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!}
```
**FastAPI** créera l'objet de type `BackgroundTasks` pour vous et le passera comme paramètre.
@@ -33,7 +33,7 @@ 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!}
```
## Ajouter une tâche d'arrière-plan
@@ -42,7 +42,7 @@ Dans votre *fonction de chemin*, passez votre fonction de tâche à l'objet de t
```Python hl_lines="14"
-{!../../../docs_src/background_tasks/tutorial001.py!}
+{!../../docs_src/background_tasks/tutorial001.py!}
```
`.add_task()` reçoit comme arguments :
@@ -58,7 +58,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!}
```
Dans cet exemple, les messages seront écrits dans le fichier `log.txt` après que la réponse soit envoyée.
diff --git a/docs/fr/docs/tutorial/body-multiple-params.md b/docs/fr/docs/tutorial/body-multiple-params.md
new file mode 100644
index 000000000..dafd869e3
--- /dev/null
+++ b/docs/fr/docs/tutorial/body-multiple-params.md
@@ -0,0 +1,384 @@
+# Body - Paramètres multiples
+
+Maintenant que nous avons vu comment manipuler `Path` et `Query`, voyons comment faire pour le corps d'une requête, communément désigné par le terme anglais "body".
+
+## Mélanger les paramètres `Path`, `Query` et body
+
+Tout d'abord, sachez que vous pouvez mélanger les déclarations des paramètres `Path`, `Query` et body, **FastAPI** saura quoi faire.
+
+Vous pouvez également déclarer des paramètres body comme étant optionnels, en leur assignant une valeur par défaut à `None` :
+
+//// tab | Python 3.10+
+
+```Python hl_lines="18-20"
+{!> ../../docs_src/body_multiple_params/tutorial001_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="18-20"
+{!> ../../docs_src/body_multiple_params/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="19-21"
+{!> ../../docs_src/body_multiple_params/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip
+
+Préférez utiliser la version `Annotated` si possible.
+
+///
+
+```Python hl_lines="17-19"
+{!> ../../docs_src/body_multiple_params/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Préférez utiliser la version `Annotated` si possible.
+
+///
+
+```Python hl_lines="19-21"
+{!> ../../docs_src/body_multiple_params/tutorial001.py!}
+```
+
+////
+
+/// note
+
+Notez que, dans ce cas, le paramètre `item` provenant du `Body` est optionnel (sa valeur par défaut est `None`).
+
+///
+
+## Paramètres multiples du body
+
+Dans l'exemple précédent, les opérations de routage attendaient un body JSON avec les attributs d'un `Item`, par exemple :
+
+```JSON
+{
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2
+}
+```
+
+Mais vous pouvez également déclarer plusieurs paramètres provenant de body, par exemple `item` et `user` simultanément :
+
+//// tab | Python 3.10+
+
+```Python hl_lines="20"
+{!> ../../docs_src/body_multiple_params/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="22"
+{!> ../../docs_src/body_multiple_params/tutorial002.py!}
+```
+
+////
+
+Dans ce cas, **FastAPI** détectera qu'il y a plus d'un paramètre dans le body (chacun correspondant à un modèle Pydantic).
+
+Il utilisera alors les noms des paramètres comme clés, et s'attendra à recevoir quelque chose de semblable à :
+
+```JSON
+{
+ "item": {
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2
+ },
+ "user": {
+ "username": "dave",
+ "full_name": "Dave Grohl"
+ }
+}
+```
+
+/// note
+
+"Notez que, bien que nous ayons déclaré le paramètre `item` de la même manière que précédemment, il est maintenant associé à la clé `item` dans le corps de la requête."`.
+
+///
+
+**FastAPI** effectue la conversion de la requête de façon transparente, de sorte que les objets `item` et `user` se trouvent correctement définis.
+
+Il effectue également la validation des données (même imbriquées les unes dans les autres), et permet de les documenter correctement (schéma OpenAPI et documentation auto-générée).
+
+## Valeurs scalaires dans le body
+
+De la même façon qu'il existe `Query` et `Path` pour définir des données supplémentaires pour les paramètres query et path, **FastAPI** fournit un équivalent `Body`.
+
+Par exemple, en étendant le modèle précédent, vous pouvez vouloir ajouter un paramètre `importance` dans le même body, en plus des paramètres `item` et `user`.
+
+Si vous le déclarez tel quel, comme c'est une valeur [scalaire](https://docs.github.com/fr/graphql/reference/scalars), **FastAPI** supposera qu'il s'agit d'un paramètre de requête (`Query`).
+
+Mais vous pouvez indiquer à **FastAPI** de la traiter comme une variable de body en utilisant `Body` :
+//// tab | Python 3.10+
+
+```Python hl_lines="23"
+{!> ../../docs_src/body_multiple_params/tutorial003_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="23"
+{!> ../../docs_src/body_multiple_params/tutorial003_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="24"
+{!> ../../docs_src/body_multiple_params/tutorial003_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip
+
+Préférez utiliser la version `Annotated` si possible.
+
+///
+
+```Python hl_lines="20"
+{!> ../../docs_src/body_multiple_params/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Préférez utiliser la version `Annotated` si possible.
+
+///
+
+```Python hl_lines="22"
+{!> ../../docs_src/body_multiple_params/tutorial003.py!}
+```
+
+////
+
+Dans ce cas, **FastAPI** s'attendra à un body semblable à :
+
+```JSON
+{
+ "item": {
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2
+ },
+ "user": {
+ "username": "dave",
+ "full_name": "Dave Grohl"
+ },
+ "importance": 5
+}
+```
+
+Encore une fois, cela convertira les types de données, les validera, permettra de générer la documentation, etc...
+
+## Paramètres multiples body et query
+
+Bien entendu, vous pouvez déclarer autant de paramètres que vous le souhaitez, en plus des paramètres body déjà déclarés.
+
+Par défaut, les valeurs [scalaires](https://docs.github.com/fr/graphql/reference/scalars) sont interprétées comme des paramètres query, donc inutile d'ajouter explicitement `Query`. Vous pouvez juste écrire :
+
+```Python
+q: Union[str, None] = None
+```
+
+Ou bien, en Python 3.10 et supérieur :
+
+```Python
+q: str | None = None
+```
+
+Par exemple :
+
+//// tab | Python 3.10+
+
+```Python hl_lines="27"
+{!> ../../docs_src/body_multiple_params/tutorial004_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="27"
+{!> ../../docs_src/body_multiple_params/tutorial004_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="28"
+{!> ../../docs_src/body_multiple_params/tutorial004_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip
+
+Préférez utiliser la version `Annotated` si possible.
+
+///
+
+```Python hl_lines="25"
+{!> ../../docs_src/body_multiple_params/tutorial004_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Préférez utiliser la version `Annotated` si possible.
+
+///
+
+```Python hl_lines="27"
+{!> ../../docs_src/body_multiple_params/tutorial004.py!}
+```
+
+////
+
+/// info
+
+`Body` possède les mêmes paramètres de validation additionnels et de gestion des métadonnées que `Query` et `Path`, ainsi que d'autres que nous verrons plus tard.
+
+///
+
+## Inclure un paramètre imbriqué dans le body
+
+Disons que vous avez seulement un paramètre `item` dans le body, correspondant à un modèle Pydantic `Item`.
+
+Par défaut, **FastAPI** attendra sa déclaration directement dans le body.
+
+Cependant, si vous souhaitez qu'il interprête correctement un JSON avec une clé `item` associée au contenu du modèle, comme cela serait le cas si vous déclariez des paramètres body additionnels, vous pouvez utiliser le paramètre spécial `embed` de `Body` :
+
+```Python
+item: Item = Body(embed=True)
+```
+
+Voici un exemple complet :
+
+//// tab | Python 3.10+
+
+```Python hl_lines="17"
+{!> ../../docs_src/body_multiple_params/tutorial005_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="17"
+{!> ../../docs_src/body_multiple_params/tutorial005_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="18"
+{!> ../../docs_src/body_multiple_params/tutorial005_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip
+
+Préférez utiliser la version `Annotated` si possible.
+
+///
+
+```Python hl_lines="15"
+{!> ../../docs_src/body_multiple_params/tutorial005_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Préférez utiliser la version `Annotated` si possible.
+
+///
+
+```Python hl_lines="17"
+{!> ../../docs_src/body_multiple_params/tutorial005.py!}
+```
+
+////
+
+Dans ce cas **FastAPI** attendra un body semblable à :
+
+```JSON hl_lines="2"
+{
+ "item": {
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2
+ }
+}
+```
+
+au lieu de :
+
+```JSON
+{
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2
+}
+```
+
+## Pour résumer
+
+Vous pouvez ajouter plusieurs paramètres body dans votre fonction de routage, même si une requête ne peut avoir qu'un seul body.
+
+Cependant, **FastAPI** se chargera de faire opérer sa magie, afin de toujours fournir à votre fonction des données correctes, les validera et documentera le schéma associé.
+
+Vous pouvez également déclarer des valeurs [scalaires](https://docs.github.com/fr/graphql/reference/scalars) à recevoir dans le body.
+
+Et vous pouvez indiquer à **FastAPI** d'inclure le body dans une autre variable, même lorsqu'un seul paramètre est déclaré.
diff --git a/docs/fr/docs/tutorial/body.md b/docs/fr/docs/tutorial/body.md
index ae952405c..96fff2ca6 100644
--- a/docs/fr/docs/tutorial/body.md
+++ b/docs/fr/docs/tutorial/body.md
@@ -8,19 +8,22 @@ Votre API aura presque toujours à envoyer un corps de **réponse**. Mais un cli
Pour déclarer un corps de **requête**, on utilise les modèles de Pydantic en profitant de tous leurs avantages et fonctionnalités.
-!!! info
- Pour envoyer de la donnée, vous devriez utiliser : `POST` (le plus populaire), `PUT`, `DELETE` ou `PATCH`.
+/// info
- Envoyer un corps dans une requête `GET` a un comportement non défini dans les spécifications, cela est néanmoins supporté par **FastAPI**, seulement pour des cas d'utilisation très complexes/extrêmes.
+Pour envoyer de la donnée, vous devriez utiliser : `POST` (le plus populaire), `PUT`, `DELETE` ou `PATCH`.
- Ceci étant découragé, la documentation interactive générée par Swagger UI ne montrera pas de documentation pour le corps d'une requête `GET`, et les proxys intermédiaires risquent de ne pas le supporter.
+Envoyer un corps dans une requête `GET` a un comportement non défini dans les spécifications, cela est néanmoins supporté par **FastAPI**, seulement pour des cas d'utilisation très complexes/extrêmes.
+
+Ceci étant découragé, la documentation interactive générée par Swagger UI ne montrera pas de documentation pour le corps d'une requête `GET`, et les proxys intermédiaires risquent de ne pas le supporter.
+
+///
## Importez le `BaseModel` de Pydantic
Commencez par importer la classe `BaseModel` du module `pydantic` :
```Python hl_lines="4"
-{!../../../docs_src/body/tutorial001.py!}
+{!../../docs_src/body/tutorial001.py!}
```
## Créez votre modèle de données
@@ -30,7 +33,7 @@ Déclarez ensuite votre modèle de données en tant que classe qui hérite de `B
Utilisez les types Python standard pour tous les attributs :
```Python hl_lines="7-11"
-{!../../../docs_src/body/tutorial001.py!}
+{!../../docs_src/body/tutorial001.py!}
```
Tout comme pour la déclaration de paramètres de requête, quand un attribut de modèle a une valeur par défaut, il n'est pas nécessaire. Sinon, cet attribut doit être renseigné dans le corps de la requête. Pour rendre ce champ optionnel simplement, utilisez `None` comme valeur par défaut.
@@ -60,7 +63,7 @@ Par exemple, le modèle ci-dessus déclare un "objet" JSON (ou `dict` Python) te
Pour l'ajouter à votre *opération de chemin*, déclarez-le comme vous déclareriez des paramètres de chemin ou de requête :
```Python hl_lines="18"
-{!../../../docs_src/body/tutorial001.py!}
+{!../../docs_src/body/tutorial001.py!}
```
...et déclarez que son type est le modèle que vous avez créé : `Item`.
@@ -110,23 +113,26 @@ Mais vous auriez le même support de l'éditeur avec
-!!! tip "Astuce"
- Si vous utilisez PyCharm comme éditeur, vous pouvez utiliser le Plugin Pydantic PyCharm Plugin.
+/// tip | "Astuce"
- Ce qui améliore le support pour les modèles Pydantic avec :
+Si vous utilisez PyCharm comme éditeur, vous pouvez utiliser le Plugin Pydantic PyCharm Plugin.
- * de l'auto-complétion
- * des vérifications de type
- * du "refactoring" (ou remaniement de code)
- * de la recherche
- * de l'inspection
+Ce qui améliore le support pour les modèles Pydantic avec :
+
+* de l'auto-complétion
+* des vérifications de type
+* du "refactoring" (ou remaniement de code)
+* de la recherche
+* de l'inspection
+
+///
## Utilisez le modèle
Dans la fonction, vous pouvez accéder à tous les attributs de l'objet du modèle directement :
```Python hl_lines="21"
-{!../../../docs_src/body/tutorial002.py!}
+{!../../docs_src/body/tutorial002.py!}
```
## Corps de la requête + paramètres de chemin
@@ -136,7 +142,7 @@ Vous pouvez déclarer des paramètres de chemin et un corps de requête pour la
**FastAPI** est capable de reconnaître que les paramètres de la fonction qui correspondent aux paramètres de chemin doivent être **récupérés depuis le chemin**, et que les paramètres de fonctions déclarés comme modèles Pydantic devraient être **récupérés depuis le corps de la requête**.
```Python hl_lines="17-18"
-{!../../../docs_src/body/tutorial003.py!}
+{!../../docs_src/body/tutorial003.py!}
```
## Corps de la requête + paramètres de chemin et de requête
@@ -146,7 +152,7 @@ Vous pouvez aussi déclarer un **corps**, et des paramètres de **chemin** et de
**FastAPI** saura reconnaître chacun d'entre eux et récupérer la bonne donnée au bon endroit.
```Python hl_lines="18"
-{!../../../docs_src/body/tutorial004.py!}
+{!../../docs_src/body/tutorial004.py!}
```
Les paramètres de la fonction seront reconnus comme tel :
@@ -155,10 +161,13 @@ Les paramètres de la fonction seront reconnus comme tel :
* Si le paramètre est d'un **type singulier** (comme `int`, `float`, `str`, `bool`, etc.), il sera interprété comme un paramètre de **requête**.
* Si le paramètre est déclaré comme ayant pour type un **modèle Pydantic**, il sera interprété comme faisant partie du **corps** de la requête.
-!!! note
- **FastAPI** saura que la valeur de `q` n'est pas requise grâce à la valeur par défaut `=None`.
+/// note
- Le type `Optional` dans `Optional[str]` n'est pas utilisé par **FastAPI**, mais sera utile à votre éditeur pour améliorer le support offert par ce dernier et détecter plus facilement des erreurs de type.
+**FastAPI** saura que la valeur de `q` n'est pas requise grâce à la valeur par défaut `=None`.
+
+Le type `Optional` dans `Optional[str]` n'est pas utilisé par **FastAPI**, mais sera utile à votre éditeur pour améliorer le support offert par ce dernier et détecter plus facilement des erreurs de type.
+
+///
## Sans Pydantic
diff --git a/docs/fr/docs/tutorial/debugging.md b/docs/fr/docs/tutorial/debugging.md
index e58872d30..914277699 100644
--- a/docs/fr/docs/tutorial/debugging.md
+++ b/docs/fr/docs/tutorial/debugging.md
@@ -7,7 +7,7 @@ Vous pouvez connecter le débogueur da
Dans votre application FastAPI, importez et exécutez directement `uvicorn` :
```Python hl_lines="1 15"
-{!../../../docs_src/debugging/tutorial001.py!}
+{!../../docs_src/debugging/tutorial001.py!}
```
### À propos de `__name__ == "__main__"`
@@ -74,9 +74,12 @@ Ainsi, la ligne :
ne sera pas exécutée.
-!!! info
+/// info
+
Pour plus d'informations, consultez la documentation officielle de Python.
+///
+
## Exécutez votre code avec votre débogueur
Parce que vous exécutez le serveur Uvicorn directement depuis votre code, vous pouvez appeler votre programme Python (votre application FastAPI) directement depuis le débogueur.
diff --git a/docs/fr/docs/tutorial/first-steps.md b/docs/fr/docs/tutorial/first-steps.md
index e98283f1e..e9511b029 100644
--- a/docs/fr/docs/tutorial/first-steps.md
+++ b/docs/fr/docs/tutorial/first-steps.md
@@ -3,7 +3,7 @@
Le fichier **FastAPI** le plus simple possible pourrait ressembler à cela :
```Python
-{!../../../docs_src/first_steps/tutorial001.py!}
+{!../../docs_src/first_steps/tutorial001.py!}
```
Copiez ce code dans un fichier nommé `main.py`.
@@ -24,12 +24,15 @@ $ uvicorn main:app --reload
get
-!!! info "`@décorateur` Info"
- Cette syntaxe `@something` en Python est appelée un "décorateur".
+/// info | "`@décorateur` Info"
- Vous la mettez au dessus d'une fonction. Comme un joli chapeau décoratif (j'imagine que ce terme vient de là 🤷🏻♂).
+Cette syntaxe `@something` en Python est appelée un "décorateur".
- Un "décorateur" prend la fonction en dessous et en fait quelque chose.
+Vous la mettez au dessus d'une fonction. Comme un joli chapeau décoratif (j'imagine que ce terme vient de là 🤷🏻♂).
- Dans notre cas, ce décorateur dit à **FastAPI** que la fonction en dessous correspond au **chemin** `/` avec l'**opération** `get`.
+Un "décorateur" prend la fonction en dessous et en fait quelque chose.
- C'est le "**décorateur d'opération de chemin**".
+Dans notre cas, ce décorateur dit à **FastAPI** que la fonction en dessous correspond au **chemin** `/` avec l'**opération** `get`.
+
+C'est le "**décorateur d'opération de chemin**".
+
+///
Vous pouvez aussi utiliser les autres opérations :
@@ -275,14 +286,17 @@ Tout comme celles les plus exotiques :
* `@app.patch()`
* `@app.trace()`
-!!! tip "Astuce"
- Vous êtes libres d'utiliser chaque opération (méthode HTTP) comme vous le désirez.
+/// tip | "Astuce"
- **FastAPI** n'impose pas de sens spécifique à chacune d'elle.
+Vous êtes libres d'utiliser chaque opération (méthode HTTP) comme vous le désirez.
- Les informations qui sont présentées ici forment une directive générale, pas des obligations.
+**FastAPI** n'impose pas de sens spécifique à chacune d'elle.
- Par exemple, quand l'on utilise **GraphQL**, toutes les actions sont effectuées en utilisant uniquement des opérations `POST`.
+Les informations qui sont présentées ici forment une directive générale, pas des obligations.
+
+Par exemple, quand l'on utilise **GraphQL**, toutes les actions sont effectuées en utilisant uniquement des opérations `POST`.
+
+///
### Étape 4 : définir la **fonction de chemin**.
@@ -293,7 +307,7 @@ Voici notre "**fonction de chemin**" (ou fonction d'opération de chemin) :
* **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!}
```
C'est une fonction Python.
@@ -307,16 +321,19 @@ 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!}
```
-!!! note
- Si vous ne connaissez pas la différence, allez voir la section [Concurrence : *"Vous êtes pressés ?"*](../async.md#vous-etes-presses){.internal-link target=_blank}.
+/// note
+
+Si vous ne connaissez pas la différence, allez voir la section [Concurrence : *"Vous êtes pressés ?"*](../async.md#vous-etes-presses){.internal-link target=_blank}.
+
+///
### Étape 5 : retourner le contenu
```Python hl_lines="8"
-{!../../../docs_src/first_steps/tutorial001.py!}
+{!../../docs_src/first_steps/tutorial001.py!}
```
Vous pouvez retourner un dictionnaire (`dict`), une liste (`list`), des valeurs seules comme des chaines de caractères (`str`) et des entiers (`int`), etc.
diff --git a/docs/fr/docs/tutorial/index.md b/docs/fr/docs/tutorial/index.md
index 4dc202b33..83cc5f9e8 100644
--- a/docs/fr/docs/tutorial/index.md
+++ b/docs/fr/docs/tutorial/index.md
@@ -52,22 +52,25 @@ $ pip install fastapi[all]
... qui comprend également `uvicorn`, que vous pouvez utiliser comme serveur pour exécuter votre code.
-!!! note
- Vous pouvez également l'installer pièce par pièce.
+/// note
- C'est ce que vous feriez probablement une fois que vous voudrez déployer votre application en production :
+Vous pouvez également l'installer pièce par pièce.
- ```
- pip install fastapi
- ```
+C'est ce que vous feriez probablement une fois que vous voudrez déployer votre application en production :
- Installez également `uvicorn` pour qu'il fonctionne comme serveur :
+```
+pip install fastapi
+```
- ```
- pip install uvicorn
- ```
+Installez également `uvicorn` pour qu'il fonctionne comme serveur :
- Et la même chose pour chacune des dépendances facultatives que vous voulez utiliser.
+```
+pip install uvicorn
+```
+
+Et la même chose pour chacune des dépendances facultatives que vous voulez utiliser.
+
+///
## Guide utilisateur avancé
diff --git a/docs/fr/docs/tutorial/path-params-numeric-validations.md b/docs/fr/docs/tutorial/path-params-numeric-validations.md
index e8dcd37fb..82e317ff7 100644
--- a/docs/fr/docs/tutorial/path-params-numeric-validations.md
+++ b/docs/fr/docs/tutorial/path-params-numeric-validations.md
@@ -6,48 +6,67 @@ De la même façon que vous pouvez déclarer plus de validations et de métadonn
Tout d'abord, importez `Path` de `fastapi`, et importez `Annotated` :
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="1 3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="1 3"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="1 3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="1 3"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="3-4"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Préférez utiliser la version `Annotated` si possible.
+```Python hl_lines="3-4"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
+```
- ```Python hl_lines="1"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Préférez utiliser la version `Annotated` si possible.
+/// tip
- ```Python hl_lines="3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
- ```
+Préférez utiliser la version `Annotated` si possible.
-!!! info
- FastAPI a ajouté le support pour `Annotated` (et a commencé à le recommander) dans la version 0.95.0.
+///
- Si vous avez une version plus ancienne, vous obtiendrez des erreurs en essayant d'utiliser `Annotated`.
+```Python hl_lines="1"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
+```
- Assurez-vous de [Mettre à jour la version de FastAPI](../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} à la version 0.95.1 à minima avant d'utiliser `Annotated`.
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Préférez utiliser la version `Annotated` si possible.
+
+///
+
+```Python hl_lines="3"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!}
+```
+
+////
+
+/// info
+
+FastAPI a ajouté le support pour `Annotated` (et a commencé à le recommander) dans la version 0.95.0.
+
+Si vous avez une version plus ancienne, vous obtiendrez des erreurs en essayant d'utiliser `Annotated`.
+
+Assurez-vous de [Mettre à jour la version de FastAPI](../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} à la version 0.95.1 à minima avant d'utiliser `Annotated`.
+
+///
## Déclarer des métadonnées
@@ -55,49 +74,71 @@ Vous pouvez déclarer les mêmes paramètres que pour `Query`.
Par exemple, pour déclarer une valeur de métadonnée `title` pour le paramètre de chemin `item_id`, vous pouvez écrire :
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="10"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="10"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="11"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Préférez utiliser la version `Annotated` si possible.
+```Python hl_lines="11"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
+```
- ```Python hl_lines="8"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Préférez utiliser la version `Annotated` si possible.
+/// tip
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
- ```
+Préférez utiliser la version `Annotated` si possible.
-!!! note
- Un paramètre de chemin est toujours requis car il doit faire partie du chemin. Même si vous l'avez déclaré avec `None` ou défini une valeur par défaut, cela ne changerait rien, il serait toujours requis.
+///
+
+```Python hl_lines="8"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Préférez utiliser la version `Annotated` si possible.
+
+///
+
+```Python hl_lines="10"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!}
+```
+
+////
+
+/// note
+
+Un paramètre de chemin est toujours requis car il doit faire partie du chemin. Même si vous l'avez déclaré avec `None` ou défini une valeur par défaut, cela ne changerait rien, il serait toujours requis.
+
+///
## Ordonnez les paramètres comme vous le souhaitez
-!!! tip
- Ce n'est probablement pas aussi important ou nécessaire si vous utilisez `Annotated`.
+/// tip
+
+Ce n'est probablement pas aussi important ou nécessaire si vous utilisez `Annotated`.
+
+///
Disons que vous voulez déclarer le paramètre de requête `q` comme un `str` requis.
@@ -113,33 +154,45 @@ Cela n'a pas d'importance pour **FastAPI**. Il détectera les paramètres par le
Ainsi, vous pouvez déclarer votre fonction comme suit :
-=== "Python 3.8 non-Annotated"
+//// tab | Python 3.8 non-Annotated
- !!! tip
- Préférez utiliser la version `Annotated` si possible.
+/// tip
- ```Python hl_lines="7"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!}
- ```
+Préférez utiliser la version `Annotated` si possible.
+
+///
+
+```Python hl_lines="7"
+{!> ../../docs_src/path_params_numeric_validations/tutorial002.py!}
+```
+
+////
Mais gardez à l'esprit que si vous utilisez `Annotated`, vous n'aurez pas ce problème, cela n'aura pas d'importance car vous n'utilisez pas les valeurs par défaut des paramètres de fonction pour `Query()` ou `Path()`.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!}
- ```
+```Python hl_lines="10"
+{!> ../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../docs_src/path_params_numeric_validations/tutorial002_an.py!}
+```
+
+////
## Ordonnez les paramètres comme vous le souhaitez (astuces)
-!!! tip
- Ce n'est probablement pas aussi important ou nécessaire si vous utilisez `Annotated`.
+/// tip
+
+Ce n'est probablement pas aussi important ou nécessaire si vous utilisez `Annotated`.
+
+///
Voici une **petite astuce** qui peut être pratique, mais vous n'en aurez pas souvent besoin.
@@ -157,24 +210,28 @@ 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!}
```
# Avec `Annotated`
Gardez à l'esprit que si vous utilisez `Annotated`, comme vous n'utilisez pas les valeurs par défaut des paramètres de fonction, vous n'aurez pas ce problème, et vous n'aurez probablement pas besoin d'utiliser `*`.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!}
- ```
+```Python hl_lines="10"
+{!> ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../docs_src/path_params_numeric_validations/tutorial003_an.py!}
+```
+
+////
## Validations numériques : supérieur ou égal
@@ -182,26 +239,35 @@ Avec `Query` et `Path` (et d'autres que vous verrez plus tard) vous pouvez décl
Ici, avec `ge=1`, `item_id` devra être un nombre entier "`g`reater than or `e`qual" à `1`.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!}
- ```
+```Python hl_lines="10"
+{!> ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="9"
+{!> ../../docs_src/path_params_numeric_validations/tutorial004_an.py!}
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="8"
+{!> ../../docs_src/path_params_numeric_validations/tutorial004.py!}
+```
+
+////
## Validations numériques : supérieur ou égal et inférieur ou égal
@@ -210,26 +276,35 @@ La même chose s'applique pour :
* `gt` : `g`reater `t`han
* `le` : `l`ess than or `e`qual
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!}
- ```
+```Python hl_lines="10"
+{!> ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="9"
+{!> ../../docs_src/path_params_numeric_validations/tutorial004_an.py!}
+```
- !!! tip
- Préférez utiliser la version `Annotated` si possible.
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Préférez utiliser la version `Annotated` si possible.
+
+///
+
+```Python hl_lines="8"
+{!> ../../docs_src/path_params_numeric_validations/tutorial004.py!}
+```
+
+////
## Validations numériques : supérieur et inférieur ou égal
@@ -238,26 +313,35 @@ La même chose s'applique pour :
* `gt` : `g`reater `t`han
* `le` : `l`ess than or `e`qual
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!}
- ```
+```Python hl_lines="10"
+{!> ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="9"
+{!> ../../docs_src/path_params_numeric_validations/tutorial005_an.py!}
+```
- !!! tip
- Préférez utiliser la version `Annotated` si possible.
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Préférez utiliser la version `Annotated` si possible.
+
+///
+
+```Python hl_lines="9"
+{!> ../../docs_src/path_params_numeric_validations/tutorial005.py!}
+```
+
+////
## Validations numériques : flottants, supérieur et inférieur
@@ -269,26 +353,35 @@ Ainsi, `0.5` serait une valeur valide. Mais `0.0` ou `0` ne le serait pas.
Et la même chose pour lt.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="13"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!}
- ```
+```Python hl_lines="13"
+{!> ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="12"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="12"
+{!> ../../docs_src/path_params_numeric_validations/tutorial006_an.py!}
+```
- !!! tip
- Préférez utiliser la version `Annotated` si possible.
+////
- ```Python hl_lines="11"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Préférez utiliser la version `Annotated` si possible.
+
+///
+
+```Python hl_lines="11"
+{!> ../../docs_src/path_params_numeric_validations/tutorial006.py!}
+```
+
+////
## Pour résumer
@@ -301,18 +394,24 @@ Et vous pouvez également déclarer des validations numériques :
* `lt` : `l`ess `t`han
* `le` : `l`ess than or `e`qual
-!!! info
- `Query`, `Path`, et d'autres classes que vous verrez plus tard sont des sous-classes d'une classe commune `Param`.
+/// info
- Tous partagent les mêmes paramètres pour des validations supplémentaires et des métadonnées que vous avez vu précédemment.
+`Query`, `Path`, et d'autres classes que vous verrez plus tard sont des sous-classes d'une classe commune `Param`.
-!!! note "Détails techniques"
- Lorsque vous importez `Query`, `Path` et d'autres de `fastapi`, ce sont en fait des fonctions.
+Tous partagent les mêmes paramètres pour des validations supplémentaires et des métadonnées que vous avez vu précédemment.
- Ces dernières, lorsqu'elles sont appelées, renvoient des instances de classes du même nom.
+///
- Ainsi, vous importez `Query`, qui est une fonction. Et lorsque vous l'appelez, elle renvoie une instance d'une classe également nommée `Query`.
+/// note | "Détails techniques"
- Ces fonctions sont là (au lieu d'utiliser simplement les classes directement) pour que votre éditeur ne marque pas d'erreurs sur leurs types.
+Lorsque vous importez `Query`, `Path` et d'autres de `fastapi`, ce sont en fait des fonctions.
- De cette façon, vous pouvez utiliser votre éditeur et vos outils de codage habituels sans avoir à ajouter des configurations personnalisées pour ignorer ces erreurs.
+Ces dernières, lorsqu'elles sont appelées, renvoient des instances de classes du même nom.
+
+Ainsi, vous importez `Query`, qui est une fonction. Et lorsque vous l'appelez, elle renvoie une instance d'une classe également nommée `Query`.
+
+Ces fonctions sont là (au lieu d'utiliser simplement les classes directement) pour que votre éditeur ne marque pas d'erreurs sur leurs types.
+
+De cette façon, vous pouvez utiliser votre éditeur et vos outils de codage habituels sans avoir à ajouter des configurations personnalisées pour ignorer ces erreurs.
+
+///
diff --git a/docs/fr/docs/tutorial/path-params.md b/docs/fr/docs/tutorial/path-params.md
index 523e2c8c2..34012c278 100644
--- a/docs/fr/docs/tutorial/path-params.md
+++ b/docs/fr/docs/tutorial/path-params.md
@@ -5,7 +5,7 @@ Vous pouvez déclarer des "paramètres" ou "variables" de chemin avec la même s
```Python hl_lines="6-7"
-{!../../../docs_src/path_params/tutorial001.py!}
+{!../../docs_src/path_params/tutorial001.py!}
```
La valeur du paramètre `item_id` sera transmise à la fonction dans l'argument `item_id`.
@@ -23,14 +23,17 @@ Vous pouvez déclarer le type d'un paramètre de chemin dans la fonction, en uti
```Python hl_lines="7"
-{!../../../docs_src/path_params/tutorial002.py!}
+{!../../docs_src/path_params/tutorial002.py!}
```
Ici, `item_id` est déclaré comme `int`.
-!!! check "vérifier"
- Ceci vous permettra d'obtenir des fonctionnalités de l'éditeur dans votre fonction, telles
- que des vérifications d'erreur, de l'auto-complétion, etc.
+/// check | "vérifier"
+
+Ceci vous permettra d'obtenir des fonctionnalités de l'éditeur dans votre fonction, telles
+que des vérifications d'erreur, de l'auto-complétion, etc.
+
+///
## Conversion de données
@@ -40,12 +43,15 @@ Si vous exécutez cet exemple et allez sur "parsing" automatique.
+Comme vous l'avez remarqué, la valeur reçue par la fonction (et renvoyée ensuite) est `3`,
+en tant qu'entier (`int`) Python, pas la chaîne de caractères (`string`) `"3"`.
+
+Grâce aux déclarations de types, **FastAPI** fournit du
+"parsing" automatique.
+
+///
## Validation de données
@@ -72,12 +78,15 @@ La même erreur se produira si vous passez un nombre flottant (`float`) et non u
http://127.0.0.1:8000/items/4.2.
-!!! check "vérifier"
- Donc, avec ces mêmes déclarations de type Python, **FastAPI** vous fournit de la validation de données.
+/// check | "vérifier"
- Notez que l'erreur mentionne le point exact où la validation n'a pas réussi.
+Donc, avec ces mêmes déclarations de type Python, **FastAPI** vous fournit de la validation de données.
- Ce qui est incroyablement utile au moment de développer et débugger du code qui interagit avec votre API.
+Notez que l'erreur mentionne le point exact où la validation n'a pas réussi.
+
+Ce qui est incroyablement utile au moment de développer et débugger du code qui interagit avec votre API.
+
+///
## Documentation
@@ -86,10 +95,13 @@ documentation générée automatiquement et interactive :
-!!! info
- À nouveau, en utilisant uniquement les déclarations de type Python, **FastAPI** vous fournit automatiquement une documentation interactive (via Swagger UI).
+/// info
- On voit bien dans la documentation que `item_id` est déclaré comme entier.
+À nouveau, en utilisant uniquement les déclarations de type Python, **FastAPI** vous fournit automatiquement une documentation interactive (via Swagger UI).
+
+On voit bien dans la documentation que `item_id` est déclaré comme entier.
+
+///
## Les avantages d'avoir une documentation basée sur une norme, et la documentation alternative.
@@ -120,7 +132,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!}
```
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"`.
@@ -138,21 +150,27 @@ 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!}
```
-!!! info
- Les énumérations (ou enums) sont disponibles en Python depuis la version 3.4.
+/// info
-!!! tip "Astuce"
- Pour ceux qui se demandent, "AlexNet", "ResNet", et "LeNet" sont juste des noms de modèles de Machine Learning.
+Les énumérations (ou enums) sont disponibles en Python depuis la version 3.4.
+
+///
+
+/// tip | "Astuce"
+
+Pour ceux qui se demandent, "AlexNet", "ResNet", et "LeNet" sont juste des noms de modèles de Machine Learning.
+
+///
### Déclarer un paramètre de chemin
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!}
```
### Documentation
@@ -170,7 +188,7 @@ 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!}
```
#### Récupérer la *valeur de l'énumération*
@@ -178,11 +196,14 @@ Vous pouvez comparer ce paramètre avec les membres de votre énumération `Mode
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!}
```
-!!! tip "Astuce"
- Vous pouvez aussi accéder la valeur `"lenet"` avec `ModelName.lenet.value`.
+/// tip | "Astuce"
+
+Vous pouvez aussi accéder la valeur `"lenet"` avec `ModelName.lenet.value`.
+
+///
#### Retourner des *membres d'énumération*
@@ -191,7 +212,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!}
```
Le client recevra une réponse JSON comme celle-ci :
@@ -232,13 +253,16 @@ 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!}
```
-!!! tip "Astuce"
- Vous pourriez avoir besoin que le paramètre contienne `/home/johndoe/myfile.txt`, avec un slash au début (`/`).
+/// tip | "Astuce"
- Dans ce cas, l'URL serait : `/files//home/johndoe/myfile.txt`, avec un double slash (`//`) entre `files` et `home`.
+Vous pourriez avoir besoin que le paramètre contienne `/home/johndoe/myfile.txt`, avec un slash au début (`/`).
+
+Dans ce cas, l'URL serait : `/files//home/johndoe/myfile.txt`, avec un double slash (`//`) entre `files` et `home`.
+
+///
## Récapitulatif
diff --git a/docs/fr/docs/tutorial/query-params-str-validations.md b/docs/fr/docs/tutorial/query-params-str-validations.md
index f5248fe8b..b71d1548a 100644
--- a/docs/fr/docs/tutorial/query-params-str-validations.md
+++ b/docs/fr/docs/tutorial/query-params-str-validations.md
@@ -5,15 +5,18 @@
Commençons avec cette application pour exemple :
```Python hl_lines="9"
-{!../../../docs_src/query_params_str_validations/tutorial001.py!}
+{!../../docs_src/query_params_str_validations/tutorial001.py!}
```
Le paramètre de requête `q` a pour type `Union[str, None]` (ou `str | None` en Python 3.10), signifiant qu'il est de type `str` mais pourrait aussi être égal à `None`, et bien sûr, la valeur par défaut est `None`, donc **FastAPI** saura qu'il n'est pas requis.
-!!! note
- **FastAPI** saura que la valeur de `q` n'est pas requise grâce à la valeur par défaut `= None`.
+/// note
- Le `Union` dans `Union[str, None]` permettra à votre éditeur de vous offrir un meilleur support et de détecter les erreurs.
+**FastAPI** saura que la valeur de `q` n'est pas requise grâce à la valeur par défaut `= None`.
+
+Le `Union` dans `Union[str, None]` permettra à votre éditeur de vous offrir un meilleur support et de détecter les erreurs.
+
+///
## Validation additionnelle
@@ -24,7 +27,7 @@ Nous allons imposer que bien que `q` soit un paramètre optionnel, dès qu'il es
Pour cela, importez d'abord `Query` depuis `fastapi` :
```Python hl_lines="3"
-{!../../../docs_src/query_params_str_validations/tutorial002.py!}
+{!../../docs_src/query_params_str_validations/tutorial002.py!}
```
## Utiliser `Query` comme valeur par défaut
@@ -32,7 +35,7 @@ Pour cela, importez d'abord `Query` depuis `fastapi` :
Construisez ensuite la valeur par défaut de votre paramètre avec `Query`, en choisissant 50 comme `max_length` :
```Python hl_lines="9"
-{!../../../docs_src/query_params_str_validations/tutorial002.py!}
+{!../../docs_src/query_params_str_validations/tutorial002.py!}
```
Comme nous devons remplacer la valeur par défaut `None` dans la fonction par `Query()`, nous pouvons maintenant définir la valeur par défaut avec le paramètre `Query(default=None)`, il sert le même objectif qui est de définir cette valeur par défaut.
@@ -51,22 +54,25 @@ q: Union[str, None] = None
Mais déclare explicitement `q` comme étant un paramètre de requête.
-!!! info
- Gardez à l'esprit que la partie la plus importante pour rendre un paramètre optionnel est :
+/// info
- ```Python
- = None
- ```
+Gardez à l'esprit que la partie la plus importante pour rendre un paramètre optionnel est :
- ou :
+```Python
+= None
+```
- ```Python
- = Query(None)
- ```
+ou :
- et utilisera ce `None` pour détecter que ce paramètre de requête **n'est pas requis**.
+```Python
+= Query(None)
+```
- Le `Union[str, None]` est uniquement là pour permettre à votre éditeur un meilleur support.
+et utilisera ce `None` pour détecter que ce paramètre de requête **n'est pas requis**.
+
+Le `Union[str, None]` est uniquement là pour permettre à votre éditeur un meilleur support.
+
+///
Ensuite, nous pouvons passer d'autres paramètres à `Query`. Dans cet exemple, le paramètre `max_length` qui s'applique aux chaînes de caractères :
@@ -81,7 +87,7 @@ Cela va valider les données, montrer une erreur claire si ces dernières ne son
Vous pouvez aussi rajouter un second paramètre `min_length` :
```Python hl_lines="9"
-{!../../../docs_src/query_params_str_validations/tutorial003.py!}
+{!../../docs_src/query_params_str_validations/tutorial003.py!}
```
## Ajouter des validations par expressions régulières
@@ -89,7 +95,7 @@ Vous pouvez aussi rajouter un second paramètre `min_length` :
On peut définir une expression régulière à laquelle le paramètre doit correspondre :
```Python hl_lines="10"
-{!../../../docs_src/query_params_str_validations/tutorial004.py!}
+{!../../docs_src/query_params_str_validations/tutorial004.py!}
```
Cette expression régulière vérifie que la valeur passée comme paramètre :
@@ -109,11 +115,14 @@ De la même façon que vous pouvez passer `None` comme premier argument pour l'u
Disons que vous déclarez le paramètre `q` comme ayant une longueur minimale de `3`, et une valeur par défaut étant `"fixedquery"` :
```Python hl_lines="7"
-{!../../../docs_src/query_params_str_validations/tutorial005.py!}
+{!../../docs_src/query_params_str_validations/tutorial005.py!}
```
-!!! note "Rappel"
- Avoir une valeur par défaut rend le paramètre optionnel.
+/// note | "Rappel"
+
+Avoir une valeur par défaut rend le paramètre optionnel.
+
+///
## Rendre ce paramètre requis
@@ -138,11 +147,14 @@ q: Union[str, None] = Query(default=None, min_length=3)
Donc pour déclarer une valeur comme requise tout en utilisant `Query`, il faut utiliser `...` comme premier argument :
```Python hl_lines="7"
-{!../../../docs_src/query_params_str_validations/tutorial006.py!}
+{!../../docs_src/query_params_str_validations/tutorial006.py!}
```
-!!! info
- Si vous n'avez jamais vu ce `...` auparavant : c'est une des constantes natives de Python appelée "Ellipsis".
+/// info
+
+Si vous n'avez jamais vu ce `...` auparavant : c'est une des constantes natives de Python appelée "Ellipsis".
+
+///
Cela indiquera à **FastAPI** que la présence de ce paramètre est obligatoire.
@@ -153,7 +165,7 @@ Quand on définit un paramètre de requête explicitement avec `Query` on peut a
Par exemple, pour déclarer un paramètre de requête `q` qui peut apparaître plusieurs fois dans une URL, on écrit :
```Python hl_lines="9"
-{!../../../docs_src/query_params_str_validations/tutorial011.py!}
+{!../../docs_src/query_params_str_validations/tutorial011.py!}
```
Ce qui fait qu'avec une URL comme :
@@ -175,8 +187,11 @@ Donc la réponse de cette URL serait :
}
```
-!!! tip "Astuce"
- Pour déclarer un paramètre de requête de type `list`, comme dans l'exemple ci-dessus, il faut explicitement utiliser `Query`, sinon cela sera interprété comme faisant partie du corps de la requête.
+/// tip | "Astuce"
+
+Pour déclarer un paramètre de requête de type `list`, comme dans l'exemple ci-dessus, il faut explicitement utiliser `Query`, sinon cela sera interprété comme faisant partie du corps de la requête.
+
+///
La documentation sera donc mise à jour automatiquement pour autoriser plusieurs valeurs :
@@ -187,7 +202,7 @@ La documentation sera donc mise à jour automatiquement pour autoriser plusieurs
Et l'on peut aussi définir une liste de valeurs par défaut si aucune n'est fournie :
```Python hl_lines="9"
-{!../../../docs_src/query_params_str_validations/tutorial012.py!}
+{!../../docs_src/query_params_str_validations/tutorial012.py!}
```
Si vous allez à :
@@ -214,13 +229,16 @@ et la réponse sera :
Il est aussi possible d'utiliser directement `list` plutôt que `List[str]` :
```Python hl_lines="7"
-{!../../../docs_src/query_params_str_validations/tutorial013.py!}
+{!../../docs_src/query_params_str_validations/tutorial013.py!}
```
-!!! note
- Dans ce cas-là, **FastAPI** ne vérifiera pas le contenu de la liste.
+/// note
- Par exemple, `List[int]` vérifiera (et documentera) que la liste est bien entièrement composée d'entiers. Alors qu'un simple `list` ne ferait pas cette vérification.
+Dans ce cas-là, **FastAPI** ne vérifiera pas le contenu de la liste.
+
+Par exemple, `List[int]` vérifiera (et documentera) que la liste est bien entièrement composée d'entiers. Alors qu'un simple `list` ne ferait pas cette vérification.
+
+///
## Déclarer des métadonnées supplémentaires
@@ -228,21 +246,24 @@ On peut aussi ajouter plus d'informations sur le paramètre.
Ces informations seront incluses dans le schéma `OpenAPI` généré et utilisées par la documentation interactive ou les outils externes utilisés.
-!!! note
- Gardez en tête que les outils externes utilisés ne supportent pas forcément tous parfaitement OpenAPI.
+/// note
- Il se peut donc que certains d'entre eux n'utilisent pas toutes les métadonnées que vous avez déclarées pour le moment, bien que dans la plupart des cas, les fonctionnalités manquantes ont prévu d'être implémentées.
+Gardez en tête que les outils externes utilisés ne supportent pas forcément tous parfaitement OpenAPI.
+
+Il se peut donc que certains d'entre eux n'utilisent pas toutes les métadonnées que vous avez déclarées pour le moment, bien que dans la plupart des cas, les fonctionnalités manquantes ont prévu d'être implémentées.
+
+///
Vous pouvez ajouter un `title` :
```Python hl_lines="10"
-{!../../../docs_src/query_params_str_validations/tutorial007.py!}
+{!../../docs_src/query_params_str_validations/tutorial007.py!}
```
Et une `description` :
```Python hl_lines="13"
-{!../../../docs_src/query_params_str_validations/tutorial008.py!}
+{!../../docs_src/query_params_str_validations/tutorial008.py!}
```
## Alias de paramètres
@@ -264,7 +285,7 @@ Mais vous avez vraiment envie que ce soit exactement `item-query`...
Pour cela vous pouvez déclarer un `alias`, et cet alias est ce qui sera utilisé pour trouver la valeur du paramètre :
```Python hl_lines="9"
-{!../../../docs_src/query_params_str_validations/tutorial009.py!}
+{!../../docs_src/query_params_str_validations/tutorial009.py!}
```
## Déprécier des paramètres
@@ -276,7 +297,7 @@ Il faut qu'il continue à exister pendant un certain temps car vos clients l'uti
On utilise alors l'argument `deprecated=True` de `Query` :
```Python hl_lines="18"
-{!../../../docs_src/query_params_str_validations/tutorial010.py!}
+{!../../docs_src/query_params_str_validations/tutorial010.py!}
```
La documentation le présentera comme il suit :
diff --git a/docs/fr/docs/tutorial/query-params.md b/docs/fr/docs/tutorial/query-params.md
index 962135f63..c847a8f5b 100644
--- a/docs/fr/docs/tutorial/query-params.md
+++ b/docs/fr/docs/tutorial/query-params.md
@@ -3,7 +3,7 @@
Quand vous déclarez des paramètres dans votre fonction de chemin qui ne font pas partie des paramètres indiqués dans le chemin associé, ces paramètres sont automatiquement considérés comme des paramètres de "requête".
```Python hl_lines="9"
-{!../../../docs_src/query_params/tutorial001.py!}
+{!../../docs_src/query_params/tutorial001.py!}
```
La partie appelée requête (ou **query**) dans une URL est l'ensemble des paires clés-valeurs placées après le `?` , séparées par des `&`.
@@ -64,26 +64,31 @@ Les valeurs des paramètres de votre fonction seront :
De la même façon, vous pouvez définir des paramètres de requête comme optionnels, en leur donnant comme valeur par défaut `None` :
```Python hl_lines="9"
-{!../../../docs_src/query_params/tutorial002.py!}
+{!../../docs_src/query_params/tutorial002.py!}
```
Ici, le paramètre `q` sera optionnel, et aura `None` comme valeur par défaut.
-!!! check "Remarque"
- On peut voir que **FastAPI** est capable de détecter que le paramètre de chemin `item_id` est un paramètre de chemin et que `q` n'en est pas un, c'est donc un paramètre de requête.
+/// check | "Remarque"
-!!! note
- **FastAPI** saura que `q` est optionnel grâce au `=None`.
+On peut voir que **FastAPI** est capable de détecter que le paramètre de chemin `item_id` est un paramètre de chemin et que `q` n'en est pas un, c'est donc un paramètre de requête.
- Le `Optional` dans `Optional[str]` n'est pas utilisé par **FastAPI** (**FastAPI** n'en utilisera que la partie `str`), mais il servira tout de même à votre éditeur de texte pour détecter des erreurs dans votre code.
+///
+/// note
+
+**FastAPI** saura que `q` est optionnel grâce au `=None`.
+
+Le `Optional` dans `Optional[str]` n'est pas utilisé par **FastAPI** (**FastAPI** n'en utilisera que la partie `str`), mais il servira tout de même à votre éditeur de texte pour détecter des erreurs dans votre code.
+
+///
## Conversion des types des paramètres de requête
Vous pouvez aussi déclarer des paramètres de requête comme booléens (`bool`), **FastAPI** les convertira :
```Python hl_lines="9"
-{!../../../docs_src/query_params/tutorial003.py!}
+{!../../docs_src/query_params/tutorial003.py!}
```
Avec ce code, en allant sur :
@@ -127,7 +132,7 @@ Et vous n'avez pas besoin de les déclarer dans un ordre spécifique.
Ils seront détectés par leurs noms :
```Python hl_lines="8 10"
-{!../../../docs_src/query_params/tutorial004.py!}
+{!../../docs_src/query_params/tutorial004.py!}
```
## Paramètres de requête requis
@@ -139,7 +144,7 @@ Si vous ne voulez pas leur donner de valeur par défaut mais juste les rendre op
Mais si vous voulez rendre un paramètre de requête obligatoire, vous pouvez juste ne pas y affecter de valeur par défaut :
```Python hl_lines="6-7"
-{!../../../docs_src/query_params/tutorial005.py!}
+{!../../docs_src/query_params/tutorial005.py!}
```
Ici le paramètre `needy` est un paramètre requis (ou obligatoire) de type `str`.
@@ -185,7 +190,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
Et bien sur, vous pouvez définir certains paramètres comme requis, certains avec des valeurs par défaut et certains entièrement optionnels :
```Python hl_lines="10"
-{!../../../docs_src/query_params/tutorial006.py!}
+{!../../docs_src/query_params/tutorial006.py!}
```
Ici, on a donc 3 paramètres de requête :
@@ -194,5 +199,8 @@ Ici, on a donc 3 paramètres de requête :
* `skip`, un `int` avec comme valeur par défaut `0`.
* `limit`, un `int` optionnel.
-!!! tip "Astuce"
- Vous pouvez utiliser les `Enum`s de la même façon qu'avec les [Paramètres de chemin](path-params.md#valeurs-predefinies){.internal-link target=_blank}.
+/// tip | "Astuce"
+
+Vous pouvez utiliser les `Enum`s de la même façon qu'avec les [Paramètres de chemin](path-params.md#valeurs-predefinies){.internal-link target=_blank}.
+
+///
diff --git a/docs/he/docs/index.md b/docs/he/docs/index.md
index 3af166ab0..23a2eb824 100644
--- a/docs/he/docs/index.md
+++ b/docs/he/docs/index.md
@@ -446,7 +446,7 @@ item: Item
בשימוש Pydantic:
-- email_validator - לאימות כתובות אימייל.
+- email-validator - לאימות כתובות אימייל.
בשימוש Starlette:
diff --git a/docs/hu/docs/index.md b/docs/hu/docs/index.md
index b7231ad56..8e326a78b 100644
--- a/docs/hu/docs/index.md
+++ b/docs/hu/docs/index.md
@@ -376,7 +376,7 @@ Visszatérve az előző kód példához. A **FastAPI**:
* Validálja hogy van egy `item_id` mező a `GET` és `PUT` kérésekben.
* Validálja hogy az `item_id` `int` típusú a `GET` és `PUT` kérésekben.
* Ha nem akkor látni fogunk egy tiszta hibát ezzel kapcsolatban.
-* ellenőrzi hogyha van egy opcionális query paraméter `q` névvel (azaz `http://127.0.0.1:8000/items/foo?q=somequery`) `GET` kérések esetén.
+* ellenőrzi hogyha van egy opcionális query paraméter `q` névvel (azaz `http://127.0.0.1:8000/items/foo?q=somequery`) `GET` kérések esetén.
* Mivel a `q` paraméter `= None`-al van deklarálva, ezért opcionális.
* `None` nélkül ez a mező kötelező lenne (mint például a body `PUT` kérések esetén).
* a `/items/{item_id}` címre érkező `PUT` kérések esetén, a JSON-t a következőképpen olvassa be:
@@ -443,7 +443,7 @@ Ezeknek a további megértéséhez: email_validator - e-mail validációkra.
+* email-validator - e-mail validációkra.
* pydantic-settings - Beállítások követésére.
* pydantic-extra-types - Extra típusok Pydantic-hoz.
diff --git a/docs/id/docs/tutorial/index.md b/docs/id/docs/tutorial/index.md
index 6b6de24f0..f0dee3d73 100644
--- a/docs/id/docs/tutorial/index.md
+++ b/docs/id/docs/tutorial/index.md
@@ -52,22 +52,25 @@ $ pip install "fastapi[all]"
...yang juga termasuk `uvicorn`, yang dapat kamu gunakan sebagai server yang menjalankan kodemu.
-!!! note "Catatan"
- Kamu juga dapat meng-installnya bagian demi bagian.
+/// note | "Catatan"
- Hal ini mungkin yang akan kamu lakukan ketika kamu hendak menyebarkan (men-deploy) aplikasimu ke tahap produksi:
+Kamu juga dapat meng-installnya bagian demi bagian.
- ```
- pip install fastapi
- ```
+Hal ini mungkin yang akan kamu lakukan ketika kamu hendak menyebarkan (men-deploy) aplikasimu ke tahap produksi:
- Juga install `uvicorn` untuk menjalankan server"
+```
+pip install fastapi
+```
- ```
- pip install "uvicorn[standard]"
- ```
+Juga install `uvicorn` untuk menjalankan server"
- Dan demikian juga untuk pilihan dependensi yang hendak kamu gunakan.
+```
+pip install "uvicorn[standard]"
+```
+
+Dan demikian juga untuk pilihan dependensi yang hendak kamu gunakan.
+
+///
## Pedoman Pengguna Lanjutan
diff --git a/docs/it/docs/index.md b/docs/it/docs/index.md
index 38f611734..3bfff82f1 100644
--- a/docs/it/docs/index.md
+++ b/docs/it/docs/index.md
@@ -1,7 +1,3 @@
-
-{!../../../docs/missing-translation.md!}
-
-
@@ -438,7 +434,7 @@ Per approfondire, consulta la sezione email_validator - per la validazione di email.
+* email-validator - per la validazione di email.
Usate da Starlette:
diff --git a/docs/ja/docs/advanced/additional-status-codes.md b/docs/ja/docs/advanced/additional-status-codes.md
index d1f8e6451..904d539e7 100644
--- a/docs/ja/docs/advanced/additional-status-codes.md
+++ b/docs/ja/docs/advanced/additional-status-codes.md
@@ -15,20 +15,26 @@
これを達成するには、 `JSONResponse` をインポートし、 `status_code` を設定して直接内容を返します。
```Python hl_lines="4 25"
-{!../../../docs_src/additional_status_codes/tutorial001.py!}
+{!../../docs_src/additional_status_codes/tutorial001.py!}
```
-!!! warning "注意"
- 上記の例のように `Response` を明示的に返す場合、それは直接返されます。
+/// warning | "注意"
- モデルなどはシリアライズされません。
+上記の例のように `Response` を明示的に返す場合、それは直接返されます。
- 必要なデータが含まれていることや、値が有効なJSONであること (`JSONResponse` を使う場合) を確認してください。
+モデルなどはシリアライズされません。
-!!! note "技術詳細"
- `from starlette.responses import JSONResponse` を利用することもできます。
+必要なデータが含まれていることや、値が有効なJSONであること (`JSONResponse` を使う場合) を確認してください。
- **FastAPI** は `fastapi.responses` と同じ `starlette.responses` を、開発者の利便性のために提供しています。しかし有効なレスポンスはほとんどStarletteから来ています。 `status` についても同じです。
+///
+
+/// note | "技術詳細"
+
+`from starlette.responses import JSONResponse` を利用することもできます。
+
+**FastAPI** は `fastapi.responses` と同じ `starlette.responses` を、開発者の利便性のために提供しています。しかし有効なレスポンスはほとんどStarletteから来ています。 `status` についても同じです。
+
+///
## OpenAPIとAPIドキュメント
diff --git a/docs/ja/docs/advanced/custom-response.md b/docs/ja/docs/advanced/custom-response.md
index d8b47629a..88269700e 100644
--- a/docs/ja/docs/advanced/custom-response.md
+++ b/docs/ja/docs/advanced/custom-response.md
@@ -12,8 +12,11 @@
そしてもし、`Response` が、`JSONResponse` や `UJSONResponse` の場合のようにJSONメディアタイプ (`application/json`) ならば、データは *path operationデコレータ* に宣言したPydantic `response_model` により自動的に変換 (もしくはフィルタ) されます。
-!!! note "備考"
- メディアタイプを指定せずにレスポンスクラスを利用すると、FastAPIは何もコンテンツがないことを期待します。そのため、生成されるOpenAPIドキュメントにレスポンスフォーマットが記載されません。
+/// note | "備考"
+
+メディアタイプを指定せずにレスポンスクラスを利用すると、FastAPIは何もコンテンツがないことを期待します。そのため、生成されるOpenAPIドキュメントにレスポンスフォーマットが記載されません。
+
+///
## `ORJSONResponse` を使う
@@ -22,18 +25,24 @@
使いたい `Response` クラス (サブクラス) をインポートし、 *path operationデコレータ* に宣言します。
```Python hl_lines="2 7"
-{!../../../docs_src/custom_response/tutorial001b.py!}
+{!../../docs_src/custom_response/tutorial001b.py!}
```
-!!! info "情報"
- パラメータ `response_class` は、レスポンスの「メディアタイプ」を定義するために利用することもできます。
+/// info | "情報"
- この場合、HTTPヘッダー `Content-Type` には `application/json` がセットされます。
+パラメータ `response_class` は、レスポンスの「メディアタイプ」を定義するために利用することもできます。
- そして、OpenAPIにはそのようにドキュメントされます。
+この場合、HTTPヘッダー `Content-Type` には `application/json` がセットされます。
-!!! tip "豆知識"
- `ORJSONResponse` は、現在はFastAPIのみで利用可能で、Starletteでは利用できません。
+そして、OpenAPIにはそのようにドキュメントされます。
+
+///
+
+/// tip | "豆知識"
+
+`ORJSONResponse` は、現在はFastAPIのみで利用可能で、Starletteでは利用できません。
+
+///
## HTMLレスポンス
@@ -43,15 +52,18 @@
* *path operation* のパラメータ `content_type` に `HTMLResponse` を渡す。
```Python hl_lines="2 7"
-{!../../../docs_src/custom_response/tutorial002.py!}
+{!../../docs_src/custom_response/tutorial002.py!}
```
-!!! info "情報"
- パラメータ `response_class` は、レスポンスの「メディアタイプ」を定義するために利用されます。
+/// info | "情報"
- この場合、HTTPヘッダー `Content-Type` には `text/html` がセットされます。
+パラメータ `response_class` は、レスポンスの「メディアタイプ」を定義するために利用されます。
- そして、OpenAPIにはそのようにドキュメント化されます。
+この場合、HTTPヘッダー `Content-Type` には `text/html` がセットされます。
+
+そして、OpenAPIにはそのようにドキュメント化されます。
+
+///
### `Response` を返す
@@ -60,14 +72,20 @@
上記と同じ例において、 `HTMLResponse` を返すと、このようになります:
```Python hl_lines="2 7 19"
-{!../../../docs_src/custom_response/tutorial003.py!}
+{!../../docs_src/custom_response/tutorial003.py!}
```
-!!! warning "注意"
- *path operation関数* から直接返される `Response` は、OpenAPIにドキュメントされず (例えば、 `Content-Type` がドキュメントされない) 、自動的な対話的ドキュメントからも閲覧できません。
+/// warning | "注意"
-!!! info "情報"
- もちろん、実際の `Content-Type` ヘッダーやステータスコードなどは、返された `Response` オブジェクトに由来しています。
+*path operation関数* から直接返される `Response` は、OpenAPIにドキュメントされず (例えば、 `Content-Type` がドキュメントされない) 、自動的な対話的ドキュメントからも閲覧できません。
+
+///
+
+/// info | "情報"
+
+もちろん、実際の `Content-Type` ヘッダーやステータスコードなどは、返された `Response` オブジェクトに由来しています。
+
+///
### OpenAPIドキュメントと `Response` のオーバーライド
@@ -80,7 +98,7 @@
例えば、このようになります:
```Python hl_lines="7 21 23"
-{!../../../docs_src/custom_response/tutorial004.py!}
+{!../../docs_src/custom_response/tutorial004.py!}
```
この例では、関数 `generate_html_response()` は、`str` のHTMLを返すのではなく `Response` を生成して返しています。
@@ -97,10 +115,13 @@
`Response` を使って他の何かを返せますし、カスタムのサブクラスも作れることを覚えておいてください。
-!!! note "技術詳細"
- `from starlette.responses import HTMLResponse` も利用できます。
+/// note | "技術詳細"
- **FastAPI** は開発者の利便性のために `fastapi.responses` として `starlette.responses` と同じものを提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。
+`from starlette.responses import HTMLResponse` も利用できます。
+
+**FastAPI** は開発者の利便性のために `fastapi.responses` として `starlette.responses` と同じものを提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。
+
+///
### `Response`
@@ -118,7 +139,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!}
```
### `HTMLResponse`
@@ -130,7 +151,7 @@ FastAPI (実際にはStarlette) は自動的にContent-Lengthヘッダーを含
テキストやバイトを受け取り、プレーンテキストのレスポンスを返します。
```Python hl_lines="2 7 9"
-{!../../../docs_src/custom_response/tutorial005.py!}
+{!../../docs_src/custom_response/tutorial005.py!}
```
### `JSONResponse`
@@ -147,22 +168,28 @@ FastAPI (実際にはStarlette) は自動的にContent-Lengthヘッダーを含
`ujson`を使った、代替のJSONレスポンスです。
-!!! warning "注意"
- `ujson` は、いくつかのエッジケースの取り扱いについて、Pythonにビルトインされた実装よりも作りこまれていません。
+/// warning | "注意"
+
+`ujson` は、いくつかのエッジケースの取り扱いについて、Pythonにビルトインされた実装よりも作りこまれていません。
+
+///
```Python hl_lines="2 7"
-{!../../../docs_src/custom_response/tutorial001.py!}
+{!../../docs_src/custom_response/tutorial001.py!}
```
-!!! tip "豆知識"
- `ORJSONResponse` のほうが高速な代替かもしれません。
+/// tip | "豆知識"
+
+`ORJSONResponse` のほうが高速な代替かもしれません。
+
+///
### `RedirectResponse`
HTTPリダイレクトを返します。デフォルトでは307ステータスコード (Temporary Redirect) となります。
```Python hl_lines="2 9"
-{!../../../docs_src/custom_response/tutorial006.py!}
+{!../../docs_src/custom_response/tutorial006.py!}
```
### `StreamingResponse`
@@ -170,7 +197,7 @@ HTTPリダイレクトを返します。デフォルトでは307ステータス
非同期なジェネレータか通常のジェネレータ・イテレータを受け取り、レスポンスボディをストリームします。
```Python hl_lines="2 14"
-{!../../../docs_src/custom_response/tutorial007.py!}
+{!../../docs_src/custom_response/tutorial007.py!}
```
#### `StreamingResponse` をファイルライクなオブジェクトとともに使う
@@ -180,11 +207,14 @@ HTTPリダイレクトを返します。デフォルトでは307ステータス
これにはクラウドストレージとの連携や映像処理など、多くのライブラリが含まれています。
```Python hl_lines="2 10-12 14"
-{!../../../docs_src/custom_response/tutorial008.py!}
+{!../../docs_src/custom_response/tutorial008.py!}
```
-!!! tip "豆知識"
- ここでは `async` や `await` をサポートしていない標準の `open()` を使っているので、通常の `def` でpath operationを宣言していることに注意してください。
+/// tip | "豆知識"
+
+ここでは `async` や `await` をサポートしていない標準の `open()` を使っているので、通常の `def` でpath operationを宣言していることに注意してください。
+
+///
### `FileResponse`
@@ -200,7 +230,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!}
```
## デフォルトレスポンスクラス
@@ -212,11 +242,14 @@ HTTPリダイレクトを返します。デフォルトでは307ステータス
以下の例では、 **FastAPI** は、全ての *path operation* で `JSONResponse` の代わりに `ORJSONResponse` をデフォルトとして利用します。
```Python hl_lines="2 4"
-{!../../../docs_src/custom_response/tutorial010.py!}
+{!../../docs_src/custom_response/tutorial010.py!}
```
-!!! tip "豆知識"
- 前に見たように、 *path operation* の中で `response_class` をオーバーライドできます。
+/// tip | "豆知識"
+
+前に見たように、 *path operation* の中で `response_class` をオーバーライドできます。
+
+///
## その他のドキュメント
diff --git a/docs/ja/docs/advanced/index.md b/docs/ja/docs/advanced/index.md
index 2d60e7489..da3c2a2bf 100644
--- a/docs/ja/docs/advanced/index.md
+++ b/docs/ja/docs/advanced/index.md
@@ -6,10 +6,13 @@
以降のセクションでは、チュートリアルでは説明しきれなかったオプションや設定、および機能について説明します。
-!!! tip "豆知識"
- 以降のセクションは、 **必ずしも"応用編"ではありません**。
+/// tip | "豆知識"
- ユースケースによっては、その中から解決策を見つけられるかもしれません。
+以降のセクションは、 **必ずしも"応用編"ではありません**。
+
+ユースケースによっては、その中から解決策を見つけられるかもしれません。
+
+///
## 先にチュートリアルを読む
diff --git a/docs/ja/docs/advanced/path-operation-advanced-configuration.md b/docs/ja/docs/advanced/path-operation-advanced-configuration.md
index 35b381cae..2dab4aec1 100644
--- a/docs/ja/docs/advanced/path-operation-advanced-configuration.md
+++ b/docs/ja/docs/advanced/path-operation-advanced-configuration.md
@@ -2,15 +2,18 @@
## OpenAPI operationId
-!!! warning "注意"
- あなたがOpenAPIの「エキスパート」でなければ、これは必要ないかもしれません。
+/// warning | "注意"
+
+あなたがOpenAPIの「エキスパート」でなければ、これは必要ないかもしれません。
+
+///
*path operation* で `operation_id` パラメータを利用することで、OpenAPIの `operationId` を設定できます。
`operation_id` は各オペレーションで一意にする必要があります。
```Python hl_lines="6"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial001.py!}
+{!../../docs_src/path_operation_advanced_configuration/tutorial001.py!}
```
### *path operation関数* の名前をoperationIdとして使用する
@@ -20,23 +23,29 @@ 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!}
```
-!!! tip "豆知識"
- `app.openapi()` を手動でコールする場合、その前に`operationId`を更新する必要があります。
+/// tip | "豆知識"
-!!! warning "注意"
- この方法をとる場合、各 *path operation関数* が一意な名前である必要があります。
+`app.openapi()` を手動でコールする場合、その前に`operationId`を更新する必要があります。
- それらが異なるモジュール (Pythonファイル) にあるとしてもです。
+///
+
+/// warning | "注意"
+
+この方法をとる場合、各 *path operation関数* が一意な名前である必要があります。
+
+それらが異なるモジュール (Pythonファイル) にあるとしてもです。
+
+///
## OpenAPIから除外する
生成されるOpenAPIスキーマ (つまり、自動ドキュメント生成の仕組み) から *path operation* を除外するには、 `include_in_schema` パラメータを `False` にします。
```Python hl_lines="6"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial003.py!}
+{!../../docs_src/path_operation_advanced_configuration/tutorial003.py!}
```
## docstringによる説明の高度な設定
@@ -48,5 +57,5 @@ 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!}
```
diff --git a/docs/ja/docs/advanced/response-directly.md b/docs/ja/docs/advanced/response-directly.md
index 10ec88548..167d15589 100644
--- a/docs/ja/docs/advanced/response-directly.md
+++ b/docs/ja/docs/advanced/response-directly.md
@@ -14,8 +14,11 @@
実際は、`Response` やそのサブクラスを返すことができます。
-!!! tip "豆知識"
- `JSONResponse` それ自体は、 `Response` のサブクラスです。
+/// tip | "豆知識"
+
+`JSONResponse` それ自体は、 `Response` のサブクラスです。
+
+///
`Response` を返した場合は、**FastAPI** は直接それを返します。
@@ -32,13 +35,16 @@
このようなケースでは、レスポンスにデータを含める前に `jsonable_encoder` を使ってデータを変換できます。
```Python hl_lines="6-7 21-22"
-{!../../../docs_src/response_directly/tutorial001.py!}
+{!../../docs_src/response_directly/tutorial001.py!}
```
-!!! note "技術詳細"
- また、`from starlette.responses import JSONResponse` も利用できます。
+/// note | "技術詳細"
- **FastAPI** は開発者の利便性のために `fastapi.responses` という `starlette.responses` と同じものを提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。
+また、`from starlette.responses import JSONResponse` も利用できます。
+
+**FastAPI** は開発者の利便性のために `fastapi.responses` という `starlette.responses` と同じものを提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。
+
+///
## カスタム `Response` を返す
@@ -51,7 +57,7 @@
XMLを文字列にし、`Response` に含め、それを返します。
```Python hl_lines="1 18"
-{!../../../docs_src/response_directly/tutorial002.py!}
+{!../../docs_src/response_directly/tutorial002.py!}
```
## 備考
diff --git a/docs/ja/docs/advanced/websockets.md b/docs/ja/docs/advanced/websockets.md
index 65e4112a6..f7bcb6af3 100644
--- a/docs/ja/docs/advanced/websockets.md
+++ b/docs/ja/docs/advanced/websockets.md
@@ -39,7 +39,7 @@ $ pip install websockets
しかし、これはWebSocketのサーバーサイドに焦点を当て、実用的な例を示す最も簡単な方法です。
```Python hl_lines="2 6-38 41-43"
-{!../../../docs_src/websockets/tutorial001.py!}
+{!../../docs_src/websockets/tutorial001.py!}
```
## `websocket` を作成する
@@ -47,20 +47,23 @@ $ pip install websockets
**FastAPI** アプリケーションで、`websocket` を作成します。
```Python hl_lines="1 46-47"
-{!../../../docs_src/websockets/tutorial001.py!}
+{!../../docs_src/websockets/tutorial001.py!}
```
-!!! note "技術詳細"
- `from starlette.websockets import WebSocket` を使用しても構いません.
+/// note | "技術詳細"
- **FastAPI** は開発者の利便性のために、同じ `WebSocket` を提供します。しかし、こちらはStarletteから直接提供されるものです。
+`from starlette.websockets import WebSocket` を使用しても構いません.
+
+**FastAPI** は開発者の利便性のために、同じ `WebSocket` を提供します。しかし、こちらはStarletteから直接提供されるものです。
+
+///
## メッセージの送受信
WebSocketルートでは、 `await` を使ってメッセージの送受信ができます。
```Python hl_lines="48-52"
-{!../../../docs_src/websockets/tutorial001.py!}
+{!../../docs_src/websockets/tutorial001.py!}
```
バイナリやテキストデータ、JSONデータを送受信できます。
@@ -113,15 +116,18 @@ WebSocketエンドポイントでは、`fastapi` から以下をインポート
これらは、他のFastAPI エンドポイント/*path operation* の場合と同じように機能します。
```Python hl_lines="58-65 68-83"
-{!../../../docs_src/websockets/tutorial002.py!}
+{!../../docs_src/websockets/tutorial002.py!}
```
-!!! info "情報"
- WebSocket で `HTTPException` を発生させることはあまり意味がありません。したがって、WebSocketの接続を直接閉じる方がよいでしょう。
+/// info | "情報"
- クロージングコードは、仕様で定義された有効なコードの中から使用することができます。
+WebSocket で `HTTPException` を発生させることはあまり意味がありません。したがって、WebSocketの接続を直接閉じる方がよいでしょう。
- 将来的には、どこからでも `raise` できる `WebSocketException` が用意され、専用の例外ハンドラを追加できるようになる予定です。これは、Starlette の PR #527 に依存するものです。
+クロージングコードは、仕様で定義された有効なコードの中から使用することができます。
+
+将来的には、どこからでも `raise` できる `WebSocketException` が用意され、専用の例外ハンドラを追加できるようになる予定です。これは、Starlette の PR #527 に依存するものです。
+
+///
### 依存関係を用いてWebSocketsを試してみる
@@ -144,8 +150,11 @@ $ uvicorn main:app --reload
* パスで使用される「Item ID」
* クエリパラメータとして使用される「Token」
-!!! tip "豆知識"
- クエリ `token` は依存パッケージによって処理されることに注意してください。
+/// tip | "豆知識"
+
+クエリ `token` は依存パッケージによって処理されることに注意してください。
+
+///
これにより、WebSocketに接続してメッセージを送受信できます。
@@ -156,7 +165,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!}
```
試してみるには、
@@ -171,12 +180,15 @@ WebSocket接続が閉じられると、 `await websocket.receive_text()` は例
Client #1596980209979 left the chat
```
-!!! tip "豆知識"
- 上記のアプリは、複数の WebSocket 接続に対してメッセージを処理し、ブロードキャストする方法を示すための最小限のシンプルな例です。
+/// tip | "豆知識"
- しかし、すべての接続がメモリ内の単一のリストで処理されるため、プロセスの実行中にのみ機能し、単一のプロセスでのみ機能することに注意してください。
+上記のアプリは、複数の WebSocket 接続に対してメッセージを処理し、ブロードキャストする方法を示すための最小限のシンプルな例です。
- もしFastAPIと簡単に統合できて、RedisやPostgreSQLなどでサポートされている、より堅牢なものが必要なら、encode/broadcaster を確認してください。
+しかし、すべての接続がメモリ内の単一のリストで処理されるため、プロセスの実行中にのみ機能し、単一のプロセスでのみ機能することに注意してください。
+
+もしFastAPIと簡単に統合できて、RedisやPostgreSQLなどでサポートされている、より堅牢なものが必要なら、encode/broadcaster を確認してください。
+
+///
## その他のドキュメント
diff --git a/docs/ja/docs/alternatives.md b/docs/ja/docs/alternatives.md
index ce4b36408..343ae4ed8 100644
--- a/docs/ja/docs/alternatives.md
+++ b/docs/ja/docs/alternatives.md
@@ -30,11 +30,17 @@ Mozilla、Red Hat、Eventbrite など多くの企業で利用されています
これは**自動的なAPIドキュメント生成**の最初の例であり、これは**FastAPI**に向けた「調査」を触発した最初のアイデアの一つでした。
-!!! note "備考"
- Django REST Framework は Tom Christie によって作成されました。StarletteとUvicornの生みの親であり、**FastAPI**のベースとなっています。
+/// note | "備考"
-!!! check "**FastAPI**へ与えたインスピレーション"
- 自動でAPIドキュメントを生成するWebユーザーインターフェースを持っている点。
+Django REST Framework は Tom Christie によって作成されました。StarletteとUvicornの生みの親であり、**FastAPI**のベースとなっています。
+
+///
+
+/// check | "**FastAPI**へ与えたインスピレーション"
+
+自動でAPIドキュメントを生成するWebユーザーインターフェースを持っている点。
+
+///
### Flask
@@ -50,11 +56,13 @@ Flask は「マイクロフレームワーク」であり、データベース
Flaskのシンプルさを考えると、APIを構築するのに適しているように思えました。次に見つけるべきは、Flask 用の「Django REST Framework」でした。
-!!! check "**FastAPI**へ与えたインスピレーション"
- マイクロフレームワークであること。ツールやパーツを目的に合うように簡単に組み合わせられる点。
+/// check | "**FastAPI**へ与えたインスピレーション"
- シンプルで簡単なルーティングの仕組みを持っている点。
+マイクロフレームワークであること。ツールやパーツを目的に合うように簡単に組み合わせられる点。
+シンプルで簡単なルーティングの仕組みを持っている点。
+
+///
### Requests
@@ -90,11 +98,13 @@ def read_url():
`requests.get(...)` と`@app.get(...)` には類似点が見受けられます。
-!!! check "**FastAPI**へ与えたインスピレーション"
- * シンプルで直感的なAPIを持っている点。
- * HTTPメソッド名を直接利用し、単純で直感的である。
- * 適切なデフォルト値を持ちつつ、強力なカスタマイズ性を持っている。
+/// check | "**FastAPI**へ与えたインスピレーション"
+* シンプルで直感的なAPIを持っている点。
+* HTTPメソッド名を直接利用し、単純で直感的である。
+* 適切なデフォルト値を持ちつつ、強力なカスタマイズ性を持っている。
+
+///
### Swagger / OpenAPI
@@ -108,15 +118,18 @@ def read_url():
そのため、バージョン2.0では「Swagger」、バージョン3以上では「OpenAPI」と表記するのが一般的です。
-!!! check "**FastAPI**へ与えたインスピレーション"
- 独自のスキーマの代わりに、API仕様のオープンな標準を採用しました。
+/// check | "**FastAPI**へ与えたインスピレーション"
- そして、標準に基づくユーザーインターフェースツールを統合しています。
+独自のスキーマの代わりに、API仕様のオープンな標準を採用しました。
- * Swagger UI
- * ReDoc
+そして、標準に基づくユーザーインターフェースツールを統合しています。
- この二つは人気で安定したものとして選択されましたが、少し検索してみると、 (**FastAPI**と同時に使用できる) OpenAPIのための多くの代替となるツールを見つけることができます。
+* Swagger UI
+* ReDoc
+
+この二つは人気で安定したものとして選択されましたが、少し検索してみると、 (**FastAPI**と同時に使用できる) OpenAPIのための多くの代替となるツールを見つけることができます。
+
+///
### Flask REST フレームワーク
@@ -134,8 +147,11 @@ APIが必要とするもう一つの大きな機能はデータのバリデー
しかし、それはPythonの型ヒントが存在する前に作られたものです。そのため、すべてのスキーマを定義するためには、Marshmallowが提供する特定のユーティリティやクラスを使用する必要があります。
-!!! check "**FastAPI**へ与えたインスピレーション"
- コードで「スキーマ」を定義し、データの型やバリデーションを自動で提供する点。
+/// check | "**FastAPI**へ与えたインスピレーション"
+
+コードで「スキーマ」を定義し、データの型やバリデーションを自動で提供する点。
+
+///
### Webargs
@@ -147,11 +163,17 @@ WebargsはFlaskをはじめとするいくつかのフレームワークの上
素晴らしいツールで、私も**FastAPI**を持つ前はよく使っていました。
-!!! info "情報"
- Webargsは、Marshmallowと同じ開発者により作られました。
+/// info | "情報"
-!!! check "**FastAPI**へ与えたインスピレーション"
- 受信したデータに対する自動的なバリデーションを持っている点。
+Webargsは、Marshmallowと同じ開発者により作られました。
+
+///
+
+/// check | "**FastAPI**へ与えたインスピレーション"
+
+受信したデータに対する自動的なバリデーションを持っている点。
+
+///
### APISpec
@@ -171,11 +193,17 @@ Flask, Starlette, Responderなどにおいてはそのように動作します
エディタでは、この問題を解決することはできません。また、パラメータやMarshmallowスキーマを変更したときに、YAMLのdocstringを変更するのを忘れてしまうと、生成されたスキーマが古くなってしまいます。
-!!! info "情報"
- APISpecは、Marshmallowと同じ開発者により作成されました。
+/// info | "情報"
-!!! check "**FastAPI**へ与えたインスピレーション"
- OpenAPIという、APIについてのオープンな標準をサポートしている点。
+APISpecは、Marshmallowと同じ開発者により作成されました。
+
+///
+
+/// check | "**FastAPI**へ与えたインスピレーション"
+
+OpenAPIという、APIについてのオープンな標準をサポートしている点。
+
+///
### Flask-apispec
@@ -197,11 +225,17 @@ Flask、Flask-apispec、Marshmallow、Webargsの組み合わせは、**FastAPI**
そして、これらのフルスタックジェネレーターは、[**FastAPI** Project Generators](project-generation.md){.internal-link target=_blank}の元となっていました。
-!!! info "情報"
- Flask-apispecはMarshmallowと同じ開発者により作成されました。
+/// info | "情報"
-!!! check "**FastAPI**へ与えたインスピレーション"
- シリアライゼーションとバリデーションを定義したコードから、OpenAPIスキーマを自動的に生成する点。
+Flask-apispecはMarshmallowと同じ開発者により作成されました。
+
+///
+
+/// check | "**FastAPI**へ与えたインスピレーション"
+
+シリアライゼーションとバリデーションを定義したコードから、OpenAPIスキーマを自動的に生成する点。
+
+///
### NestJS (とAngular)
@@ -217,24 +251,33 @@ Angular 2にインスピレーションを受けた、統合された依存性
入れ子になったモデルをうまく扱えません。そのため、リクエストのJSONボディが内部フィールドを持つJSONオブジェクトで、それが順番にネストされたJSONオブジェクトになっている場合、適切にドキュメント化やバリデーションをすることができません。
-!!! check "**FastAPI**へ与えたインスピレーション"
- 素晴らしいエディターの補助を得るために、Pythonの型ヒントを利用している点。
+/// check | "**FastAPI**へ与えたインスピレーション"
- 強力な依存性注入の仕組みを持ち、コードの繰り返しを最小化する方法を見つけた点。
+素晴らしいエディターの補助を得るために、Pythonの型ヒントを利用している点。
+
+強力な依存性注入の仕組みを持ち、コードの繰り返しを最小化する方法を見つけた点。
+
+///
### Sanic
`asyncio`に基づいた、Pythonのフレームワークの中でも非常に高速なものの一つです。Flaskと非常に似た作りになっています。
-!!! note "技術詳細"
- Pythonの`asyncio`ループの代わりに、`uvloop`が利用されています。それにより、非常に高速です。
+/// note | "技術詳細"
- `Uvicorn`と`Starlette`に明らかなインスピレーションを与えており、それらは現在オープンなベンチマークにおいてSanicより高速です。
+Pythonの`asyncio`ループの代わりに、`uvloop`が利用されています。それにより、非常に高速です。
-!!! check "**FastAPI**へ与えたインスピレーション"
- 物凄い性能を出す方法を見つけた点。
+`Uvicorn`と`Starlette`に明らかなインスピレーションを与えており、それらは現在オープンなベンチマークにおいてSanicより高速です。
- **FastAPI**が、(サードパーティのベンチマークによりテストされた) 最も高速なフレームワークであるStarletteに基づいている理由です。
+///
+
+/// check | "**FastAPI**へ与えたインスピレーション"
+
+物凄い性能を出す方法を見つけた点。
+
+**FastAPI**が、(サードパーティのベンチマークによりテストされた) 最も高速なフレームワークであるStarletteに基づいている理由です。
+
+///
### Falcon
@@ -246,12 +289,15 @@ Pythonのウェブフレームワーク標準規格 (WSGI) を使用していま
そのため、データのバリデーション、シリアライゼーション、ドキュメント化は、自動的にできずコードの中で行わなければなりません。あるいは、HugのようにFalconの上にフレームワークとして実装されなければなりません。このような分断は、パラメータとして1つのリクエストオブジェクトと1つのレスポンスオブジェクトを持つというFalconのデザインにインスピレーションを受けた他のフレームワークでも起こります。
-!!! check "**FastAPI**へ与えたインスピレーション"
- 素晴らしい性能を得るための方法を見つけた点。
+/// check | "**FastAPI**へ与えたインスピレーション"
- Hug (HugはFalconをベースにしています) と一緒に、**FastAPI**が`response`引数を関数に持つことにインスピレーションを与えました。
+素晴らしい性能を得るための方法を見つけた点。
- **FastAPI**では任意ですが、ヘッダーやCookieやステータスコードを設定するために利用されています。
+Hug (HugはFalconをベースにしています) と一緒に、**FastAPI**が`response`引数を関数に持つことにインスピレーションを与えました。
+
+**FastAPI**では任意ですが、ヘッダーやCookieやステータスコードを設定するために利用されています。
+
+///
### Molten
@@ -269,10 +315,13 @@ Pydanticのようなデータのバリデーション、シリアライゼーシ
ルーティングは一つの場所で宣言され、他の場所で宣言された関数を使用します (エンドポイントを扱う関数のすぐ上に配置できるデコレータを使用するのではなく) 。これはFlask (やStarlette) よりも、Djangoに近いです。これは、比較的緊密に結合されているものをコードの中で分離しています。
-!!! check "**FastAPI**へ与えたインスピレーション"
- モデルの属性の「デフォルト」値を使用したデータ型の追加バリデーションを定義します。これはエディタの補助を改善するもので、以前はPydanticでは利用できませんでした。
+/// check | "**FastAPI**へ与えたインスピレーション"
- 同様の方法でのバリデーションの宣言をサポートするよう、Pydanticを部分的にアップデートするインスピーレションを与えました。(現在はこれらの機能は全てPydanticで可能となっています。)
+モデルの属性の「デフォルト」値を使用したデータ型の追加バリデーションを定義します。これはエディタの補助を改善するもので、以前はPydanticでは利用できませんでした。
+
+同様の方法でのバリデーションの宣言をサポートするよう、Pydanticを部分的にアップデートするインスピーレションを与えました。(現在はこれらの機能は全てPydanticで可能となっています。)
+
+///
### Hug
@@ -288,15 +337,21 @@ OpenAPIやJSON Schemaのような標準に基づいたものではありませ
以前のPythonの同期型Webフレームワーク標準 (WSGI) をベースにしているため、Websocketなどは扱えませんが、それでも高性能です。
-!!! info "情報"
- HugはTimothy Crosleyにより作成されました。彼は`isort`など、Pythonのファイル内のインポートの並び替えを自動的におこうなう素晴らしいツールの開発者です。
+/// info | "情報"
-!!! check "**FastAPI**へ与えたインスピレーション"
- HugはAPIStarに部分的なインスピレーションを与えており、私が発見した中ではAPIStarと同様に最も期待の持てるツールの一つでした。
+HugはTimothy Crosleyにより作成されました。彼は`isort`など、Pythonのファイル内のインポートの並び替えを自動的におこうなう素晴らしいツールの開発者です。
- Hugは、**FastAPI**がPythonの型ヒントを用いてパラメータを宣言し自動的にAPIを定義するスキーマを生成することを触発しました。
+///
- Hugは、**FastAPI**がヘッダーやクッキーを設定するために関数に `response`引数を宣言することにインスピレーションを与えました。
+/// check | "**FastAPI**へ与えたインスピレーション"
+
+HugはAPIStarに部分的なインスピレーションを与えており、私が発見した中ではAPIStarと同様に最も期待の持てるツールの一つでした。
+
+Hugは、**FastAPI**がPythonの型ヒントを用いてパラメータを宣言し自動的にAPIを定義するスキーマを生成することを触発しました。
+
+Hugは、**FastAPI**がヘッダーやクッキーを設定するために関数に `response`引数を宣言することにインスピレーションを与えました。
+
+///
### APIStar (<= 0.5)
@@ -322,23 +377,29 @@ OpenAPIやJSON Schemaのような標準に基づいたものではありませ
今ではAPIStarはOpenAPI仕様を検証するためのツールセットであり、ウェブフレームワークではありません。
-!!! info "情報"
- APIStarはTom Christieにより開発されました。以下の開発者でもあります:
+/// info | "情報"
- * Django REST Framework
- * Starlette (**FastAPI**のベースになっています)
- * Uvicorn (Starletteや**FastAPI**で利用されています)
+APIStarはTom Christieにより開発されました。以下の開発者でもあります:
-!!! check "**FastAPI**へ与えたインスピレーション"
- 存在そのもの。
+* Django REST Framework
+* Starlette (**FastAPI**のベースになっています)
+* Uvicorn (Starletteや**FastAPI**で利用されています)
- 複数の機能 (データのバリデーション、シリアライゼーション、ドキュメント化) を同じPython型で宣言し、同時に優れたエディタの補助を提供するというアイデアは、私にとって素晴らしいアイデアでした。
+///
- そして、長い間同じようなフレームワークを探し、多くの異なる代替ツールをテストした結果、APIStarが最良の選択肢となりました。
+/// check | "**FastAPI**へ与えたインスピレーション"
- その後、APIStarはサーバーとして存在しなくなり、Starletteが作られ、そのようなシステムのための新しくより良い基盤となりました。これが**FastAPI**を構築するための最終的なインスピレーションでした。
+存在そのもの。
- 私は、これまでのツールから学んだことをもとに、機能や型システムなどの部分を改善・拡充しながら、**FastAPI**をAPIStarの「精神的な後継者」と考えています。
+複数の機能 (データのバリデーション、シリアライゼーション、ドキュメント化) を同じPython型で宣言し、同時に優れたエディタの補助を提供するというアイデアは、私にとって素晴らしいアイデアでした。
+
+そして、長い間同じようなフレームワークを探し、多くの異なる代替ツールをテストした結果、APIStarが最良の選択肢となりました。
+
+その後、APIStarはサーバーとして存在しなくなり、Starletteが作られ、そのようなシステムのための新しくより良い基盤となりました。これが**FastAPI**を構築するための最終的なインスピレーションでした。
+
+私は、これまでのツールから学んだことをもとに、機能や型システムなどの部分を改善・拡充しながら、**FastAPI**をAPIStarの「精神的な後継者」と考えています。
+
+///
## **FastAPI**が利用しているもの
@@ -350,10 +411,13 @@ Pydanticは、Pythonの型ヒントを元にデータのバリデーション、
Marshmallowに匹敵しますが、ベンチマークではMarshmallowよりも高速です。また、Pythonの型ヒントを元にしているので、エディタの補助が素晴らしいです。
-!!! check "**FastAPI**での使用用途"
- データのバリデーション、データのシリアライゼーション、自動的なモデルの (JSON Schemaに基づいた) ドキュメント化の全てを扱えます。
+/// check | "**FastAPI**での使用用途"
- **FastAPI**はJSON SchemaのデータをOpenAPIに利用します。
+データのバリデーション、データのシリアライゼーション、自動的なモデルの (JSON Schemaに基づいた) ドキュメント化の全てを扱えます。
+
+**FastAPI**はJSON SchemaのデータをOpenAPIに利用します。
+
+///
### Starlette
@@ -383,17 +447,23 @@ Starletteは基本的なWebマイクロフレームワークの機能をすべ
これは **FastAPI** が追加する主な機能の一つで、すべての機能は Pythonの型ヒントに基づいています (Pydanticを使用しています) 。これに加えて、依存性注入の仕組み、セキュリティユーティリティ、OpenAPIスキーマ生成などがあります。
-!!! note "技術詳細"
- ASGIはDjangoのコアチームメンバーにより開発された新しい「標準」です。まだ「Pythonの標準 (PEP) 」ではありませんが、現在そうなるように進めています。
+/// note | "技術詳細"
- しかしながら、いくつかのツールにおいてすでに「標準」として利用されています。このことは互換性を大きく改善するもので、Uvicornから他のASGIサーバー (DaphneやHypercorn) に乗り換えることができたり、あなたが`python-socketio`のようなASGI互換のツールを追加することもできます。
+ASGIはDjangoのコアチームメンバーにより開発された新しい「標準」です。まだ「Pythonの標準 (PEP) 」ではありませんが、現在そうなるように進めています。
-!!! check "**FastAPI**での使用用途"
- webに関するコアな部分を全て扱います。その上に機能を追加します。
+しかしながら、いくつかのツールにおいてすでに「標準」として利用されています。このことは互換性を大きく改善するもので、Uvicornから他のASGIサーバー (DaphneやHypercorn) に乗り換えることができたり、あなたが`python-socketio`のようなASGI互換のツールを追加することもできます。
- `FastAPI`クラスそのものは、`Starlette`クラスを直接継承しています。
+///
- 基本的にはStarletteの強化版であるため、Starletteで可能なことは**FastAPI**で直接可能です。
+/// check | "**FastAPI**での使用用途"
+
+webに関するコアな部分を全て扱います。その上に機能を追加します。
+
+`FastAPI`クラスそのものは、`Starlette`クラスを直接継承しています。
+
+基本的にはStarletteの強化版であるため、Starletteで可能なことは**FastAPI**で直接可能です。
+
+///
### Uvicorn
@@ -403,12 +473,15 @@ Uvicornは非常に高速なASGIサーバーで、uvloopとhttptoolsにより構
Starletteや**FastAPI**のサーバーとして推奨されています。
-!!! check "**FastAPI**が推奨する理由"
- **FastAPI**アプリケーションを実行するメインのウェブサーバーである点。
+/// check | "**FastAPI**が推奨する理由"
- Gunicornと組み合わせることで、非同期でマルチプロセスなサーバーを持つことがきます。
+**FastAPI**アプリケーションを実行するメインのウェブサーバーである点。
- 詳細は[デプロイ](deployment/index.md){.internal-link target=_blank}の項目で確認してください。
+Gunicornと組み合わせることで、非同期でマルチプロセスなサーバーを持つことがきます。
+
+詳細は[デプロイ](deployment/index.md){.internal-link target=_blank}の項目で確認してください。
+
+///
## ベンチマーク と スピード
diff --git a/docs/ja/docs/async.md b/docs/ja/docs/async.md
index 5e38d1cec..ce9dac56f 100644
--- a/docs/ja/docs/async.md
+++ b/docs/ja/docs/async.md
@@ -21,8 +21,11 @@ async def read_results():
return results
```
-!!! note "備考"
- `async def` を使用して作成された関数の内部でしか `await` は使用できません。
+/// note | "備考"
+
+`async def` を使用して作成された関数の内部でしか `await` は使用できません。
+
+///
---
@@ -355,12 +358,15 @@ async def read_burgers():
## 非常に発展的な技術的詳細
-!!! warning "注意"
- 恐らくスキップしても良いでしょう。
+/// warning | "注意"
- この部分は**FastAPI**の仕組みに関する非常に技術的な詳細です。
+恐らくスキップしても良いでしょう。
- かなりの技術知識 (コルーチン、スレッド、ブロッキングなど) があり、FastAPIが `async def` と通常の `def` をどのように処理するか知りたい場合は、先に進んでください。
+この部分は**FastAPI**の仕組みに関する非常に技術的な詳細です。
+
+かなりの技術知識 (コルーチン、スレッド、ブロッキングなど) があり、FastAPIが `async def` と通常の `def` をどのように処理するか知りたい場合は、先に進んでください。
+
+///
### Path operation 関数
diff --git a/docs/ja/docs/contributing.md b/docs/ja/docs/contributing.md
index be8e9280e..86926b213 100644
--- a/docs/ja/docs/contributing.md
+++ b/docs/ja/docs/contributing.md
@@ -24,71 +24,84 @@ $ python -m venv env
新しい環境を有効化するには:
-=== "Linux, macOS"
+//// tab | Linux, macOS
- email_validator - E メールの検証
+- email-validator - E メールの検証
Starlette によって使用されるもの:
diff --git a/docs/ja/docs/learn/index.md b/docs/ja/docs/learn/index.md
new file mode 100644
index 000000000..2f24c670a
--- /dev/null
+++ b/docs/ja/docs/learn/index.md
@@ -0,0 +1,5 @@
+# 学習
+
+ここでは、**FastAPI** を学習するための入門セクションとチュートリアルを紹介します。
+
+これは、FastAPIを学習するにあたっての**書籍**や**コース**であり、**公式**かつ推奨される方法とみなすことができます 😎
diff --git a/docs/ja/docs/python-types.md b/docs/ja/docs/python-types.md
index f8e02fdc3..7af6ce0c0 100644
--- a/docs/ja/docs/python-types.md
+++ b/docs/ja/docs/python-types.md
@@ -12,15 +12,18 @@
しかしたとえまったく **FastAPI** を使用しない場合でも、それらについて少し学ぶことで利点を得ることができるでしょう。
-!!! note "備考"
- もしあなたがPythonの専門家で、すでに型ヒントについてすべて知っているのであれば、次の章まで読み飛ばしてください。
+/// note | "備考"
+
+もしあなたがPythonの専門家で、すでに型ヒントについてすべて知っているのであれば、次の章まで読み飛ばしてください。
+
+///
## 動機
簡単な例から始めてみましょう:
```Python
-{!../../../docs_src/python_types/tutorial001.py!}
+{!../../docs_src/python_types/tutorial001.py!}
```
このプログラムを実行すると以下が出力されます:
@@ -36,7 +39,7 @@ John Doe
* 真ん中にスペースを入れて連結します。
```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial001.py!}
+{!../../docs_src/python_types/tutorial001.py!}
```
### 編集
@@ -80,7 +83,7 @@ John Doe
それが「型ヒント」です:
```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial002.py!}
+{!../../docs_src/python_types/tutorial002.py!}
```
これは、以下のようにデフォルト値を宣言するのと同じではありません:
@@ -110,7 +113,7 @@ John Doe
この関数を見てください。すでに型ヒントを持っています:
```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial003.py!}
+{!../../docs_src/python_types/tutorial003.py!}
```
エディタは変数の型を知っているので、補完だけでなく、エラーチェックをすることもできます。
@@ -120,7 +123,7 @@ John Doe
これで`age`を`str(age)`で文字列に変換して修正する必要があることがわかります:
```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial004.py!}
+{!../../docs_src/python_types/tutorial004.py!}
```
## 型の宣言
@@ -141,7 +144,7 @@ John Doe
* `bytes`
```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial005.py!}
+{!../../docs_src/python_types/tutorial005.py!}
```
### 型パラメータを持つジェネリック型
@@ -159,7 +162,7 @@ John Doe
`typing`から`List`をインポートします(大文字の`L`を含む):
```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial006.py!}
+{!../../docs_src/python_types/tutorial006.py!}
```
同じようにコロン(`:`)の構文で変数を宣言します。
@@ -169,13 +172,16 @@ John Doe
リストはいくつかの内部の型を含む型なので、それらを角括弧で囲んでいます。
```Python hl_lines="4"
-{!../../../docs_src/python_types/tutorial006.py!}
+{!../../docs_src/python_types/tutorial006.py!}
```
-!!! tip "豆知識"
- 角括弧内の内部の型は「型パラメータ」と呼ばれています。
+/// tip | "豆知識"
- この場合、`str`は`List`に渡される型パラメータです。
+角括弧内の内部の型は「型パラメータ」と呼ばれています。
+
+この場合、`str`は`List`に渡される型パラメータです。
+
+///
つまり: 変数`items`は`list`であり、このリストの各項目は`str`です。
@@ -194,7 +200,7 @@ John Doe
`tuple`と`set`の宣言も同様です:
```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial007.py!}
+{!../../docs_src/python_types/tutorial007.py!}
```
つまり:
@@ -212,7 +218,7 @@ John Doe
2番目の型パラメータは`dict`の値です。
```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial008.py!}
+{!../../docs_src/python_types/tutorial008.py!}
```
つまり:
@@ -226,7 +232,7 @@ John Doe
また、`Optional`を使用して、変数が`str`のような型を持つことを宣言することもできますが、それは「オプション」であり、`None`にすることもできます。
```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009.py!}
+{!../../docs_src/python_types/tutorial009.py!}
```
ただの`str`の代わりに`Optional[str]`を使用することで、エディタは値が常に`str`であると仮定している場合に実際には`None`である可能性があるエラーを検出するのに役立ちます。
@@ -251,13 +257,13 @@ John Doe
例えば、`Person`クラスという名前のクラスがあるとしましょう:
```Python hl_lines="1 2 3"
-{!../../../docs_src/python_types/tutorial010.py!}
+{!../../docs_src/python_types/tutorial010.py!}
```
変数の型を`Person`として宣言することができます:
```Python hl_lines="6"
-{!../../../docs_src/python_types/tutorial010.py!}
+{!../../docs_src/python_types/tutorial010.py!}
```
そして、再び、すべてのエディタのサポートを得ることができます:
@@ -279,11 +285,14 @@ John Doe
Pydanticの公式ドキュメントから引用:
```Python
-{!../../../docs_src/python_types/tutorial011.py!}
+{!../../docs_src/python_types/tutorial011.py!}
```
-!!! info "情報"
- Pydanticについてより学びたい方はドキュメントを参照してください.
+/// info | "情報"
+
+Pydanticについてより学びたい方はドキュメントを参照してください.
+
+///
**FastAPI** はすべてPydanticをベースにしています。
@@ -311,5 +320,8 @@ Pydanticの公式ドキュメントから引用:
重要なのは、Pythonの標準的な型を使うことで、(クラスやデコレータなどを追加するのではなく)1つの場所で **FastAPI** が多くの作業を代わりにやってくれているということです。
-!!! info "情報"
- すでにすべてのチュートリアルを終えて、型についての詳細を見るためにこのページに戻ってきた場合は、`mypy`のチートシートを参照してください
+/// info | "情報"
+
+すでにすべてのチュートリアルを終えて、型についての詳細を見るためにこのページに戻ってきた場合は、`mypy`のチートシートを参照してください
+
+///
diff --git a/docs/ja/docs/tutorial/background-tasks.md b/docs/ja/docs/tutorial/background-tasks.md
index 6094c370f..6f9340817 100644
--- a/docs/ja/docs/tutorial/background-tasks.md
+++ b/docs/ja/docs/tutorial/background-tasks.md
@@ -16,7 +16,7 @@
まず初めに、`BackgroundTasks` をインポートし、` BackgroundTasks` の型宣言と共に、*path operation 関数* のパラメーターを定義します:
```Python hl_lines="1 13"
-{!../../../docs_src/background_tasks/tutorial001.py!}
+{!../../docs_src/background_tasks/tutorial001.py!}
```
**FastAPI** は、`BackgroundTasks` 型のオブジェクトを作成し、そのパラメーターに渡します。
@@ -34,7 +34,7 @@
また、書き込み操作では `async` と `await` を使用しないため、通常の `def` で関数を定義します。
```Python hl_lines="6-9"
-{!../../../docs_src/background_tasks/tutorial001.py!}
+{!../../docs_src/background_tasks/tutorial001.py!}
```
## バックグラウンドタスクの追加
@@ -42,7 +42,7 @@
*path operations 関数* 内で、`.add_task()` メソッドを使用してタスク関数を *background tasks* オブジェクトに渡します。
```Python hl_lines="14"
-{!../../../docs_src/background_tasks/tutorial001.py!}
+{!../../docs_src/background_tasks/tutorial001.py!}
```
`.add_task()` は以下の引数を受け取ります:
@@ -58,7 +58,7 @@
**FastAPI** は、それぞれの場合の処理方法と同じオブジェクトの再利用方法を知っているため、すべてのバックグラウンドタスクがマージされ、バックグラウンドで後で実行されます。
```Python hl_lines="13 15 22 25"
-{!../../../docs_src/background_tasks/tutorial002.py!}
+{!../../docs_src/background_tasks/tutorial002.py!}
```
この例では、レスポンスが送信された *後* にメッセージが `log.txt` ファイルに書き込まれます。
diff --git a/docs/ja/docs/tutorial/body-fields.md b/docs/ja/docs/tutorial/body-fields.md
index 8f01e8216..1d386040a 100644
--- a/docs/ja/docs/tutorial/body-fields.md
+++ b/docs/ja/docs/tutorial/body-fields.md
@@ -7,33 +7,42 @@
まず、以下のようにインポートします:
```Python hl_lines="4"
-{!../../../docs_src/body_fields/tutorial001.py!}
+{!../../docs_src/body_fields/tutorial001.py!}
```
-!!! warning "注意"
- `Field`は他の全てのもの(`Query`、`Path`、`Body`など)とは違い、`fastapi`からではなく、`pydantic`から直接インポートされていることに注意してください。
+/// warning | "注意"
+
+`Field`は他の全てのもの(`Query`、`Path`、`Body`など)とは違い、`fastapi`からではなく、`pydantic`から直接インポートされていることに注意してください。
+
+///
## モデルの属性の宣言
以下のように`Field`をモデルの属性として使用することができます:
```Python hl_lines="11 12 13 14"
-{!../../../docs_src/body_fields/tutorial001.py!}
+{!../../docs_src/body_fields/tutorial001.py!}
```
`Field`は`Query`や`Path`、`Body`と同じように動作し、全く同様のパラメータなどを持ちます。
-!!! note "技術詳細"
- 実際には次に見る`Query`や`Path`などは、共通の`Param`クラスのサブクラスのオブジェクトを作成しますが、それ自体はPydanticの`FieldInfo`クラスのサブクラスです。
+/// note | "技術詳細"
- また、Pydanticの`Field`は`FieldInfo`のインスタンスも返します。
+実際には次に見る`Query`や`Path`などは、共通の`Param`クラスのサブクラスのオブジェクトを作成しますが、それ自体はPydanticの`FieldInfo`クラスのサブクラスです。
- `Body`は`FieldInfo`のサブクラスのオブジェクトを直接返すこともできます。そして、他にも`Body`クラスのサブクラスであるものがあります。
+また、Pydanticの`Field`は`FieldInfo`のインスタンスも返します。
- `fastapi`から`Query`や`Path`などをインポートする場合、これらは実際には特殊なクラスを返す関数であることに注意してください。
+`Body`は`FieldInfo`のサブクラスのオブジェクトを直接返すこともできます。そして、他にも`Body`クラスのサブクラスであるものがあります。
-!!! tip "豆知識"
- 型、デフォルト値、`Field`を持つ各モデルの属性が、`Path`や`Query`、`Body`の代わりに`Field`を持つ、*path operation 関数の*パラメータと同じ構造になっていることに注目してください。
+`fastapi`から`Query`や`Path`などをインポートする場合、これらは実際には特殊なクラスを返す関数であることに注意してください。
+
+///
+
+/// tip | "豆知識"
+
+型、デフォルト値、`Field`を持つ各モデルの属性が、`Path`や`Query`、`Body`の代わりに`Field`を持つ、*path operation 関数の*パラメータと同じ構造になっていることに注目してください。
+
+///
## 追加情報の追加
diff --git a/docs/ja/docs/tutorial/body-multiple-params.md b/docs/ja/docs/tutorial/body-multiple-params.md
index 2ba10c583..647143ee5 100644
--- a/docs/ja/docs/tutorial/body-multiple-params.md
+++ b/docs/ja/docs/tutorial/body-multiple-params.md
@@ -9,11 +9,14 @@
また、デフォルトの`None`を設定することで、ボディパラメータをオプションとして宣言することもできます:
```Python hl_lines="19 20 21"
-{!../../../docs_src/body_multiple_params/tutorial001.py!}
+{!../../docs_src/body_multiple_params/tutorial001.py!}
```
-!!! note "備考"
- この場合、ボディから取得する`item`はオプションであることに注意してください。デフォルト値は`None`です。
+/// note | "備考"
+
+この場合、ボディから取得する`item`はオプションであることに注意してください。デフォルト値は`None`です。
+
+///
## 複数のボディパラメータ
@@ -31,7 +34,7 @@
しかし、`item`と`user`のように複数のボディパラメータを宣言することもできます:
```Python hl_lines="22"
-{!../../../docs_src/body_multiple_params/tutorial002.py!}
+{!../../docs_src/body_multiple_params/tutorial002.py!}
```
この場合、**FastAPI**は関数内に複数のボディパラメータ(Pydanticモデルである2つのパラメータ)があることに気付きます。
@@ -53,8 +56,11 @@
}
```
-!!! note "備考"
- 以前と同じように`item`が宣言されていたにもかかわらず、`item`はキー`item`を持つボディの内部にあることが期待されていることに注意してください。
+/// note | "備考"
+
+以前と同じように`item`が宣言されていたにもかかわらず、`item`はキー`item`を持つボディの内部にあることが期待されていることに注意してください。
+
+///
**FastAPI** はリクエストから自動で変換を行い、パラメータ`item`が特定の内容を受け取り、`user`も同じように特定の内容を受け取ります。
@@ -72,7 +78,7 @@
```Python hl_lines="23"
-{!../../../docs_src/body_multiple_params/tutorial003.py!}
+{!../../docs_src/body_multiple_params/tutorial003.py!}
```
この場合、**FastAPI** は以下のようなボディを期待します:
@@ -109,12 +115,14 @@ q: str = None
以下において:
```Python hl_lines="27"
-{!../../../docs_src/body_multiple_params/tutorial004.py!}
+{!../../docs_src/body_multiple_params/tutorial004.py!}
```
-!!! info "情報"
- `Body`もまた、後述する `Query` や `Path` などと同様に、すべての検証パラメータとメタデータパラメータを持っています。
+/// info | "情報"
+`Body`もまた、後述する `Query` や `Path` などと同様に、すべての検証パラメータとメタデータパラメータを持っています。
+
+///
## 単一のボディパラメータの埋め込み
@@ -131,7 +139,7 @@ item: Item = Body(..., embed=True)
以下において:
```Python hl_lines="17"
-{!../../../docs_src/body_multiple_params/tutorial005.py!}
+{!../../docs_src/body_multiple_params/tutorial005.py!}
```
この場合、**FastAPI** は以下のようなボディを期待します:
diff --git a/docs/ja/docs/tutorial/body-nested-models.md b/docs/ja/docs/tutorial/body-nested-models.md
index 092e25798..8703a40e7 100644
--- a/docs/ja/docs/tutorial/body-nested-models.md
+++ b/docs/ja/docs/tutorial/body-nested-models.md
@@ -7,7 +7,7 @@
属性をサブタイプとして定義することができます。例えば、Pythonの`list`は以下のように定義できます:
```Python hl_lines="12"
-{!../../../docs_src/body_nested_models/tutorial001.py!}
+{!../../docs_src/body_nested_models/tutorial001.py!}
```
これにより、各項目の型は宣言されていませんが、`tags`はある項目のリストになります。
@@ -21,7 +21,7 @@
まず、Pythonの標準の`typing`モジュールから`List`をインポートします:
```Python hl_lines="1"
-{!../../../docs_src/body_nested_models/tutorial002.py!}
+{!../../docs_src/body_nested_models/tutorial002.py!}
```
### タイプパラメータを持つ`List`の宣言
@@ -44,7 +44,7 @@ my_list: List[str]
そのため、以下の例では`tags`を具体的な「文字列のリスト」にすることができます:
```Python hl_lines="14"
-{!../../../docs_src/body_nested_models/tutorial002.py!}
+{!../../docs_src/body_nested_models/tutorial002.py!}
```
## セット型
@@ -56,7 +56,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!}
```
これを使えば、データが重複しているリクエストを受けた場合でも、ユニークな項目のセットに変換されます。
@@ -80,7 +80,7 @@ Pydanticモデルの各属性には型があります。
例えば、`Image`モデルを定義することができます:
```Python hl_lines="9 10 11"
-{!../../../docs_src/body_nested_models/tutorial004.py!}
+{!../../docs_src/body_nested_models/tutorial004.py!}
```
### サブモデルを型として使用
@@ -88,7 +88,7 @@ Pydanticモデルの各属性には型があります。
そして、それを属性の型として使用することができます:
```Python hl_lines="20"
-{!../../../docs_src/body_nested_models/tutorial004.py!}
+{!../../docs_src/body_nested_models/tutorial004.py!}
```
これは **FastAPI** が以下のようなボディを期待することを意味します:
@@ -123,7 +123,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!}
```
文字列は有効なURLであることが確認され、そのようにJSONスキーマ・OpenAPIで文書化されます。
@@ -133,7 +133,7 @@ Pydanticモデルの各属性には型があります。
Pydanticモデルを`list`や`set`などのサブタイプとして使用することもできます:
```Python hl_lines="20"
-{!../../../docs_src/body_nested_models/tutorial006.py!}
+{!../../docs_src/body_nested_models/tutorial006.py!}
```
これは、次のようなJSONボディを期待します(変換、検証、ドキュメントなど):
@@ -162,19 +162,25 @@ Pydanticモデルを`list`や`set`などのサブタイプとして使用する
}
```
-!!! info "情報"
- `images`キーが画像オブジェクトのリストを持つようになったことに注目してください。
+/// info | "情報"
+
+`images`キーが画像オブジェクトのリストを持つようになったことに注目してください。
+
+///
## 深くネストされたモデル
深くネストされた任意のモデルを定義することができます:
```Python hl_lines="9 14 20 23 27"
-{!../../../docs_src/body_nested_models/tutorial007.py!}
+{!../../docs_src/body_nested_models/tutorial007.py!}
```
-!!! info "情報"
- `Offer`は`Item`のリストであり、オプションの`Image`のリストを持っていることに注目してください。
+/// info | "情報"
+
+`Offer`は`Item`のリストであり、オプションの`Image`のリストを持っていることに注目してください。
+
+///
## 純粋なリストのボディ
@@ -187,7 +193,7 @@ images: List[Image]
以下のように:
```Python hl_lines="15"
-{!../../../docs_src/body_nested_models/tutorial008.py!}
+{!../../docs_src/body_nested_models/tutorial008.py!}
```
## あらゆる場所でのエディタサポート
@@ -219,17 +225,20 @@ Pydanticモデルではなく、`dict`を直接使用している場合はこの
この場合、`int`のキーと`float`の値を持つものであれば、どんな`dict`でも受け入れることができます:
```Python hl_lines="15"
-{!../../../docs_src/body_nested_models/tutorial009.py!}
+{!../../docs_src/body_nested_models/tutorial009.py!}
```
-!!! tip "豆知識"
- JSONはキーとして`str`しかサポートしていないことに注意してください。
+/// tip | "豆知識"
- しかしPydanticには自動データ変換機能があります。
+JSONはキーとして`str`しかサポートしていないことに注意してください。
- これは、APIクライアントがキーとして文字列しか送信できなくても、それらの文字列に純粋な整数が含まれている限り、Pydanticが変換して検証することを意味します。
+しかしPydanticには自動データ変換機能があります。
- そして、`weights`として受け取る`dict`は、実際には`int`のキーと`float`の値を持つことになります。
+これは、APIクライアントがキーとして文字列しか送信できなくても、それらの文字列に純粋な整数が含まれている限り、Pydanticが変換して検証することを意味します。
+
+そして、`weights`として受け取る`dict`は、実際には`int`のキーと`float`の値を持つことになります。
+
+///
## まとめ
diff --git a/docs/ja/docs/tutorial/body-updates.md b/docs/ja/docs/tutorial/body-updates.md
index 95d328ec5..fde9f4f5e 100644
--- a/docs/ja/docs/tutorial/body-updates.md
+++ b/docs/ja/docs/tutorial/body-updates.md
@@ -7,7 +7,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!}
```
既存のデータを置き換えるべきデータを受け取るために`PUT`は使用されます。
@@ -34,14 +34,17 @@
つまり、更新したいデータだけを送信して、残りはそのままにしておくことができます。
-!!! note "備考"
- `PATCH`は`PUT`よりもあまり使われておらず、知られていません。
+/// note | "備考"
- また、多くのチームは部分的な更新であっても`PUT`だけを使用しています。
+`PATCH`は`PUT`よりもあまり使われておらず、知られていません。
- **FastAPI** はどんな制限も課けていないので、それらを使うのは **自由** です。
+また、多くのチームは部分的な更新であっても`PUT`だけを使用しています。
- しかし、このガイドでは、それらがどのように使用されることを意図しているかを多かれ少なかれ、示しています。
+**FastAPI** はどんな制限も課けていないので、それらを使うのは **自由** です。
+
+しかし、このガイドでは、それらがどのように使用されることを意図しているかを多かれ少なかれ、示しています。
+
+///
### Pydanticの`exclude_unset`パラメータの使用
@@ -54,7 +57,7 @@
これを使うことで、デフォルト値を省略して、設定された(リクエストで送られた)データのみを含む`dict`を生成することができます:
```Python hl_lines="34"
-{!../../../docs_src/body_updates/tutorial002.py!}
+{!../../docs_src/body_updates/tutorial002.py!}
```
### Pydanticの`update`パラメータ
@@ -64,7 +67,7 @@
`stored_item_model.copy(update=update_data)`のように:
```Python hl_lines="35"
-{!../../../docs_src/body_updates/tutorial002.py!}
+{!../../docs_src/body_updates/tutorial002.py!}
```
### 部分的更新のまとめ
@@ -83,17 +86,23 @@
* 更新されたモデルを返します。
```Python hl_lines="30 31 32 33 34 35 36 37"
-{!../../../docs_src/body_updates/tutorial002.py!}
+{!../../docs_src/body_updates/tutorial002.py!}
```
-!!! tip "豆知識"
- 実際には、HTTPの`PUT`操作でも同じテクニックを使用することができます。
+/// tip | "豆知識"
- しかし、これらのユースケースのために作成されたので、ここでの例では`PATCH`を使用しています。
+実際には、HTTPの`PUT`操作でも同じテクニックを使用することができます。
-!!! note "備考"
- 入力モデルがまだ検証されていることに注目してください。
+しかし、これらのユースケースのために作成されたので、ここでの例では`PATCH`を使用しています。
- そのため、すべての属性を省略できる部分的な変更を受け取りたい場合は、すべての属性をオプションとしてマークしたモデルを用意する必要があります(デフォルト値または`None`を使用して)。
+///
- **更新** のためのオプション値がすべて設定されているモデルと、**作成** のための必須値が設定されているモデルを区別するには、[追加モデル](extra-models.md){.internal-link target=_blank}で説明されている考え方を利用することができます。
+/// note | "備考"
+
+入力モデルがまだ検証されていることに注目してください。
+
+そのため、すべての属性を省略できる部分的な変更を受け取りたい場合は、すべての属性をオプションとしてマークしたモデルを用意する必要があります(デフォルト値または`None`を使用して)。
+
+**更新** のためのオプション値がすべて設定されているモデルと、**作成** のための必須値が設定されているモデルを区別するには、[追加モデル](extra-models.md){.internal-link target=_blank}で説明されている考え方を利用することができます。
+
+///
diff --git a/docs/ja/docs/tutorial/body.md b/docs/ja/docs/tutorial/body.md
index ccce9484d..888d4388a 100644
--- a/docs/ja/docs/tutorial/body.md
+++ b/docs/ja/docs/tutorial/body.md
@@ -8,19 +8,22 @@ APIはほとんどの場合 **レスポンス** ボディを送らなければ
**リクエスト** ボディを宣言するために Pydantic モデルを使用します。そして、その全てのパワーとメリットを利用します。
-!!! info "情報"
- データを送るには、`POST` (もっともよく使われる)、`PUT`、`DELETE` または `PATCH` を使うべきです。
+/// info | "情報"
- GET リクエストでボディを送信することは、仕様では未定義の動作ですが、FastAPI でサポートされており、非常に複雑な(極端な)ユースケースにのみ対応しています。
+データを送るには、`POST` (もっともよく使われる)、`PUT`、`DELETE` または `PATCH` を使うべきです。
- 非推奨なので、Swagger UIを使った対話型のドキュメントにはGETのボディ情報は表示されません。さらに、中継するプロキシが対応していない可能性があります。
+GET リクエストでボディを送信することは、仕様では未定義の動作ですが、FastAPI でサポートされており、非常に複雑な(極端な)ユースケースにのみ対応しています。
+
+非推奨なので、Swagger UIを使った対話型のドキュメントにはGETのボディ情報は表示されません。さらに、中継するプロキシが対応していない可能性があります。
+
+///
## Pydanticの `BaseModel` をインポート
ます初めに、 `pydantic` から `BaseModel` をインポートする必要があります:
```Python hl_lines="2"
-{!../../../docs_src/body/tutorial001.py!}
+{!../../docs_src/body/tutorial001.py!}
```
## データモデルの作成
@@ -30,7 +33,7 @@ APIはほとんどの場合 **レスポンス** ボディを送らなければ
すべての属性にpython標準の型を使用します:
```Python hl_lines="5-9"
-{!../../../docs_src/body/tutorial001.py!}
+{!../../docs_src/body/tutorial001.py!}
```
クエリパラメータの宣言と同様に、モデル属性がデフォルト値をもつとき、必須な属性ではなくなります。それ以外は必須になります。オプショナルな属性にしたい場合は `None` を使用してください。
@@ -60,7 +63,7 @@ APIはほとんどの場合 **レスポンス** ボディを送らなければ
*パスオペレーション* に加えるために、パスパラメータやクエリパラメータと同じ様に宣言します:
```Python hl_lines="16"
-{!../../../docs_src/body/tutorial001.py!}
+{!../../docs_src/body/tutorial001.py!}
```
...そして、作成したモデル `Item` で型を宣言します。
@@ -110,23 +113,26 @@ APIはほとんどの場合 **レスポンス** ボディを送らなければ
-!!! tip "豆知識"
- PyCharmエディタを使用している場合は、Pydantic PyCharm Pluginが使用可能です。
+/// tip | "豆知識"
- 以下のエディターサポートが強化されます:
+PyCharmエディタを使用している場合は、Pydantic PyCharm Pluginが使用可能です。
- * 自動補完
- * 型チェック
- * リファクタリング
- * 検索
- * インスペクション
+以下のエディターサポートが強化されます:
+
+* 自動補完
+* 型チェック
+* リファクタリング
+* 検索
+* インスペクション
+
+///
## モデルの使用
関数内部で、モデルの全ての属性に直接アクセスできます:
```Python hl_lines="19"
-{!../../../docs_src/body/tutorial002.py!}
+{!../../docs_src/body/tutorial002.py!}
```
## リクエストボディ + パスパラメータ
@@ -136,7 +142,7 @@ APIはほとんどの場合 **レスポンス** ボディを送らなければ
**FastAPI** はパスパラメータである関数パラメータは**パスから受け取り**、Pydanticモデルによって宣言された関数パラメータは**リクエストボディから受け取る**ということを認識します。
```Python hl_lines="15-16"
-{!../../../docs_src/body/tutorial003.py!}
+{!../../docs_src/body/tutorial003.py!}
```
## リクエストボディ + パスパラメータ + クエリパラメータ
@@ -146,7 +152,7 @@ APIはほとんどの場合 **レスポンス** ボディを送らなければ
**FastAPI** はそれぞれを認識し、適切な場所からデータを取得します。
```Python hl_lines="16"
-{!../../../docs_src/body/tutorial004.py!}
+{!../../docs_src/body/tutorial004.py!}
```
関数パラメータは以下の様に認識されます:
@@ -155,10 +161,13 @@ APIはほとんどの場合 **レスポンス** ボディを送らなければ
* パラメータが**単数型** (`int`、`float`、`str`、`bool` など)の場合は**クエリ**パラメータとして解釈されます。
* パラメータが **Pydantic モデル**型で宣言された場合、リクエスト**ボディ**として解釈されます。
-!!! note "備考"
- FastAPIは、`= None`があるおかげで、`q`がオプショナルだとわかります。
+/// note | "備考"
- `Optional[str]` の`Optional` はFastAPIでは使用されていません(FastAPIは`str`の部分のみ使用します)。しかし、`Optional[str]` はエディタがコードのエラーを見つけるのを助けてくれます。
+FastAPIは、`= None`があるおかげで、`q`がオプショナルだとわかります。
+
+`Optional[str]` の`Optional` はFastAPIでは使用されていません(FastAPIは`str`の部分のみ使用します)。しかし、`Optional[str]` はエディタがコードのエラーを見つけるのを助けてくれます。
+
+///
## Pydanticを使わない方法
diff --git a/docs/ja/docs/tutorial/cookie-params.md b/docs/ja/docs/tutorial/cookie-params.md
index 193be305f..1f45db17c 100644
--- a/docs/ja/docs/tutorial/cookie-params.md
+++ b/docs/ja/docs/tutorial/cookie-params.md
@@ -7,7 +7,7 @@
まず、`Cookie`をインポートします:
```Python hl_lines="3"
-{!../../../docs_src/cookie_params/tutorial001.py!}
+{!../../docs_src/cookie_params/tutorial001.py!}
```
## `Cookie`のパラメータを宣言
@@ -17,16 +17,22 @@
最初の値がデフォルト値で、追加の検証パラメータや注釈パラメータをすべて渡すことができます:
```Python hl_lines="9"
-{!../../../docs_src/cookie_params/tutorial001.py!}
+{!../../docs_src/cookie_params/tutorial001.py!}
```
-!!! note "技術詳細"
- `Cookie`は`Path`と`Query`の「姉妹」クラスです。また、同じ共通の`Param`クラスを継承しています。
+/// note | "技術詳細"
- しかし、`fastapi`から`Query`や`Path`、`Cookie`などをインポートする場合、それらは実際には特殊なクラスを返す関数であることを覚えておいてください。
+`Cookie`は`Path`と`Query`の「姉妹」クラスです。また、同じ共通の`Param`クラスを継承しています。
-!!! info "情報"
- クッキーを宣言するには、`Cookie`を使う必要があります。なぜなら、そうしないとパラメータがクエリのパラメータとして解釈されてしまうからです。
+しかし、`fastapi`から`Query`や`Path`、`Cookie`などをインポートする場合、それらは実際には特殊なクラスを返す関数であることを覚えておいてください。
+
+///
+
+/// info | "情報"
+
+クッキーを宣言するには、`Cookie`を使う必要があります。なぜなら、そうしないとパラメータがクエリのパラメータとして解釈されてしまうからです。
+
+///
## まとめ
diff --git a/docs/ja/docs/tutorial/cors.md b/docs/ja/docs/tutorial/cors.md
index 9d6ce8cdc..9530c51bf 100644
--- a/docs/ja/docs/tutorial/cors.md
+++ b/docs/ja/docs/tutorial/cors.md
@@ -47,7 +47,7 @@
* 特定のHTTPヘッダー、またはワイルドカード `"*"`を使用してすべて許可。
```Python hl_lines="2 6-11 13-19"
-{!../../../docs_src/cors/tutorial001.py!}
+{!../../docs_src/cors/tutorial001.py!}
```
`CORSMiddleware` 実装のデフォルトのパラメータはCORSに関して制限を与えるものになっているので、ブラウザにドメインを跨いで特定のオリジン、メソッド、またはヘッダーを使用可能にするためには、それらを明示的に有効にする必要があります
@@ -78,7 +78,10 @@
CORSについてより詳しい情報は、Mozilla CORS documentation を参照して下さい。
-!!! note "技術詳細"
- `from starlette.middleware.cors import CORSMiddleware` も使用できます。
+/// note | "技術詳細"
- **FastAPI** は、開発者の利便性を高めるために、`fastapi.middleware` でいくつかのミドルウェアを提供します。利用可能なミドルウェアのほとんどは、Starletteから直接提供されています。
+`from starlette.middleware.cors import CORSMiddleware` も使用できます。
+
+**FastAPI** は、開発者の利便性を高めるために、`fastapi.middleware` でいくつかのミドルウェアを提供します。利用可能なミドルウェアのほとんどは、Starletteから直接提供されています。
+
+///
diff --git a/docs/ja/docs/tutorial/debugging.md b/docs/ja/docs/tutorial/debugging.md
index 35e1ca7ad..be0ff81d4 100644
--- a/docs/ja/docs/tutorial/debugging.md
+++ b/docs/ja/docs/tutorial/debugging.md
@@ -7,7 +7,7 @@ Visual Studio CodeやPyCharmなどを使用して、エディター上でデバ
FastAPIアプリケーション上で、`uvicorn` を直接インポートして実行します:
```Python hl_lines="1 15"
-{!../../../docs_src/debugging/tutorial001.py!}
+{!../../docs_src/debugging/tutorial001.py!}
```
### `__name__ == "__main__"` について
@@ -74,8 +74,11 @@ from myapp import app
は実行されません。
-!!! info "情報"
- より詳しい情報は、公式Pythonドキュメントを参照してください。
+/// info | "情報"
+
+より詳しい情報は、公式Pythonドキュメントを参照してください。
+
+///
## デバッガーでコードを実行
diff --git a/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md
index 5c150d00c..fb23a7b2b 100644
--- a/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md
+++ b/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md
@@ -7,7 +7,7 @@
前の例では、依存関係("dependable")から`dict`を返していました:
```Python hl_lines="9"
-{!../../../docs_src/dependencies/tutorial001.py!}
+{!../../docs_src/dependencies/tutorial001.py!}
```
しかし、*path operation関数*のパラメータ`commons`に`dict`が含まれています。
@@ -72,19 +72,19 @@ FastAPIが実際にチェックしているのは、それが「呼び出し可
そこで、上で紹介した依存関係の`common_parameters`を`CommonQueryParams`クラスに変更します:
```Python hl_lines="11 12 13 14 15"
-{!../../../docs_src/dependencies/tutorial002.py!}
+{!../../docs_src/dependencies/tutorial002.py!}
```
クラスのインスタンスを作成するために使用される`__init__`メソッドに注目してください:
```Python hl_lines="12"
-{!../../../docs_src/dependencies/tutorial002.py!}
+{!../../docs_src/dependencies/tutorial002.py!}
```
...以前の`common_parameters`と同じパラメータを持っています:
```Python hl_lines="8"
-{!../../../docs_src/dependencies/tutorial001.py!}
+{!../../docs_src/dependencies/tutorial001.py!}
```
これらのパラメータは **FastAPI** が依存関係を「解決」するために使用するものです。
@@ -102,7 +102,7 @@ FastAPIが実際にチェックしているのは、それが「呼び出し可
これで、このクラスを使用して依存関係を宣言することができます。
```Python hl_lines="19"
-{!../../../docs_src/dependencies/tutorial002.py!}
+{!../../docs_src/dependencies/tutorial002.py!}
```
**FastAPI** は`CommonQueryParams`クラスを呼び出します。これにより、そのクラスの「インスタンス」が作成され、インスタンスはパラメータ`commons`として関数に渡されます。
@@ -144,7 +144,7 @@ commons = Depends(CommonQueryParams)
以下にあるように:
```Python hl_lines="19"
-{!../../../docs_src/dependencies/tutorial003.py!}
+{!../../docs_src/dependencies/tutorial003.py!}
```
しかし、型を宣言することは推奨されています。そうすれば、エディタは`commons`のパラメータとして何が渡されるかを知ることができ、コードの補完や型チェックなどを行うのに役立ちます:
@@ -180,12 +180,15 @@ commons: CommonQueryParams = Depends()
同じ例では以下のようになります:
```Python hl_lines="19"
-{!../../../docs_src/dependencies/tutorial004.py!}
+{!../../docs_src/dependencies/tutorial004.py!}
```
...そして **FastAPI** は何をすべきか知っています。
-!!! tip "豆知識"
- 役に立つというよりも、混乱するようであれば無視してください。それをする*必要*はありません。
+/// tip | "豆知識"
- それは単なるショートカットです。なぜなら **FastAPI** はコードの繰り返しを最小限に抑えることに気を使っているからです。
+役に立つというよりも、混乱するようであれば無視してください。それをする*必要*はありません。
+
+それは単なるショートカットです。なぜなら **FastAPI** はコードの繰り返しを最小限に抑えることに気を使っているからです。
+
+///
diff --git a/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
index 1684d9ca1..59f21c3df 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
@@ -15,17 +15,20 @@
それは`Depends()`の`list`であるべきです:
```Python hl_lines="17"
-{!../../../docs_src/dependencies/tutorial006.py!}
+{!../../docs_src/dependencies/tutorial006.py!}
```
これらの依存関係は、通常の依存関係と同様に実行・解決されます。しかし、それらの値(何かを返す場合)は*path operation関数*には渡されません。
-!!! tip "豆知識"
- エディタによっては、未使用の関数パラメータをチェックしてエラーとして表示するものもあります。
+/// tip | "豆知識"
- `dependencies`を`path operationデコレータ`で使用することで、エディタやツールのエラーを回避しながら確実に実行することができます。
+エディタによっては、未使用の関数パラメータをチェックしてエラーとして表示するものもあります。
- また、コードの未使用のパラメータがあるのを見て、それが不要だと思ってしまうような新しい開発者の混乱を避けるのにも役立つかもしれません。
+`dependencies`を`path operationデコレータ`で使用することで、エディタやツールのエラーを回避しながら確実に実行することができます。
+
+また、コードの未使用のパラメータがあるのを見て、それが不要だと思ってしまうような新しい開発者の混乱を避けるのにも役立つかもしれません。
+
+///
## 依存関係のエラーと戻り値
@@ -36,7 +39,7 @@
これらはリクエストの要件(ヘッダのようなもの)やその他のサブ依存関係を宣言することができます:
```Python hl_lines="6 11"
-{!../../../docs_src/dependencies/tutorial006.py!}
+{!../../docs_src/dependencies/tutorial006.py!}
```
### 例外の発生
@@ -44,7 +47,7 @@
これらの依存関係は通常の依存関係と同じように、例外を`raise`発生させることができます:
```Python hl_lines="8 13"
-{!../../../docs_src/dependencies/tutorial006.py!}
+{!../../docs_src/dependencies/tutorial006.py!}
```
### 戻り値
@@ -54,7 +57,7 @@
つまり、すでにどこかで使っている通常の依存関係(値を返すもの)を再利用することができ、値は使われなくても依存関係は実行されます:
```Python hl_lines="9 14"
-{!../../../docs_src/dependencies/tutorial006.py!}
+{!../../docs_src/dependencies/tutorial006.py!}
```
## *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 c0642efd4..7ef1caf0d 100644
--- a/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md
+++ b/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md
@@ -4,27 +4,36 @@ FastAPIは、いくつかのContext Managersのおかげで動作します。
+/// note | "技術詳細"
- **FastAPI** はこれを実現するために内部的に使用しています。
+これはPythonのContext Managersのおかげで動作します。
+
+**FastAPI** はこれを実現するために内部的に使用しています。
+
+///
## `yield`と`HTTPException`を持つ依存関係
@@ -122,8 +137,11 @@ FastAPIは、いくつかのしてカスタムの独自ヘッダーを追加できます。
+/// tip | "豆知識"
- ただし、ブラウザのクライアントに表示させたいカスタムヘッダーがある場合は、StarletteのCORSドキュメントに記載されているパラメータ `expose_headers` を使用して、それらをCORS設定に追加する必要があります ([CORS (オリジン間リソース共有)](cors.md){.internal-link target=_blank})
+'X-'プレフィックスを使用してカスタムの独自ヘッダーを追加できます。
-!!! note "技術詳細"
- `from starlette.requests import Request` を使用することもできます。
+ただし、ブラウザのクライアントに表示させたいカスタムヘッダーがある場合は、StarletteのCORSドキュメントに記載されているパラメータ `expose_headers` を使用して、それらをCORS設定に追加する必要があります ([CORS (オリジン間リソース共有)](cors.md){.internal-link target=_blank})
- **FastAPI**は、開発者の便利のためにこれを提供していますが、Starletteから直接きています。
+///
+
+/// note | "技術詳細"
+
+`from starlette.requests import Request` を使用することもできます。
+
+**FastAPI**は、開発者の便利のためにこれを提供していますが、Starletteから直接きています。
+
+///
### `response` の前後
@@ -51,7 +60,7 @@
例えば、リクエストの処理とレスポンスの生成にかかった秒数を含むカスタムヘッダー `X-Process-Time` を追加できます:
```Python hl_lines="10 12-13"
-{!../../../docs_src/middleware/tutorial001.py!}
+{!../../docs_src/middleware/tutorial001.py!}
```
## その他のミドルウェア
diff --git a/docs/ja/docs/tutorial/path-operation-configuration.md b/docs/ja/docs/tutorial/path-operation-configuration.md
index 486c4b204..7eceb377d 100644
--- a/docs/ja/docs/tutorial/path-operation-configuration.md
+++ b/docs/ja/docs/tutorial/path-operation-configuration.md
@@ -2,8 +2,11 @@
*path operationデコレータ*を設定するためのパラメータがいくつかあります。
-!!! warning "注意"
- これらのパラメータは*path operation関数*ではなく、*path operationデコレータ*に直接渡されることに注意してください。
+/// warning | "注意"
+
+これらのパラメータは*path operation関数*ではなく、*path operationデコレータ*に直接渡されることに注意してください。
+
+///
## レスポンスステータスコード
@@ -14,22 +17,25 @@
しかし、それぞれの番号コードが何のためのものか覚えていない場合は、`status`のショートカット定数を使用することができます:
```Python hl_lines="3 17"
-{!../../../docs_src/path_operation_configuration/tutorial001.py!}
+{!../../docs_src/path_operation_configuration/tutorial001.py!}
```
そのステータスコードはレスポンスで使用され、OpenAPIスキーマに追加されます。
-!!! note "技術詳細"
- また、`from starlette import status`を使用することもできます。
+/// note | "技術詳細"
- **FastAPI** は開発者の利便性を考慮して、`fastapi.status`と同じ`starlette.status`を提供しています。しかし、これはStarletteから直接提供されています。
+また、`from starlette import status`を使用することもできます。
+
+**FastAPI** は開発者の利便性を考慮して、`fastapi.status`と同じ`starlette.status`を提供しています。しかし、これはStarletteから直接提供されています。
+
+///
## タグ
`tags`パラメータを`str`の`list`(通常は1つの`str`)と一緒に渡すと、*path operation*にタグを追加できます:
```Python hl_lines="17 22 27"
-{!../../../docs_src/path_operation_configuration/tutorial002.py!}
+{!../../docs_src/path_operation_configuration/tutorial002.py!}
```
これらはOpenAPIスキーマに追加され、自動ドキュメントのインターフェースで使用されます:
@@ -41,7 +47,7 @@
`summary`と`description`を追加できます:
```Python hl_lines="20-21"
-{!../../../docs_src/path_operation_configuration/tutorial003.py!}
+{!../../docs_src/path_operation_configuration/tutorial003.py!}
```
## docstringを用いた説明
@@ -51,7 +57,7 @@
docstringにMarkdownを記述すれば、正しく解釈されて表示されます。(docstringのインデントを考慮して)
```Python hl_lines="19-27"
-{!../../../docs_src/path_operation_configuration/tutorial004.py!}
+{!../../docs_src/path_operation_configuration/tutorial004.py!}
```
これは対話的ドキュメントで使用されます:
@@ -63,16 +69,22 @@ docstringに
@@ -81,7 +93,7 @@ docstringにdeprecatedとしてマークする必要があるが、それを削除しない場合は、`deprecated`パラメータを渡します:
```Python hl_lines="16"
-{!../../../docs_src/path_operation_configuration/tutorial006.py!}
+{!../../docs_src/path_operation_configuration/tutorial006.py!}
```
対話的ドキュメントでは非推奨と明記されます:
diff --git a/docs/ja/docs/tutorial/path-params-numeric-validations.md b/docs/ja/docs/tutorial/path-params-numeric-validations.md
index 551aeabb3..42fbb2ee2 100644
--- a/docs/ja/docs/tutorial/path-params-numeric-validations.md
+++ b/docs/ja/docs/tutorial/path-params-numeric-validations.md
@@ -7,7 +7,7 @@
まず初めに、`fastapi`から`Path`をインポートします:
```Python hl_lines="1"
-{!../../../docs_src/path_params_numeric_validations/tutorial001.py!}
+{!../../docs_src/path_params_numeric_validations/tutorial001.py!}
```
## メタデータの宣言
@@ -17,15 +17,18 @@
例えば、パスパラメータ`item_id`に対して`title`のメタデータを宣言するには以下のようにします:
```Python hl_lines="8"
-{!../../../docs_src/path_params_numeric_validations/tutorial001.py!}
+{!../../docs_src/path_params_numeric_validations/tutorial001.py!}
```
-!!! note "備考"
- パスの一部でなければならないので、パスパラメータは常に必須です。
+/// note | "備考"
- そのため、`...`を使用して必須と示す必要があります。
+パスの一部でなければならないので、パスパラメータは常に必須です。
- それでも、`None`で宣言しても、デフォルト値を設定しても、何の影響もなく、常に必要とされていることに変わりはありません。
+そのため、`...`を使用して必須と示す必要があります。
+
+それでも、`None`で宣言しても、デフォルト値を設定しても、何の影響もなく、常に必要とされていることに変わりはありません。
+
+///
## 必要に応じてパラメータを並び替える
@@ -44,7 +47,7 @@ Pythonは「デフォルト」を持たない値の前に「デフォルト」
そのため、以下のように関数を宣言することができます:
```Python hl_lines="8"
-{!../../../docs_src/path_params_numeric_validations/tutorial002.py!}
+{!../../docs_src/path_params_numeric_validations/tutorial002.py!}
```
## 必要に応じてパラメータを並び替えるトリック
@@ -56,7 +59,7 @@ Pythonは「デフォルト」を持たない値の前に「デフォルト」
Pythonはその`*`で何かをすることはありませんが、それ以降のすべてのパラメータがキーワード引数(キーと値のペア)として呼ばれるべきものであると知っているでしょう。それはkwargsとしても知られています。たとえデフォルト値がなくても。
```Python hl_lines="8"
-{!../../../docs_src/path_params_numeric_validations/tutorial003.py!}
+{!../../docs_src/path_params_numeric_validations/tutorial003.py!}
```
## 数値の検証: 以上
@@ -66,7 +69,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!}
```
## 数値の検証: より大きいと小なりイコール
@@ -77,7 +80,7 @@ Pythonはその`*`で何かをすることはありませんが、それ以降
* `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!}
```
## 数値の検証: 浮動小数点、 大なり小なり
@@ -91,7 +94,7 @@ Pythonはその`*`で何かをすることはありませんが、それ以降
これはltも同じです。
```Python hl_lines="11"
-{!../../../docs_src/path_params_numeric_validations/tutorial006.py!}
+{!../../docs_src/path_params_numeric_validations/tutorial006.py!}
```
## まとめ
@@ -105,18 +108,24 @@ Pythonはその`*`で何かをすることはありませんが、それ以降
* `lt`: より小さい(`l`ess `t`han)
* `le`: 以下(`l`ess than or `e`qual)
-!!! info "情報"
- `Query`、`Path`などは後に共通の`Param`クラスのサブクラスを見ることになります。(使う必要はありません)
+/// info | "情報"
- そして、それらすべては、これまで見てきた追加のバリデーションとメタデータと同じパラメータを共有しています。
+`Query`、`Path`などは後に共通の`Param`クラスのサブクラスを見ることになります。(使う必要はありません)
-!!! note "技術詳細"
- `fastapi`から`Query`、`Path`などをインポートすると、これらは実際には関数です。
+そして、それらすべては、これまで見てきた追加のバリデーションとメタデータと同じパラメータを共有しています。
- 呼び出されると、同じ名前のクラスのインスタンスを返します。
+///
- そのため、関数である`Query`をインポートし、それを呼び出すと、`Query`という名前のクラスのインスタンスが返されます。
+/// note | "技術詳細"
- これらの関数は(クラスを直接使うのではなく)エディタが型についてエラーとしないようにするために存在します。
+`fastapi`から`Query`、`Path`などをインポートすると、これらは実際には関数です。
- この方法によって、これらのエラーを無視するための設定を追加することなく、通常のエディタやコーディングツールを使用することができます。
+呼び出されると、同じ名前のクラスのインスタンスを返します。
+
+そのため、関数である`Query`をインポートし、それを呼び出すと、`Query`という名前のクラスのインスタンスが返されます。
+
+これらの関数は(クラスを直接使うのではなく)エディタが型についてエラーとしないようにするために存在します。
+
+この方法によって、これらのエラーを無視するための設定を追加することなく、通常のエディタやコーディングツールを使用することができます。
+
+///
diff --git a/docs/ja/docs/tutorial/path-params.md b/docs/ja/docs/tutorial/path-params.md
index b395dc41d..e1cb67a13 100644
--- a/docs/ja/docs/tutorial/path-params.md
+++ b/docs/ja/docs/tutorial/path-params.md
@@ -3,7 +3,7 @@
Pythonのformat文字列と同様のシンタックスで「パスパラメータ」や「パス変数」を宣言できます:
```Python hl_lines="6 7"
-{!../../../docs_src/path_params/tutorial001.py!}
+{!../../docs_src/path_params/tutorial001.py!}
```
パスパラメータ `item_id` の値は、引数 `item_id` として関数に渡されます。
@@ -19,13 +19,16 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー
標準のPythonの型アノテーションを使用して、関数内のパスパラメータの型を宣言できます:
```Python hl_lines="7"
-{!../../../docs_src/path_params/tutorial002.py!}
+{!../../docs_src/path_params/tutorial002.py!}
```
ここでは、 `item_id` は `int` として宣言されています。
-!!! check "確認"
- これにより、関数内でのエディターサポート (エラーチェックや補完など) が提供されます。
+/// check | "確認"
+
+これにより、関数内でのエディターサポート (エラーチェックや補完など) が提供されます。
+
+///
## データ変換
@@ -35,10 +38,13 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー
{"item_id":3}
```
-!!! check "確認"
- 関数が受け取った(および返した)値は、文字列の `"3"` ではなく、Pythonの `int` としての `3` であることに注意してください。
+/// check | "確認"
- したがって、型宣言を使用すると、**FastAPI**は自動リクエスト "解析" を行います。
+関数が受け取った(および返した)値は、文字列の `"3"` ではなく、Pythonの `int` としての `3` であることに注意してください。
+
+したがって、型宣言を使用すると、**FastAPI**は自動リクエスト "解析" を行います。
+
+///
## データバリデーション
@@ -63,12 +69,15 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー
http://127.0.0.1:8000/items/4.2 で見られるように、intのかわりに `float` が与えられた場合にも同様なエラーが表示されます。
-!!! check "確認"
- したがって、Pythonの型宣言を使用することで、**FastAPI**はデータのバリデーションを行います。
+/// check | "確認"
- 表示されたエラーには問題のある箇所が明確に指摘されていることに注意してください。
+したがって、Pythonの型宣言を使用することで、**FastAPI**はデータのバリデーションを行います。
- これは、APIに関連するコードの開発およびデバッグに非常に役立ちます。
+表示されたエラーには問題のある箇所が明確に指摘されていることに注意してください。
+
+これは、APIに関連するコードの開発およびデバッグに非常に役立ちます。
+
+///
## ドキュメント
@@ -76,10 +85,13 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー
-!!! check "確認"
- 繰り返しになりますが、Python型宣言を使用するだけで、**FastAPI**は対話的なAPIドキュメントを自動的に生成します(Swagger UIを統合)。
+/// check | "確認"
- パスパラメータが整数として宣言されていることに注意してください。
+繰り返しになりますが、Python型宣言を使用するだけで、**FastAPI**は対話的なAPIドキュメントを自動的に生成します(Swagger UIを統合)。
+
+パスパラメータが整数として宣言されていることに注意してください。
+
+///
## 標準であることのメリット、ドキュメンテーションの代替物
@@ -110,7 +122,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!}
```
それ以外の場合、 `/users/{users_id}` は `/users/me` としてもマッチします。値が「"me"」であるパラメータ `user_id` を受け取ると「考え」ます。
@@ -128,21 +140,27 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー
そして、固定値のクラス属性を作ります。すると、その値が使用可能な値となります:
```Python hl_lines="1 6 7 8 9"
-{!../../../docs_src/path_params/tutorial005.py!}
+{!../../docs_src/path_params/tutorial005.py!}
```
-!!! info "情報"
- Enumerations (もしくは、enums)はPython 3.4以降で利用できます。
+/// info | "情報"
-!!! tip "豆知識"
- "AlexNet"、"ResNet"そして"LeNet"は機械学習モデルの名前です。
+Enumerations (もしくは、enums)はPython 3.4以降で利用できます。
+
+///
+
+/// tip | "豆知識"
+
+"AlexNet"、"ResNet"そして"LeNet"は機械学習モデルの名前です。
+
+///
### *パスパラメータ*の宣言
次に、作成したenumクラスである`ModelName`を使用した型アノテーションをもつ*パスパラメータ*を作成します:
```Python hl_lines="16"
-{!../../../docs_src/path_params/tutorial005.py!}
+{!../../docs_src/path_params/tutorial005.py!}
```
### ドキュメントの確認
@@ -160,7 +178,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー
これは、作成した列挙型 `ModelName` の*列挙型メンバ*と比較できます:
```Python hl_lines="17"
-{!../../../docs_src/path_params/tutorial005.py!}
+{!../../docs_src/path_params/tutorial005.py!}
```
#### *列挙値*の取得
@@ -168,11 +186,14 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー
`model_name.value` 、もしくは一般に、 `your_enum_member.value` を使用して実際の値 (この場合は `str`) を取得できます。
```Python hl_lines="20"
-{!../../../docs_src/path_params/tutorial005.py!}
+{!../../docs_src/path_params/tutorial005.py!}
```
-!!! tip "豆知識"
- `ModelName.lenet.value` でも `"lenet"` 値にアクセスできます。
+/// tip | "豆知識"
+
+`ModelName.lenet.value` でも `"lenet"` 値にアクセスできます。
+
+///
#### *列挙型メンバ*の返却
@@ -181,7 +202,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー
それらはクライアントに返される前に適切な値 (この場合は文字列) に変換されます。
```Python hl_lines="18 21 23"
-{!../../../docs_src/path_params/tutorial005.py!}
+{!../../docs_src/path_params/tutorial005.py!}
```
クライアントは以下の様なJSONレスポンスを得ます:
@@ -222,13 +243,16 @@ Starletteのオプションを直接使用することで、以下のURLの様
したがって、以下の様に使用できます:
```Python hl_lines="6"
-{!../../../docs_src/path_params/tutorial004.py!}
+{!../../docs_src/path_params/tutorial004.py!}
```
-!!! tip "豆知識"
- 最初のスラッシュ (`/`)が付いている `/home/johndoe/myfile.txt` をパラメータが含んでいる必要があります。
+/// tip | "豆知識"
- この場合、URLは `files` と `home` の間にダブルスラッシュ (`//`) のある、 `/files//home/johndoe/myfile.txt` になります。
+最初のスラッシュ (`/`)が付いている `/home/johndoe/myfile.txt` をパラメータが含んでいる必要があります。
+
+この場合、URLは `files` と `home` の間にダブルスラッシュ (`//`) のある、 `/files//home/johndoe/myfile.txt` になります。
+
+///
## まとめ
diff --git a/docs/ja/docs/tutorial/query-params-str-validations.md b/docs/ja/docs/tutorial/query-params-str-validations.md
index 8d375d7ce..9e54a6f55 100644
--- a/docs/ja/docs/tutorial/query-params-str-validations.md
+++ b/docs/ja/docs/tutorial/query-params-str-validations.md
@@ -5,15 +5,19 @@
以下のアプリケーションを例にしてみましょう:
```Python hl_lines="9"
-{!../../../docs_src/query_params_str_validations/tutorial001.py!}
+{!../../docs_src/query_params_str_validations/tutorial001.py!}
```
クエリパラメータ `q` は `Optional[str]` 型で、`None` を許容する `str` 型を意味しており、デフォルトは `None` です。そのため、FastAPIはそれが必須ではないと理解します。
-!!! note "備考"
- FastAPIは、 `q` はデフォルト値が `=None` であるため、必須ではないと理解します。
+/// note | "備考"
+
+FastAPIは、 `q` はデフォルト値が `=None` であるため、必須ではないと理解します。
+
+`Optional[str]` における `Optional` はFastAPIには利用されませんが、エディターによるより良いサポートとエラー検出を可能にします。
+
+///
- `Optional[str]` における `Optional` はFastAPIには利用されませんが、エディターによるより良いサポートとエラー検出を可能にします。
## バリデーションの追加
`q`はオプショナルですが、もし値が渡されてきた場合には、**50文字を超えないこと**を強制してみましょう。
@@ -23,7 +27,7 @@
そのために、まずは`fastapi`から`Query`をインポートします:
```Python hl_lines="3"
-{!../../../docs_src/query_params_str_validations/tutorial002.py!}
+{!../../docs_src/query_params_str_validations/tutorial002.py!}
```
## デフォルト値として`Query`を使用
@@ -31,7 +35,7 @@
パラメータのデフォルト値として使用し、パラメータ`max_length`を50に設定します:
```Python hl_lines="9"
-{!../../../docs_src/query_params_str_validations/tutorial002.py!}
+{!../../docs_src/query_params_str_validations/tutorial002.py!}
```
デフォルト値`None`を`Query(default=None)`に置き換える必要があるので、`Query`の最初の引数はデフォルト値を定義するのと同じです。
@@ -50,22 +54,25 @@ q: Optional[str] = None
しかし、これはクエリパラメータとして明示的に宣言しています。
-!!! info "情報"
- FastAPIは以下の部分を気にすることを覚えておいてください:
+/// info | "情報"
- ```Python
- = None
- ```
+FastAPIは以下の部分を気にすることを覚えておいてください:
- もしくは:
+```Python
+= None
+```
- ```Python
- = Query(default=None)
- ```
+もしくは:
- そして、 `None` を利用することでクエリパラメータが必須ではないと検知します。
+```Python
+= Query(default=None)
+```
- `Optional` の部分は、エディターによるより良いサポートを可能にします。
+そして、 `None` を利用することでクエリパラメータが必須ではないと検知します。
+
+`Optional` の部分は、エディターによるより良いサポートを可能にします。
+
+///
そして、さらに多くのパラメータを`Query`に渡すことができます。この場合、文字列に適用される、`max_length`パラメータを指定します。
@@ -80,7 +87,7 @@ 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!}
```
## 正規表現の追加
@@ -88,7 +95,7 @@ q: Union[str, None] = Query(default=None, max_length=50)
パラメータが一致するべき正規表現を定義することができます:
```Python hl_lines="11"
-{!../../../docs_src/query_params_str_validations/tutorial004.py!}
+{!../../docs_src/query_params_str_validations/tutorial004.py!}
```
この特定の正規表現は受け取ったパラメータの値をチェックします:
@@ -108,11 +115,14 @@ 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!}
```
-!!! note "備考"
- デフォルト値を指定すると、パラメータは任意になります。
+/// note | "備考"
+
+デフォルト値を指定すると、パラメータは任意になります。
+
+///
## 必須にする
@@ -137,11 +147,14 @@ 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!}
```
-!!! info "情報"
- これまで`...`を見たことがない方へ: これは特殊な単一値です。Pythonの一部であり、"Ellipsis"と呼ばれています。
+/// info | "情報"
+
+これまで`...`を見たことがない方へ: これは特殊な単一値です。Pythonの一部であり、"Ellipsis"と呼ばれています。
+
+///
これは **FastAPI** にこのパラメータが必須であることを知らせます。
@@ -152,7 +165,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!}
```
そしてURLは以下です:
@@ -174,8 +187,11 @@ http://localhost:8000/items/?q=foo&q=bar
}
```
-!!! tip "豆知識"
- 上述の例のように、`list`型のクエリパラメータを宣言するには明示的に`Query`を使用する必要があります。そうしない場合、リクエストボディと解釈されます。
+/// tip | "豆知識"
+
+上述の例のように、`list`型のクエリパラメータを宣言するには明示的に`Query`を使用する必要があります。そうしない場合、リクエストボディと解釈されます。
+
+///
対話的APIドキュメントは複数の値を許可するために自動的に更新されます。
@@ -186,7 +202,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!}
```
以下のURLを開くと:
@@ -211,13 +227,16 @@ 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!}
```
-!!! note "備考"
- この場合、FastAPIはリストの内容をチェックしないことを覚えておいてください。
+/// note | "備考"
- 例えば`List[int]`はリストの内容が整数であるかどうかをチェックします(そして、文書化します)。しかし`list`だけではそうしません。
+この場合、FastAPIはリストの内容をチェックしないことを覚えておいてください。
+
+例えば`List[int]`はリストの内容が整数であるかどうかをチェックします(そして、文書化します)。しかし`list`だけではそうしません。
+
+///
## より多くのメタデータを宣言する
@@ -225,21 +244,24 @@ http://localhost:8000/items/
その情報は、生成されたOpenAPIに含まれ、ドキュメントのユーザーインターフェースや外部のツールで使用されます。
-!!! note "備考"
- ツールによってOpenAPIのサポートのレベルが異なる可能性があることを覚えておいてください。
+/// note | "備考"
- その中には、宣言されたすべての追加情報が表示されていないものもあるかもしれませんが、ほとんどの場合、不足している機能はすでに開発の計画がされています。
+ツールによってOpenAPIのサポートのレベルが異なる可能性があることを覚えておいてください。
+
+その中には、宣言されたすべての追加情報が表示されていないものもあるかもしれませんが、ほとんどの場合、不足している機能はすでに開発の計画がされています。
+
+///
`title`を追加できます:
```Python hl_lines="9"
-{!../../../docs_src/query_params_str_validations/tutorial007.py!}
+{!../../docs_src/query_params_str_validations/tutorial007.py!}
```
`description`を追加できます:
```Python hl_lines="13"
-{!../../../docs_src/query_params_str_validations/tutorial008.py!}
+{!../../docs_src/query_params_str_validations/tutorial008.py!}
```
## エイリアスパラメータ
@@ -261,7 +283,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!}
```
## 非推奨パラメータ
@@ -273,7 +295,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!}
```
ドキュメントは以下のようになります:
diff --git a/docs/ja/docs/tutorial/query-params.md b/docs/ja/docs/tutorial/query-params.md
index 5c4cfc5fc..6d41d3742 100644
--- a/docs/ja/docs/tutorial/query-params.md
+++ b/docs/ja/docs/tutorial/query-params.md
@@ -1,10 +1,9 @@
-
# クエリパラメータ
パスパラメータではない関数パラメータを宣言すると、それらは自動的に "クエリ" パラメータとして解釈されます。
```Python hl_lines="9"
-{!../../../docs_src/query_params/tutorial001.py!}
+{!../../docs_src/query_params/tutorial001.py!}
```
クエリはURL内で `?` の後に続くキーとバリューの組で、 `&` で区切られています。
@@ -65,20 +64,23 @@ 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!}
```
この場合、関数パラメータ `q` はオプショナルとなり、デフォルトでは `None` になります。
-!!! check "確認"
- パスパラメータ `item_id` はパスパラメータであり、`q` はそれとは違ってクエリパラメータであると判別できるほど**FastAPI** が賢いということにも注意してください。
+/// check | "確認"
+
+パスパラメータ `item_id` はパスパラメータであり、`q` はそれとは違ってクエリパラメータであると判別できるほど**FastAPI** が賢いということにも注意してください。
+
+///
## クエリパラメータの型変換
`bool` 型も宣言できます。これは以下の様に変換されます:
```Python hl_lines="9"
-{!../../../docs_src/query_params/tutorial003.py!}
+{!../../docs_src/query_params/tutorial003.py!}
```
この場合、以下にアクセスすると:
@@ -122,7 +124,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!}
```
## 必須のクエリパラメータ
@@ -134,7 +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!}
```
ここで、クエリパラメータ `needy` は `str` 型の必須のクエリパラメータです
@@ -180,7 +182,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!}
```
この場合、3つのクエリパラメータがあります。:
@@ -189,6 +191,8 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
* `skip`、デフォルト値を `0` とする `int` 。
* `limit`、オプショナルな `int` 。
-!!! tip "豆知識"
+/// tip | "豆知識"
- [パスパラメータ](path-params.md#_8){.internal-link target=_blank}と同様に `Enum` を使用できます。
+[パスパラメータ](path-params.md#_8){.internal-link target=_blank}と同様に `Enum` を使用できます。
+
+///
diff --git a/docs/ja/docs/tutorial/request-forms-and-files.md b/docs/ja/docs/tutorial/request-forms-and-files.md
index 86913ccac..e03b9166d 100644
--- a/docs/ja/docs/tutorial/request-forms-and-files.md
+++ b/docs/ja/docs/tutorial/request-forms-and-files.md
@@ -2,15 +2,18 @@
`File`と`Form`を同時に使うことでファイルとフォームフィールドを定義することができます。
-!!! info "情報"
- アップロードされたファイルやフォームデータを受信するには、まず`python-multipart`をインストールします。
+/// info | "情報"
- 例えば、`pip install python-multipart`のように。
+アップロードされたファイルやフォームデータを受信するには、まず`python-multipart`をインストールします。
+
+例えば、`pip install python-multipart`のように。
+
+///
## `File`と`Form`のインポート
```Python hl_lines="1"
-{!../../../docs_src/request_forms_and_files/tutorial001.py!}
+{!../../docs_src/request_forms_and_files/tutorial001.py!}
```
## `File`と`Form`のパラメータの定義
@@ -18,17 +21,20 @@
ファイルやフォームのパラメータは`Body`や`Query`の場合と同じように作成します:
```Python hl_lines="8"
-{!../../../docs_src/request_forms_and_files/tutorial001.py!}
+{!../../docs_src/request_forms_and_files/tutorial001.py!}
```
ファイルとフォームフィールドがフォームデータとしてアップロードされ、ファイルとフォームフィールドを受け取ります。
また、いくつかのファイルを`bytes`として、いくつかのファイルを`UploadFile`として宣言することができます。
-!!! warning "注意"
- *path operation*で複数の`File`と`Form`パラメータを宣言することができますが、JSONとして受け取ることを期待している`Body`フィールドを宣言することはできません。なぜなら、リクエストのボディは`application/json`の代わりに`multipart/form-data`を使ってエンコードされているからです。
+/// warning | "注意"
- これは **FastAPI** の制限ではなく、HTTPプロトコルの一部です。
+*path operation*で複数の`File`と`Form`パラメータを宣言することができますが、JSONとして受け取ることを期待している`Body`フィールドを宣言することはできません。なぜなら、リクエストのボディは`application/json`の代わりに`multipart/form-data`を使ってエンコードされているからです。
+
+これは **FastAPI** の制限ではなく、HTTPプロトコルの一部です。
+
+///
## まとめ
diff --git a/docs/ja/docs/tutorial/request-forms.md b/docs/ja/docs/tutorial/request-forms.md
index f90c49746..eb453c04a 100644
--- a/docs/ja/docs/tutorial/request-forms.md
+++ b/docs/ja/docs/tutorial/request-forms.md
@@ -2,17 +2,20 @@
JSONの代わりにフィールドを受け取る場合は、`Form`を使用します。
-!!! info "情報"
- フォームを使うためには、まず`python-multipart`をインストールします。
+/// info | "情報"
- たとえば、`pip install python-multipart`のように。
+フォームを使うためには、まず`python-multipart`をインストールします。
+
+たとえば、`pip install python-multipart`のように。
+
+///
## `Form`のインポート
`fastapi`から`Form`をインポートします:
```Python hl_lines="1"
-{!../../../docs_src/request_forms/tutorial001.py!}
+{!../../docs_src/request_forms/tutorial001.py!}
```
## `Form`のパラメータの定義
@@ -20,7 +23,7 @@ JSONの代わりにフィールドを受け取る場合は、`Form`を使用し
`Body`や`Query`の場合と同じようにフォームパラメータを作成します:
```Python hl_lines="7"
-{!../../../docs_src/request_forms/tutorial001.py!}
+{!../../docs_src/request_forms/tutorial001.py!}
```
例えば、OAuth2仕様が使用できる方法の1つ(「パスワードフロー」と呼ばれる)では、フォームフィールドとして`username`と`password`を送信する必要があります。
@@ -29,11 +32,17 @@ JSONの代わりにフィールドを受け取る場合は、`Form`を使用し
`Form`では`Body`(および`Query`や`Path`、`Cookie`)と同じメタデータとバリデーションを宣言することができます。
-!!! info "情報"
- `Form`は`Body`を直接継承するクラスです。
+/// info | "情報"
-!!! tip "豆知識"
- フォームのボディを宣言するには、明示的に`Form`を使用する必要があります。なぜなら、これを使わないと、パラメータはクエリパラメータやボディ(JSON)パラメータとして解釈されるからです。
+`Form`は`Body`を直接継承するクラスです。
+
+///
+
+/// tip | "豆知識"
+
+フォームのボディを宣言するには、明示的に`Form`を使用する必要があります。なぜなら、これを使わないと、パラメータはクエリパラメータやボディ(JSON)パラメータとして解釈されるからです。
+
+///
## 「フォームフィールド」について
@@ -41,17 +50,23 @@ HTMLフォーム(``)がサーバにデータを送信する方
**FastAPI** は、JSONの代わりにそのデータを適切な場所から読み込むようにします。
-!!! note "技術詳細"
- フォームからのデータは通常、`application/x-www-form-urlencoded`の「media type」を使用してエンコードされます。
+/// note | "技術詳細"
- しかし、フォームがファイルを含む場合は、`multipart/form-data`としてエンコードされます。ファイルの扱いについては次の章で説明します。
+フォームからのデータは通常、`application/x-www-form-urlencoded`の「media type」を使用してエンコードされます。
- これらのエンコーディングやフォームフィールドの詳細については、MDNのPOSTのウェブドキュメントを参照してください。
+しかし、フォームがファイルを含む場合は、`multipart/form-data`としてエンコードされます。ファイルの扱いについては次の章で説明します。
-!!! warning "注意"
- *path operation*で複数の`Form`パラメータを宣言することができますが、JSONとして受け取ることを期待している`Body`フィールドを宣言することはできません。なぜなら、リクエストは`application/json`の代わりに`application/x-www-form-urlencoded`を使ってボディをエンコードするからです。
+これらのエンコーディングやフォームフィールドの詳細については、MDNのPOSTのウェブドキュメントを参照してください。
- これは **FastAPI**の制限ではなく、HTTPプロトコルの一部です。
+///
+
+/// warning | "注意"
+
+*path operation*で複数の`Form`パラメータを宣言することができますが、JSONとして受け取ることを期待している`Body`フィールドを宣言することはできません。なぜなら、リクエストは`application/json`の代わりに`application/x-www-form-urlencoded`を使ってボディをエンコードするからです。
+
+これは **FastAPI**の制限ではなく、HTTPプロトコルの一部です。
+
+///
## まとめ
diff --git a/docs/ja/docs/tutorial/response-model.md b/docs/ja/docs/tutorial/response-model.md
index b8b6978d4..973f893de 100644
--- a/docs/ja/docs/tutorial/response-model.md
+++ b/docs/ja/docs/tutorial/response-model.md
@@ -9,11 +9,14 @@
* など。
```Python hl_lines="17"
-{!../../../docs_src/response_model/tutorial001.py!}
+{!../../docs_src/response_model/tutorial001.py!}
```
-!!! note "備考"
- `response_model`は「デコレータ」メソッド(`get`、`post`など)のパラメータであることに注意してください。すべてのパラメータやボディのように、*path operation関数* のパラメータではありません。
+/// note | "備考"
+
+`response_model`は「デコレータ」メソッド(`get`、`post`など)のパラメータであることに注意してください。すべてのパラメータやボディのように、*path operation関数* のパラメータではありません。
+
+///
Pydanticモデルの属性に対して宣言するのと同じ型を受け取るので、Pydanticモデルになることもできますが、例えば、`List[Item]`のようなPydanticモデルの`list`になることもできます。
@@ -28,21 +31,24 @@ FastAPIは`response_model`を使って以下のことをします:
* 出力データをモデルのデータに限定します。これがどのように重要なのか以下で見ていきましょう。
-!!! note "技術詳細"
- レスポンスモデルは、関数の戻り値のアノテーションではなく、このパラメータで宣言されています。なぜなら、パス関数は実際にはそのレスポンスモデルを返すのではなく、`dict`やデータベースオブジェクト、あるいは他のモデルを返し、`response_model`を使用してフィールドの制限やシリアライズを行うからです。
+/// note | "技術詳細"
+
+レスポンスモデルは、関数の戻り値のアノテーションではなく、このパラメータで宣言されています。なぜなら、パス関数は実際にはそのレスポンスモデルを返すのではなく、`dict`やデータベースオブジェクト、あるいは他のモデルを返し、`response_model`を使用してフィールドの制限やシリアライズを行うからです。
+
+///
## 同じ入力データの返却
ここでは`UserIn`モデルを宣言しています。それには平文のパスワードが含まれています:
```Python hl_lines="9 11"
-{!../../../docs_src/response_model/tutorial002.py!}
+{!../../docs_src/response_model/tutorial002.py!}
```
そして、このモデルを使用して入力を宣言し、同じモデルを使って出力を宣言しています:
```Python hl_lines="17 18"
-{!../../../docs_src/response_model/tutorial002.py!}
+{!../../docs_src/response_model/tutorial002.py!}
```
これで、ブラウザがパスワードを使ってユーザーを作成する際に、APIがレスポンスで同じパスワードを返すようになりました。
@@ -51,27 +57,30 @@ FastAPIは`response_model`を使って以下のことをします:
しかし、同じモデルを別の*path operation*に使用すると、すべてのクライアントにユーザーのパスワードを送信してしまうことになります。
-!!! danger "危険"
- ユーザーの平文のパスワードを保存したり、レスポンスで送信したりすることは絶対にしないでください。
+/// danger | "危険"
+
+ユーザーの平文のパスワードを保存したり、レスポンスで送信したりすることは絶対にしないでください。
+
+///
## 出力モデルの追加
代わりに、平文のパスワードを持つ入力モデルと、パスワードを持たない出力モデルを作成することができます:
```Python hl_lines="9 11 16"
-{!../../../docs_src/response_model/tutorial003.py!}
+{!../../docs_src/response_model/tutorial003.py!}
```
ここでは、*path operation関数*がパスワードを含む同じ入力ユーザーを返しているにもかかわらず:
```Python hl_lines="24"
-{!../../../docs_src/response_model/tutorial003.py!}
+{!../../docs_src/response_model/tutorial003.py!}
```
...`response_model`を`UserOut`と宣言したことで、パスワードが含まれていません:
```Python hl_lines="22"
-{!../../../docs_src/response_model/tutorial003.py!}
+{!../../docs_src/response_model/tutorial003.py!}
```
そのため、**FastAPI** は出力モデルで宣言されていない全てのデータをフィルタリングしてくれます(Pydanticを使用)。
@@ -91,7 +100,7 @@ FastAPIは`response_model`を使って以下のことをします:
レスポンスモデルにはデフォルト値を設定することができます:
```Python hl_lines="11 13 14"
-{!../../../docs_src/response_model/tutorial004.py!}
+{!../../docs_src/response_model/tutorial004.py!}
```
* `description: str = None`は`None`がデフォルト値です。
@@ -107,7 +116,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!}
```
そして、これらのデフォルト値はレスポンスに含まれず、実際に設定された値のみが含まれます。
@@ -121,16 +130,22 @@ FastAPIは`response_model`を使って以下のことをします:
}
```
-!!! info "情報"
- FastAPIはこれをするために、Pydanticモデルの`.dict()`をその`exclude_unset`パラメータで使用しています。
+/// info | "情報"
-!!! info "情報"
- 以下も使用することができます:
+FastAPIはこれをするために、Pydanticモデルの`.dict()`をその`exclude_unset`パラメータで使用しています。
- * `response_model_exclude_defaults=True`
- * `response_model_exclude_none=True`
+///
- `exclude_defaults`と`exclude_none`については、Pydanticのドキュメントで説明されている通りです。
+/// info | "情報"
+
+以下も使用することができます:
+
+* `response_model_exclude_defaults=True`
+* `response_model_exclude_none=True`
+
+`exclude_defaults`と`exclude_none`については、Pydanticのドキュメントで説明されている通りです。
+
+///
#### デフォルト値を持つフィールドの値を持つデータ
@@ -165,9 +180,12 @@ FastAPIは十分に賢いので(実際には、Pydanticが十分に賢い)`d
そのため、それらはJSONレスポンスに含まれることになります。
-!!! tip "豆知識"
- デフォルト値は`None`だけでなく、なんでも良いことに注意してください。
- 例えば、リスト(`[]`)や`10.5`の`float`などです。
+/// tip | "豆知識"
+
+デフォルト値は`None`だけでなく、なんでも良いことに注意してください。
+例えば、リスト(`[]`)や`10.5`の`float`などです。
+
+///
### `response_model_include`と`response_model_exclude`
@@ -177,28 +195,34 @@ FastAPIは十分に賢いので(実際には、Pydanticが十分に賢い)`d
これは、Pydanticモデルが1つしかなく、出力からいくつかのデータを削除したい場合のクイックショートカットとして使用することができます。
-!!! tip "豆知識"
- それでも、これらのパラメータではなく、複数のクラスを使用して、上記のようなアイデアを使うことをおすすめします。
+/// tip | "豆知識"
- これは`response_model_include`や`response_mode_exclude`を使用していくつかの属性を省略しても、アプリケーションのOpenAPI(とドキュメント)で生成されたJSON Schemaが完全なモデルになるからです。
+それでも、これらのパラメータではなく、複数のクラスを使用して、上記のようなアイデアを使うことをおすすめします。
- 同様に動作する`response_model_by_alias`にも当てはまります。
+これは`response_model_include`や`response_mode_exclude`を使用していくつかの属性を省略しても、アプリケーションのOpenAPI(とドキュメント)で生成されたJSON Schemaが完全なモデルになるからです。
+
+同様に動作する`response_model_by_alias`にも当てはまります。
+
+///
```Python hl_lines="31 37"
-{!../../../docs_src/response_model/tutorial005.py!}
+{!../../docs_src/response_model/tutorial005.py!}
```
-!!! tip "豆知識"
- `{"name", "description"}`の構文はこれら2つの値をもつ`set`を作成します。
+/// tip | "豆知識"
- これは`set(["name", "description"])`と同等です。
+`{"name", "description"}`の構文はこれら2つの値をもつ`set`を作成します。
+
+これは`set(["name", "description"])`と同等です。
+
+///
#### `set`の代わりに`list`を使用する
もし`set`を使用することを忘れて、代わりに`list`や`tuple`を使用しても、FastAPIはそれを`set`に変換して正しく動作します:
```Python hl_lines="31 37"
-{!../../../docs_src/response_model/tutorial006.py!}
+{!../../docs_src/response_model/tutorial006.py!}
```
## まとめ
diff --git a/docs/ja/docs/tutorial/response-status-code.md b/docs/ja/docs/tutorial/response-status-code.md
index ead2addda..90b290887 100644
--- a/docs/ja/docs/tutorial/response-status-code.md
+++ b/docs/ja/docs/tutorial/response-status-code.md
@@ -9,16 +9,22 @@
* など。
```Python hl_lines="6"
-{!../../../docs_src/response_status_code/tutorial001.py!}
+{!../../docs_src/response_status_code/tutorial001.py!}
```
-!!! note "備考"
- `status_code`は「デコレータ」メソッド(`get`、`post`など)のパラメータであることに注意してください。すべてのパラメータやボディのように、*path operation関数*のものではありません。
+/// note | "備考"
+
+`status_code`は「デコレータ」メソッド(`get`、`post`など)のパラメータであることに注意してください。すべてのパラメータやボディのように、*path operation関数*のものではありません。
+
+///
`status_code`パラメータはHTTPステータスコードを含む数値を受け取ります。
-!!! info "情報"
- `status_code`は代わりに、Pythonの`http.HTTPStatus`のように、`IntEnum`を受け取ることもできます。
+/// info | "情報"
+
+`status_code`は代わりに、Pythonの`http.HTTPStatus`のように、`IntEnum`を受け取ることもできます。
+
+///
これは:
@@ -27,15 +33,21 @@
-!!! note "備考"
- いくつかのレスポンスコード(次のセクションを参照)は、レスポンスにボディがないことを示しています。
+/// note | "備考"
- FastAPIはこれを知っていて、レスポンスボディがないというOpenAPIドキュメントを生成します。
+いくつかのレスポンスコード(次のセクションを参照)は、レスポンスにボディがないことを示しています。
+
+FastAPIはこれを知っていて、レスポンスボディがないというOpenAPIドキュメントを生成します。
+
+///
## HTTPステータスコードについて
-!!! note "備考"
- すでにHTTPステータスコードが何であるかを知っている場合は、次のセクションにスキップしてください。
+/// note | "備考"
+
+すでにHTTPステータスコードが何であるかを知っている場合は、次のセクションにスキップしてください。
+
+///
HTTPでは、レスポンスの一部として3桁の数字のステータスコードを送信します。
@@ -54,15 +66,18 @@ HTTPでは、レスポンスの一部として3桁の数字のステータス
* クライアントからの一般的なエラーについては、`400`を使用することができます。
* `500`以上はサーバーエラーのためのものです。これらを直接使うことはほとんどありません。アプリケーションコードやサーバーのどこかで何か問題が発生した場合、これらのステータスコードのいずれかが自動的に返されます。
-!!! tip "豆知識"
- それぞれのステータスコードとどのコードが何のためのコードなのかについて詳細はMDN HTTP レスポンスステータスコードについてのドキュメントを参照してください。
+/// tip | "豆知識"
+
+それぞれのステータスコードとどのコードが何のためのコードなのかについて詳細はMDN HTTP レスポンスステータスコードについてのドキュメントを参照してください。
+
+///
## 名前を覚えるための近道
先ほどの例をもう一度見てみましょう:
```Python hl_lines="6"
-{!../../../docs_src/response_status_code/tutorial001.py!}
+{!../../docs_src/response_status_code/tutorial001.py!}
```
`201`は「作成完了」のためのステータスコードです。
@@ -72,17 +87,20 @@ HTTPでは、レスポンスの一部として3桁の数字のステータス
`fastapi.status`の便利な変数を利用することができます。
```Python hl_lines="1 6"
-{!../../../docs_src/response_status_code/tutorial002.py!}
+{!../../docs_src/response_status_code/tutorial002.py!}
```
それらは便利です。それらは同じ番号を保持しており、その方法ではエディタの自動補完を使用してそれらを見つけることができます。
-!!! note "技術詳細"
- また、`from starlette import status`を使うこともできます。
+/// note | "技術詳細"
- **FastAPI** は、`開発者の利便性を考慮して、fastapi.status`と同じ`starlette.status`を提供しています。しかし、これはStarletteから直接提供されています。
+また、`from starlette import status`を使うこともできます。
+
+**FastAPI** は、`開発者の利便性を考慮して、fastapi.status`と同じ`starlette.status`を提供しています。しかし、これはStarletteから直接提供されています。
+
+///
## デフォルトの変更
diff --git a/docs/ja/docs/tutorial/schema-extra-example.md b/docs/ja/docs/tutorial/schema-extra-example.md
index d96163b82..baf1bbedd 100644
--- a/docs/ja/docs/tutorial/schema-extra-example.md
+++ b/docs/ja/docs/tutorial/schema-extra-example.md
@@ -11,7 +11,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!}
```
その追加情報はそのまま出力され、JSON Schemaに追加されます。
@@ -21,11 +21,14 @@ 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!}
```
-!!! warning "注意"
- これらの追加引数が渡されても、文書化のためのバリデーションは追加されず、注釈だけが追加されることを覚えておいてください。
+/// warning | "注意"
+
+これらの追加引数が渡されても、文書化のためのバリデーションは追加されず、注釈だけが追加されることを覚えておいてください。
+
+///
## `Body`の追加引数
@@ -34,7 +37,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!}
```
## ドキュメントのUIの例
diff --git a/docs/ja/docs/tutorial/security/first-steps.md b/docs/ja/docs/tutorial/security/first-steps.md
index dc3267e62..51f7bf829 100644
--- a/docs/ja/docs/tutorial/security/first-steps.md
+++ b/docs/ja/docs/tutorial/security/first-steps.md
@@ -21,17 +21,20 @@
`main.py`に、下記の例をコピーします:
```Python
-{!../../../docs_src/security/tutorial001.py!}
+{!../../docs_src/security/tutorial001.py!}
```
## 実行
-!!! info "情報"
- まず`python-multipart`をインストールします。
+/// info | "情報"
- 例えば、`pip install python-multipart`。
+まず`python-multipart`をインストールします。
- これは、**OAuth2**が `ユーザー名` や `パスワード` を送信するために、「フォームデータ」を使うからです。
+例えば、`pip install python-multipart`。
+
+これは、**OAuth2**が `ユーザー名` や `パスワード` を送信するために、「フォームデータ」を使うからです。
+
+///
例を実行します:
@@ -53,17 +56,23 @@ $ uvicorn main:app --reload
-!!! check "Authorizeボタン!"
- すでにピカピカの新しい「Authorize」ボタンがあります。
+/// check | "Authorizeボタン!"
- そして、あなたの*path operation*には、右上にクリックできる小さな鍵アイコンがあります。
+すでにピカピカの新しい「Authorize」ボタンがあります。
+
+そして、あなたの*path operation*には、右上にクリックできる小さな鍵アイコンがあります。
+
+///
それをクリックすると、`ユーザー名`と`パスワード` (およびその他のオプションフィールド) を入力する小さな認証フォームが表示されます:
-!!! note "備考"
- フォームに何を入力しても、まだうまくいきません。ですが、これから動くようになります。
+/// note | "備考"
+
+フォームに何を入力しても、まだうまくいきません。ですが、これから動くようになります。
+
+///
もちろんエンドユーザーのためのフロントエンドではありません。しかし、すべてのAPIをインタラクティブにドキュメント化するための素晴らしい自動ツールです。
@@ -105,36 +114,45 @@ OAuth2は、バックエンドやAPIがユーザーを認証するサーバー
この例では、**Bearer**トークンを使用して**OAuth2**を**パスワード**フローで使用します。これには`OAuth2PasswordBearer`クラスを使用します。
-!!! info "情報"
- 「bearer」トークンが、唯一の選択肢ではありません。
+/// info | "情報"
- しかし、私たちのユースケースには最適です。
+「bearer」トークンが、唯一の選択肢ではありません。
- あなたがOAuth2の専門家で、あなたのニーズに適した別のオプションがある理由を正確に知っている場合を除き、ほとんどのユースケースに最適かもしれません。
+しかし、私たちのユースケースには最適です。
- その場合、**FastAPI**はそれを構築するためのツールも提供します。
+あなたがOAuth2の専門家で、あなたのニーズに適した別のオプションがある理由を正確に知っている場合を除き、ほとんどのユースケースに最適かもしれません。
+
+その場合、**FastAPI**はそれを構築するためのツールも提供します。
+
+///
`OAuth2PasswordBearer` クラスのインスタンスを作成する時に、パラメーター`tokenUrl`を渡します。このパラメーターには、クライアント (ユーザーのブラウザで動作するフロントエンド) がトークンを取得するために`ユーザー名`と`パスワード`を送信するURLを指定します。
```Python hl_lines="6"
-{!../../../docs_src/security/tutorial001.py!}
+{!../../docs_src/security/tutorial001.py!}
```
-!!! tip "豆知識"
- ここで、`tokenUrl="token"`は、まだ作成していない相対URL`token`を指します。相対URLなので、`./token`と同じです。
+/// tip | "豆知識"
- 相対URLを使っているので、APIが`https://example.com/`にある場合、`https://example.com/token`を参照します。しかし、APIが`https://example.com/api/v1/`にある場合は`https://example.com/api/v1/token`を参照することになります。
+ここで、`tokenUrl="token"`は、まだ作成していない相対URL`token`を指します。相対URLなので、`./token`と同じです。
- 相対 URL を使うことは、[プロキシと接続](../../advanced/behind-a-proxy.md){.internal-link target=_blank}のような高度なユースケースでもアプリケーションを動作させ続けるために重要です。
+相対URLを使っているので、APIが`https://example.com/`にある場合、`https://example.com/token`を参照します。しかし、APIが`https://example.com/api/v1/`にある場合は`https://example.com/api/v1/token`を参照することになります。
+
+相対 URL を使うことは、[プロキシと接続](../../advanced/behind-a-proxy.md){.internal-link target=_blank}のような高度なユースケースでもアプリケーションを動作させ続けるために重要です。
+
+///
このパラメーターはエンドポイント/ *path operation*を作成しません。しかし、URL`/token`はクライアントがトークンを取得するために使用するものであると宣言します。この情報は OpenAPI やインタラクティブな API ドキュメントシステムで使われます。
実際のpath operationもすぐに作ります。
-!!! info "情報"
- 非常に厳格な「Pythonista」であれば、パラメーター名のスタイルが`token_url`ではなく`tokenUrl`であることを気に入らないかもしれません。
+/// info | "情報"
- それはOpenAPI仕様と同じ名前を使用しているからです。そのため、これらのセキュリティスキームについてもっと調べる必要がある場合は、それをコピーして貼り付ければ、それについての詳細な情報を見つけることができます。
+非常に厳格な「Pythonista」であれば、パラメーター名のスタイルが`token_url`ではなく`tokenUrl`であることを気に入らないかもしれません。
+
+それはOpenAPI仕様と同じ名前を使用しているからです。そのため、これらのセキュリティスキームについてもっと調べる必要がある場合は、それをコピーして貼り付ければ、それについての詳細な情報を見つけることができます。
+
+///
変数`oauth2_scheme`は`OAuth2PasswordBearer`のインスタンスですが、「呼び出し可能」です。
@@ -151,17 +169,20 @@ oauth2_scheme(some, parameters)
これで`oauth2_scheme`を`Depends`で依存関係に渡すことができます。
```Python hl_lines="10"
-{!../../../docs_src/security/tutorial001.py!}
+{!../../docs_src/security/tutorial001.py!}
```
この依存関係は、*path operation function*のパラメーター`token`に代入される`str`を提供します。
**FastAPI**は、この依存関係を使用してOpenAPIスキーマ (および自動APIドキュメント) で「セキュリティスキーム」を定義できることを知っています。
-!!! info "技術詳細"
- **FastAPI**は、`OAuth2PasswordBearer` クラス (依存関係で宣言されている) を使用してOpenAPIのセキュリティスキームを定義できることを知っています。これは`fastapi.security.oauth2.OAuth2`、`fastapi.security.base.SecurityBase`を継承しているからです。
+/// info | "技術詳細"
- OpenAPIと統合するセキュリティユーティリティ (および自動APIドキュメント) はすべて`SecurityBase`を継承しています。それにより、**FastAPI**はそれらをOpenAPIに統合する方法を知ることができます。
+**FastAPI**は、`OAuth2PasswordBearer` クラス (依存関係で宣言されている) を使用してOpenAPIのセキュリティスキームを定義できることを知っています。これは`fastapi.security.oauth2.OAuth2`、`fastapi.security.base.SecurityBase`を継承しているからです。
+
+OpenAPIと統合するセキュリティユーティリティ (および自動APIドキュメント) はすべて`SecurityBase`を継承しています。それにより、**FastAPI**はそれらをOpenAPIに統合する方法を知ることができます。
+
+///
## どのように動作するか
diff --git a/docs/ja/docs/tutorial/security/get-current-user.md b/docs/ja/docs/tutorial/security/get-current-user.md
index 7f8dcaad2..0edbd983f 100644
--- a/docs/ja/docs/tutorial/security/get-current-user.md
+++ b/docs/ja/docs/tutorial/security/get-current-user.md
@@ -3,7 +3,7 @@
一つ前の章では、(依存性注入システムに基づいた)セキュリティシステムは、 *path operation関数* に `str` として `token` を与えていました:
```Python hl_lines="10"
-{!../../../docs_src/security/tutorial001.py!}
+{!../../docs_src/security/tutorial001.py!}
```
しかし、それはまだそんなに有用ではありません。
@@ -17,7 +17,7 @@
ボディを宣言するのにPydanticを使用するのと同じやり方で、Pydanticを別のどんなところでも使うことができます:
```Python hl_lines="5 12-16"
-{!../../../docs_src/security/tutorial002.py!}
+{!../../docs_src/security/tutorial002.py!}
```
## 依存関係 `get_current_user` を作成
@@ -31,7 +31,7 @@
以前直接 *path operation* の中でしていたのと同じように、新しい依存関係である `get_current_user` は `str` として `token` を受け取るようになります:
```Python hl_lines="25"
-{!../../../docs_src/security/tutorial002.py!}
+{!../../docs_src/security/tutorial002.py!}
```
## ユーザーの取得
@@ -39,7 +39,7 @@
`get_current_user` は作成した(偽物の)ユーティリティ関数を使って、 `str` としてトークンを受け取り、先ほどのPydanticの `User` モデルを返却します:
```Python hl_lines="19-22 26-27"
-{!../../../docs_src/security/tutorial002.py!}
+{!../../docs_src/security/tutorial002.py!}
```
## 現在のユーザーの注入
@@ -47,24 +47,28 @@
ですので、 `get_current_user` に対して同様に *path operation* の中で `Depends` を利用できます。
```Python hl_lines="31"
-{!../../../docs_src/security/tutorial002.py!}
+{!../../docs_src/security/tutorial002.py!}
```
Pydanticモデルの `User` として、 `current_user` の型を宣言することに注意してください。
その関数の中ですべての入力補完や型チェックを行う際に役に立ちます。
-!!! tip "豆知識"
- リクエストボディはPydanticモデルでも宣言できることを覚えているかもしれません。
+/// tip | "豆知識"
- ここでは `Depends` を使っているおかげで、 **FastAPI** が混乱することはありません。
+リクエストボディはPydanticモデルでも宣言できることを覚えているかもしれません。
+ここでは `Depends` を使っているおかげで、 **FastAPI** が混乱することはありません。
-!!! check "確認"
- 依存関係システムがこのように設計されているおかげで、 `User` モデルを返却する別の依存関係(別の"dependables")を持つことができます。
+///
- 同じデータ型を返却する依存関係は一つだけしか持てない、という制約が入ることはないのです。
+/// check | "確認"
+依存関係システムがこのように設計されているおかげで、 `User` モデルを返却する別の依存関係(別の"dependables")を持つことができます。
+
+同じデータ型を返却する依存関係は一つだけしか持てない、という制約が入ることはないのです。
+
+///
## 別のモデル
@@ -100,7 +104,7 @@ Pydanticモデルの `User` として、 `current_user` の型を宣言するこ
さらに、こうした何千もの *path operations* は、たった3行で表現できるのです:
```Python hl_lines="30-32"
-{!../../../docs_src/security/tutorial002.py!}
+{!../../docs_src/security/tutorial002.py!}
```
## まとめ
diff --git a/docs/ja/docs/tutorial/security/index.md b/docs/ja/docs/tutorial/security/index.md
index 390f21047..c68e7e7f2 100644
--- a/docs/ja/docs/tutorial/security/index.md
+++ b/docs/ja/docs/tutorial/security/index.md
@@ -32,9 +32,11 @@ OAuth 1というものもありましたが、これはOAuth2とは全く異な
OAuth2は、通信を暗号化する方法を指定せず、アプリケーションがHTTPSで提供されることを想定しています。
-!!! tip "豆知識"
- **デプロイ**のセクションでは、TraefikとLet's Encryptを使用して、無料でHTTPSを設定する方法が紹介されています。
+/// tip | "豆知識"
+**デプロイ**のセクションでは、TraefikとLet's Encryptを使用して、無料でHTTPSを設定する方法が紹介されています。
+
+///
## OpenID Connect
@@ -87,10 +89,13 @@ OpenAPIでは、以下のセキュリティスキームを定義しています:
* この自動検出メカニズムは、OpenID Connectの仕様で定義されているものです。
-!!! tip "豆知識"
- Google、Facebook、Twitter、GitHubなど、他の認証/認可プロバイダを統合することも可能で、比較的簡単です。
+/// tip | "豆知識"
- 最も複雑な問題は、それらのような認証/認可プロバイダを構築することですが、**FastAPI**は、あなたのために重い仕事をこなしながら、それを簡単に行うためのツールを提供します。
+Google、Facebook、Twitter、GitHubなど、他の認証/認可プロバイダを統合することも可能で、比較的簡単です。
+
+最も複雑な問題は、それらのような認証/認可プロバイダを構築することですが、**FastAPI**は、あなたのために重い仕事をこなしながら、それを簡単に行うためのツールを提供します。
+
+///
## **FastAPI** ユーティリティ
diff --git a/docs/ja/docs/tutorial/security/oauth2-jwt.md b/docs/ja/docs/tutorial/security/oauth2-jwt.md
index d5b179aa0..b2f511610 100644
--- a/docs/ja/docs/tutorial/security/oauth2-jwt.md
+++ b/docs/ja/docs/tutorial/security/oauth2-jwt.md
@@ -44,10 +44,13 @@ $ pip install python-jose[cryptography]
ここでは、推奨されているものを使用します:pyca/cryptography。
-!!! tip "豆知識"
- このチュートリアルでは以前、PyJWTを使用していました。
+/// tip | "豆知識"
- しかし、Python-joseは、PyJWTのすべての機能に加えて、後に他のツールと統合して構築する際におそらく必要となる可能性のあるいくつかの追加機能を提供しています。そのため、代わりにPython-joseを使用するように更新されました。
+このチュートリアルでは以前、PyJWTを使用していました。
+
+しかし、Python-joseは、PyJWTのすべての機能に加えて、後に他のツールと統合して構築する際におそらく必要となる可能性のあるいくつかの追加機能を提供しています。そのため、代わりにPython-joseを使用するように更新されました。
+
+///
## パスワードのハッシュ化
@@ -83,13 +86,15 @@ $ pip install passlib[bcrypt]
-!!! tip "豆知識"
- `passlib`を使用すると、**Django**や**Flask**のセキュリティプラグインなどで作成されたパスワードを読み取れるように設定できます。
+/// tip | "豆知識"
- 例えば、Djangoアプリケーションからデータベース内の同じデータをFastAPIアプリケーションと共有できるだけではなく、同じデータベースを使用してDjangoアプリケーションを徐々に移行することもできます。
+`passlib`を使用すると、**Django**や**Flask**のセキュリティプラグインなどで作成されたパスワードを読み取れるように設定できます。
- また、ユーザーはDjangoアプリまたは**FastAPI**アプリからも、同時にログインできるようになります。
+例えば、Djangoアプリケーションからデータベース内の同じデータをFastAPIアプリケーションと共有できるだけではなく、同じデータベースを使用してDjangoアプリケーションを徐々に移行することもできます。
+また、ユーザーはDjangoアプリまたは**FastAPI**アプリからも、同時にログインできるようになります。
+
+///
## パスワードのハッシュ化と検証
@@ -97,12 +102,15 @@ $ pip install passlib[bcrypt]
PassLib の「context」を作成します。これは、パスワードのハッシュ化と検証に使用されるものです。
-!!! tip "豆知識"
- PassLibのcontextには、検証だけが許された非推奨の古いハッシュアルゴリズムを含む、様々なハッシュアルゴリズムを使用した検証機能もあります。
+/// tip | "豆知識"
- 例えば、この機能を使用して、別のシステム(Djangoなど)によって生成されたパスワードを読み取って検証し、Bcryptなどの別のアルゴリズムを使用して新しいパスワードをハッシュするといったことができます。
+PassLibのcontextには、検証だけが許された非推奨の古いハッシュアルゴリズムを含む、様々なハッシュアルゴリズムを使用した検証機能もあります。
- そして、同時にそれらはすべてに互換性があります。
+例えば、この機能を使用して、別のシステム(Djangoなど)によって生成されたパスワードを読み取って検証し、Bcryptなどの別のアルゴリズムを使用して新しいパスワードをハッシュするといったことができます。
+
+そして、同時にそれらはすべてに互換性があります。
+
+///
ユーザーから送られてきたパスワードをハッシュ化するユーティリティー関数を作成します。
@@ -111,11 +119,14 @@ PassLib の「context」を作成します。これは、パスワードのハ
さらに、ユーザーを認証して返す関数も作成します。
```Python hl_lines="7 48 55-56 59-60 69-75"
-{!../../../docs_src/security/tutorial004.py!}
+{!../../docs_src/security/tutorial004.py!}
```
-!!! note "備考"
- 新しい(偽の)データベース`fake_users_db`を確認すると、ハッシュ化されたパスワードが次のようになっていることがわかります:`"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`
+/// note | "備考"
+
+新しい(偽の)データベース`fake_users_db`を確認すると、ハッシュ化されたパスワードが次のようになっていることがわかります:`"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`
+
+///
## JWTトークンの取り扱い
@@ -146,7 +157,7 @@ JWTトークンの署名に使用するアルゴリズム`"HS256"`を指定し
新しいアクセストークンを生成するユーティリティ関数を作成します。
```Python hl_lines="6 12-14 28-30 78-86"
-{!../../../docs_src/security/tutorial004.py!}
+{!../../docs_src/security/tutorial004.py!}
```
## 依存関係の更新
@@ -158,7 +169,7 @@ JWTトークンの署名に使用するアルゴリズム`"HS256"`を指定し
トークンが無効な場合は、すぐにHTTPエラーを返します。
```Python hl_lines="89-106"
-{!../../../docs_src/security/tutorial004.py!}
+{!../../docs_src/security/tutorial004.py!}
```
## `/token` パスオペレーションの更新
@@ -168,7 +179,7 @@ JWTトークンの署名に使用するアルゴリズム`"HS256"`を指定し
JWTアクセストークンを作成し、それを返します。
```Python hl_lines="115-130"
-{!../../../docs_src/security/tutorial004.py!}
+{!../../docs_src/security/tutorial004.py!}
```
### JWTの"subject" `sub` についての技術的な詳細
@@ -208,8 +219,11 @@ IDの衝突を回避するために、ユーザーのJWTトークンを作成す
Username: `johndoe`
Password: `secret`
-!!! check "確認"
- コードのどこにも平文のパスワード"`secret`"はなく、ハッシュ化されたものしかないことを確認してください。
+/// check | "確認"
+
+コードのどこにも平文のパスワード"`secret`"はなく、ハッシュ化されたものしかないことを確認してください。
+
+///
@@ -230,8 +244,11 @@ Password: `secret`
-!!! note "備考"
- ヘッダーの`Authorization`には、`Bearer`で始まる値があります。
+/// note | "備考"
+
+ヘッダーの`Authorization`には、`Bearer`で始まる値があります。
+
+///
## `scopes` を使った高度なユースケース
diff --git a/docs/ja/docs/tutorial/static-files.md b/docs/ja/docs/tutorial/static-files.md
index 1d9c434c3..e6002a1fb 100644
--- a/docs/ja/docs/tutorial/static-files.md
+++ b/docs/ja/docs/tutorial/static-files.md
@@ -8,13 +8,16 @@
* `StaticFiles()` インスタンスを生成し、特定のパスに「マウント」。
```Python hl_lines="2 6"
-{!../../../docs_src/static_files/tutorial001.py!}
+{!../../docs_src/static_files/tutorial001.py!}
```
-!!! note "技術詳細"
- `from starlette.staticfiles import StaticFiles` も使用できます。
+/// note | "技術詳細"
- **FastAPI**は、開発者の利便性のために、`starlette.staticfiles` と同じ `fastapi.staticfiles` を提供します。しかし、実際にはStarletteから直接渡されています。
+`from starlette.staticfiles import StaticFiles` も使用できます。
+
+**FastAPI**は、開発者の利便性のために、`starlette.staticfiles` と同じ `fastapi.staticfiles` を提供します。しかし、実際にはStarletteから直接渡されています。
+
+///
### 「マウント」とは
diff --git a/docs/ja/docs/tutorial/testing.md b/docs/ja/docs/tutorial/testing.md
index 037e9628f..6c5e712e8 100644
--- a/docs/ja/docs/tutorial/testing.md
+++ b/docs/ja/docs/tutorial/testing.md
@@ -19,23 +19,32 @@
チェックしたい Python の標準的な式と共に、シンプルに `assert` 文を記述します。
```Python hl_lines="2 12 15-18"
-{!../../../docs_src/app_testing/tutorial001.py!}
+{!../../docs_src/app_testing/tutorial001.py!}
```
-!!! tip "豆知識"
- テスト関数は `async def` ではなく、通常の `def` であることに注意してください。
+/// tip | "豆知識"
- また、クライアントへの呼び出しも通常の呼び出しであり、`await` を使用しません。
+テスト関数は `async def` ではなく、通常の `def` であることに注意してください。
- これにより、煩雑にならずに、`pytest` を直接使用できます。
+また、クライアントへの呼び出しも通常の呼び出しであり、`await` を使用しません。
-!!! note "技術詳細"
- `from starlette.testclient import TestClient` も使用できます。
+これにより、煩雑にならずに、`pytest` を直接使用できます。
- **FastAPI** は開発者の利便性のために `fastapi.testclient` と同じ `starlette.testclient` を提供します。しかし、実際にはStarletteから直接渡されています。
+///
-!!! tip "豆知識"
- FastAPIアプリケーションへのリクエストの送信とは別に、テストで `async` 関数 (非同期データベース関数など) を呼び出したい場合は、高度なチュートリアルの[Async Tests](../advanced/async-tests.md){.internal-link target=_blank} を参照してください。
+/// note | "技術詳細"
+
+`from starlette.testclient import TestClient` も使用できます。
+
+**FastAPI** は開発者の利便性のために `fastapi.testclient` と同じ `starlette.testclient` を提供します。しかし、実際にはStarletteから直接渡されています。
+
+///
+
+/// tip | "豆知識"
+
+FastAPIアプリケーションへのリクエストの送信とは別に、テストで `async` 関数 (非同期データベース関数など) を呼び出したい場合は、高度なチュートリアルの[Async Tests](../advanced/async-tests.md){.internal-link target=_blank} を参照してください。
+
+///
## テストの分離
@@ -48,7 +57,7 @@
**FastAPI** アプリに `main.py` ファイルがあるとします:
```Python
-{!../../../docs_src/app_testing/main.py!}
+{!../../docs_src/app_testing/main.py!}
```
### テストファイル
@@ -56,7 +65,7 @@
次に、テストを含む `test_main.py` ファイルを作成し、`main` モジュール (`main.py`) から `app` をインポートします:
```Python
-{!../../../docs_src/app_testing/test_main.py!}
+{!../../docs_src/app_testing/test_main.py!}
```
## テスト: 例の拡張
@@ -74,24 +83,28 @@
これらの *path operation* には `X-Token` ヘッダーが必要です。
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python
- {!> ../../../docs_src/app_testing/app_b_py310/main.py!}
- ```
+```Python
+{!> ../../docs_src/app_testing/app_b_py310/main.py!}
+```
-=== "Python 3.6+"
+////
- ```Python
- {!> ../../../docs_src/app_testing/app_b/main.py!}
- ```
+//// tab | Python 3.6+
+
+```Python
+{!> ../../docs_src/app_testing/app_b/main.py!}
+```
+
+////
### 拡張版テストファイル
次に、先程のものに拡張版のテストを加えた、`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) できます。
@@ -108,10 +121,13 @@
(`httpx` または `TestClient` を使用して) バックエンドにデータを渡す方法の詳細は、HTTPXのドキュメントを確認してください。
-!!! info "情報"
- `TestClient` は、Pydanticモデルではなく、JSONに変換できるデータを受け取ることに注意してください。
+/// info | "情報"
- テストにPydanticモデルがあり、テスト中にそのデータをアプリケーションに送信したい場合は、[JSON互換エンコーダ](encoder.md){.internal-link target=_blank} で説明されている `jsonable_encoder` が利用できます。
+`TestClient` は、Pydanticモデルではなく、JSONに変換できるデータを受け取ることに注意してください。
+
+テストにPydanticモデルがあり、テスト中にそのデータをアプリケーションに送信したい場合は、[JSON互換エンコーダ](encoder.md){.internal-link target=_blank} で説明されている `jsonable_encoder` が利用できます。
+
+///
## 実行
diff --git a/docs/ko/docs/advanced/events.md b/docs/ko/docs/advanced/events.md
index d3227497b..94867c198 100644
--- a/docs/ko/docs/advanced/events.md
+++ b/docs/ko/docs/advanced/events.md
@@ -4,15 +4,18 @@
이 함수들은 `async def` 또는 평범하게 `def`으로 선언할 수 있습니다.
-!!! warning "경고"
- 이벤트 핸들러는 주 응용 프로그램에서만 작동합니다. [하위 응용 프로그램 - 마운트](./sub-applications.md){.internal-link target=_blank}에서는 작동하지 않습니다.
+/// warning | "경고"
+
+이벤트 핸들러는 주 응용 프로그램에서만 작동합니다. [하위 응용 프로그램 - 마운트](./sub-applications.md){.internal-link target=_blank}에서는 작동하지 않습니다.
+
+///
## `startup` 이벤트
응용 프로그램을 시작하기 전에 실행하려는 함수를 "startup" 이벤트로 선언합니다:
```Python hl_lines="8"
-{!../../../docs_src/events/tutorial001.py!}
+{!../../docs_src/events/tutorial001.py!}
```
이 경우 `startup` 이벤트 핸들러 함수는 단순히 몇 가지 값으로 구성된 `dict` 형식의 "데이터베이스"를 초기화합니다.
@@ -26,20 +29,29 @@
응용 프로그램이 종료될 때 실행하려는 함수를 추가하려면 `"shutdown"` 이벤트로 선언합니다:
```Python hl_lines="6"
-{!../../../docs_src/events/tutorial002.py!}
+{!../../docs_src/events/tutorial002.py!}
```
이 예제에서 `shutdown` 이벤트 핸들러 함수는 `"Application shutdown"`이라는 텍스트가 적힌 `log.txt` 파일을 추가할 것입니다.
-!!! info "정보"
- `open()` 함수에서 `mode="a"`는 "추가"를 의미합니다. 따라서 이미 존재하는 파일의 내용을 덮어쓰지 않고 새로운 줄을 추가합니다.
+/// info | "정보"
-!!! tip "팁"
- 이 예제에서는 파일과 상호작용 하기 위해 파이썬 표준 함수인 `open()`을 사용하고 있습니다.
+`open()` 함수에서 `mode="a"`는 "추가"를 의미합니다. 따라서 이미 존재하는 파일의 내용을 덮어쓰지 않고 새로운 줄을 추가합니다.
- 따라서 디스크에 데이터를 쓰기 위해 "대기"가 필요한 I/O (입력/출력) 작업을 수행합니다.
+///
- 그러나 `open()`은 `async`와 `await`을 사용하지 않기 때문에 이벤트 핸들러 함수는 `async def`가 아닌 표준 `def`로 선언하고 있습니다.
+/// tip | "팁"
-!!! info "정보"
- 이벤트 핸들러에 관한 내용은 Starlette 이벤트 문서에서 추가로 확인할 수 있습니다.
+이 예제에서는 파일과 상호작용 하기 위해 파이썬 표준 함수인 `open()`을 사용하고 있습니다.
+
+따라서 디스크에 데이터를 쓰기 위해 "대기"가 필요한 I/O (입력/출력) 작업을 수행합니다.
+
+그러나 `open()`은 `async`와 `await`을 사용하지 않기 때문에 이벤트 핸들러 함수는 `async def`가 아닌 표준 `def`로 선언하고 있습니다.
+
+///
+
+/// info | "정보"
+
+이벤트 핸들러에 관한 내용은 Starlette 이벤트 문서에서 추가로 확인할 수 있습니다.
+
+///
diff --git a/docs/ko/docs/advanced/index.md b/docs/ko/docs/advanced/index.md
index 5fd1711a1..cb628fa10 100644
--- a/docs/ko/docs/advanced/index.md
+++ b/docs/ko/docs/advanced/index.md
@@ -6,10 +6,13 @@
이어지는 장에서는 여러분이 다른 옵션, 구성 및 추가 기능을 보실 수 있습니다.
-!!! tip "팁"
- 다음 장들이 **반드시 "심화"**인 것은 아닙니다.
+/// tip | "팁"
- 그리고 여러분의 사용 사례에 대한 해결책이 그중 하나에 있을 수 있습니다.
+다음 장들이 **반드시 "심화"**인 것은 아닙니다.
+
+그리고 여러분의 사용 사례에 대한 해결책이 그중 하나에 있을 수 있습니다.
+
+///
## 자습서를 먼저 읽으십시오
diff --git a/docs/ko/docs/async.md b/docs/ko/docs/async.md
index 65ee124ec..dfc2caa78 100644
--- a/docs/ko/docs/async.md
+++ b/docs/ko/docs/async.md
@@ -21,8 +21,11 @@ async def read_results():
return results
```
-!!! note "참고"
- `async def`로 생성된 함수 내부에서만 `await`를 사용할 수 있습니다.
+/// note | "참고"
+
+`async def`로 생성된 함수 내부에서만 `await`를 사용할 수 있습니다.
+
+///
---
@@ -366,12 +369,15 @@ FastAPI를 사용하지 않더라도, 높은 호환성 및
email_validator - 이메일 유효성 검사.
+* email-validator - 이메일 유효성 검사.
Starlette이 사용하는:
diff --git a/docs/ko/docs/project-generation.md b/docs/ko/docs/project-generation.md
new file mode 100644
index 000000000..dd11fca70
--- /dev/null
+++ b/docs/ko/docs/project-generation.md
@@ -0,0 +1,28 @@
+# Full Stack FastAPI 템플릿
+
+템플릿은 일반적으로 특정 설정과 함께 제공되지만, 유연하고 커스터마이징이 가능하게 디자인 되었습니다. 이 특성들은 여러분이 프로젝트의 요구사항에 맞춰 수정, 적용을 할 수 있게 해주고, 템플릿이 완벽한 시작점이 되게 해줍니다. 🏁
+
+많은 초기 설정, 보안, 데이터베이스 및 일부 API 엔드포인트가 이미 준비되어 있으므로, 여러분은 이 템플릿을 (프로젝트를) 시작하는 데 사용할 수 있습니다.
+
+GitHub 저장소: Full Stack FastAPI 템플릿
+
+## Full Stack FastAPI 템플릿 - 기술 스택과 기능들
+
+- ⚡ [**FastAPI**](https://fastapi.tiangolo.com): Python 백엔드 API.
+ - 🧰 [SQLModel](https://sqlmodel.tiangolo.com): Python SQL 데이터 상호작용을 위한 (ORM).
+ - 🔍 [Pydantic](https://docs.pydantic.dev): FastAPI에 의해 사용되는, 데이터 검증과 설정관리.
+ - 💾 [PostgreSQL](https://www.postgresql.org): SQL 데이터베이스.
+- 🚀 [React](https://react.dev): 프론트엔드.
+ - 💃 TypeScript, hooks, [Vite](https://vitejs.dev) 및 기타 현대적인 프론트엔드 스택을 사용.
+ - 🎨 [Chakra UI](https://chakra-ui.com): 프론트엔드 컴포넌트.
+ - 🤖 자동으로 생성된 프론트엔드 클라이언트.
+ - 🧪 E2E 테스트를 위한 [Playwright](https://playwright.dev).
+ - 🦇 다크 모드 지원.
+- 🐋 [Docker Compose](https://www.docker.com): 개발 환경과 프로덕션(운영).
+- 🔒 기본으로 지원되는 안전한 비밀번호 해싱.
+- 🔑 JWT 토큰 인증.
+- 📫 이메일 기반 비밀번호 복구.
+- ✅ [Pytest]를 이용한 테스트(https://pytest.org).
+- 📞 [Traefik](https://traefik.io): 리버스 프록시 / 로드 밸런서.
+- 🚢 Docker Compose를 이용한 배포 지침: 자동 HTTPS 인증서를 처리하기 위한 프론트엔드 Traefik 프록시 설정 방법을 포함.
+- 🏭 GitHub Actions를 기반으로 CI (지속적인 통합) 및 CD (지속적인 배포).
diff --git a/docs/ko/docs/python-types.md b/docs/ko/docs/python-types.md
index 267ce6c7e..6d7346189 100644
--- a/docs/ko/docs/python-types.md
+++ b/docs/ko/docs/python-types.md
@@ -12,15 +12,18 @@
비록 **FastAPI**를 쓰지 않는다고 하더라도, 조금이라도 알아두면 도움이 될 것입니다.
-!!! note "참고"
- 파이썬에 능숙하셔서 타입 힌트에 대해 모두 아신다면, 다음 챕터로 건너뛰세요.
+/// note | "참고"
+
+파이썬에 능숙하셔서 타입 힌트에 대해 모두 아신다면, 다음 챕터로 건너뛰세요.
+
+///
## 동기 부여
간단한 예제부터 시작해봅시다:
```Python
-{!../../../docs_src/python_types/tutorial001.py!}
+{!../../docs_src/python_types/tutorial001.py!}
```
이 프로그램을 실행한 결과값:
@@ -36,7 +39,7 @@ John Doe
* 두 단어를 중간에 공백을 두고 연결합니다.
```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial001.py!}
+{!../../docs_src/python_types/tutorial001.py!}
```
### 코드 수정
@@ -80,7 +83,7 @@ John Doe
이게 "타입 힌트"입니다:
```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial002.py!}
+{!../../docs_src/python_types/tutorial002.py!}
```
타입힌트는 다음과 같이 기본 값을 선언하는 것과는 다릅니다:
@@ -110,7 +113,7 @@ John Doe
아래 함수를 보면, 이미 타입 힌트가 적용되어 있는 걸 볼 수 있습니다:
```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial003.py!}
+{!../../docs_src/python_types/tutorial003.py!}
```
편집기가 변수의 타입을 알고 있기 때문에, 자동완성 뿐 아니라 에러도 확인할 수 있습니다:
@@ -120,7 +123,7 @@ John Doe
이제 고쳐야하는 걸 알기 때문에, `age`를 `str(age)`과 같이 문자열로 바꾸게 됩니다:
```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial004.py!}
+{!../../docs_src/python_types/tutorial004.py!}
```
## 타입 선언
@@ -141,7 +144,7 @@ John Doe
* `bytes`
```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial005.py!}
+{!../../docs_src/python_types/tutorial005.py!}
```
### 타입 매개변수를 활용한 Generic(제네릭) 타입
@@ -159,7 +162,7 @@ John Doe
`typing`에서 `List`(대문자 `L`)를 import 합니다.
```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial006.py!}
+{!../../docs_src/python_types/tutorial006.py!}
```
콜론(`:`) 문법을 이용하여 변수를 선언합니다.
@@ -169,13 +172,16 @@ John Doe
이때 배열은 내부 타입을 포함하는 타입이기 때문에 대괄호 안에 넣어줍니다.
```Python hl_lines="4"
-{!../../../docs_src/python_types/tutorial006.py!}
+{!../../docs_src/python_types/tutorial006.py!}
```
-!!! tip "팁"
- 대괄호 안의 내부 타입은 "타입 매개변수(type paramters)"라고 합니다.
+/// tip | "팁"
- 이번 예제에서는 `str`이 `List`에 들어간 타입 매개변수 입니다.
+대괄호 안의 내부 타입은 "타입 매개변수(type paramters)"라고 합니다.
+
+이번 예제에서는 `str`이 `List`에 들어간 타입 매개변수 입니다.
+
+///
이는 "`items`은 `list`인데, 배열에 들어있는 아이템 각각은 `str`이다"라는 뜻입니다.
@@ -194,7 +200,7 @@ John Doe
`tuple`과 `set`도 동일하게 선언할 수 있습니다.
```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial007.py!}
+{!../../docs_src/python_types/tutorial007.py!}
```
이 뜻은 아래와 같습니다:
@@ -211,7 +217,7 @@ John Doe
두 번째 매개변수는 `dict`의 값(value)입니다.
```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial008.py!}
+{!../../docs_src/python_types/tutorial008.py!}
```
이 뜻은 아래와 같습니다:
@@ -225,7 +231,7 @@ John Doe
`str`과 같이 타입을 선언할 때 `Optional`을 쓸 수도 있는데, "선택적(Optional)"이기때문에 `None`도 될 수 있습니다:
```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009.py!}
+{!../../docs_src/python_types/tutorial009.py!}
```
`Optional[str]`을 `str` 대신 쓰게 되면, 특정 값이 실제로는 `None`이 될 수도 있는데 항상 `str`이라고 가정하는 상황에서 에디터가 에러를 찾게 도와줄 수 있습니다.
@@ -250,13 +256,13 @@ John Doe
이름(name)을 가진 `Person` 클래스가 있다고 해봅시다.
```Python hl_lines="1-3"
-{!../../../docs_src/python_types/tutorial010.py!}
+{!../../docs_src/python_types/tutorial010.py!}
```
그렇게 하면 변수를 `Person`이라고 선언할 수 있게 됩니다.
```Python hl_lines="6"
-{!../../../docs_src/python_types/tutorial010.py!}
+{!../../docs_src/python_types/tutorial010.py!}
```
그리고 역시나 모든 에디터 도움을 받게 되겠죠.
@@ -278,12 +284,14 @@ John Doe
Pydantic 공식 문서 예시:
```Python
-{!../../../docs_src/python_types/tutorial011.py!}
+{!../../docs_src/python_types/tutorial011.py!}
```
-!!! info "정보"
- Pydantic<에 대해 더 배우고 싶다면 공식 문서를 참고하세요.
+/// info | "정보"
+Pydantic<에 대해 더 배우고 싶다면 공식 문서를 참고하세요.
+
+///
**FastAPI**는 모두 Pydantic을 기반으로 되어 있습니다.
@@ -311,5 +319,8 @@ Pydantic 공식 문서 예시:
가장 중요한 건, 표준 파이썬 타입을 한 곳에서(클래스를 더하거나, 데코레이터 사용하는 대신) 사용함으로써 **FastAPI**가 당신을 위해 많은 일을 해준다는 사실이죠.
-!!! info "정보"
- 만약 모든 자습서를 다 보았음에도 타입에 대해서 더 보고자 방문한 경우에는 `mypy`에서 제공하는 "cheat sheet"이 좋은 자료가 될 겁니다.
+/// info | "정보"
+
+만약 모든 자습서를 다 보았음에도 타입에 대해서 더 보고자 방문한 경우에는 `mypy`에서 제공하는 "cheat sheet"이 좋은 자료가 될 겁니다.
+
+///
diff --git a/docs/ko/docs/tutorial/background-tasks.md b/docs/ko/docs/tutorial/background-tasks.md
index ee83d6570..376c52524 100644
--- a/docs/ko/docs/tutorial/background-tasks.md
+++ b/docs/ko/docs/tutorial/background-tasks.md
@@ -16,7 +16,7 @@ FastAPI에서는 응답을 반환한 후에 실행할 백그라운드 작업을
먼저 아래와 같이 `BackgroundTasks`를 임포트하고, `BackgroundTasks`를 _경로 작동 함수_ 에서 매개변수로 가져오고 정의합니다.
```Python hl_lines="1 13"
-{!../../../docs_src/background_tasks/tutorial001.py!}
+{!../../docs_src/background_tasks/tutorial001.py!}
```
**FastAPI** 는 `BackgroundTasks` 개체를 생성하고, 매개 변수로 전달합니다.
@@ -34,7 +34,7 @@ FastAPI에서는 응답을 반환한 후에 실행할 백그라운드 작업을
그리고 이 작업은 `async`와 `await`를 사용하지 않으므로 일반 `def` 함수로 선언합니다.
```Python hl_lines="6-9"
-{!../../../docs_src/background_tasks/tutorial001.py!}
+{!../../docs_src/background_tasks/tutorial001.py!}
```
## 백그라운드 작업 추가
@@ -42,7 +42,7 @@ FastAPI에서는 응답을 반환한 후에 실행할 백그라운드 작업을
_경로 작동 함수_ 내에서 작업 함수를 `.add_task()` 함수 통해 _백그라운드 작업_ 개체에 전달합니다.
```Python hl_lines="14"
-{!../../../docs_src/background_tasks/tutorial001.py!}
+{!../../docs_src/background_tasks/tutorial001.py!}
```
`.add_task()` 함수는 다음과 같은 인자를 받습니다 :
@@ -57,17 +57,21 @@ _경로 작동 함수_ 내에서 작업 함수를 `.add_task()` 함수 통해 _
**FastAPI**는 각 경우에 수행할 작업과 동일한 개체를 내부적으로 재사용하기에, 모든 백그라운드 작업이 함께 병합되고 나중에 백그라운드에서 실행됩니다.
-=== "Python 3.6 and above"
+//// tab | Python 3.6 and above
- ```Python hl_lines="13 15 22 25"
- {!> ../../../docs_src/background_tasks/tutorial002.py!}
- ```
+```Python hl_lines="13 15 22 25"
+{!> ../../docs_src/background_tasks/tutorial002.py!}
+```
-=== "Python 3.10 and above"
+////
- ```Python hl_lines="11 13 20 23"
- {!> ../../../docs_src/background_tasks/tutorial002_py310.py!}
- ```
+//// tab | Python 3.10 and above
+
+```Python hl_lines="11 13 20 23"
+{!> ../../docs_src/background_tasks/tutorial002_py310.py!}
+```
+
+////
이 예제에서는 응답이 반환된 후에 `log.txt` 파일에 메시지가 기록됩니다.
diff --git a/docs/ko/docs/tutorial/body-fields.md b/docs/ko/docs/tutorial/body-fields.md
index c91d6130b..a13159c27 100644
--- a/docs/ko/docs/tutorial/body-fields.md
+++ b/docs/ko/docs/tutorial/body-fields.md
@@ -6,98 +6,139 @@
먼저 이를 임포트해야 합니다:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="4"
+{!> ../../docs_src/body_fields/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="4"
+{!> ../../docs_src/body_fields/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ Annotated가 없는 경우"
+//// tab | Python 3.8+
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+```Python hl_lines="4"
+{!> ../../docs_src/body_fields/tutorial001_an.py!}
+```
- ```Python hl_lines="2"
- {!> ../../../docs_src/body_fields/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ Annotated가 없는 경우"
+//// tab | Python 3.10+ Annotated가 없는 경우
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+/// tip | "팁"
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001.py!}
- ```
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
-!!! warning "경고"
- `Field`는 다른 것들처럼 (`Query`, `Path`, `Body` 등) `fastapi`에서가 아닌 `pydantic`에서 바로 임포트 되는 점에 주의하세요.
+///
+
+```Python hl_lines="2"
+{!> ../../docs_src/body_fields/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ Annotated가 없는 경우
+
+/// tip | "팁"
+
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
+
+///
+
+```Python hl_lines="4"
+{!> ../../docs_src/body_fields/tutorial001.py!}
+```
+
+////
+
+/// warning | "경고"
+
+`Field`는 다른 것들처럼 (`Query`, `Path`, `Body` 등) `fastapi`에서가 아닌 `pydantic`에서 바로 임포트 되는 점에 주의하세요.
+
+///
## 모델 어트리뷰트 선언
그 다음 모델 어트리뷰트와 함께 `Field`를 사용할 수 있습니다:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="11-14"
+{!> ../../docs_src/body_fields/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="11-14"
+{!> ../../docs_src/body_fields/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="12-15"
- {!> ../../../docs_src/body_fields/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ Annotated가 없는 경우"
+//// tab | Python 3.8+
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+```Python hl_lines="12-15"
+{!> ../../docs_src/body_fields/tutorial001_an.py!}
+```
- ```Python hl_lines="9-12"
- {!> ../../../docs_src/body_fields/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ Annotated가 없는 경우"
+//// tab | Python 3.10+ Annotated가 없는 경우
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+/// tip | "팁"
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001.py!}
- ```
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
+
+///
+
+```Python hl_lines="9-12"
+{!> ../../docs_src/body_fields/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ Annotated가 없는 경우
+
+/// tip | "팁"
+
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
+
+///
+
+```Python hl_lines="11-14"
+{!> ../../docs_src/body_fields/tutorial001.py!}
+```
+
+////
`Field`는 `Query`, `Path`와 `Body`와 같은 방식으로 동작하며, 모두 같은 매개변수들 등을 가집니다.
-!!! note "기술적 세부사항"
- 실제로 `Query`, `Path`등, 여러분이 앞으로 볼 다른 것들은 공통 클래스인 `Param` 클래스의 서브클래스 객체를 만드는데, 그 자체로 Pydantic의 `FieldInfo` 클래스의 서브클래스입니다.
+/// note | "기술적 세부사항"
- 그리고 Pydantic의 `Field` 또한 `FieldInfo`의 인스턴스를 반환합니다.
+실제로 `Query`, `Path`등, 여러분이 앞으로 볼 다른 것들은 공통 클래스인 `Param` 클래스의 서브클래스 객체를 만드는데, 그 자체로 Pydantic의 `FieldInfo` 클래스의 서브클래스입니다.
- `Body` 또한 `FieldInfo`의 서브클래스 객체를 직접적으로 반환합니다. 그리고 `Body` 클래스의 서브클래스인 것들도 여러분이 나중에 보게될 것입니다.
+그리고 Pydantic의 `Field` 또한 `FieldInfo`의 인스턴스를 반환합니다.
- `Query`, `Path`와 그 외 것들을 `fastapi`에서 임포트할 때, 이는 실제로 특별한 클래스를 반환하는 함수인 것을 기억해 주세요.
+`Body` 또한 `FieldInfo`의 서브클래스 객체를 직접적으로 반환합니다. 그리고 `Body` 클래스의 서브클래스인 것들도 여러분이 나중에 보게될 것입니다.
-!!! tip "팁"
- 주목할 점은 타입, 기본 값 및 `Field`로 이루어진 각 모델 어트리뷰트가 `Path`, `Query`와 `Body`대신 `Field`를 사용하는 *경로 작동 함수*의 매개변수와 같은 구조를 가진다는 점 입니다.
+ `Query`, `Path`와 그 외 것들을 `fastapi`에서 임포트할 때, 이는 실제로 특별한 클래스를 반환하는 함수인 것을 기억해 주세요.
+
+///
+
+/// tip | "팁"
+
+주목할 점은 타입, 기본 값 및 `Field`로 이루어진 각 모델 어트리뷰트가 `Path`, `Query`와 `Body`대신 `Field`를 사용하는 *경로 작동 함수*의 매개변수와 같은 구조를 가진다는 점 입니다.
+
+///
## 별도 정보 추가
@@ -105,9 +146,12 @@
여러분이 예제를 선언할 때 나중에 이 공식 문서에서 별도 정보를 추가하는 방법을 배울 것입니다.
-!!! warning "경고"
- 별도 키가 전달된 `Field` 또한 여러분의 어플리케이션의 OpenAPI 스키마에 나타날 것입니다.
- 이런 키가 OpenAPI 명세서, [the OpenAPI validator](https://validator.swagger.io/)같은 몇몇 OpenAPI 도구들에 포함되지 못할 수 있으며, 여러분이 생성한 스키마와 호환되지 않을 수 있습니다.
+/// warning | "경고"
+
+별도 키가 전달된 `Field` 또한 여러분의 어플리케이션의 OpenAPI 스키마에 나타날 것입니다.
+이런 키가 OpenAPI 명세서, [the OpenAPI validator](https://validator.swagger.io/)같은 몇몇 OpenAPI 도구들에 포함되지 못할 수 있으며, 여러분이 생성한 스키마와 호환되지 않을 수 있습니다.
+
+///
## 요약
diff --git a/docs/ko/docs/tutorial/body-multiple-params.md b/docs/ko/docs/tutorial/body-multiple-params.md
index 2cf5df7f3..0a0f34585 100644
--- a/docs/ko/docs/tutorial/body-multiple-params.md
+++ b/docs/ko/docs/tutorial/body-multiple-params.md
@@ -11,11 +11,14 @@
또한, 기본 값을 `None`으로 설정해 본문 매개변수를 선택사항으로 선언할 수 있습니다.
```Python hl_lines="19-21"
-{!../../../docs_src/body_multiple_params/tutorial001.py!}
+{!../../docs_src/body_multiple_params/tutorial001.py!}
```
-!!! note "참고"
- 이 경우에는 본문으로 부터 가져온 ` item`은 기본값이 `None`이기 때문에, 선택사항이라는 점을 유의해야 합니다.
+/// note | "참고"
+
+이 경우에는 본문으로 부터 가져온 ` item`은 기본값이 `None`이기 때문에, 선택사항이라는 점을 유의해야 합니다.
+
+///
## 다중 본문 매개변수
@@ -33,7 +36,7 @@
하지만, 다중 본문 매개변수 역시 선언할 수 있습니다. 예. `item`과 `user`:
```Python hl_lines="22"
-{!../../../docs_src/body_multiple_params/tutorial002.py!}
+{!../../docs_src/body_multiple_params/tutorial002.py!}
```
이 경우에, **FastAPI**는 이 함수 안에 한 개 이상의 본문 매개변수(Pydantic 모델인 두 매개변수)가 있다고 알 것입니다.
@@ -55,8 +58,11 @@
}
```
-!!! note "참고"
- 이전과 같이 `item`이 선언 되었더라도, 본문 내의 `item` 키가 있을 것이라고 예측합니다.
+/// note | "참고"
+
+이전과 같이 `item`이 선언 되었더라도, 본문 내의 `item` 키가 있을 것이라고 예측합니다.
+
+///
FastAPI는 요청을 자동으로 변환해, 매개변수의 `item`과 `user`를 특별한 내용으로 받도록 할 것입니다.
@@ -74,7 +80,7 @@ FastAPI는 요청을 자동으로 변환해, 매개변수의 `item`과 `user`를
```Python hl_lines="23"
-{!../../../docs_src/body_multiple_params/tutorial003.py!}
+{!../../docs_src/body_multiple_params/tutorial003.py!}
```
이 경우에는 **FastAPI**는 본문을 이와 같이 예측할 것입니다:
@@ -105,7 +111,7 @@ FastAPI는 요청을 자동으로 변환해, 매개변수의 `item`과 `user`를
기본적으로 단일 값은 쿼리 매개변수로 해석되므로, 명시적으로 `Query`를 추가할 필요가 없고, 아래처럼 할 수 있습니다:
```Python hl_lines="27"
-{!../../../docs_src/body_multiple_params/tutorial004.py!}
+{!../../docs_src/body_multiple_params/tutorial004.py!}
```
이렇게:
@@ -114,8 +120,11 @@ FastAPI는 요청을 자동으로 변환해, 매개변수의 `item`과 `user`를
q: Optional[str] = None
```
-!!! info "정보"
- `Body` 또한 `Query`, `Path` 그리고 이후에 볼 다른 것들처럼 동일한 추가 검증과 메타데이터 매개변수를 갖고 있습니다.
+/// info | "정보"
+
+`Body` 또한 `Query`, `Path` 그리고 이후에 볼 다른 것들처럼 동일한 추가 검증과 메타데이터 매개변수를 갖고 있습니다.
+
+///
## 단일 본문 매개변수 삽입하기
@@ -126,7 +135,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!}
```
아래 처럼:
diff --git a/docs/ko/docs/tutorial/body-nested-models.md b/docs/ko/docs/tutorial/body-nested-models.md
index 10af0a062..12fb4e0cc 100644
--- a/docs/ko/docs/tutorial/body-nested-models.md
+++ b/docs/ko/docs/tutorial/body-nested-models.md
@@ -6,7 +6,7 @@
어트리뷰트를 서브타입으로 정의할 수 있습니다. 예를 들어 파이썬 `list`는:
```Python hl_lines="14"
-{!../../../docs_src/body_nested_models/tutorial001.py!}
+{!../../docs_src/body_nested_models/tutorial001.py!}
```
이는 `tags`를 항목 리스트로 만듭니다. 각 항목의 타입을 선언하지 않더라도요.
@@ -20,7 +20,7 @@
먼저, 파이썬 표준 `typing` 모듈에서 `List`를 임포트합니다:
```Python hl_lines="1"
-{!../../../docs_src/body_nested_models/tutorial002.py!}
+{!../../docs_src/body_nested_models/tutorial002.py!}
```
### 타입 매개변수로 `List` 선언
@@ -43,7 +43,7 @@ my_list: List[str]
마찬가지로 예제에서 `tags`를 구체적으로 "문자열의 리스트"로 만들 수 있습니다:
```Python hl_lines="14"
-{!../../../docs_src/body_nested_models/tutorial002.py!}
+{!../../docs_src/body_nested_models/tutorial002.py!}
```
## 집합 타입
@@ -55,7 +55,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!}
```
덕분에 중복 데이터가 있는 요청을 수신하더라도 고유한 항목들의 집합으로 변환됩니다.
@@ -79,7 +79,7 @@ Pydantic 모델의 각 어트리뷰트는 타입을 갖습니다.
예를 들어, `Image` 모델을 선언할 수 있습니다:
```Python hl_lines="9-11"
-{!../../../docs_src/body_nested_models/tutorial004.py!}
+{!../../docs_src/body_nested_models/tutorial004.py!}
```
### 서브모듈을 타입으로 사용
@@ -87,7 +87,7 @@ Pydantic 모델의 각 어트리뷰트는 타입을 갖습니다.
그리고 어트리뷰트의 타입으로 사용할 수 있습니다:
```Python hl_lines="20"
-{!../../../docs_src/body_nested_models/tutorial004.py!}
+{!../../docs_src/body_nested_models/tutorial004.py!}
```
이는 **FastAPI**가 다음과 유사한 본문을 기대한다는 것을 의미합니다:
@@ -122,7 +122,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!}
```
이 문자열이 유효한 URL인지 검사하고 JSON 스키마/OpenAPI로 문서화 됩니다.
@@ -132,7 +132,7 @@ Pydantic 모델의 각 어트리뷰트는 타입을 갖습니다.
`list`, `set` 등의 서브타입으로 Pydantic 모델을 사용할 수도 있습니다:
```Python hl_lines="20"
-{!../../../docs_src/body_nested_models/tutorial006.py!}
+{!../../docs_src/body_nested_models/tutorial006.py!}
```
아래와 같은 JSON 본문으로 예상(변환, 검증, 문서화 등을)합니다:
@@ -161,19 +161,25 @@ Pydantic 모델의 각 어트리뷰트는 타입을 갖습니다.
}
```
-!!! info "정보"
- `images` 키가 어떻게 이미지 객체 리스트를 갖는지 주목하세요.
+/// info | "정보"
+
+`images` 키가 어떻게 이미지 객체 리스트를 갖는지 주목하세요.
+
+///
## 깊게 중첩된 모델
단독으로 깊게 중첩된 모델을 정의할 수 있습니다:
```Python hl_lines="9 14 20 23 27"
-{!../../../docs_src/body_nested_models/tutorial007.py!}
+{!../../docs_src/body_nested_models/tutorial007.py!}
```
-!!! info "정보"
- `Offer`가 선택사항 `Image` 리스트를 차례로 갖는 `Item` 리스트를 어떻게 가지고 있는지 주목하세요
+/// info | "정보"
+
+`Offer`가 선택사항 `Image` 리스트를 차례로 갖는 `Item` 리스트를 어떻게 가지고 있는지 주목하세요
+
+///
## 순수 리스트의 본문
@@ -186,7 +192,7 @@ images: List[Image]
이를 아래처럼:
```Python hl_lines="15"
-{!../../../docs_src/body_nested_models/tutorial008.py!}
+{!../../docs_src/body_nested_models/tutorial008.py!}
```
## 어디서나 편집기 지원
@@ -218,17 +224,20 @@ Pydantic 모델 대신에 `dict`를 직접 사용하여 작업할 경우, 이러
이 경우, `float` 값을 가진 `int` 키가 있는 모든 `dict`를 받아들입니다:
```Python hl_lines="15"
-{!../../../docs_src/body_nested_models/tutorial009.py!}
+{!../../docs_src/body_nested_models/tutorial009.py!}
```
-!!! tip "팁"
- JSON은 오직 `str`형 키만 지원한다는 것을 염두에 두세요.
+/// tip | "팁"
- 하지만 Pydantic은 자동 데이터 변환이 있습니다.
+JSON은 오직 `str`형 키만 지원한다는 것을 염두에 두세요.
- 즉, API 클라이언트가 문자열을 키로 보내더라도 해당 문자열이 순수한 정수를 포함하는한 Pydantic은 이를 변환하고 검증합니다.
+하지만 Pydantic은 자동 데이터 변환이 있습니다.
- 그러므로 `weights`로 받은 `dict`는 실제로 `int` 키와 `float` 값을 가집니다.
+즉, API 클라이언트가 문자열을 키로 보내더라도 해당 문자열이 순수한 정수를 포함하는한 Pydantic은 이를 변환하고 검증합니다.
+
+그러므로 `weights`로 받은 `dict`는 실제로 `int` 키와 `float` 값을 가집니다.
+
+///
## 요약
diff --git a/docs/ko/docs/tutorial/body.md b/docs/ko/docs/tutorial/body.md
index 0ab8b7162..8df8d556e 100644
--- a/docs/ko/docs/tutorial/body.md
+++ b/docs/ko/docs/tutorial/body.md
@@ -8,28 +8,35 @@
**요청** 본문을 선언하기 위해서 모든 강력함과 이점을 갖춘 Pydantic 모델을 사용합니다.
-!!! info "정보"
- 데이터를 보내기 위해, (좀 더 보편적인) `POST`, `PUT`, `DELETE` 혹은 `PATCH` 중에 하나를 사용하는 것이 좋습니다.
+/// info | "정보"
- `GET` 요청에 본문을 담아 보내는 것은 명세서에 정의되지 않은 행동입니다. 그럼에도 불구하고, 이 방식은 아주 복잡한/극한의 사용 상황에서만 FastAPI에 의해 지원됩니다.
+데이터를 보내기 위해, (좀 더 보편적인) `POST`, `PUT`, `DELETE` 혹은 `PATCH` 중에 하나를 사용하는 것이 좋습니다.
- `GET` 요청에 본문을 담는 것은 권장되지 않기에, Swagger UI같은 대화형 문서에서는 `GET` 사용시 담기는 본문에 대한 문서를 표시하지 않으며, 중간에 있는 프록시는 이를 지원하지 않을 수도 있습니다.
+`GET` 요청에 본문을 담아 보내는 것은 명세서에 정의되지 않은 행동입니다. 그럼에도 불구하고, 이 방식은 아주 복잡한/극한의 사용 상황에서만 FastAPI에 의해 지원됩니다.
+
+`GET` 요청에 본문을 담는 것은 권장되지 않기에, Swagger UI같은 대화형 문서에서는 `GET` 사용시 담기는 본문에 대한 문서를 표시하지 않으며, 중간에 있는 프록시는 이를 지원하지 않을 수도 있습니다.
+
+///
## Pydantic의 `BaseModel` 임포트
먼저 `pydantic`에서 `BaseModel`를 임포트해야 합니다:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="2"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
+```Python hl_lines="2"
+{!> ../../docs_src/body/tutorial001_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="4"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="4"
+{!> ../../docs_src/body/tutorial001.py!}
+```
+
+////
## 여러분의 데이터 모델 만들기
@@ -37,17 +44,21 @@
모든 어트리뷰트에 대해 표준 파이썬 타입을 사용합니다:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="5-9"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
+```Python hl_lines="5-9"
+{!> ../../docs_src/body/tutorial001_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="7-11"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="7-11"
+{!> ../../docs_src/body/tutorial001.py!}
+```
+
+////
쿼리 매개변수를 선언할 때와 같이, 모델 어트리뷰트가 기본 값을 가지고 있어도 이는 필수가 아닙니다. 그외에는 필수입니다. 그저 `None`을 사용하여 선택적으로 만들 수 있습니다.
@@ -75,17 +86,21 @@
여러분의 *경로 작동*에 추가하기 위해, 경로 매개변수 그리고 쿼리 매개변수에서 선언했던 것과 같은 방식으로 선언하면 됩니다.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="16"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
+```Python hl_lines="16"
+{!> ../../docs_src/body/tutorial001_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="18"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="18"
+{!> ../../docs_src/body/tutorial001.py!}
+```
+
+////
...그리고 만들어낸 모델인 `Item`으로 타입을 선언합니다.
@@ -134,32 +149,39 @@
-!!! tip "팁"
- 만약 PyCharm를 편집기로 사용한다면, Pydantic PyCharm Plugin을 사용할 수 있습니다.
+/// tip | "팁"
- 다음 사항을 포함해 Pydantic 모델에 대한 편집기 지원을 향상시킵니다:
+만약 PyCharm를 편집기로 사용한다면, Pydantic PyCharm Plugin을 사용할 수 있습니다.
- * 자동 완성
- * 타입 확인
- * 리팩토링
- * 검색
- * 점검
+다음 사항을 포함해 Pydantic 모델에 대한 편집기 지원을 향상시킵니다:
+
+* 자동 완성
+* 타입 확인
+* 리팩토링
+* 검색
+* 점검
+
+///
## 모델 사용하기
함수 안에서 모델 객체의 모든 어트리뷰트에 직접 접근 가능합니다:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="19"
- {!> ../../../docs_src/body/tutorial002_py310.py!}
- ```
+```Python hl_lines="19"
+{!> ../../docs_src/body/tutorial002_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="21"
- {!> ../../../docs_src/body/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="21"
+{!> ../../docs_src/body/tutorial002.py!}
+```
+
+////
## 요청 본문 + 경로 매개변수
@@ -167,17 +189,21 @@
**FastAPI**는 경로 매개변수와 일치하는 함수 매개변수가 **경로에서 가져와야 한다**는 것을 인지하며, Pydantic 모델로 선언된 그 함수 매개변수는 **요청 본문에서 가져와야 한다**는 것을 인지할 것입니다.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="15-16"
- {!> ../../../docs_src/body/tutorial003_py310.py!}
- ```
+```Python hl_lines="15-16"
+{!> ../../docs_src/body/tutorial003_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="17-18"
- {!> ../../../docs_src/body/tutorial003.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="17-18"
+{!> ../../docs_src/body/tutorial003.py!}
+```
+
+////
## 요청 본문 + 경로 + 쿼리 매개변수
@@ -185,17 +211,21 @@
**FastAPI**는 각각을 인지하고 데이터를 옳바른 위치에 가져올 것입니다.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="16"
- {!> ../../../docs_src/body/tutorial004_py310.py!}
- ```
+```Python hl_lines="16"
+{!> ../../docs_src/body/tutorial004_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="18"
- {!> ../../../docs_src/body/tutorial004.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="18"
+{!> ../../docs_src/body/tutorial004.py!}
+```
+
+////
함수 매개변수는 다음을 따라서 인지하게 됩니다:
@@ -203,10 +233,13 @@
* 만약 매개변수가 (`int`, `float`, `str`, `bool` 등과 같은) **유일한 타입**으로 되어있으면, **쿼리** 매개변수로 해석될 것입니다.
* 만약 매개변수가 **Pydantic 모델** 타입으로 선언되어 있으면, 요청 **본문**으로 해석될 것입니다.
-!!! note "참고"
- FastAPI는 `q`의 값이 필요없음을 알게 될 것입니다. 기본 값이 `= None`이기 때문입니다.
+/// note | "참고"
- `Union[str, None]`에 있는 `Union`은 FastAPI에 의해 사용된 것이 아니지만, 편집기로 하여금 더 나은 지원과 에러 탐지를 지원할 것입니다.
+FastAPI는 `q`의 값이 필요없음을 알게 될 것입니다. 기본 값이 `= None`이기 때문입니다.
+
+`Union[str, None]`에 있는 `Union`은 FastAPI에 의해 사용된 것이 아니지만, 편집기로 하여금 더 나은 지원과 에러 탐지를 지원할 것입니다.
+
+///
## Pydantic없이
diff --git a/docs/ko/docs/tutorial/cookie-params.md b/docs/ko/docs/tutorial/cookie-params.md
index d4f3d57a3..1e21e069d 100644
--- a/docs/ko/docs/tutorial/cookie-params.md
+++ b/docs/ko/docs/tutorial/cookie-params.md
@@ -6,41 +6,57 @@
먼저 `Cookie`를 임포트합니다:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="3"
+{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="3"
+{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ Annotated가 없는 경우"
+//// tab | Python 3.8+
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+```Python hl_lines="3"
+{!> ../../docs_src/cookie_params/tutorial001_an.py!}
+```
- ```Python hl_lines="1"
- {!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ Annotated가 없는 경우"
+//// tab | Python 3.10+ Annotated가 없는 경우
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+/// tip | "팁"
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001.py!}
- ```
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
+
+///
+
+```Python hl_lines="1"
+{!> ../../docs_src/cookie_params/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ Annotated가 없는 경우
+
+/// tip | "팁"
+
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
+
+///
+
+```Python hl_lines="3"
+{!> ../../docs_src/cookie_params/tutorial001.py!}
+```
+
+////
## `Cookie` 매개변수 선언
@@ -48,49 +64,71 @@
첫 번째 값은 기본값이며, 추가 검증이나 어노테이션 매개변수 모두 전달할 수 있습니다:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="9"
+{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/cookie_params/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ Annotated가 없는 경우"
+//// tab | Python 3.8+
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+```Python hl_lines="10"
+{!> ../../docs_src/cookie_params/tutorial001_an.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ Annotated가 없는 경우"
+//// tab | Python 3.10+ Annotated가 없는 경우
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+/// tip | "팁"
- ```Python hl_lines="9"
- {!> ../../../docs_src/cookie_params/tutorial001.py!}
- ```
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
-!!! note "기술 세부사항"
- `Cookie`는 `Path` 및 `Query`의 "자매"클래스입니다. 이 역시 동일한 공통 `Param` 클래스를 상속합니다.
+///
- `Query`, `Path`, `Cookie` 그리고 다른 것들은 `fastapi`에서 임포트 할 때, 실제로는 특별한 클래스를 반환하는 함수임을 기억하세요.
+```Python hl_lines="7"
+{!> ../../docs_src/cookie_params/tutorial001_py310.py!}
+```
-!!! info "정보"
- 쿠키를 선언하기 위해서는 `Cookie`를 사용해야 합니다. 그렇지 않으면 해당 매개변수를 쿼리 매개변수로 해석하기 때문입니다.
+////
+
+//// tab | Python 3.8+ Annotated가 없는 경우
+
+/// tip | "팁"
+
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
+
+///
+
+```Python hl_lines="9"
+{!> ../../docs_src/cookie_params/tutorial001.py!}
+```
+
+////
+
+/// note | "기술 세부사항"
+
+`Cookie`는 `Path` 및 `Query`의 "자매"클래스입니다. 이 역시 동일한 공통 `Param` 클래스를 상속합니다.
+
+`Query`, `Path`, `Cookie` 그리고 다른 것들은 `fastapi`에서 임포트 할 때, 실제로는 특별한 클래스를 반환하는 함수임을 기억하세요.
+
+///
+
+/// info | "정보"
+
+쿠키를 선언하기 위해서는 `Cookie`를 사용해야 합니다. 그렇지 않으면 해당 매개변수를 쿼리 매개변수로 해석하기 때문입니다.
+
+///
## 요약
diff --git a/docs/ko/docs/tutorial/cors.md b/docs/ko/docs/tutorial/cors.md
index 39e9ea83f..65357ae3f 100644
--- a/docs/ko/docs/tutorial/cors.md
+++ b/docs/ko/docs/tutorial/cors.md
@@ -47,7 +47,7 @@
* 특정한 HTTP 헤더 또는 와일드카드 `"*"` 를 사용한 모든 HTTP 헤더.
```Python hl_lines="2 6-11 13-19"
-{!../../../docs_src/cors/tutorial001.py!}
+{!../../docs_src/cors/tutorial001.py!}
```
`CORSMiddleware` 에서 사용하는 기본 매개변수는 제한적이므로, 브라우저가 교차-도메인 상황에서 특정한 출처, 메소드, 헤더 등을 사용할 수 있도록 하려면 이들을 명시적으로 허용해야 합니다.
@@ -78,7 +78,10 @@
CORS에 대한 더 많은 정보를 알고싶다면, Mozilla CORS 문서를 참고하기 바랍니다.
-!!! note "기술적 세부 사항"
- `from starlette.middleware.cors import CORSMiddleware` 역시 사용할 수 있습니다.
+/// note | "기술적 세부 사항"
- **FastAPI**는 개발자인 당신의 편의를 위해 `fastapi.middleware` 에서 몇가지의 미들웨어를 제공합니다. 하지만 대부분의 미들웨어가 Stralette으로부터 직접 제공됩니다.
+`from starlette.middleware.cors import CORSMiddleware` 역시 사용할 수 있습니다.
+
+**FastAPI**는 개발자인 당신의 편의를 위해 `fastapi.middleware` 에서 몇가지의 미들웨어를 제공합니다. 하지만 대부분의 미들웨어가 Stralette으로부터 직접 제공됩니다.
+
+///
diff --git a/docs/ko/docs/tutorial/debugging.md b/docs/ko/docs/tutorial/debugging.md
index c3e588537..27e8f9abf 100644
--- a/docs/ko/docs/tutorial/debugging.md
+++ b/docs/ko/docs/tutorial/debugging.md
@@ -7,7 +7,7 @@
FastAPI 애플리케이션에서 `uvicorn`을 직접 임포트하여 실행합니다
```Python hl_lines="1 15"
-{!../../../docs_src/debugging/tutorial001.py!}
+{!../../docs_src/debugging/tutorial001.py!}
```
### `__name__ == "__main__"` 에 대하여
@@ -74,8 +74,11 @@ from myapp import app
은 실행되지 않습니다.
-!!! info "정보"
- 자세한 내용은 공식 Python 문서를 확인하세요
+/// 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 38cdc2e1a..7430efbb4 100644
--- a/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md
+++ b/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md
@@ -6,17 +6,21 @@
이전 예제에서, 우리는 의존성(의존 가능한) 함수에서 `딕셔너리`객체를 반환하고 있었습니다:
-=== "파이썬 3.6 이상"
+//// tab | 파이썬 3.6 이상
- ```Python hl_lines="9"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/dependencies/tutorial001.py!}
+```
-=== "파이썬 3.10 이상"
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+//// tab | 파이썬 3.10 이상
+
+```Python hl_lines="7"
+{!> ../../docs_src/dependencies/tutorial001_py310.py!}
+```
+
+////
우리는 *경로 작동 함수*의 매개변수 `commons`에서 `딕셔너리` 객체를 얻습니다.
@@ -77,45 +81,57 @@ FastAPI가 실질적으로 확인하는 것은 "호출 가능성"(함수, 클래
그래서, 우리는 위 예제에서의 `common_paramenters` 의존성을 클래스 `CommonQueryParams`로 바꿀 수 있습니다.
-=== "파이썬 3.6 이상"
+//// tab | 파이썬 3.6 이상
- ```Python hl_lines="11-15"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
- ```
+```Python hl_lines="11-15"
+{!> ../../docs_src/dependencies/tutorial002.py!}
+```
-=== "파이썬 3.10 이상"
+////
- ```Python hl_lines="9-13"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
+//// tab | 파이썬 3.10 이상
+
+```Python hl_lines="9-13"
+{!> ../../docs_src/dependencies/tutorial002_py310.py!}
+```
+
+////
클래스의 인스턴스를 생성하는 데 사용되는 `__init__` 메서드에 주목하기 바랍니다:
-=== "파이썬 3.6 이상"
+//// tab | 파이썬 3.6 이상
- ```Python hl_lines="12"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
- ```
+```Python hl_lines="12"
+{!> ../../docs_src/dependencies/tutorial002.py!}
+```
-=== "파이썬 3.10 이상"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
+//// tab | 파이썬 3.10 이상
+
+```Python hl_lines="10"
+{!> ../../docs_src/dependencies/tutorial002_py310.py!}
+```
+
+////
...이전 `common_parameters`와 동일한 매개변수를 가집니다:
-=== "파이썬 3.6 이상"
+//// tab | 파이썬 3.6 이상
- ```Python hl_lines="9"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/dependencies/tutorial001.py!}
+```
-=== "파이썬 3.10 이상"
+////
- ```Python hl_lines="6"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+//// tab | 파이썬 3.10 이상
+
+```Python hl_lines="6"
+{!> ../../docs_src/dependencies/tutorial001_py310.py!}
+```
+
+////
이 매개변수들은 **FastAPI**가 의존성을 "해결"하기 위해 사용할 것입니다
@@ -131,17 +147,21 @@ FastAPI가 실질적으로 확인하는 것은 "호출 가능성"(함수, 클래
이제 아래의 클래스를 이용해서 의존성을 정의할 수 있습니다.
-=== "파이썬 3.6 이상"
+//// tab | 파이썬 3.6 이상
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
- ```
+```Python hl_lines="19"
+{!> ../../docs_src/dependencies/tutorial002.py!}
+```
-=== "파이썬 3.10 이상"
+////
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
+//// tab | 파이썬 3.10 이상
+
+```Python hl_lines="17"
+{!> ../../docs_src/dependencies/tutorial002_py310.py!}
+```
+
+////
**FastAPI**는 `CommonQueryParams` 클래스를 호출합니다. 이것은 해당 클래스의 "인스턴스"를 생성하고 그 인스턴스는 함수의 매개변수 `commons`로 전달됩니다.
@@ -180,17 +200,21 @@ commons = Depends(CommonQueryParams)
..전체적인 코드는 아래와 같습니다:
-=== "파이썬 3.6 이상"
+//// tab | 파이썬 3.6 이상
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial003.py!}
- ```
+```Python hl_lines="19"
+{!> ../../docs_src/dependencies/tutorial003.py!}
+```
-=== "파이썬 3.10 이상"
+////
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial003_py310.py!}
- ```
+//// tab | 파이썬 3.10 이상
+
+```Python hl_lines="17"
+{!> ../../docs_src/dependencies/tutorial003_py310.py!}
+```
+
+////
그러나 자료형을 선언하면 에디터가 매개변수 `commons`로 전달될 것이 무엇인지 알게 되고, 이를 통해 코드 완성, 자료형 확인 등에 도움이 될 수 있으므로 권장됩니다.
@@ -224,21 +248,28 @@ commons: CommonQueryParams = Depends()
아래에 같은 예제가 있습니다:
-=== "파이썬 3.6 이상"
+//// tab | 파이썬 3.6 이상
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial004.py!}
- ```
+```Python hl_lines="19"
+{!> ../../docs_src/dependencies/tutorial004.py!}
+```
-=== "파이썬 3.10 이상"
+////
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial004_py310.py!}
- ```
+//// tab | 파이썬 3.10 이상
+
+```Python hl_lines="17"
+{!> ../../docs_src/dependencies/tutorial004_py310.py!}
+```
+
+////
...이렇게 코드를 단축하여도 **FastAPI**는 무엇을 해야하는지 알고 있습니다.
-!!! tip "팁"
- 만약 이것이 도움이 되기보다 더 헷갈리게 만든다면, 잊어버리십시오. 이것이 반드시 필요한 것은 아닙니다.
+/// tip | "팁"
- 이것은 단지 손쉬운 방법일 뿐입니다. 왜냐하면 **FastAPI**는 코드 반복을 최소화할 수 있는 방법을 고민하기 때문입니다.
+만약 이것이 도움이 되기보다 더 헷갈리게 만든다면, 잊어버리십시오. 이것이 반드시 필요한 것은 아닙니다.
+
+이것은 단지 손쉬운 방법일 뿐입니다. 왜냐하면 **FastAPI**는 코드 반복을 최소화할 수 있는 방법을 고민하기 때문입니다.
+
+///
diff --git a/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
index 92b2c7d1c..e71ba8546 100644
--- a/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
+++ b/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
@@ -14,40 +14,55 @@
`Depends()`로 된 `list`이어야합니다:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
- ```
+```Python hl_lines="19"
+{!> ../../docs_src/dependencies/tutorial006_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="18"
- {!> ../../../docs_src/dependencies/tutorial006_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8 Annotated가 없는 경우"
+```Python hl_lines="18"
+{!> ../../docs_src/dependencies/tutorial006_an.py!}
+```
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+////
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial006.py!}
- ```
+//// tab | Python 3.8 Annotated가 없는 경우
+
+/// tip | "팁"
+
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
+
+///
+
+```Python hl_lines="17"
+{!> ../../docs_src/dependencies/tutorial006.py!}
+```
+
+////
이러한 의존성들은 기존 의존성들과 같은 방식으로 실행/해결됩니다. 그러나 값은 (무엇이든 반환한다면) *경로 작동 함수*에 제공되지 않습니다.
-!!! tip "팁"
- 일부 편집기에서는 사용되지 않는 함수 매개변수를 검사하고 오류로 표시합니다.
+/// tip | "팁"
- *경로 작동 데코레이터*에서 `dependencies`를 사용하면 편집기/도구 오류를 피하며 실행되도록 할 수 있습니다.
+일부 편집기에서는 사용되지 않는 함수 매개변수를 검사하고 오류로 표시합니다.
- 또한 코드에서 사용되지 않는 매개변수를 보고 불필요하다고 생각할 수 있는 새로운 개발자의 혼란을 방지하는데 도움이 될 수 있습니다.
+*경로 작동 데코레이터*에서 `dependencies`를 사용하면 편집기/도구 오류를 피하며 실행되도록 할 수 있습니다.
-!!! info "정보"
- 이 예시에서 `X-Key`와 `X-Token`이라는 커스텀 헤더를 만들어 사용했습니다.
+또한 코드에서 사용되지 않는 매개변수를 보고 불필요하다고 생각할 수 있는 새로운 개발자의 혼란을 방지하는데 도움이 될 수 있습니다.
- 그러나 실제로 보안을 구현할 때는 통합된 [보안 유틸리티 (다음 챕터)](../security/index.md){.internal-link target=_blank}를 사용하는 것이 더 많은 이점을 얻을 수 있습니다.
+///
+
+/// info | "정보"
+
+이 예시에서 `X-Key`와 `X-Token`이라는 커스텀 헤더를 만들어 사용했습니다.
+
+그러나 실제로 보안을 구현할 때는 통합된 [보안 유틸리티 (다음 챕터)](../security/index.md){.internal-link target=_blank}를 사용하는 것이 더 많은 이점을 얻을 수 있습니다.
+
+///
## 의존성 오류와 값 반환하기
@@ -57,51 +72,69 @@
(헤더같은) 요청 요구사항이나 하위-의존성을 선언할 수 있습니다:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="8 13"
- {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
- ```
+```Python hl_lines="8 13"
+{!> ../../docs_src/dependencies/tutorial006_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="7 12"
- {!> ../../../docs_src/dependencies/tutorial006_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8 Annotated가 없는 경우"
+```Python hl_lines="7 12"
+{!> ../../docs_src/dependencies/tutorial006_an.py!}
+```
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+////
- ```Python hl_lines="6 11"
- {!> ../../../docs_src/dependencies/tutorial006.py!}
- ```
+//// tab | Python 3.8 Annotated가 없는 경우
+
+/// tip | "팁"
+
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
+
+///
+
+```Python hl_lines="6 11"
+{!> ../../docs_src/dependencies/tutorial006.py!}
+```
+
+////
### 오류 발생시키기
다음 의존성은 기존 의존성과 동일하게 예외를 `raise`를 일으킬 수 있습니다:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="10 15"
- {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
- ```
+```Python hl_lines="10 15"
+{!> ../../docs_src/dependencies/tutorial006_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9 14"
- {!> ../../../docs_src/dependencies/tutorial006_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8 Annotated가 없는 경우"
+```Python hl_lines="9 14"
+{!> ../../docs_src/dependencies/tutorial006_an.py!}
+```
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+////
- ```Python hl_lines="8 13"
- {!> ../../../docs_src/dependencies/tutorial006.py!}
- ```
+//// tab | Python 3.8 Annotated가 없는 경우
+
+/// tip | "팁"
+
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
+
+///
+
+```Python hl_lines="8 13"
+{!> ../../docs_src/dependencies/tutorial006.py!}
+```
+
+////
### 값 반환하기
@@ -109,26 +142,35 @@
그래서 이미 다른 곳에서 사용된 (값을 반환하는) 일반적인 의존성을 재사용할 수 있고, 비록 값은 사용되지 않지만 의존성은 실행될 것입니다:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="11 16"
- {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
- ```
+```Python hl_lines="11 16"
+{!> ../../docs_src/dependencies/tutorial006_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="10 15"
- {!> ../../../docs_src/dependencies/tutorial006_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8 Annotated가 없는 경우"
+```Python hl_lines="10 15"
+{!> ../../docs_src/dependencies/tutorial006_an.py!}
+```
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+////
- ```Python hl_lines="9 14"
- {!> ../../../docs_src/dependencies/tutorial006.py!}
- ```
+//// tab | Python 3.8 Annotated가 없는 경우
+
+/// tip | "팁"
+
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
+
+///
+
+```Python hl_lines="9 14"
+{!> ../../docs_src/dependencies/tutorial006.py!}
+```
+
+////
## *경로 작동* 모음에 대한 의존성
diff --git a/docs/ko/docs/tutorial/dependencies/global-dependencies.md b/docs/ko/docs/tutorial/dependencies/global-dependencies.md
index 930f6e678..dd6586c3e 100644
--- a/docs/ko/docs/tutorial/dependencies/global-dependencies.md
+++ b/docs/ko/docs/tutorial/dependencies/global-dependencies.md
@@ -6,26 +6,35 @@
그런 경우에, 애플리케이션의 모든 *경로 작동*에 적용될 것입니다:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="16"
- {!> ../../../docs_src/dependencies/tutorial012_an_py39.py!}
- ```
+```Python hl_lines="16"
+{!> ../../docs_src/dependencies/tutorial012_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="16"
- {!> ../../../docs_src/dependencies/tutorial012_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8 Annotated가 없는 경우"
+```Python hl_lines="16"
+{!> ../../docs_src/dependencies/tutorial012_an.py!}
+```
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+////
- ```Python hl_lines="15"
- {!> ../../../docs_src/dependencies/tutorial012.py!}
- ```
+//// tab | Python 3.8 Annotated가 없는 경우
+
+/// tip | "팁"
+
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
+
+///
+
+```Python hl_lines="15"
+{!> ../../docs_src/dependencies/tutorial012.py!}
+```
+
+////
그리고 [*경로 작동 데코레이터*에 `dependencies` 추가하기](dependencies-in-path-operation-decorators.md){.internal-link target=_blank}에 대한 아이디어는 여전히 적용되지만 여기에서는 앱에 있는 모든 *경로 작동*에 적용됩니다.
diff --git a/docs/ko/docs/tutorial/dependencies/index.md b/docs/ko/docs/tutorial/dependencies/index.md
index d06864ab8..f7b2f1788 100644
--- a/docs/ko/docs/tutorial/dependencies/index.md
+++ b/docs/ko/docs/tutorial/dependencies/index.md
@@ -31,41 +31,57 @@
*경로 작동 함수*가 가질 수 있는 모든 매개변수를 갖는 단순한 함수입니다:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="8-9"
- {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="8-9"
+{!> ../../docs_src/dependencies/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="8-11"
- {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="8-11"
+{!> ../../docs_src/dependencies/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="9-12"
- {!> ../../../docs_src/dependencies/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ Annotated가 없는 경우"
+//// tab | Python 3.8+
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+```Python hl_lines="9-12"
+{!> ../../docs_src/dependencies/tutorial001_an.py!}
+```
- ```Python hl_lines="6-7"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ Annotated가 없는 경우"
+//// tab | Python 3.10+ Annotated가 없는 경우
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+/// tip | "팁"
- ```Python hl_lines="8-11"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
+
+///
+
+```Python hl_lines="6-7"
+{!> ../../docs_src/dependencies/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ Annotated가 없는 경우
+
+/// tip | "팁"
+
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
+
+///
+
+```Python hl_lines="8-11"
+{!> ../../docs_src/dependencies/tutorial001.py!}
+```
+
+////
이게 다입니다.
@@ -85,90 +101,125 @@
그 후 위의 값을 포함한 `dict` 자료형으로 반환할 뿐입니다.
-!!! info "정보"
- FastAPI는 0.95.0 버전부터 `Annotated`에 대한 지원을 (그리고 이를 사용하기 권장합니다) 추가했습니다.
+/// info | "정보"
- 옛날 버전을 가지고 있는 경우, `Annotated`를 사용하려 하면 에러를 맞이하게 될 것입니다.
+FastAPI는 0.95.0 버전부터 `Annotated`에 대한 지원을 (그리고 이를 사용하기 권장합니다) 추가했습니다.
- `Annotated`를 사용하기 전에 최소 0.95.1로 [FastAPI 버전 업그레이드](../../deployment/versions.md#fastapi_2){.internal-link target=_blank}를 확실하게 하세요.
+옛날 버전을 가지고 있는 경우, `Annotated`를 사용하려 하면 에러를 맞이하게 될 것입니다.
+
+`Annotated`를 사용하기 전에 최소 0.95.1로 [FastAPI 버전 업그레이드](../../deployment/versions.md#fastapi_2){.internal-link target=_blank}를 확실하게 하세요.
+
+///
### `Depends` 불러오기
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="3"
- {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="3"
+{!> ../../docs_src/dependencies/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="3"
- {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="3"
+{!> ../../docs_src/dependencies/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="3"
- {!> ../../../docs_src/dependencies/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ Annotated가 없는 경우"
+//// tab | Python 3.8+
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+```Python hl_lines="3"
+{!> ../../docs_src/dependencies/tutorial001_an.py!}
+```
- ```Python hl_lines="1"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ Annotated가 없는 경우"
+//// tab | Python 3.10+ Annotated가 없는 경우
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+/// tip | "팁"
- ```Python hl_lines="3"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
+
+///
+
+```Python hl_lines="1"
+{!> ../../docs_src/dependencies/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ Annotated가 없는 경우
+
+/// tip | "팁"
+
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
+
+///
+
+```Python hl_lines="3"
+{!> ../../docs_src/dependencies/tutorial001.py!}
+```
+
+////
### "의존자"에 의존성 명시하기
*경로 작동 함수*의 매개변수로 `Body`, `Query` 등을 사용하는 방식과 같이 새로운 매개변수로 `Depends`를 사용합니다:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="13 18"
- {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="13 18"
+{!> ../../docs_src/dependencies/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="15 20"
- {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="15 20"
+{!> ../../docs_src/dependencies/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="16 21"
- {!> ../../../docs_src/dependencies/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ Annotated가 없는 경우"
+//// tab | Python 3.8+
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+```Python hl_lines="16 21"
+{!> ../../docs_src/dependencies/tutorial001_an.py!}
+```
- ```Python hl_lines="11 16"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ Annotated가 없는 경우"
+//// tab | Python 3.10+ Annotated가 없는 경우
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+/// tip | "팁"
- ```Python hl_lines="15 20"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
+
+///
+
+```Python hl_lines="11 16"
+{!> ../../docs_src/dependencies/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ Annotated가 없는 경우
+
+/// tip | "팁"
+
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
+
+///
+
+```Python hl_lines="15 20"
+{!> ../../docs_src/dependencies/tutorial001.py!}
+```
+
+////
비록 `Body`, `Query` 등을 사용하는 것과 같은 방식으로 여러분의 함수의 매개변수에 있는 `Depends`를 사용하지만, `Depends`는 약간 다르게 작동합니다.
@@ -180,8 +231,11 @@
그리고 그 함수는 *경로 작동 함수*가 작동하는 것과 같은 방식으로 매개변수를 받습니다.
-!!! tip "팁"
- 여러분은 다음 장에서 함수를 제외하고서, "다른 것들"이 어떻게 의존성으로 사용되는지 알게 될 것입니다.
+/// tip | "팁"
+
+여러분은 다음 장에서 함수를 제외하고서, "다른 것들"이 어떻게 의존성으로 사용되는지 알게 될 것입니다.
+
+///
새로운 요청이 도착할 때마다, **FastAPI**는 다음을 처리합니다:
@@ -202,10 +256,13 @@ common_parameters --> read_users
이렇게 하면 공용 코드를 한번만 적어도 되며, **FastAPI**는 *경로 작동*을 위해 이에 대한 호출을 처리합니다.
-!!! check "확인"
- 특별한 클래스를 만들지 않아도 되며, 이러한 것 혹은 비슷한 종류를 **FastAPI**에 "등록"하기 위해 어떤 곳에 넘겨주지 않아도 됩니다.
+/// check | "확인"
- 단순히 `Depends`에 넘겨주기만 하면 되며, **FastAPI**는 나머지를 어찌할지 알고 있습니다.
+특별한 클래스를 만들지 않아도 되며, 이러한 것 혹은 비슷한 종류를 **FastAPI**에 "등록"하기 위해 어떤 곳에 넘겨주지 않아도 됩니다.
+
+단순히 `Depends`에 넘겨주기만 하면 되며, **FastAPI**는 나머지를 어찌할지 알고 있습니다.
+
+///
## `Annotated`인 의존성 공유하기
@@ -219,28 +276,37 @@ commons: Annotated[dict, Depends(common_parameters)]
하지만 `Annotated`를 사용하고 있기에, `Annotated` 값을 변수에 저장하고 여러 장소에서 사용할 수 있습니다:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="12 16 21"
- {!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!}
- ```
+```Python hl_lines="12 16 21"
+{!> ../../docs_src/dependencies/tutorial001_02_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="14 18 23"
- {!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="14 18 23"
+{!> ../../docs_src/dependencies/tutorial001_02_an_py39.py!}
+```
- ```Python hl_lines="15 19 24"
- {!> ../../../docs_src/dependencies/tutorial001_02_an.py!}
- ```
+////
-!!! tip "팁"
- 이는 그저 표준 파이썬이고 "type alias"라고 부르며 사실 **FastAPI**에 국한되는 것은 아닙니다.
+//// tab | Python 3.8+
- 하지만, `Annotated`를 포함하여, **FastAPI**가 파이썬 표준을 기반으로 하고 있기에, 이를 여러분의 코드 트릭으로 사용할 수 있습니다. 😎
+```Python hl_lines="15 19 24"
+{!> ../../docs_src/dependencies/tutorial001_02_an.py!}
+```
+
+////
+
+/// tip | "팁"
+
+이는 그저 표준 파이썬이고 "type alias"라고 부르며 사실 **FastAPI**에 국한되는 것은 아닙니다.
+
+하지만, `Annotated`를 포함하여, **FastAPI**가 파이썬 표준을 기반으로 하고 있기에, 이를 여러분의 코드 트릭으로 사용할 수 있습니다. 😎
+
+///
이 의존성은 계속해서 예상한대로 작동할 것이며, **제일 좋은 부분**은 **타입 정보가 보존된다는 것입니다**. 즉 여러분의 편집기가 **자동 완성**, **인라인 에러** 등을 계속해서 제공할 수 있다는 것입니다. `mypy`같은 다른 도구도 마찬가지입니다.
@@ -256,8 +322,11 @@ commons: Annotated[dict, Depends(common_parameters)]
아무 문제 없습니다. **FastAPI**는 무엇을 할지 알고 있습니다.
-!!! note "참고"
- 잘 모르시겠다면, [Async: *"In a hurry?"*](../../async.md){.internal-link target=_blank} 문서에서 `async`와 `await`에 대해 확인할 수 있습니다.
+/// note | "참고"
+
+잘 모르시겠다면, [Async: *"In a hurry?"*](../../async.md){.internal-link target=_blank} 문서에서 `async`와 `await`에 대해 확인할 수 있습니다.
+
+///
## OpenAPI와 통합
diff --git a/docs/ko/docs/tutorial/encoder.md b/docs/ko/docs/tutorial/encoder.md
index 8b5fdb8b7..732566d6d 100644
--- a/docs/ko/docs/tutorial/encoder.md
+++ b/docs/ko/docs/tutorial/encoder.md
@@ -21,7 +21,7 @@ JSON 호환 가능 데이터만 수신하는 `fake_db` 데이터베이스가 존
Pydantic 모델과 같은 객체를 받고 JSON 호환 가능한 버전으로 반환합니다:
```Python hl_lines="5 22"
-{!../../../docs_src/encoder/tutorial001.py!}
+{!../../docs_src/encoder/tutorial001.py!}
```
이 예시는 Pydantic 모델을 `dict`로, `datetime` 형식을 `str`로 변환합니다.
@@ -30,5 +30,8 @@ Pydantic 모델과 같은 객체를 받고 JSON 호환 가능한 버전으로
길이가 긴 문자열 형태의 JSON 형식(문자열)의 데이터가 들어있는 상황에서는 `str`로 반환하지 않습니다. JSON과 모두 호환되는 값과 하위 값이 있는 Python 표준 데이터 구조 (예: `dict`)를 반환합니다.
-!!! note "참고"
- 실제로 `jsonable_encoder`는 **FastAPI** 에서 내부적으로 데이터를 변환하는 데 사용하지만, 다른 많은 곳에서도 이는 유용합니다.
+/// note | "참고"
+
+실제로 `jsonable_encoder`는 **FastAPI** 에서 내부적으로 데이터를 변환하는 데 사용하지만, 다른 많은 곳에서도 이는 유용합니다.
+
+///
diff --git a/docs/ko/docs/tutorial/extra-data-types.md b/docs/ko/docs/tutorial/extra-data-types.md
index 673cf5b73..8baaa64fc 100644
--- a/docs/ko/docs/tutorial/extra-data-types.md
+++ b/docs/ko/docs/tutorial/extra-data-types.md
@@ -55,76 +55,108 @@
위의 몇몇 자료형을 매개변수로 사용하는 *경로 작동* 예시입니다.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="1 3 12-16"
- {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="1 3 12-16"
+{!> ../../docs_src/extra_data_types/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="1 3 12-16"
- {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="1 3 12-16"
+{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="1 3 13-17"
- {!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="1 3 13-17"
+{!> ../../docs_src/extra_data_types/tutorial001_an.py!}
+```
- ```Python hl_lines="1 2 11-15"
- {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="1 2 12-16"
- {!> ../../../docs_src/extra_data_types/tutorial001.py!}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="1 2 11-15"
+{!> ../../docs_src/extra_data_types/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="1 2 12-16"
+{!> ../../docs_src/extra_data_types/tutorial001.py!}
+```
+
+////
함수 안의 매개변수가 그들만의 데이터 자료형을 가지고 있으며, 예를 들어, 다음과 같이 날짜를 조작할 수 있음을 참고하십시오:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="18-19"
+{!> ../../docs_src/extra_data_types/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="18-19"
+{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="19-20"
- {!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="19-20"
+{!> ../../docs_src/extra_data_types/tutorial001_an.py!}
+```
- ```Python hl_lines="17-18"
- {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/extra_data_types/tutorial001.py!}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="17-18"
+{!> ../../docs_src/extra_data_types/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="18-19"
+{!> ../../docs_src/extra_data_types/tutorial001.py!}
+```
+
+////
diff --git a/docs/ko/docs/tutorial/first-steps.md b/docs/ko/docs/tutorial/first-steps.md
index bdec3a377..c2c48fb3e 100644
--- a/docs/ko/docs/tutorial/first-steps.md
+++ b/docs/ko/docs/tutorial/first-steps.md
@@ -3,7 +3,7 @@
가장 단순한 FastAPI 파일은 다음과 같이 보일 것입니다:
```Python
-{!../../../docs_src/first_steps/tutorial001.py!}
+{!../../docs_src/first_steps/tutorial001.py!}
```
위 코드를 `main.py`에 복사합니다.
@@ -24,12 +24,15 @@ $ uvicorn main:app --reload
-!!! note "참고"
- `uvicorn main:app` 명령은 다음을 의미합니다:
+/// note | "참고"
- * `main`: 파일 `main.py` (파이썬 "모듈").
- * `app`: `main.py` 내부의 `app = FastAPI()` 줄에서 생성한 오브젝트.
- * `--reload`: 코드 변경 시 자동으로 서버 재시작. 개발 시에만 사용.
+`uvicorn main:app` 명령은 다음을 의미합니다:
+
+* `main`: 파일 `main.py` (파이썬 "모듈").
+* `app`: `main.py` 내부의 `app = FastAPI()` 줄에서 생성한 오브젝트.
+* `--reload`: 코드 변경 시 자동으로 서버 재시작. 개발 시에만 사용.
+
+///
출력되는 줄들 중에는 아래와 같은 내용이 있습니다:
@@ -131,20 +134,23 @@ API와 통신하는 클라이언트(프론트엔드, 모바일, IoT 애플리케
### 1 단계: `FastAPI` 임포트
```Python hl_lines="1"
-{!../../../docs_src/first_steps/tutorial001.py!}
+{!../../docs_src/first_steps/tutorial001.py!}
```
`FastAPI`는 당신의 API를 위한 모든 기능을 제공하는 파이썬 클래스입니다.
-!!! note "기술 세부사항"
- `FastAPI`는 `Starlette`를 직접 상속하는 클래스입니다.
+/// note | "기술 세부사항"
- `FastAPI`로 Starlette의 모든 기능을 사용할 수 있습니다.
+`FastAPI`는 `Starlette`를 직접 상속하는 클래스입니다.
+
+`FastAPI`로 Starlette의 모든 기능을 사용할 수 있습니다.
+
+///
### 2 단계: `FastAPI` "인스턴스" 생성
```Python hl_lines="3"
-{!../../../docs_src/first_steps/tutorial001.py!}
+{!../../docs_src/first_steps/tutorial001.py!}
```
여기에서 `app` 변수는 `FastAPI` 클래스의 "인스턴스"가 됩니다.
@@ -166,7 +172,7 @@ $ uvicorn main:app --reload
아래처럼 앱을 만든다면:
```Python hl_lines="3"
-{!../../../docs_src/first_steps/tutorial002.py!}
+{!../../docs_src/first_steps/tutorial002.py!}
```
이를 `main.py` 파일에 넣고, `uvicorn`을 아래처럼 호출해야 합니다:
@@ -199,8 +205,11 @@ https://example.com/items/foo
/items/foo
```
-!!! info "정보"
- "경로"는 일반적으로 "엔드포인트" 또는 "라우트"라고도 불립니다.
+/// info | "정보"
+
+"경로"는 일반적으로 "엔드포인트" 또는 "라우트"라고도 불립니다.
+
+///
API를 설계할 때 "경로"는 "관심사"와 "리소스"를 분리하기 위한 주요한 방법입니다.
@@ -242,7 +251,7 @@ API를 설계할 때 일반적으로 특정 행동을 수행하기 위해 특정
#### *경로 작동 데코레이터* 정의
```Python hl_lines="6"
-{!../../../docs_src/first_steps/tutorial001.py!}
+{!../../docs_src/first_steps/tutorial001.py!}
```
`@app.get("/")`은 **FastAPI**에게 바로 아래에 있는 함수가 다음으로 이동하는 요청을 처리한다는 것을 알려줍니다.
@@ -250,16 +259,19 @@ API를 설계할 때 일반적으로 특정 행동을 수행하기 위해 특정
* 경로 `/`
* get 작동 사용
-!!! info "`@decorator` 정보"
- 이 `@something` 문법은 파이썬에서 "데코레이터"라 부릅니다.
+/// info | "`@decorator` 정보"
- 마치 예쁜 장식용(Decorative) 모자처럼(개인적으로 이 용어가 여기서 유래한 것 같습니다) 함수 맨 위에 놓습니다.
+이 `@something` 문법은 파이썬에서 "데코레이터"라 부릅니다.
- "데코레이터"는 아래 있는 함수를 받아 그것으로 무언가를 합니다.
+마치 예쁜 장식용(Decorative) 모자처럼(개인적으로 이 용어가 여기서 유래한 것 같습니다) 함수 맨 위에 놓습니다.
- 우리의 경우, 이 데코레이터는 **FastAPI**에게 아래 함수가 **경로** `/`의 `get` **작동**에 해당한다고 알려줍니다.
+"데코레이터"는 아래 있는 함수를 받아 그것으로 무언가를 합니다.
- 이것이 "**경로 작동 데코레이터**"입니다.
+우리의 경우, 이 데코레이터는 **FastAPI**에게 아래 함수가 **경로** `/`의 `get` **작동**에 해당한다고 알려줍니다.
+
+이것이 "**경로 작동 데코레이터**"입니다.
+
+///
다른 작동도 사용할 수 있습니다:
@@ -274,14 +286,17 @@ API를 설계할 때 일반적으로 특정 행동을 수행하기 위해 특정
* `@app.patch()`
* `@app.trace()`
-!!! tip "팁"
- 각 작동(HTTP 메소드)을 원하는 대로 사용해도 됩니다.
+/// tip | "팁"
- **FastAPI**는 특정 의미를 강제하지 않습니다.
+각 작동(HTTP 메소드)을 원하는 대로 사용해도 됩니다.
- 여기서 정보는 지침서일뿐 강제사항이 아닙니다.
+**FastAPI**는 특정 의미를 강제하지 않습니다.
- 예를 들어 GraphQL을 사용하는 경우, 일반적으로 `POST` 작동만 사용하여 모든 행동을 수행합니다.
+여기서 정보는 지침서일뿐 강제사항이 아닙니다.
+
+예를 들어 GraphQL을 사용하는 경우, 일반적으로 `POST` 작동만 사용하여 모든 행동을 수행합니다.
+
+///
### 4 단계: **경로 작동 함수** 정의
@@ -292,7 +307,7 @@ API를 설계할 때 일반적으로 특정 행동을 수행하기 위해 특정
* **함수**: 는 "데코레이터" 아래에 있는 함수입니다 (`@app.get("/")` 아래).
```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial001.py!}
+{!../../docs_src/first_steps/tutorial001.py!}
```
이것은 파이썬 함수입니다.
@@ -306,16 +321,19 @@ URL "`/`"에 대한 `GET` 작동을 사용하는 요청을 받을 때마다 **Fa
`async def`을 이용하는 대신 일반 함수로 정의할 수 있습니다:
```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial003.py!}
+{!../../docs_src/first_steps/tutorial003.py!}
```
-!!! note "참고"
- 차이점을 모르겠다면 [Async: *"바쁘신 경우"*](../async.md#_1){.internal-link target=_blank}을 확인하세요.
+/// note | "참고"
+
+차이점을 모르겠다면 [Async: *"바쁘신 경우"*](../async.md#_1){.internal-link target=_blank}을 확인하세요.
+
+///
### 5 단계: 콘텐츠 반환
```Python hl_lines="8"
-{!../../../docs_src/first_steps/tutorial001.py!}
+{!../../docs_src/first_steps/tutorial001.py!}
```
`dict`, `list`, 단일값을 가진 `str`, `int` 등을 반환할 수 있습니다.
diff --git a/docs/ko/docs/tutorial/header-params.md b/docs/ko/docs/tutorial/header-params.md
index 484554e97..26e198869 100644
--- a/docs/ko/docs/tutorial/header-params.md
+++ b/docs/ko/docs/tutorial/header-params.md
@@ -7,7 +7,7 @@
먼저 `Header`를 임포트합니다:
```Python hl_lines="3"
-{!../../../docs_src/header_params/tutorial001.py!}
+{!../../docs_src/header_params/tutorial001.py!}
```
## `Header` 매개변수 선언
@@ -17,16 +17,22 @@
첫 번째 값은 기본값이며, 추가 검증이나 어노테이션 매개변수 모두 전달할 수 있습니다:
```Python hl_lines="9"
-{!../../../docs_src/header_params/tutorial001.py!}
+{!../../docs_src/header_params/tutorial001.py!}
```
-!!! note "기술 세부사항"
- `Header`는 `Path`, `Query` 및 `Cookie`의 "자매"클래스입니다. 이 역시 동일한 공통 `Param` 클래스를 상속합니다.
+/// note | "기술 세부사항"
- `Query`, `Path`, `Header` 그리고 다른 것들을 `fastapi`에서 임포트 할 때, 이들은 실제로 특별한 클래스를 반환하는 함수임을 기억하세요.
+`Header`는 `Path`, `Query` 및 `Cookie`의 "자매"클래스입니다. 이 역시 동일한 공통 `Param` 클래스를 상속합니다.
-!!! info "정보"
- 헤더를 선언하기 위해서 `Header`를 사용해야 합니다. 그렇지 않으면 해당 매개변수를 쿼리 매개변수로 해석하기 때문입니다.
+`Query`, `Path`, `Header` 그리고 다른 것들을 `fastapi`에서 임포트 할 때, 이들은 실제로 특별한 클래스를 반환하는 함수임을 기억하세요.
+
+///
+
+/// info | "정보"
+
+헤더를 선언하기 위해서 `Header`를 사용해야 합니다. 그렇지 않으면 해당 매개변수를 쿼리 매개변수로 해석하기 때문입니다.
+
+///
## 자동 변환
@@ -45,11 +51,14 @@
만약 언더스코어를 하이픈으로 자동 변환을 비활성화해야 할 어떤 이유가 있다면, `Header`의 `convert_underscores` 매개변수를 `False`로 설정하십시오:
```Python hl_lines="10"
-{!../../../docs_src/header_params/tutorial002.py!}
+{!../../docs_src/header_params/tutorial002.py!}
```
-!!! warning "경고"
- `convert_underscore`를 `False`로 설정하기 전에, 어떤 HTTP 프록시들과 서버들은 언더스코어가 포함된 헤더 사용을 허락하지 않는다는 것을 명심하십시오.
+/// warning | "경고"
+
+`convert_underscore`를 `False`로 설정하기 전에, 어떤 HTTP 프록시들과 서버들은 언더스코어가 포함된 헤더 사용을 허락하지 않는다는 것을 명심하십시오.
+
+///
## 중복 헤더
@@ -62,7 +71,7 @@
예를 들어, 두 번 이상 나타날 수 있는 `X-Token`헤더를 선언하려면, 다음과 같이 작성합니다:
```Python hl_lines="9"
-{!../../../docs_src/header_params/tutorial003.py!}
+{!../../docs_src/header_params/tutorial003.py!}
```
다음과 같은 두 개의 HTTP 헤더를 전송하여 해당 *경로* 와 통신할 경우:
diff --git a/docs/ko/docs/tutorial/index.md b/docs/ko/docs/tutorial/index.md
index 94d6dfb92..a148bc76e 100644
--- a/docs/ko/docs/tutorial/index.md
+++ b/docs/ko/docs/tutorial/index.md
@@ -30,7 +30,7 @@ $ uvicorn main:app --reload
코드를 작성하거나 복사, 편집할 때, 로컬 환경에서 실행하는 것을 **강력히 권장**합니다.
-로컬 편집기에서 사용한다면, 모든 타입 검사와 자동완성 등 작성해야 하는 코드가 얼마나 적은지 보면서 FastAPI의 비로소 경험할 수 있습니다.
+로컬 편집기에서 사용한다면, 모든 타입 검사와 자동완성 등 작성해야 하는 코드가 얼마나 적은지 보면서 FastAPI의 이점을 비로소 경험할 수 있습니다.
---
@@ -53,22 +53,25 @@ $ pip install "fastapi[all]"
...이는 코드를 실행하는 서버로 사용할 수 있는 `uvicorn` 또한 포함하고 있습니다.
-!!! note "참고"
- 부분적으로 설치할 수도 있습니다.
+/// note | "참고"
- 애플리케이션을 운영 환경에 배포하려는 경우 다음과 같이 합니다:
+부분적으로 설치할 수도 있습니다.
- ```
- pip install fastapi
- ```
+애플리케이션을 운영 환경에 배포하려는 경우 다음과 같이 합니다:
- 추가로 서버 역할을 하는 `uvicorn`을 설치합니다:
+```
+pip install fastapi
+```
- ```
- pip install uvicorn
- ```
+추가로 서버 역할을 하는 `uvicorn`을 설치합니다:
- 사용하려는 각 선택적인 의존성에 대해서도 동일합니다.
+```
+pip install uvicorn
+```
+
+사용하려는 각 선택적인 의존성에 대해서도 동일합니다.
+
+///
## 고급 사용자 안내서
diff --git a/docs/ko/docs/tutorial/middleware.md b/docs/ko/docs/tutorial/middleware.md
index f35b446a6..f36f11a27 100644
--- a/docs/ko/docs/tutorial/middleware.md
+++ b/docs/ko/docs/tutorial/middleware.md
@@ -11,10 +11,13 @@
* **응답** 또는 다른 필요한 코드를 실행시키는 동작을 할 수 있습니다.
* **응답**를 반환합니다.
-!!! note "기술 세부사항"
- 만약 `yield`를 사용한 의존성을 가지고 있다면, 미들웨어가 실행되고 난 후에 exit이 실행됩니다.
+/// note | "기술 세부사항"
- 만약 (나중에 문서에서 다룰) 백그라운드 작업이 있다면, 모든 미들웨어가 실행되고 *난 후에* 실행됩니다.
+만약 `yield`를 사용한 의존성을 가지고 있다면, 미들웨어가 실행되고 난 후에 exit이 실행됩니다.
+
+만약 (나중에 문서에서 다룰) 백그라운드 작업이 있다면, 모든 미들웨어가 실행되고 *난 후에* 실행됩니다.
+
+///
## 미들웨어 만들기
@@ -29,18 +32,24 @@
* `response`를 반환하기 전에 추가로 `response`를 수정할 수 있습니다.
```Python hl_lines="8-9 11 14"
-{!../../../docs_src/middleware/tutorial001.py!}
+{!../../docs_src/middleware/tutorial001.py!}
```
-!!! tip "팁"
- 사용자 정의 헤더는 'X-' 접두사를 사용하여 추가할 수 있습니다.
+/// tip | "팁"
- 그러나 만약 클라이언트의 브라우저에서 볼 수 있는 사용자 정의 헤더를 가지고 있다면, 그것들을 CORS 설정([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank})에 Starlette CORS 문서에 명시된 `expose_headers` 매개변수를 이용하여 헤더들을 추가하여야합니다.
+사용자 정의 헤더는 'X-' 접두사를 사용하여 추가할 수 있습니다.
-!!! note "기술적 세부사항"
- `from starlette.requests import request`를 사용할 수도 있습니다.
+그러나 만약 클라이언트의 브라우저에서 볼 수 있는 사용자 정의 헤더를 가지고 있다면, 그것들을 CORS 설정([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank})에 Starlette CORS 문서에 명시된 `expose_headers` 매개변수를 이용하여 헤더들을 추가하여야합니다.
- **FastAPI**는 개발자에게 편의를 위해 이를 제공합니다. 그러나 Starlette에서 직접 파생되었습니다.
+///
+
+/// note | "기술적 세부사항"
+
+`from starlette.requests import request`를 사용할 수도 있습니다.
+
+**FastAPI**는 개발자에게 편의를 위해 이를 제공합니다. 그러나 Starlette에서 직접 파생되었습니다.
+
+///
### `response`의 전과 후
@@ -51,7 +60,7 @@
예를 들어, 요청을 수행하고 응답을 생성하는데 까지 걸린 시간 값을 가지고 있는 `X-Process-Time` 같은 사용자 정의 헤더를 추가할 수 있습니다.
```Python hl_lines="10 12-13"
-{!../../../docs_src/middleware/tutorial001.py!}
+{!../../docs_src/middleware/tutorial001.py!}
```
## 다른 미들웨어
diff --git a/docs/ko/docs/tutorial/path-operation-configuration.md b/docs/ko/docs/tutorial/path-operation-configuration.md
index 411c43493..6ebe613a8 100644
--- a/docs/ko/docs/tutorial/path-operation-configuration.md
+++ b/docs/ko/docs/tutorial/path-operation-configuration.md
@@ -2,8 +2,11 @@
*경로 작동 데코레이터*를 설정하기 위해서 전달할수 있는 몇 가지 매개변수가 있습니다.
-!!! warning "경고"
- 아래 매개변수들은 *경로 작동 함수*가 아닌 *경로 작동 데코레이터*에 직접 전달된다는 사실을 기억하십시오.
+/// warning | "경고"
+
+아래 매개변수들은 *경로 작동 함수*가 아닌 *경로 작동 데코레이터*에 직접 전달된다는 사실을 기억하십시오.
+
+///
## 응답 상태 코드
@@ -14,22 +17,25 @@
하지만 각 코드의 의미를 모른다면, `status`에 있는 단축 상수들을 사용할수 있습니다:
```Python hl_lines="3 17"
-{!../../../docs_src/path_operation_configuration/tutorial001.py!}
+{!../../docs_src/path_operation_configuration/tutorial001.py!}
```
각 상태 코드들은 응답에 사용되며, OpenAPI 스키마에 추가됩니다.
-!!! note "기술적 세부사항"
- 다음과 같이 임포트하셔도 좋습니다. `from starlette import status`.
+/// note | "기술적 세부사항"
- **FastAPI**는 개발자 여러분의 편의를 위해서 `starlette.status`와 동일한 `fastapi.status`를 제공합니다. 하지만 Starlette에서 직접 온 것입니다.
+다음과 같이 임포트하셔도 좋습니다. `from starlette import status`.
+
+**FastAPI**는 개발자 여러분의 편의를 위해서 `starlette.status`와 동일한 `fastapi.status`를 제공합니다. 하지만 Starlette에서 직접 온 것입니다.
+
+///
## 태그
(보통 단일 `str`인) `str`로 구성된 `list`와 함께 매개변수 `tags`를 전달하여, `경로 작동`에 태그를 추가할 수 있습니다:
```Python hl_lines="17 22 27"
-{!../../../docs_src/path_operation_configuration/tutorial002.py!}
+{!../../docs_src/path_operation_configuration/tutorial002.py!}
```
전달된 태그들은 OpenAPI의 스키마에 추가되며, 자동 문서 인터페이스에서 사용됩니다:
@@ -41,7 +47,7 @@
`summary`와 `description`을 추가할 수 있습니다:
```Python hl_lines="20-21"
-{!../../../docs_src/path_operation_configuration/tutorial003.py!}
+{!../../docs_src/path_operation_configuration/tutorial003.py!}
```
## 독스트링으로 만든 기술
@@ -51,7 +57,7 @@
마크다운 문법으로 독스트링을 작성할 수 있습니다, 작성된 마크다운 형식의 독스트링은 (마크다운의 들여쓰기를 고려하여) 올바르게 화면에 출력됩니다.
```Python hl_lines="19-27"
-{!../../../docs_src/path_operation_configuration/tutorial004.py!}
+{!../../docs_src/path_operation_configuration/tutorial004.py!}
```
이는 대화형 문서에서 사용됩니다:
@@ -63,16 +69,22 @@
`response_description` 매개변수로 응답에 관한 설명을 명시할 수 있습니다:
```Python hl_lines="21"
-{!../../../docs_src/path_operation_configuration/tutorial005.py!}
+{!../../docs_src/path_operation_configuration/tutorial005.py!}
```
-!!! info "정보"
- `response_description`은 구체적으로 응답을 지칭하며, `description`은 일반적인 *경로 작동*을 지칭합니다.
+/// info | "정보"
-!!! check "확인"
- OpenAPI는 각 *경로 작동*이 응답에 관한 설명을 요구할 것을 명시합니다.
+`response_description`은 구체적으로 응답을 지칭하며, `description`은 일반적인 *경로 작동*을 지칭합니다.
- 따라서, 응답에 관한 설명이 없을경우, **FastAPI**가 자동으로 "성공 응답" 중 하나를 생성합니다.
+///
+
+/// check | "확인"
+
+OpenAPI는 각 *경로 작동*이 응답에 관한 설명을 요구할 것을 명시합니다.
+
+따라서, 응답에 관한 설명이 없을경우, **FastAPI**가 자동으로 "성공 응답" 중 하나를 생성합니다.
+
+///
@@ -81,7 +93,7 @@
단일 *경로 작동*을 없애지 않고 지원중단을 해야한다면, `deprecated` 매개변수를 전달하면 됩니다.
```Python hl_lines="16"
-{!../../../docs_src/path_operation_configuration/tutorial006.py!}
+{!../../docs_src/path_operation_configuration/tutorial006.py!}
```
대화형 문서에 지원중단이라고 표시됩니다.
diff --git a/docs/ko/docs/tutorial/path-params-numeric-validations.md b/docs/ko/docs/tutorial/path-params-numeric-validations.md
index cadf543fc..caab2d453 100644
--- a/docs/ko/docs/tutorial/path-params-numeric-validations.md
+++ b/docs/ko/docs/tutorial/path-params-numeric-validations.md
@@ -7,7 +7,7 @@
먼저 `fastapi`에서 `Path`를 임포트합니다:
```Python hl_lines="3"
-{!../../../docs_src/path_params_numeric_validations/tutorial001.py!}
+{!../../docs_src/path_params_numeric_validations/tutorial001.py!}
```
## 메타데이터 선언
@@ -17,15 +17,18 @@
예를 들어, `title` 메타데이터 값을 경로 매개변수 `item_id`에 선언하려면 다음과 같이 입력할 수 있습니다:
```Python hl_lines="10"
-{!../../../docs_src/path_params_numeric_validations/tutorial001.py!}
+{!../../docs_src/path_params_numeric_validations/tutorial001.py!}
```
-!!! note "참고"
- 경로 매개변수는 경로의 일부여야 하므로 언제나 필수적입니다.
+/// note | "참고"
- 즉, `...`로 선언해서 필수임을 나타내는게 좋습니다.
+경로 매개변수는 경로의 일부여야 하므로 언제나 필수적입니다.
- 그럼에도 `None`으로 선언하거나 기본값을 지정할지라도 아무 영향을 끼치지 않으며 언제나 필수입니다.
+즉, `...`로 선언해서 필수임을 나타내는게 좋습니다.
+
+그럼에도 `None`으로 선언하거나 기본값을 지정할지라도 아무 영향을 끼치지 않으며 언제나 필수입니다.
+
+///
## 필요한 경우 매개변수 정렬하기
@@ -44,7 +47,7 @@
따라서 함수를 다음과 같이 선언 할 수 있습니다:
```Python hl_lines="7"
-{!../../../docs_src/path_params_numeric_validations/tutorial002.py!}
+{!../../docs_src/path_params_numeric_validations/tutorial002.py!}
```
## 필요한 경우 매개변수 정렬하기, 트릭
@@ -56,7 +59,7 @@
파이썬은 `*`으로 아무런 행동도 하지 않지만, 따르는 매개변수들은 kwargs로도 알려진 키워드 인자(키-값 쌍)여야 함을 인지합니다. 기본값을 가지고 있지 않더라도 그렇습니다.
```Python hl_lines="7"
-{!../../../docs_src/path_params_numeric_validations/tutorial003.py!}
+{!../../docs_src/path_params_numeric_validations/tutorial003.py!}
```
## 숫자 검증: 크거나 같음
@@ -66,7 +69,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!}
```
## 숫자 검증: 크거나 같음 및 작거나 같음
@@ -77,7 +80,7 @@
* `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!}
```
## 숫자 검증: 부동소수, 크거나 및 작거나
@@ -91,7 +94,7 @@
lt 역시 마찬가지입니다.
```Python hl_lines="11"
-{!../../../docs_src/path_params_numeric_validations/tutorial006.py!}
+{!../../docs_src/path_params_numeric_validations/tutorial006.py!}
```
## 요약
@@ -105,18 +108,24 @@
* `lt`: 작거나(`l`ess `t`han)
* `le`: 작거나 같은(`l`ess than or `e`qual)
-!!! info "정보"
- `Query`, `Path`, 그리고 나중에게 보게될 것들은 (여러분이 사용할 필요가 없는) 공통 `Param` 클래스의 서브 클래스입니다.
+/// info | "정보"
- 그리고 이들 모두는 여태까지 본 추가 검증과 메타데이터의 동일한 모든 매개변수를 공유합니다.
+`Query`, `Path`, 그리고 나중에게 보게될 것들은 (여러분이 사용할 필요가 없는) 공통 `Param` 클래스의 서브 클래스입니다.
-!!! note "기술 세부사항"
- `fastapi`에서 `Query`, `Path` 등을 임포트 할 때, 이것들은 실제로 함수입니다.
+그리고 이들 모두는 여태까지 본 추가 검증과 메타데이터의 동일한 모든 매개변수를 공유합니다.
- 호출되면 동일한 이름의 클래스의 인스턴스를 반환합니다.
+///
- 즉, 함수인 `Query`를 임포트한 겁니다. 그리고 호출하면 `Query`라는 이름을 가진 클래스의 인스턴스를 반환합니다.
+/// note | "기술 세부사항"
- 편집기에서 타입에 대한 오류를 표시하지 않도록 하기 위해 (클래스를 직접 사용하는 대신) 이러한 함수들이 있습니다.
+`fastapi`에서 `Query`, `Path` 등을 임포트 할 때, 이것들은 실제로 함수입니다.
- 이렇게 하면 오류를 무시하기 위한 사용자 설정을 추가하지 않고도 일반 편집기와 코딩 도구를 사용할 수 있습니다.
+호출되면 동일한 이름의 클래스의 인스턴스를 반환합니다.
+
+즉, 함수인 `Query`를 임포트한 겁니다. 그리고 호출하면 `Query`라는 이름을 가진 클래스의 인스턴스를 반환합니다.
+
+편집기에서 타입에 대한 오류를 표시하지 않도록 하기 위해 (클래스를 직접 사용하는 대신) 이러한 함수들이 있습니다.
+
+이렇게 하면 오류를 무시하기 위한 사용자 설정을 추가하지 않고도 일반 편집기와 코딩 도구를 사용할 수 있습니다.
+
+///
diff --git a/docs/ko/docs/tutorial/path-params.md b/docs/ko/docs/tutorial/path-params.md
index a75c3cc8c..09a27a7b3 100644
--- a/docs/ko/docs/tutorial/path-params.md
+++ b/docs/ko/docs/tutorial/path-params.md
@@ -3,7 +3,7 @@
파이썬의 포맷 문자열 리터럴에서 사용되는 문법을 이용하여 경로 "매개변수" 또는 "변수"를 선언할 수 있습니다:
```Python hl_lines="6-7"
-{!../../../docs_src/path_params/tutorial001.py!}
+{!../../docs_src/path_params/tutorial001.py!}
```
경로 매개변수 `item_id`의 값은 함수의 `item_id` 인자로 전달됩니다.
@@ -19,13 +19,16 @@
파이썬 표준 타입 어노테이션을 사용하여 함수에 있는 경로 매개변수의 타입을 선언할 수 있습니다:
```Python hl_lines="7"
-{!../../../docs_src/path_params/tutorial002.py!}
+{!../../docs_src/path_params/tutorial002.py!}
```
위의 예시에서, `item_id`는 `int`로 선언되었습니다.
-!!! check "확인"
- 이 기능은 함수 내에서 오류 검사, 자동완성 등의 편집기 기능을 활용할 수 있게 해줍니다.
+/// check | "확인"
+
+이 기능은 함수 내에서 오류 검사, 자동완성 등의 편집기 기능을 활용할 수 있게 해줍니다.
+
+///
## 데이터 변환
@@ -35,10 +38,13 @@
{"item_id":3}
```
-!!! check "확인"
- 함수가 받은(반환도 하는) 값은 문자열 `"3"`이 아니라 파이썬 `int` 형인 `3`입니다.
+/// check | "확인"
- 즉, 타입 선언을 하면 **FastAPI**는 자동으로 요청을 "파싱"합니다.
+함수가 받은(반환도 하는) 값은 문자열 `"3"`이 아니라 파이썬 `int` 형인 `3`입니다.
+
+즉, 타입 선언을 하면 **FastAPI**는 자동으로 요청을 "파싱"합니다.
+
+///
## 데이터 검증
@@ -63,12 +69,15 @@
`int`가 아닌 `float`을 전달하는 경우에도 동일한 오류가 나타납니다: http://127.0.0.1:8000/items/4.2
-!!! check "확인"
- 즉, 파이썬 타입 선언을 하면 **FastAPI**는 데이터 검증을 합니다.
+/// check | "확인"
- 오류에는 정확히 어느 지점에서 검증을 통과하지 못했는지 명시됩니다.
+즉, 파이썬 타입 선언을 하면 **FastAPI**는 데이터 검증을 합니다.
- 이는 API와 상호 작용하는 코드를 개발하고 디버깅하는 데 매우 유용합니다.
+오류에는 정확히 어느 지점에서 검증을 통과하지 못했는지 명시됩니다.
+
+이는 API와 상호 작용하는 코드를 개발하고 디버깅하는 데 매우 유용합니다.
+
+///
## 문서화
@@ -76,10 +85,13 @@
-!!! check "확인"
- 그저 파이썬 타입 선언을 하기만 하면 **FastAPI**는 자동 대화형 API 문서(Swagger UI)를 제공합니다.
+/// check | "확인"
- 경로 매개변수가 정수형으로 명시된 것을 확인할 수 있습니다.
+그저 파이썬 타입 선언을 하기만 하면 **FastAPI**는 자동 대화형 API 문서(Swagger UI)를 제공합니다.
+
+경로 매개변수가 정수형으로 명시된 것을 확인할 수 있습니다.
+
+///
## 표준 기반의 이점, 대체 문서
@@ -110,7 +122,7 @@
*경로 작동*은 순차적으로 실행되기 때문에 `/users/{user_id}` 이전에 `/users/me`를 먼저 선언해야 합니다:
```Python hl_lines="6 11"
-{!../../../docs_src/path_params/tutorial003.py!}
+{!../../docs_src/path_params/tutorial003.py!}
```
그렇지 않으면 `/users/{user_id}`는 `/users/me` 요청 또한 매개변수 `user_id`의 값이 `"me"`인 것으로 "생각하게" 됩니다.
@@ -128,21 +140,27 @@
가능한 값들에 해당하는 고정된 값의 클래스 어트리뷰트들을 만듭니다:
```Python hl_lines="1 6-9"
-{!../../../docs_src/path_params/tutorial005.py!}
+{!../../docs_src/path_params/tutorial005.py!}
```
-!!! info "정보"
- 열거형(또는 enums)은 파이썬 버전 3.4 이후로 사용 가능합니다.
+/// info | "정보"
-!!! tip "팁"
- 혹시 궁금하다면, "AlexNet", "ResNet", 그리고 "LeNet"은 그저 기계 학습 모델들의 이름입니다.
+열거형(또는 enums)은 파이썬 버전 3.4 이후로 사용 가능합니다.
+
+///
+
+/// tip | "팁"
+
+혹시 궁금하다면, "AlexNet", "ResNet", 그리고 "LeNet"은 그저 기계 학습 모델들의 이름입니다.
+
+///
### *경로 매개변수* 선언
생성한 열거형 클래스(`ModelName`)를 사용하는 타입 어노테이션으로 *경로 매개변수*를 만듭니다:
```Python hl_lines="16"
-{!../../../docs_src/path_params/tutorial005.py!}
+{!../../docs_src/path_params/tutorial005.py!}
```
### 문서 확인
@@ -160,7 +178,7 @@
열거형 `ModelName`의 *열거형 멤버*를 비교할 수 있습니다:
```Python hl_lines="17"
-{!../../../docs_src/path_params/tutorial005.py!}
+{!../../docs_src/path_params/tutorial005.py!}
```
#### *열거형 값* 가져오기
@@ -168,11 +186,14 @@
`model_name.value` 또는 일반적으로 `your_enum_member.value`를 이용하여 실제 값(위 예시의 경우 `str`)을 가져올 수 있습니다:
```Python hl_lines="20"
-{!../../../docs_src/path_params/tutorial005.py!}
+{!../../docs_src/path_params/tutorial005.py!}
```
-!!! tip "팁"
- `ModelName.lenet.value`로도 값 `"lenet"`에 접근할 수 있습니다.
+/// tip | "팁"
+
+`ModelName.lenet.value`로도 값 `"lenet"`에 접근할 수 있습니다.
+
+///
#### *열거형 멤버* 반환
@@ -181,7 +202,7 @@
클라이언트에 반환하기 전에 해당 값(이 경우 문자열)으로 변환됩니다:
```Python hl_lines="18 21 23"
-{!../../../docs_src/path_params/tutorial005.py!}
+{!../../docs_src/path_params/tutorial005.py!}
```
클라이언트는 아래의 JSON 응답을 얻습니다:
@@ -222,13 +243,16 @@ Starlette의 옵션을 직접 이용하여 다음과 같은 URL을 사용함으
따라서 다음과 같이 사용할 수 있습니다:
```Python hl_lines="6"
-{!../../../docs_src/path_params/tutorial004.py!}
+{!../../docs_src/path_params/tutorial004.py!}
```
-!!! tip "팁"
- 매개변수가 가져야 하는 값이 `/home/johndoe/myfile.txt`와 같이 슬래시로 시작(`/`)해야 할 수 있습니다.
+/// tip | "팁"
- 이 경우 URL은: `/files//home/johndoe/myfile.txt`이며 `files`과 `home` 사이에 이중 슬래시(`//`)가 생깁니다.
+매개변수가 가져야 하는 값이 `/home/johndoe/myfile.txt`와 같이 슬래시로 시작(`/`)해야 할 수 있습니다.
+
+이 경우 URL은: `/files//home/johndoe/myfile.txt`이며 `files`과 `home` 사이에 이중 슬래시(`//`)가 생깁니다.
+
+///
## 요약
diff --git a/docs/ko/docs/tutorial/query-params-str-validations.md b/docs/ko/docs/tutorial/query-params-str-validations.md
index 2e6396ccc..e44f6dd16 100644
--- a/docs/ko/docs/tutorial/query-params-str-validations.md
+++ b/docs/ko/docs/tutorial/query-params-str-validations.md
@@ -5,15 +5,18 @@
이 응용 프로그램을 예로 들어보겠습니다:
```Python hl_lines="9"
-{!../../../docs_src/query_params_str_validations/tutorial001.py!}
+{!../../docs_src/query_params_str_validations/tutorial001.py!}
```
쿼리 매개변수 `q`는 `Optional[str]` 자료형입니다. 즉, `str` 자료형이지만 `None` 역시 될 수 있음을 뜻하고, 실제로 기본값은 `None`이기 때문에 FastAPI는 이 매개변수가 필수가 아니라는 것을 압니다.
-!!! note "참고"
- FastAPI는 `q`의 기본값이 `= None`이기 때문에 필수가 아님을 압니다.
+/// note | "참고"
- `Optional[str]`에 있는 `Optional`은 FastAPI가 사용하는게 아니지만, 편집기에게 더 나은 지원과 오류 탐지를 제공하게 해줍니다.
+FastAPI는 `q`의 기본값이 `= None`이기 때문에 필수가 아님을 압니다.
+
+`Optional[str]`에 있는 `Optional`은 FastAPI가 사용하는게 아니지만, 편집기에게 더 나은 지원과 오류 탐지를 제공하게 해줍니다.
+
+///
## 추가 검증
@@ -24,7 +27,7 @@
이를 위해 먼저 `fastapi`에서 `Query`를 임포트합니다:
```Python hl_lines="3"
-{!../../../docs_src/query_params_str_validations/tutorial002.py!}
+{!../../docs_src/query_params_str_validations/tutorial002.py!}
```
## 기본값으로 `Query` 사용
@@ -32,7 +35,7 @@
이제 `Query`를 매개변수의 기본값으로 사용하여 `max_length` 매개변수를 50으로 설정합니다:
```Python hl_lines="9"
-{!../../../docs_src/query_params_str_validations/tutorial002.py!}
+{!../../docs_src/query_params_str_validations/tutorial002.py!}
```
기본값 `None`을 `Query(None)`으로 바꿔야 하므로, `Query`의 첫 번째 매개변수는 기본값을 정의하는 것과 같은 목적으로 사용됩니다.
@@ -51,22 +54,25 @@ q: Optional[str] = None
하지만 명시적으로 쿼리 매개변수를 선언합니다.
-!!! info "정보"
- FastAPI는 다음 부분에 관심이 있습니다:
+/// info | "정보"
- ```Python
- = None
- ```
+FastAPI는 다음 부분에 관심이 있습니다:
- 또는:
+```Python
+= None
+```
- ```Python
- = Query(None)
- ```
+또는:
- 그리고 `None`을 사용하여 쿼라 매개변수가 필수적이지 않다는 것을 파악합니다.
+```Python
+= Query(None)
+```
- `Optional` 부분은 편집기에게 더 나은 지원을 제공하기 위해서만 사용됩니다.
+그리고 `None`을 사용하여 쿼라 매개변수가 필수적이지 않다는 것을 파악합니다.
+
+`Optional` 부분은 편집기에게 더 나은 지원을 제공하기 위해서만 사용됩니다.
+
+///
또한 `Query`로 더 많은 매개변수를 전달할 수 있습니다. 지금의 경우 문자열에 적용되는 `max_length` 매개변수입니다:
@@ -81,7 +87,7 @@ 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!}
```
## 정규식 추가
@@ -89,7 +95,7 @@ q: str = Query(None, max_length=50)
매개변수와 일치해야 하는 정규표현식을 정의할 수 있습니다:
```Python hl_lines="10"
-{!../../../docs_src/query_params_str_validations/tutorial004.py!}
+{!../../docs_src/query_params_str_validations/tutorial004.py!}
```
이 특정 정규표현식은 전달 받은 매개변수 값을 검사합니다:
@@ -109,11 +115,14 @@ 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!}
```
-!!! note "참고"
- 기본값을 갖는 것만으로 매개변수는 선택적이 됩니다.
+/// note | "참고"
+
+기본값을 갖는 것만으로 매개변수는 선택적이 됩니다.
+
+///
## 필수로 만들기
@@ -138,11 +147,14 @@ 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!}
```
-!!! info "정보"
- 이전에 `...`를 본적이 없다면: 특별한 단일값으로, 파이썬의 일부이며 "Ellipsis"라 부릅니다.
+/// info | "정보"
+
+이전에 `...`를 본적이 없다면: 특별한 단일값으로, 파이썬의 일부이며 "Ellipsis"라 부릅니다.
+
+///
이렇게 하면 **FastAPI**가 이 매개변수는 필수임을 알 수 있습니다.
@@ -153,7 +165,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!}
```
아래와 같은 URL을 사용합니다:
@@ -175,8 +187,11 @@ http://localhost:8000/items/?q=foo&q=bar
}
```
-!!! tip "팁"
- 위의 예와 같이 `list` 자료형으로 쿼리 매개변수를 선언하려면 `Query`를 명시적으로 사용해야 합니다. 그렇지 않으면 요청 본문으로 해석됩니다.
+/// tip | "팁"
+
+위의 예와 같이 `list` 자료형으로 쿼리 매개변수를 선언하려면 `Query`를 명시적으로 사용해야 합니다. 그렇지 않으면 요청 본문으로 해석됩니다.
+
+///
대화형 API 문서는 여러 값을 허용하도록 수정 됩니다:
@@ -187,7 +202,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!}
```
아래로 이동한다면:
@@ -212,13 +227,16 @@ 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!}
```
-!!! note "참고"
- 이 경우 FastAPI는 리스트의 내용을 검사하지 않음을 명심하기 바랍니다.
+/// note | "참고"
- 예를 들어, `List[int]`는 리스트 내용이 정수인지 검사(및 문서화)합니다. 하지만 `list` 단독일 경우는 아닙니다.
+이 경우 FastAPI는 리스트의 내용을 검사하지 않음을 명심하기 바랍니다.
+
+예를 들어, `List[int]`는 리스트 내용이 정수인지 검사(및 문서화)합니다. 하지만 `list` 단독일 경우는 아닙니다.
+
+///
## 더 많은 메타데이터 선언
@@ -226,21 +244,24 @@ http://localhost:8000/items/
해당 정보는 생성된 OpenAPI에 포함되고 문서 사용자 인터페이스 및 외부 도구에서 사용됩니다.
-!!! note "참고"
- 도구에 따라 OpenAPI 지원 수준이 다를 수 있음을 명심하기 바랍니다.
+/// note | "참고"
- 일부는 아직 선언된 추가 정보를 모두 표시하지 않을 수 있지만, 대부분의 경우 누락된 기능은 이미 개발 계획이 있습니다.
+도구에 따라 OpenAPI 지원 수준이 다를 수 있음을 명심하기 바랍니다.
+
+일부는 아직 선언된 추가 정보를 모두 표시하지 않을 수 있지만, 대부분의 경우 누락된 기능은 이미 개발 계획이 있습니다.
+
+///
`title`을 추가할 수 있습니다:
```Python hl_lines="10"
-{!../../../docs_src/query_params_str_validations/tutorial007.py!}
+{!../../docs_src/query_params_str_validations/tutorial007.py!}
```
그리고 `description`도 추가할 수 있습니다:
```Python hl_lines="13"
-{!../../../docs_src/query_params_str_validations/tutorial008.py!}
+{!../../docs_src/query_params_str_validations/tutorial008.py!}
```
## 별칭 매개변수
@@ -262,7 +283,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!}
```
## 매개변수 사용하지 않게 하기
@@ -274,7 +295,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!}
```
문서가 아래와 같이 보일겁니다:
diff --git a/docs/ko/docs/tutorial/query-params.md b/docs/ko/docs/tutorial/query-params.md
index 43a6c1a36..b2a946c09 100644
--- a/docs/ko/docs/tutorial/query-params.md
+++ b/docs/ko/docs/tutorial/query-params.md
@@ -3,7 +3,7 @@
경로 매개변수의 일부가 아닌 다른 함수 매개변수를 선언하면 "쿼리" 매개변수로 자동 해석합니다.
```Python hl_lines="9"
-{!../../../docs_src/query_params/tutorial001.py!}
+{!../../docs_src/query_params/tutorial001.py!}
```
쿼리는 URL에서 `?` 후에 나오고 `&`으로 구분되는 키-값 쌍의 집합입니다.
@@ -64,25 +64,31 @@ 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!}
```
이 경우 함수 매개변수 `q`는 선택적이며 기본값으로 `None` 값이 됩니다.
-!!! check "확인"
- **FastAPI**는 `item_id`가 경로 매개변수이고 `q`는 경로 매개변수가 아닌 쿼리 매개변수라는 것을 알 정도로 충분히 똑똑합니다.
+/// check | "확인"
-!!! note "참고"
- FastAPI는 `q`가 `= None`이므로 선택적이라는 것을 인지합니다.
+**FastAPI**는 `item_id`가 경로 매개변수이고 `q`는 경로 매개변수가 아닌 쿼리 매개변수라는 것을 알 정도로 충분히 똑똑합니다.
- `Union[str, None]`에 있는 `Union`은 FastAPI(FastAPI는 `str` 부분만 사용합니다)가 사용하는게 아니지만, `Union[str, None]`은 편집기에게 코드에서 오류를 찾아낼 수 있게 도와줍니다.
+///
+
+/// note | "참고"
+
+FastAPI는 `q`가 `= None`이므로 선택적이라는 것을 인지합니다.
+
+`Union[str, None]`에 있는 `Union`은 FastAPI(FastAPI는 `str` 부분만 사용합니다)가 사용하는게 아니지만, `Union[str, None]`은 편집기에게 코드에서 오류를 찾아낼 수 있게 도와줍니다.
+
+///
## 쿼리 매개변수 형변환
`bool` 형으로 선언할 수도 있고, 아래처럼 변환됩니다:
```Python hl_lines="9"
-{!../../../docs_src/query_params/tutorial003.py!}
+{!../../docs_src/query_params/tutorial003.py!}
```
이 경우, 아래로 이동하면:
@@ -127,7 +133,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!}
```
## 필수 쿼리 매개변수
@@ -139,7 +145,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!}
```
여기 쿼리 매개변수 `needy`는 `str`형인 필수 쿼리 매개변수입니다.
@@ -185,7 +191,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!}
```
위 예시에서는 3가지 쿼리 매개변수가 있습니다:
@@ -194,5 +200,8 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
* `skip`, 기본값이 `0`인 `int`.
* `limit`, 선택적인 `int`.
-!!! tip "팁"
- [경로 매개변수](path-params.md#_8){.internal-link target=_blank}와 마찬가지로 `Enum`을 사용할 수 있습니다.
+/// tip | "팁"
+
+[경로 매개변수](path-params.md#_8){.internal-link target=_blank}와 마찬가지로 `Enum`을 사용할 수 있습니다.
+
+///
diff --git a/docs/ko/docs/tutorial/request-files.md b/docs/ko/docs/tutorial/request-files.md
index 468c46283..40579dd51 100644
--- a/docs/ko/docs/tutorial/request-files.md
+++ b/docs/ko/docs/tutorial/request-files.md
@@ -2,19 +2,22 @@
`File`을 사용하여 클라이언트가 업로드할 파일들을 정의할 수 있습니다.
-!!! info "정보"
- 업로드된 파일을 전달받기 위해 먼저 `python-multipart`를 설치해야합니다.
+/// info | "정보"
- 예시) `pip install python-multipart`.
+업로드된 파일을 전달받기 위해 먼저 `python-multipart`를 설치해야합니다.
- 업로드된 파일들은 "폼 데이터"의 형태로 전송되기 때문에 이 작업이 필요합니다.
+예시) `pip install python-multipart`.
+
+업로드된 파일들은 "폼 데이터"의 형태로 전송되기 때문에 이 작업이 필요합니다.
+
+///
## `File` 임포트
`fastapi` 에서 `File` 과 `UploadFile` 을 임포트 합니다:
```Python hl_lines="1"
-{!../../../docs_src/request_files/tutorial001.py!}
+{!../../docs_src/request_files/tutorial001.py!}
```
## `File` 매개변수 정의
@@ -22,16 +25,22 @@
`Body` 및 `Form` 과 동일한 방식으로 파일의 매개변수를 생성합니다:
```Python hl_lines="7"
-{!../../../docs_src/request_files/tutorial001.py!}
+{!../../docs_src/request_files/tutorial001.py!}
```
-!!! info "정보"
- `File` 은 `Form` 으로부터 직접 상속된 클래스입니다.
+/// info | "정보"
- 하지만 `fastapi`로부터 `Query`, `Path`, `File` 등을 임포트 할 때, 이것들은 특별한 클래스들을 반환하는 함수라는 것을 기억하기 바랍니다.
+`File` 은 `Form` 으로부터 직접 상속된 클래스입니다.
-!!! tip "팁"
- File의 본문을 선언할 때, 매개변수가 쿼리 매개변수 또는 본문(JSON) 매개변수로 해석되는 것을 방지하기 위해 `File` 을 사용해야합니다.
+하지만 `fastapi`로부터 `Query`, `Path`, `File` 등을 임포트 할 때, 이것들은 특별한 클래스들을 반환하는 함수라는 것을 기억하기 바랍니다.
+
+///
+
+/// tip | "팁"
+
+File의 본문을 선언할 때, 매개변수가 쿼리 매개변수 또는 본문(JSON) 매개변수로 해석되는 것을 방지하기 위해 `File` 을 사용해야합니다.
+
+///
파일들은 "폼 데이터"의 형태로 업로드 됩니다.
@@ -46,7 +55,7 @@
`File` 매개변수를 `UploadFile` 타입으로 정의합니다:
```Python hl_lines="12"
-{!../../../docs_src/request_files/tutorial001.py!}
+{!../../docs_src/request_files/tutorial001.py!}
```
`UploadFile` 을 사용하는 것은 `bytes` 과 비교해 다음과 같은 장점이 있습니다:
@@ -89,11 +98,17 @@ contents = await myfile.read()
contents = myfile.file.read()
```
-!!! note "`async` 기술적 세부사항"
- `async` 메소드들을 사용할 때 **FastAPI**는 스레드풀에서 파일 메소드들을 실행하고 그들을 기다립니다.
+/// note | "`async` 기술적 세부사항"
-!!! note "Starlette 기술적 세부사항"
- **FastAPI**의 `UploadFile` 은 **Starlette**의 `UploadFile` 을 직접적으로 상속받지만, **Pydantic** 및 FastAPI의 다른 부분들과의 호환성을 위해 필요한 부분들이 추가되었습니다.
+`async` 메소드들을 사용할 때 **FastAPI**는 스레드풀에서 파일 메소드들을 실행하고 그들을 기다립니다.
+
+///
+
+/// note | "Starlette 기술적 세부사항"
+
+**FastAPI**의 `UploadFile` 은 **Starlette**의 `UploadFile` 을 직접적으로 상속받지만, **Pydantic** 및 FastAPI의 다른 부분들과의 호환성을 위해 필요한 부분들이 추가되었습니다.
+
+///
## "폼 데이터"란
@@ -101,17 +116,23 @@ HTML의 폼들(``)이 서버에 데이터를 전송하는 방식은
**FastAPI**는 JSON 대신 올바른 위치에서 데이터를 읽을 수 있도록 합니다.
-!!! note "기술적 세부사항"
- 폼의 데이터는 파일이 포함되지 않은 경우 일반적으로 "미디어 유형" `application/x-www-form-urlencoded` 을 사용해 인코딩 됩니다.
+/// note | "기술적 세부사항"
- 하지만 파일이 포함된 경우, `multipart/form-data`로 인코딩됩니다. `File`을 사용하였다면, **FastAPI**는 본문의 적합한 부분에서 파일을 가져와야 한다는 것을 인지합니다.
+폼의 데이터는 파일이 포함되지 않은 경우 일반적으로 "미디어 유형" `application/x-www-form-urlencoded` 을 사용해 인코딩 됩니다.
- 인코딩과 폼 필드에 대해 더 알고싶다면, POST에 관한MDN웹 문서 를 참고하기 바랍니다,.
+하지만 파일이 포함된 경우, `multipart/form-data`로 인코딩됩니다. `File`을 사용하였다면, **FastAPI**는 본문의 적합한 부분에서 파일을 가져와야 한다는 것을 인지합니다.
-!!! warning "경고"
- 다수의 `File` 과 `Form` 매개변수를 한 *경로 작동*에 선언하는 것이 가능하지만, 요청의 본문이 `application/json` 가 아닌 `multipart/form-data` 로 인코딩 되기 때문에 JSON으로 받아야하는 `Body` 필드를 함께 선언할 수는 없습니다.
+인코딩과 폼 필드에 대해 더 알고싶다면, POST에 관한MDN웹 문서 를 참고하기 바랍니다,.
- 이는 **FastAPI**의 한계가 아니라, HTTP 프로토콜에 의한 것입니다.
+///
+
+/// warning | "경고"
+
+다수의 `File` 과 `Form` 매개변수를 한 *경로 작동*에 선언하는 것이 가능하지만, 요청의 본문이 `application/json` 가 아닌 `multipart/form-data` 로 인코딩 되기 때문에 JSON으로 받아야하는 `Body` 필드를 함께 선언할 수는 없습니다.
+
+이는 **FastAPI**의 한계가 아니라, HTTP 프로토콜에 의한 것입니다.
+
+///
## 다중 파일 업로드
@@ -122,22 +143,28 @@ HTML의 폼들(``)이 서버에 데이터를 전송하는 방식은
이 기능을 사용하기 위해 , `bytes` 의 `List` 또는 `UploadFile` 를 선언하기 바랍니다:
```Python hl_lines="10 15"
-{!../../../docs_src/request_files/tutorial002.py!}
+{!../../docs_src/request_files/tutorial002.py!}
```
선언한대로, `bytes` 의 `list` 또는 `UploadFile` 들을 전송받을 것입니다.
-!!! note "참고"
- 2019년 4월 14일부터 Swagger UI가 하나의 폼 필드로 다수의 파일을 업로드하는 것을 지원하지 않습니다. 더 많은 정보를 원하면, #4276과 #3641을 참고하세요.
+/// note | "참고"
- 그럼에도, **FastAPI**는 표준 Open API를 사용해 이미 호환이 가능합니다.
+2019년 4월 14일부터 Swagger UI가 하나의 폼 필드로 다수의 파일을 업로드하는 것을 지원하지 않습니다. 더 많은 정보를 원하면, #4276과 #3641을 참고하세요.
- 따라서 Swagger UI 또는 기타 그 외의 OpenAPI를 지원하는 툴이 다중 파일 업로드를 지원하는 경우, 이들은 **FastAPI**와 호환됩니다.
+그럼에도, **FastAPI**는 표준 Open API를 사용해 이미 호환이 가능합니다.
-!!! note "기술적 세부사항"
- `from starlette.responses import HTMLResponse` 역시 사용할 수 있습니다.
+따라서 Swagger UI 또는 기타 그 외의 OpenAPI를 지원하는 툴이 다중 파일 업로드를 지원하는 경우, 이들은 **FastAPI**와 호환됩니다.
- **FastAPI**는 개발자의 편의를 위해 `fastapi.responses` 와 동일한 `starlette.responses` 도 제공합니다. 하지만 대부분의 응답들은 Starlette로부터 직접 제공됩니다.
+///
+
+/// note | "기술적 세부사항"
+
+`from starlette.responses import HTMLResponse` 역시 사용할 수 있습니다.
+
+**FastAPI**는 개발자의 편의를 위해 `fastapi.responses` 와 동일한 `starlette.responses` 도 제공합니다. 하지만 대부분의 응답들은 Starlette로부터 직접 제공됩니다.
+
+///
## 요약
diff --git a/docs/ko/docs/tutorial/request-forms-and-files.md b/docs/ko/docs/tutorial/request-forms-and-files.md
index bd5f41918..24501fe34 100644
--- a/docs/ko/docs/tutorial/request-forms-and-files.md
+++ b/docs/ko/docs/tutorial/request-forms-and-files.md
@@ -2,15 +2,18 @@
`File` 과 `Form` 을 사용하여 파일과 폼을 함께 정의할 수 있습니다.
-!!! info "정보"
- 파일과 폼 데이터를 함께, 또는 각각 업로드하기 위해 먼저 `python-multipart`를 설치해야합니다.
+/// info | "정보"
- 예 ) `pip install python-multipart`.
+파일과 폼 데이터를 함께, 또는 각각 업로드하기 위해 먼저 `python-multipart`를 설치해야합니다.
+
+예 ) `pip install python-multipart`.
+
+///
## `File` 및 `Form` 업로드
```Python hl_lines="1"
-{!../../../docs_src/request_forms_and_files/tutorial001.py!}
+{!../../docs_src/request_forms_and_files/tutorial001.py!}
```
## `File` 및 `Form` 매개변수 정의
@@ -18,17 +21,20 @@
`Body` 및 `Query`와 동일한 방식으로 파일과 폼의 매개변수를 생성합니다:
```Python hl_lines="8"
-{!../../../docs_src/request_forms_and_files/tutorial001.py!}
+{!../../docs_src/request_forms_and_files/tutorial001.py!}
```
파일과 폼 필드는 폼 데이터 형식으로 업로드되어 파일과 폼 필드로 전달됩니다.
어떤 파일들은 `bytes`로, 또 어떤 파일들은 `UploadFile`로 선언할 수 있습니다.
-!!! warning "경고"
- 다수의 `File`과 `Form` 매개변수를 한 *경로 작동*에 선언하는 것이 가능하지만, 요청의 본문이 `application/json`가 아닌 `multipart/form-data`로 인코딩 되기 때문에 JSON으로 받아야하는 `Body` 필드를 함께 선언할 수는 없습니다.
+/// warning | "경고"
- 이는 **FastAPI**의 한계가 아니라, HTTP 프로토콜에 의한 것입니다.
+다수의 `File`과 `Form` 매개변수를 한 *경로 작동*에 선언하는 것이 가능하지만, 요청의 본문이 `application/json`가 아닌 `multipart/form-data`로 인코딩 되기 때문에 JSON으로 받아야하는 `Body` 필드를 함께 선언할 수는 없습니다.
+
+이는 **FastAPI**의 한계가 아니라, HTTP 프로토콜에 의한 것입니다.
+
+///
## 요약
diff --git a/docs/ko/docs/tutorial/response-model.md b/docs/ko/docs/tutorial/response-model.md
index feff88a42..74034e34d 100644
--- a/docs/ko/docs/tutorial/response-model.md
+++ b/docs/ko/docs/tutorial/response-model.md
@@ -9,11 +9,14 @@
* 기타.
```Python hl_lines="17"
-{!../../../docs_src/response_model/tutorial001.py!}
+{!../../docs_src/response_model/tutorial001.py!}
```
-!!! note "참고"
- `response_model`은 "데코레이터" 메소드(`get`, `post`, 등)의 매개변수입니다. 모든 매개변수들과 본문(body)처럼 *경로 작동 함수*가 아닙니다.
+/// note | "참고"
+
+`response_model`은 "데코레이터" 메소드(`get`, `post`, 등)의 매개변수입니다. 모든 매개변수들과 본문(body)처럼 *경로 작동 함수*가 아닙니다.
+
+///
Pydantic 모델 어트리뷰트를 선언한 것과 동일한 타입을 수신하므로 Pydantic 모델이 될 수 있지만, `List[Item]`과 같이 Pydantic 모델들의 `list`일 수도 있습니다.
@@ -28,21 +31,24 @@ FastAPI는 이 `response_model`를 사용하여:
* 해당 모델의 출력 데이터 제한. 이것이 얼마나 중요한지 아래에서 볼 것입니다.
-!!! note "기술 세부사항"
- 응답 모델은 함수의 타입 어노테이션 대신 이 매개변수로 선언하는데, 경로 함수가 실제 응답 모델을 반환하지 않고 `dict`, 데이터베이스 객체나 기타 다른 모델을 `response_model`을 사용하여 필드 제한과 직렬화를 수행하고 반환할 수 있기 때문입니다
+/// note | "기술 세부사항"
+
+응답 모델은 함수의 타입 어노테이션 대신 이 매개변수로 선언하는데, 경로 함수가 실제 응답 모델을 반환하지 않고 `dict`, 데이터베이스 객체나 기타 다른 모델을 `response_model`을 사용하여 필드 제한과 직렬화를 수행하고 반환할 수 있기 때문입니다
+
+///
## 동일한 입력 데이터 반환
여기서 우리는 평문 비밀번호를 포함하는 `UserIn` 모델을 선언합니다:
```Python hl_lines="9 11"
-{!../../../docs_src/response_model/tutorial002.py!}
+{!../../docs_src/response_model/tutorial002.py!}
```
그리고 이 모델을 사용하여 입력을 선언하고 같은 모델로 출력을 선언합니다:
```Python hl_lines="17-18"
-{!../../../docs_src/response_model/tutorial002.py!}
+{!../../docs_src/response_model/tutorial002.py!}
```
이제 브라우저가 비밀번호로 사용자를 만들 때마다 API는 응답으로 동일한 비밀번호를 반환합니다.
@@ -51,27 +57,30 @@ FastAPI는 이 `response_model`를 사용하여:
그러나 동일한 모델을 다른 *경로 작동*에서 사용할 경우, 모든 클라이언트에게 사용자의 비밀번호를 발신할 수 있습니다.
-!!! danger "위험"
- 절대로 사용자의 평문 비밀번호를 저장하거나 응답으로 발신하지 마십시오.
+/// danger | "위험"
+
+절대로 사용자의 평문 비밀번호를 저장하거나 응답으로 발신하지 마십시오.
+
+///
## 출력 모델 추가
대신 평문 비밀번호로 입력 모델을 만들고 해당 비밀번호 없이 출력 모델을 만들 수 있습니다:
```Python hl_lines="9 11 16"
-{!../../../docs_src/response_model/tutorial003.py!}
+{!../../docs_src/response_model/tutorial003.py!}
```
여기서 *경로 작동 함수*가 비밀번호를 포함하는 동일한 입력 사용자를 반환할지라도:
```Python hl_lines="24"
-{!../../../docs_src/response_model/tutorial003.py!}
+{!../../docs_src/response_model/tutorial003.py!}
```
...`response_model`을 `UserOut` 모델로 선언했기 때문에 비밀번호를 포함하지 않습니다:
```Python hl_lines="22"
-{!../../../docs_src/response_model/tutorial003.py!}
+{!../../docs_src/response_model/tutorial003.py!}
```
따라서 **FastAPI**는 출력 모델에서 선언하지 않은 모든 데이터를 (Pydantic을 사용하여) 필터링합니다.
@@ -91,7 +100,7 @@ FastAPI는 이 `response_model`를 사용하여:
응답 모델은 아래와 같이 기본값을 가질 수 있습니다:
```Python hl_lines="11 13-14"
-{!../../../docs_src/response_model/tutorial004.py!}
+{!../../docs_src/response_model/tutorial004.py!}
```
* `description: Optional[str] = None`은 기본값으로 `None`을 갖습니다.
@@ -107,7 +116,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!}
```
이러한 기본값은 응답에 포함되지 않고 실제로 설정된 값만 포함됩니다.
@@ -121,16 +130,22 @@ FastAPI는 이 `response_model`를 사용하여:
}
```
-!!! info "정보"
- FastAPI는 이를 위해 Pydantic 모델의 `.dict()`의 `exclude_unset` 매개변수를 사용합니다.
+/// info | "정보"
-!!! info "정보"
- 아래 또한 사용할 수 있습니다:
+FastAPI는 이를 위해 Pydantic 모델의 `.dict()`의 `exclude_unset` 매개변수를 사용합니다.
- * `response_model_exclude_defaults=True`
- * `response_model_exclude_none=True`
+///
- Pydantic 문서에서 `exclude_defaults` 및 `exclude_none`에 대해 설명한 대로 사용할 수 있습니다.
+/// info | "정보"
+
+아래 또한 사용할 수 있습니다:
+
+* `response_model_exclude_defaults=True`
+* `response_model_exclude_none=True`
+
+Pydantic 문서에서 `exclude_defaults` 및 `exclude_none`에 대해 설명한 대로 사용할 수 있습니다.
+
+///
#### 기본값이 있는 필드를 갖는 값의 데이터
@@ -166,10 +181,13 @@ ID가 `baz`인 항목(items)처럼 기본값과 동일한 값을 갖는다면:
따라서 JSON 스키마에 포함됩니다.
-!!! tip "팁"
- `None` 뿐만 아니라 다른 어떤 것도 기본값이 될 수 있습니다.
+/// tip | "팁"
- 리스트(`[]`), `float`인 `10.5` 등이 될 수 있습니다.
+`None` 뿐만 아니라 다른 어떤 것도 기본값이 될 수 있습니다.
+
+리스트(`[]`), `float`인 `10.5` 등이 될 수 있습니다.
+
+///
### `response_model_include` 및 `response_model_exclude`
@@ -179,28 +197,34 @@ ID가 `baz`인 항목(items)처럼 기본값과 동일한 값을 갖는다면:
Pydantic 모델이 하나만 있고 출력에서 일부 데이터를 제거하려는 경우 빠른 지름길로 사용할 수 있습니다.
-!!! tip "팁"
- 하지만 이러한 매개변수 대신 여러 클래스를 사용하여 위 아이디어를 사용하는 것을 추천합니다.
+/// tip | "팁"
- 이는 일부 어트리뷰트를 생략하기 위해 `response_model_include` 또는 `response_model_exclude`를 사용하더라도 앱의 OpenAPI(및 문서)가 생성한 JSON 스키마가 여전히 전체 모델에 대한 스키마이기 때문입니다.
+하지만 이러한 매개변수 대신 여러 클래스를 사용하여 위 아이디어를 사용하는 것을 추천합니다.
- 비슷하게 작동하는 `response_model_by_alias` 역시 마찬가지로 적용됩니다.
+이는 일부 어트리뷰트를 생략하기 위해 `response_model_include` 또는 `response_model_exclude`를 사용하더라도 앱의 OpenAPI(및 문서)가 생성한 JSON 스키마가 여전히 전체 모델에 대한 스키마이기 때문입니다.
+
+비슷하게 작동하는 `response_model_by_alias` 역시 마찬가지로 적용됩니다.
+
+///
```Python hl_lines="31 37"
-{!../../../docs_src/response_model/tutorial005.py!}
+{!../../docs_src/response_model/tutorial005.py!}
```
-!!! tip "팁"
- 문법 `{"name", "description"}`은 두 값을 갖는 `set`을 만듭니다.
+/// tip | "팁"
- 이는 `set(["name", "description"])`과 동일합니다.
+문법 `{"name", "description"}`은 두 값을 갖는 `set`을 만듭니다.
+
+이는 `set(["name", "description"])`과 동일합니다.
+
+///
#### `set` 대신 `list` 사용하기
`list` 또는 `tuple` 대신 `set`을 사용하는 법을 잊었더라도, FastAPI는 `set`으로 변환하고 정상적으로 작동합니다:
```Python hl_lines="31 37"
-{!../../../docs_src/response_model/tutorial006.py!}
+{!../../docs_src/response_model/tutorial006.py!}
```
## 요약
diff --git a/docs/ko/docs/tutorial/response-status-code.md b/docs/ko/docs/tutorial/response-status-code.md
index e6eed5120..57eef6ba1 100644
--- a/docs/ko/docs/tutorial/response-status-code.md
+++ b/docs/ko/docs/tutorial/response-status-code.md
@@ -9,16 +9,22 @@
* 기타
```Python hl_lines="6"
-{!../../../docs_src/response_status_code/tutorial001.py!}
+{!../../docs_src/response_status_code/tutorial001.py!}
```
-!!! note "참고"
- `status_code` 는 "데코레이터" 메소드(`get`, `post` 등)의 매개변수입니다. 모든 매개변수들과 본문처럼 *경로 작동 함수*가 아닙니다.
+/// note | "참고"
+
+`status_code` 는 "데코레이터" 메소드(`get`, `post` 등)의 매개변수입니다. 모든 매개변수들과 본문처럼 *경로 작동 함수*가 아닙니다.
+
+///
`status_code` 매개변수는 HTTP 상태 코드를 숫자로 입력받습니다.
-!!! info "정보"
- `status_code` 는 파이썬의 `http.HTTPStatus` 와 같은 `IntEnum` 을 입력받을 수도 있습니다.
+/// info | "정보"
+
+`status_code` 는 파이썬의 `http.HTTPStatus` 와 같은 `IntEnum` 을 입력받을 수도 있습니다.
+
+///
`status_code` 매개변수는:
@@ -27,15 +33,21 @@
-!!! note "참고"
- 어떤 응답 코드들은 해당 응답에 본문이 없다는 것을 의미하기도 합니다 (다음 항목 참고).
+/// note | "참고"
- 이에 따라 FastAPI는 응답 본문이 없음을 명시하는 OpenAPI를 생성합니다.
+어떤 응답 코드들은 해당 응답에 본문이 없다는 것을 의미하기도 합니다 (다음 항목 참고).
+
+이에 따라 FastAPI는 응답 본문이 없음을 명시하는 OpenAPI를 생성합니다.
+
+///
## HTTP 상태 코드에 대하여
-!!! note "참고"
- 만약 HTTP 상태 코드에 대하여 이미 알고있다면, 다음 항목으로 넘어가십시오.
+/// note | "참고"
+
+만약 HTTP 상태 코드에 대하여 이미 알고있다면, 다음 항목으로 넘어가십시오.
+
+///
HTTP는 세자리의 숫자 상태 코드를 응답의 일부로 전송합니다.
@@ -54,15 +66,18 @@ HTTP는 세자리의 숫자 상태 코드를 응답의 일부로 전송합니다
* 일반적인 클라이언트 오류의 경우 `400` 을 사용할 수 있습니다.
* `5xx` 상태 코드는 서버 오류에 사용됩니다. 이것들을 직접 사용할 일은 거의 없습니다. 응용 프로그램 코드나 서버의 일부에서 문제가 발생하면 자동으로 이들 상태 코드 중 하나를 반환합니다.
-!!! tip "팁"
- 각각의 상태 코드와 이들이 의미하는 내용에 대해 더 알고싶다면 MDN HTTP 상태 코드에 관한 문서 를 확인하십시오.
+/// tip | "팁"
+
+각각의 상태 코드와 이들이 의미하는 내용에 대해 더 알고싶다면 MDN HTTP 상태 코드에 관한 문서 를 확인하십시오.
+
+///
## 이름을 기억하는 쉬운 방법
상기 예시 참고:
```Python hl_lines="6"
-{!../../../docs_src/response_status_code/tutorial001.py!}
+{!../../docs_src/response_status_code/tutorial001.py!}
```
`201` 은 "생성됨"를 의미하는 상태 코드입니다.
@@ -72,17 +87,20 @@ HTTP는 세자리의 숫자 상태 코드를 응답의 일부로 전송합니다
`fastapi.status` 의 편의 변수를 사용할 수 있습니다.
```Python hl_lines="1 6"
-{!../../../docs_src/response_status_code/tutorial002.py!}
+{!../../docs_src/response_status_code/tutorial002.py!}
```
이것은 단순히 작업을 편리하게 하기 위한 것으로, HTTP 상태 코드와 동일한 번호를 갖고있지만, 이를 사용하면 편집기의 자동완성 기능을 사용할 수 있습니다:
-!!! note "기술적 세부사항"
- `from starlette import status` 역시 사용할 수 있습니다.
+/// note | "기술적 세부사항"
- **FastAPI**는 개발자인 여러분의 편의를 위해 `fastapi.status` 와 동일한 `starlette.status` 도 제공합니다. 하지만 이것은 Starlette로부터 직접 제공됩니다.
+`from starlette import status` 역시 사용할 수 있습니다.
+
+**FastAPI**는 개발자인 여러분의 편의를 위해 `fastapi.status` 와 동일한 `starlette.status` 도 제공합니다. 하지만 이것은 Starlette로부터 직접 제공됩니다.
+
+///
## 기본값 변경
diff --git a/docs/ko/docs/tutorial/schema-extra-example.md b/docs/ko/docs/tutorial/schema-extra-example.md
index 4e319e075..71052b334 100644
--- a/docs/ko/docs/tutorial/schema-extra-example.md
+++ b/docs/ko/docs/tutorial/schema-extra-example.md
@@ -8,71 +8,93 @@
생성된 JSON 스키마에 추가될 Pydantic 모델을 위한 `examples`을 선언할 수 있습니다.
-=== "Python 3.10+ Pydantic v2"
+//// tab | Python 3.10+ Pydantic v2
- ```Python hl_lines="13-24"
- {!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!}
- ```
+```Python hl_lines="13-24"
+{!> ../../docs_src/schema_extra_example/tutorial001_py310.py!}
+```
-=== "Python 3.10+ Pydantic v1"
+////
- ```Python hl_lines="13-23"
- {!> ../../../docs_src/schema_extra_example/tutorial001_py310_pv1.py!}
- ```
+//// tab | Python 3.10+ Pydantic v1
-=== "Python 3.8+ Pydantic v2"
+```Python hl_lines="13-23"
+{!> ../../docs_src/schema_extra_example/tutorial001_py310_pv1.py!}
+```
- ```Python hl_lines="15-26"
- {!> ../../../docs_src/schema_extra_example/tutorial001.py!}
- ```
+////
-=== "Python 3.8+ Pydantic v1"
+//// tab | Python 3.8+ Pydantic v2
- ```Python hl_lines="15-25"
- {!> ../../../docs_src/schema_extra_example/tutorial001_pv1.py!}
- ```
+```Python hl_lines="15-26"
+{!> ../../docs_src/schema_extra_example/tutorial001.py!}
+```
+
+////
+
+//// tab | Python 3.8+ Pydantic v1
+
+```Python hl_lines="15-25"
+{!> ../../docs_src/schema_extra_example/tutorial001_pv1.py!}
+```
+
+////
추가 정보는 있는 그대로 해당 모델의 **JSON 스키마** 결과에 추가되고, API 문서에서 사용합니다.
-=== "Pydantic v2"
+//// tab | Pydantic v2
- Pydantic 버전 2에서 Pydantic 공식 문서: Model Config에 나와 있는 것처럼 `dict`를 받는 `model_config` 어트리뷰트를 사용할 것입니다.
+Pydantic 버전 2에서 Pydantic 공식 문서: Model Config에 나와 있는 것처럼 `dict`를 받는 `model_config` 어트리뷰트를 사용할 것입니다.
- `"json_schema_extra"`를 생성된 JSON 스키마에서 보여주고 싶은 별도의 데이터와 `examples`를 포함하는 `dict`으로 설정할 수 있습니다.
+`"json_schema_extra"`를 생성된 JSON 스키마에서 보여주고 싶은 별도의 데이터와 `examples`를 포함하는 `dict`으로 설정할 수 있습니다.
-=== "Pydantic v1"
+////
- Pydantic v1에서 Pydantic 공식 문서: Schema customization에서 설명하는 것처럼, 내부 클래스인 `Config`와 `schema_extra`를 사용할 것입니다.
+//// tab | Pydantic v1
- `schema_extra`를 생성된 JSON 스키마에서 보여주고 싶은 별도의 데이터와 `examples`를 포함하는 `dict`으로 설정할 수 있습니다.
+Pydantic v1에서 Pydantic 공식 문서: Schema customization에서 설명하는 것처럼, 내부 클래스인 `Config`와 `schema_extra`를 사용할 것입니다.
-!!! tip "팁"
- JSON 스키마를 확장하고 여러분의 별도의 자체 데이터를 추가하기 위해 같은 기술을 사용할 수 있습니다.
+`schema_extra`를 생성된 JSON 스키마에서 보여주고 싶은 별도의 데이터와 `examples`를 포함하는 `dict`으로 설정할 수 있습니다.
- 예를 들면, 프론트엔드 사용자 인터페이스에 메타데이터를 추가하는 등에 사용할 수 있습니다.
+////
-!!! info "정보"
- (FastAPI 0.99.0부터 쓰이기 시작한) OpenAPI 3.1.0은 **JSON 스키마** 표준의 일부인 `examples`에 대한 지원을 추가했습니다.
+/// tip | "팁"
- 그 전에는, 하나의 예제만 가능한 `example` 키워드만 지원했습니다. 이는 아직 OpenAPI 3.1.0에서 지원하지만, 지원이 종료될 것이며 JSON 스키마 표준에 포함되지 않습니다. 그렇기에 `example`을 `examples`으로 이전하는 것을 추천합니다. 🤓
+JSON 스키마를 확장하고 여러분의 별도의 자체 데이터를 추가하기 위해 같은 기술을 사용할 수 있습니다.
- 이 문서 끝에 더 많은 읽을거리가 있습니다.
+예를 들면, 프론트엔드 사용자 인터페이스에 메타데이터를 추가하는 등에 사용할 수 있습니다.
+
+///
+
+/// info | "정보"
+
+(FastAPI 0.99.0부터 쓰이기 시작한) OpenAPI 3.1.0은 **JSON 스키마** 표준의 일부인 `examples`에 대한 지원을 추가했습니다.
+
+그 전에는, 하나의 예제만 가능한 `example` 키워드만 지원했습니다. 이는 아직 OpenAPI 3.1.0에서 지원하지만, 지원이 종료될 것이며 JSON 스키마 표준에 포함되지 않습니다. 그렇기에 `example`을 `examples`으로 이전하는 것을 추천합니다. 🤓
+
+이 문서 끝에 더 많은 읽을거리가 있습니다.
+
+///
## `Field` 추가 인자
Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 선언할 수 있습니다:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="2 8-11"
- {!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!}
- ```
+```Python hl_lines="2 8-11"
+{!> ../../docs_src/schema_extra_example/tutorial002_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="4 10-13"
- {!> ../../../docs_src/schema_extra_example/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="4 10-13"
+{!> ../../docs_src/schema_extra_example/tutorial002.py!}
+```
+
+////
## JSON Schema에서의 `examples` - OpenAPI
@@ -92,41 +114,57 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를
여기, `Body()`에 예상되는 예제 데이터 하나를 포함한 `examples`를 넘겼습니다:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="22-29"
- {!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!}
- ```
+```Python hl_lines="22-29"
+{!> ../../docs_src/schema_extra_example/tutorial003_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="22-29"
- {!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="22-29"
+{!> ../../docs_src/schema_extra_example/tutorial003_an_py39.py!}
+```
- ```Python hl_lines="23-30"
- {!> ../../../docs_src/schema_extra_example/tutorial003_an.py!}
- ```
+////
-=== "Python 3.10+ Annotated가 없는 경우"
+//// tab | Python 3.8+
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+```Python hl_lines="23-30"
+{!> ../../docs_src/schema_extra_example/tutorial003_an.py!}
+```
- ```Python hl_lines="18-25"
- {!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!}
- ```
+////
-=== "Python 3.8+ Annotated가 없는 경우"
+//// tab | Python 3.10+ Annotated가 없는 경우
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+/// tip | "팁"
- ```Python hl_lines="20-27"
- {!> ../../../docs_src/schema_extra_example/tutorial003.py!}
- ```
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
+
+///
+
+```Python hl_lines="18-25"
+{!> ../../docs_src/schema_extra_example/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ Annotated가 없는 경우
+
+/// tip | "팁"
+
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
+
+///
+
+```Python hl_lines="20-27"
+{!> ../../docs_src/schema_extra_example/tutorial003.py!}
+```
+
+////
### 문서 UI 예시
@@ -138,41 +176,57 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를
물론 여러 `examples`를 넘길 수 있습니다:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="23-38"
- {!> ../../../docs_src/schema_extra_example/tutorial004_an_py310.py!}
- ```
+```Python hl_lines="23-38"
+{!> ../../docs_src/schema_extra_example/tutorial004_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="23-38"
- {!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="23-38"
+{!> ../../docs_src/schema_extra_example/tutorial004_an_py39.py!}
+```
- ```Python hl_lines="24-39"
- {!> ../../../docs_src/schema_extra_example/tutorial004_an.py!}
- ```
+////
-=== "Python 3.10+ Annotated가 없는 경우"
+//// tab | Python 3.8+
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+```Python hl_lines="24-39"
+{!> ../../docs_src/schema_extra_example/tutorial004_an.py!}
+```
- ```Python hl_lines="19-34"
- {!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!}
- ```
+////
-=== "Python 3.8+ Annotated가 없는 경우"
+//// tab | Python 3.10+ Annotated가 없는 경우
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+/// tip | "팁"
- ```Python hl_lines="21-36"
- {!> ../../../docs_src/schema_extra_example/tutorial004.py!}
- ```
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
+
+///
+
+```Python hl_lines="19-34"
+{!> ../../docs_src/schema_extra_example/tutorial004_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ Annotated가 없는 경우
+
+/// tip | "팁"
+
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
+
+///
+
+```Python hl_lines="21-36"
+{!> ../../docs_src/schema_extra_example/tutorial004.py!}
+```
+
+////
이와 같이 하면 이 예제는 그 본문 데이터를 위한 내부 **JSON 스키마**의 일부가 될 것입니다.
@@ -213,41 +267,57 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를
이를 다음과 같이 사용할 수 있습니다:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="23-49"
- {!> ../../../docs_src/schema_extra_example/tutorial005_an_py310.py!}
- ```
+```Python hl_lines="23-49"
+{!> ../../docs_src/schema_extra_example/tutorial005_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="23-49"
- {!> ../../../docs_src/schema_extra_example/tutorial005_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="23-49"
+{!> ../../docs_src/schema_extra_example/tutorial005_an_py39.py!}
+```
- ```Python hl_lines="24-50"
- {!> ../../../docs_src/schema_extra_example/tutorial005_an.py!}
- ```
+////
-=== "Python 3.10+ Annotated가 없는 경우"
+//// tab | Python 3.8+
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+```Python hl_lines="24-50"
+{!> ../../docs_src/schema_extra_example/tutorial005_an.py!}
+```
- ```Python hl_lines="19-45"
- {!> ../../../docs_src/schema_extra_example/tutorial005_py310.py!}
- ```
+////
-=== "Python 3.8+ Annotated가 없는 경우"
+//// tab | Python 3.10+ Annotated가 없는 경우
- !!! tip "팁"
- 가능하다면 `Annotated`가 달린 버전을 권장합니다.
+/// tip | "팁"
- ```Python hl_lines="21-47"
- {!> ../../../docs_src/schema_extra_example/tutorial005.py!}
- ```
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
+
+///
+
+```Python hl_lines="19-45"
+{!> ../../docs_src/schema_extra_example/tutorial005_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ Annotated가 없는 경우
+
+/// tip | "팁"
+
+가능하다면 `Annotated`가 달린 버전을 권장합니다.
+
+///
+
+```Python hl_lines="21-47"
+{!> ../../docs_src/schema_extra_example/tutorial005.py!}
+```
+
+////
### 문서 UI에서의 OpenAPI 예시
@@ -257,17 +327,23 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를
## 기술적 세부 사항
-!!! tip "팁"
- 이미 **FastAPI**의 **0.99.0 혹은 그 이상** 버전을 사용하고 있다면, 이 세부 사항을 **스킵**해도 상관 없을 것입니다.
+/// tip | "팁"
- 세부 사항은 OpenAPI 3.1.0이 사용가능하기 전, 예전 버전과 더 관련있습니다.
+이미 **FastAPI**의 **0.99.0 혹은 그 이상** 버전을 사용하고 있다면, 이 세부 사항을 **스킵**해도 상관 없을 것입니다.
- 간략한 OpenAPI와 JSON 스키마 **역사 강의**로 생각할 수 있습니다. 🤓
+세부 사항은 OpenAPI 3.1.0이 사용가능하기 전, 예전 버전과 더 관련있습니다.
-!!! warning "경고"
- 표준 **JSON 스키마**와 **OpenAPI**에 대한 아주 기술적인 세부사항입니다.
+간략한 OpenAPI와 JSON 스키마 **역사 강의**로 생각할 수 있습니다. 🤓
- 만약 위의 생각이 작동한다면, 그것으로 충분하며 이 세부 사항은 필요없을 것이니, 마음 편하게 스킵하셔도 됩니다.
+///
+
+/// warning | "경고"
+
+표준 **JSON 스키마**와 **OpenAPI**에 대한 아주 기술적인 세부사항입니다.
+
+만약 위의 생각이 작동한다면, 그것으로 충분하며 이 세부 사항은 필요없을 것이니, 마음 편하게 스킵하셔도 됩니다.
+
+///
OpenAPI 3.1.0 전에 OpenAPI는 오래된 **JSON 스키마**의 수정된 버전을 사용했습니다.
@@ -285,8 +361,11 @@ OpenAPI는 또한 `example`과 `examples` 필드를 명세서의 다른 부분
* `File()`
* `Form()`
-!!! info "정보"
- 이 예전 OpenAPI-특화 `examples` 매개변수는 이제 FastAPI `0.103.0`부터 `openapi_examples`입니다.
+/// info | "정보"
+
+이 예전 OpenAPI-특화 `examples` 매개변수는 이제 FastAPI `0.103.0`부터 `openapi_examples`입니다.
+
+///
### JSON 스키마의 `examples` 필드
@@ -298,10 +377,13 @@ OpenAPI는 또한 `example`과 `examples` 필드를 명세서의 다른 부분
JSON 스키마의 새로운 `examples` 필드는 예제 속 **단순한 `list`**이며, (위에서 상술한 것처럼) OpenAPI의 다른 곳에 존재하는 dict으로 된 추가적인 메타데이터가 아닙니다.
-!!! info "정보"
- 더 쉽고 새로운 JSON 스키마와의 통합과 함께 OpenAPI 3.1.0가 배포되었지만, 잠시동안 자동 문서 생성을 제공하는 도구인 Swagger UI는 OpenAPI 3.1.0을 지원하지 않았습니다 (5.0.0 버전부터 지원합니다 🎉).
+/// info | "정보"
- 이로인해, FastAPI 0.99.0 이전 버전은 아직 OpenAPI 3.1.0 보다 낮은 버전을 사용했습니다.
+더 쉽고 새로운 JSON 스키마와의 통합과 함께 OpenAPI 3.1.0가 배포되었지만, 잠시동안 자동 문서 생성을 제공하는 도구인 Swagger UI는 OpenAPI 3.1.0을 지원하지 않았습니다 (5.0.0 버전부터 지원합니다 🎉).
+
+이로인해, FastAPI 0.99.0 이전 버전은 아직 OpenAPI 3.1.0 보다 낮은 버전을 사용했습니다.
+
+///
### Pydantic과 FastAPI `examples`
diff --git a/docs/ko/docs/tutorial/security/get-current-user.md b/docs/ko/docs/tutorial/security/get-current-user.md
index f4b6f9471..56f5792a7 100644
--- a/docs/ko/docs/tutorial/security/get-current-user.md
+++ b/docs/ko/docs/tutorial/security/get-current-user.md
@@ -3,7 +3,7 @@
이전 장에서 (의존성 주입 시스템을 기반으로 한)보안 시스템은 *경로 작동 함수*에서 `str`로 `token`을 제공했습니다:
```Python hl_lines="10"
-{!../../../docs_src/security/tutorial001.py!}
+{!../../docs_src/security/tutorial001.py!}
```
그러나 아직도 유용하지 않습니다.
@@ -16,17 +16,21 @@
Pydantic을 사용하여 본문을 선언하는 것과 같은 방식으로 다른 곳에서 사용할 수 있습니다.
-=== "파이썬 3.7 이상"
+//// tab | 파이썬 3.7 이상
- ```Python hl_lines="5 12-16"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+```Python hl_lines="5 12-16"
+{!> ../../docs_src/security/tutorial002.py!}
+```
-=== "파이썬 3.10 이상"
+////
- ```Python hl_lines="3 10-14"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+//// tab | 파이썬 3.10 이상
+
+```Python hl_lines="3 10-14"
+{!> ../../docs_src/security/tutorial002_py310.py!}
+```
+
+////
## `get_current_user` 의존성 생성하기
@@ -38,63 +42,81 @@ Pydantic을 사용하여 본문을 선언하는 것과 같은 방식으로 다
이전에 *경로 작동*에서 직접 수행했던 것과 동일하게 새 종속성 `get_current_user`는 하위 종속성 `oauth2_scheme`에서 `str`로 `token`을 수신합니다.
-=== "파이썬 3.7 이상"
+//// tab | 파이썬 3.7 이상
- ```Python hl_lines="25"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+```Python hl_lines="25"
+{!> ../../docs_src/security/tutorial002.py!}
+```
-=== "파이썬 3.10 이상"
+////
- ```Python hl_lines="23"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+//// tab | 파이썬 3.10 이상
+
+```Python hl_lines="23"
+{!> ../../docs_src/security/tutorial002_py310.py!}
+```
+
+////
## 유저 가져오기
`get_current_user`는 토큰을 `str`로 취하고 Pydantic `User` 모델을 반환하는 우리가 만든 (가짜) 유틸리티 함수를 사용합니다.
-=== "파이썬 3.7 이상"
+//// tab | 파이썬 3.7 이상
- ```Python hl_lines="19-22 26-27"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+```Python hl_lines="19-22 26-27"
+{!> ../../docs_src/security/tutorial002.py!}
+```
-=== "파이썬 3.10 이상"
+////
- ```Python hl_lines="17-20 24-25"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+//// tab | 파이썬 3.10 이상
+
+```Python hl_lines="17-20 24-25"
+{!> ../../docs_src/security/tutorial002_py310.py!}
+```
+
+////
## 현재 유저 주입하기
이제 *경로 작동*에서 `get_current_user`와 동일한 `Depends`를 사용할 수 있습니다.
-=== "파이썬 3.7 이상"
+//// tab | 파이썬 3.7 이상
- ```Python hl_lines="31"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+```Python hl_lines="31"
+{!> ../../docs_src/security/tutorial002.py!}
+```
-=== "파이썬 3.10 이상"
+////
- ```Python hl_lines="29"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+//// tab | 파이썬 3.10 이상
+
+```Python hl_lines="29"
+{!> ../../docs_src/security/tutorial002_py310.py!}
+```
+
+////
Pydantic 모델인 `User`로 `current_user`의 타입을 선언하는 것을 알아야 합니다.
이것은 모든 완료 및 타입 검사를 통해 함수 내부에서 우리를 도울 것입니다.
-!!! tip "팁"
- 요청 본문도 Pydantic 모델로 선언된다는 것을 기억할 것입니다.
+/// tip | "팁"
- 여기서 **FastAPI**는 `Depends`를 사용하고 있기 때문에 혼동되지 않습니다.
+요청 본문도 Pydantic 모델로 선언된다는 것을 기억할 것입니다.
-!!! check "확인"
- 이 의존성 시스템이 설계된 방식은 모두 `User` 모델을 반환하는 다양한 의존성(다른 "의존적인")을 가질 수 있도록 합니다.
+여기서 **FastAPI**는 `Depends`를 사용하고 있기 때문에 혼동되지 않습니다.
- 해당 타입의 데이터를 반환할 수 있는 의존성이 하나만 있는 것으로 제한되지 않습니다.
+///
+
+/// check | "확인"
+
+이 의존성 시스템이 설계된 방식은 모두 `User` 모델을 반환하는 다양한 의존성(다른 "의존적인")을 가질 수 있도록 합니다.
+
+해당 타입의 데이터를 반환할 수 있는 의존성이 하나만 있는 것으로 제한되지 않습니다.
+
+///
## 다른 모델
@@ -128,17 +150,21 @@ Pydantic 모델인 `User`로 `current_user`의 타입을 선언하는 것을 알
그리고 이 수천 개의 *경로 작동*은 모두 3줄 정도로 줄일 수 있습니다.
-=== "파이썬 3.7 이상"
+//// tab | 파이썬 3.7 이상
- ```Python hl_lines="30-32"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+```Python hl_lines="30-32"
+{!> ../../docs_src/security/tutorial002.py!}
+```
-=== "파이썬 3.10 이상"
+////
- ```Python hl_lines="28-30"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+//// tab | 파이썬 3.10 이상
+
+```Python hl_lines="28-30"
+{!> ../../docs_src/security/tutorial002_py310.py!}
+```
+
+////
## 요약
diff --git a/docs/ko/docs/tutorial/security/simple-oauth2.md b/docs/ko/docs/tutorial/security/simple-oauth2.md
index 1e33f5766..fd18c1d47 100644
--- a/docs/ko/docs/tutorial/security/simple-oauth2.md
+++ b/docs/ko/docs/tutorial/security/simple-oauth2.md
@@ -32,14 +32,17 @@ OAuth2는 (우리가 사용하고 있는) "패스워드 플로우"을 사용할
* `instagram_basic`은 페이스북/인스타그램에서 사용합니다.
* `https://www.googleapis.com/auth/drive`는 Google에서 사용합니다.
-!!! 정보
- OAuth2에서 "범위"는 필요한 특정 권한을 선언하는 문자열입니다.
+/// 정보
- `:`과 같은 다른 문자가 있는지 또는 URL인지는 중요하지 않습니다.
+OAuth2에서 "범위"는 필요한 특정 권한을 선언하는 문자열입니다.
- 이러한 세부 사항은 구현에 따라 다릅니다.
+`:`과 같은 다른 문자가 있는지 또는 URL인지는 중요하지 않습니다.
- OAuth2의 경우 문자열일 뿐입니다.
+이러한 세부 사항은 구현에 따라 다릅니다.
+
+OAuth2의 경우 문자열일 뿐입니다.
+
+///
## `username`과 `password`를 가져오는 코드
@@ -49,17 +52,21 @@ OAuth2는 (우리가 사용하고 있는) "패스워드 플로우"을 사용할
먼저 `OAuth2PasswordRequestForm`을 가져와 `/token`에 대한 *경로 작동*에서 `Depends`의 의존성으로 사용합니다.
-=== "파이썬 3.7 이상"
+//// tab | 파이썬 3.7 이상
- ```Python hl_lines="4 76"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+```Python hl_lines="4 76"
+{!> ../../docs_src/security/tutorial003.py!}
+```
-=== "파이썬 3.10 이상"
+////
- ```Python hl_lines="2 74"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+//// tab | 파이썬 3.10 이상
+
+```Python hl_lines="2 74"
+{!> ../../docs_src/security/tutorial003_py310.py!}
+```
+
+////
`OAuth2PasswordRequestForm`은 다음을 사용하여 폼 본문을 선언하는 클래스 의존성입니다:
@@ -68,29 +75,38 @@ OAuth2는 (우리가 사용하고 있는) "패스워드 플로우"을 사용할
* `scope`는 선택적인 필드로 공백으로 구분된 문자열로 구성된 큰 문자열입니다.
* `grant_type`(선택적으로 사용).
-!!! 팁
- OAuth2 사양은 실제로 `password`라는 고정 값이 있는 `grant_type` 필드를 *요구*하지만 `OAuth2PasswordRequestForm`은 이를 강요하지 않습니다.
+/// 팁
- 사용해야 한다면 `OAuth2PasswordRequestForm` 대신 `OAuth2PasswordRequestFormStrict`를 사용하면 됩니다.
+OAuth2 사양은 실제로 `password`라는 고정 값이 있는 `grant_type` 필드를 *요구*하지만 `OAuth2PasswordRequestForm`은 이를 강요하지 않습니다.
+
+사용해야 한다면 `OAuth2PasswordRequestForm` 대신 `OAuth2PasswordRequestFormStrict`를 사용하면 됩니다.
+
+///
* `client_id`(선택적으로 사용) (예제에서는 필요하지 않습니다).
* `client_secret`(선택적으로 사용) (예제에서는 필요하지 않습니다).
-!!! 정보
- `OAuth2PasswordRequestForm`은 `OAuth2PasswordBearer`와 같이 **FastAPI**에 대한 특수 클래스가 아닙니다.
+/// 정보
- `OAuth2PasswordBearer`는 **FastAPI**가 보안 체계임을 알도록 합니다. 그래서 OpenAPI에 그렇게 추가됩니다.
+`OAuth2PasswordRequestForm`은 `OAuth2PasswordBearer`와 같이 **FastAPI**에 대한 특수 클래스가 아닙니다.
- 그러나 `OAuth2PasswordRequestForm`은 직접 작성하거나 `Form` 매개변수를 직접 선언할 수 있는 클래스 의존성일 뿐입니다.
+`OAuth2PasswordBearer`는 **FastAPI**가 보안 체계임을 알도록 합니다. 그래서 OpenAPI에 그렇게 추가됩니다.
- 그러나 일반적인 사용 사례이므로 더 쉽게 하기 위해 **FastAPI**에서 직접 제공합니다.
+그러나 `OAuth2PasswordRequestForm`은 직접 작성하거나 `Form` 매개변수를 직접 선언할 수 있는 클래스 의존성일 뿐입니다.
+
+그러나 일반적인 사용 사례이므로 더 쉽게 하기 위해 **FastAPI**에서 직접 제공합니다.
+
+///
### 폼 데이터 사용하기
-!!! 팁
- 종속성 클래스 `OAuth2PasswordRequestForm`의 인스턴스에는 공백으로 구분된 긴 문자열이 있는 `scope` 속성이 없고 대신 전송된 각 범위에 대한 실제 문자열 목록이 있는 `scopes` 속성이 있습니다.
+/// 팁
- 이 예제에서는 `scopes`를 사용하지 않지만 필요한 경우, 기능이 있습니다.
+종속성 클래스 `OAuth2PasswordRequestForm`의 인스턴스에는 공백으로 구분된 긴 문자열이 있는 `scope` 속성이 없고 대신 전송된 각 범위에 대한 실제 문자열 목록이 있는 `scopes` 속성이 있습니다.
+
+이 예제에서는 `scopes`를 사용하지 않지만 필요한 경우, 기능이 있습니다.
+
+///
이제 폼 필드의 `username`을 사용하여 (가짜) 데이터베이스에서 유저 데이터를 가져옵니다.
@@ -98,17 +114,21 @@ OAuth2는 (우리가 사용하고 있는) "패스워드 플로우"을 사용할
오류의 경우 `HTTPException` 예외를 사용합니다:
-=== "파이썬 3.7 이상"
+//// tab | 파이썬 3.7 이상
- ```Python hl_lines="3 77-79"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+```Python hl_lines="3 77-79"
+{!> ../../docs_src/security/tutorial003.py!}
+```
-=== "파이썬 3.10 이상"
+////
- ```Python hl_lines="1 75-77"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+//// tab | 파이썬 3.10 이상
+
+```Python hl_lines="1 75-77"
+{!> ../../docs_src/security/tutorial003_py310.py!}
+```
+
+////
### 패스워드 확인하기
@@ -134,17 +154,21 @@ OAuth2는 (우리가 사용하고 있는) "패스워드 플로우"을 사용할
따라서 해커는 다른 시스템에서 동일한 암호를 사용하려고 시도할 수 없습니다(많은 사용자가 모든 곳에서 동일한 암호를 사용하므로 이는 위험할 수 있습니다).
-=== "P파이썬 3.7 이상"
+//// tab | P파이썬 3.7 이상
- ```Python hl_lines="80-83"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+```Python hl_lines="80-83"
+{!> ../../docs_src/security/tutorial003.py!}
+```
-=== "파이썬 3.10 이상"
+////
- ```Python hl_lines="78-81"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+//// tab | 파이썬 3.10 이상
+
+```Python hl_lines="78-81"
+{!> ../../docs_src/security/tutorial003_py310.py!}
+```
+
+////
#### `**user_dict`에 대해
@@ -162,8 +186,11 @@ UserInDB(
)
```
-!!! 정보
- `**user_dict`에 대한 자세한 설명은 [**추가 모델** 문서](../extra-models.md#about-user_indict){.internal-link target=_blank}를 다시 읽어봅시다.
+/// 정보
+
+`**user_dict`에 대한 자세한 설명은 [**추가 모델** 문서](../extra-models.md#about-user_indict){.internal-link target=_blank}를 다시 읽어봅시다.
+
+///
## 토큰 반환하기
@@ -175,31 +202,41 @@ UserInDB(
이 간단한 예제에서는 완전히 안전하지 않고, 동일한 `username`을 토큰으로 반환합니다.
-!!! 팁
- 다음 장에서는 패스워드 해싱 및 JWT 토큰을 사용하여 실제 보안 구현을 볼 수 있습니다.
+/// 팁
- 하지만 지금은 필요한 세부 정보에 집중하겠습니다.
+다음 장에서는 패스워드 해싱 및 JWT 토큰을 사용하여 실제 보안 구현을 볼 수 있습니다.
-=== "파이썬 3.7 이상"
+하지만 지금은 필요한 세부 정보에 집중하겠습니다.
- ```Python hl_lines="85"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+///
-=== "파이썬 3.10 이상"
+//// tab | 파이썬 3.7 이상
- ```Python hl_lines="83"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+```Python hl_lines="85"
+{!> ../../docs_src/security/tutorial003.py!}
+```
-!!! 팁
- 사양에 따라 이 예제와 동일하게 `access_token` 및 `token_type`이 포함된 JSON을 반환해야 합니다.
+////
- 이는 코드에서 직접 수행해야 하며 해당 JSON 키를 사용해야 합니다.
+//// tab | 파이썬 3.10 이상
- 사양을 준수하기 위해 스스로 올바르게 수행하기 위해 거의 유일하게 기억해야 하는 것입니다.
+```Python hl_lines="83"
+{!> ../../docs_src/security/tutorial003_py310.py!}
+```
- 나머지는 **FastAPI**가 처리합니다.
+////
+
+/// 팁
+
+사양에 따라 이 예제와 동일하게 `access_token` 및 `token_type`이 포함된 JSON을 반환해야 합니다.
+
+이는 코드에서 직접 수행해야 하며 해당 JSON 키를 사용해야 합니다.
+
+사양을 준수하기 위해 스스로 올바르게 수행하기 위해 거의 유일하게 기억해야 하는 것입니다.
+
+나머지는 **FastAPI**가 처리합니다.
+
+///
## 의존성 업데이트하기
@@ -213,32 +250,39 @@ UserInDB(
따라서 엔드포인트에서는 사용자가 존재하고 올바르게 인증되었으며 활성 상태인 경우에만 사용자를 얻습니다:
-=== "파이썬 3.7 이상"
+//// tab | 파이썬 3.7 이상
- ```Python hl_lines="58-66 69-72 90"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+```Python hl_lines="58-66 69-72 90"
+{!> ../../docs_src/security/tutorial003.py!}
+```
-=== "파이썬 3.10 이상"
+////
- ```Python hl_lines="55-64 67-70 88"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+//// tab | 파이썬 3.10 이상
-!!! 정보
- 여기서 반환하는 값이 `Bearer`인 추가 헤더 `WWW-Authenticate`도 사양의 일부입니다.
+```Python hl_lines="55-64 67-70 88"
+{!> ../../docs_src/security/tutorial003_py310.py!}
+```
- 모든 HTTP(오류) 상태 코드 401 "UNAUTHORIZED"는 `WWW-Authenticate` 헤더도 반환해야 합니다.
+////
- 베어러 토큰의 경우(지금의 경우) 해당 헤더의 값은 `Bearer`여야 합니다.
+/// 정보
- 실제로 추가 헤더를 건너뛸 수 있으며 여전히 작동합니다.
+여기서 반환하는 값이 `Bearer`인 추가 헤더 `WWW-Authenticate`도 사양의 일부입니다.
- 그러나 여기에서는 사양을 준수하도록 제공됩니다.
+모든 HTTP(오류) 상태 코드 401 "UNAUTHORIZED"는 `WWW-Authenticate` 헤더도 반환해야 합니다.
- 또한 이를 예상하고 (현재 또는 미래에) 사용하는 도구가 있을 수 있으며, 현재 또는 미래에 자신 혹은 자신의 유저들에게 유용할 것입니다.
+베어러 토큰의 경우(지금의 경우) 해당 헤더의 값은 `Bearer`여야 합니다.
- 그것이 표준의 이점입니다 ...
+실제로 추가 헤더를 건너뛸 수 있으며 여전히 작동합니다.
+
+그러나 여기에서는 사양을 준수하도록 제공됩니다.
+
+또한 이를 예상하고 (현재 또는 미래에) 사용하는 도구가 있을 수 있으며, 현재 또는 미래에 자신 혹은 자신의 유저들에게 유용할 것입니다.
+
+그것이 표준의 이점입니다 ...
+
+///
## 확인하기
diff --git a/docs/ko/docs/tutorial/static-files.md b/docs/ko/docs/tutorial/static-files.md
index fe1aa4e5e..90a60d193 100644
--- a/docs/ko/docs/tutorial/static-files.md
+++ b/docs/ko/docs/tutorial/static-files.md
@@ -8,13 +8,16 @@
* 특정 경로에 `StaticFiles()` 인스턴스를 "마운트" 합니다.
```Python hl_lines="2 6"
-{!../../../docs_src/static_files/tutorial001.py!}
+{!../../docs_src/static_files/tutorial001.py!}
```
-!!! note "기술적 세부사항"
- `from starlette.staticfiles import StaticFiles` 를 사용할 수도 있습니다.
+/// note | "기술적 세부사항"
- **FastAPI**는 단지 개발자인, 당신에게 편의를 제공하기 위해 `fastapi.static files` 와 동일한 `starlett.static files`를 제공합니다. 하지만 사실 이것은 Starlett에서 직접 온 것입니다.
+`from starlette.staticfiles import StaticFiles` 를 사용할 수도 있습니다.
+
+**FastAPI**는 단지 개발자인, 당신에게 편의를 제공하기 위해 `fastapi.static files` 와 동일한 `starlett.static files`를 제공합니다. 하지만 사실 이것은 Starlett에서 직접 온 것입니다.
+
+///
### "마운팅" 이란
diff --git a/docs/missing-translation.md b/docs/missing-translation.md
index 32b6016f9..c2882e90e 100644
--- a/docs/missing-translation.md
+++ b/docs/missing-translation.md
@@ -1,4 +1,7 @@
-!!! warning
- The current page still doesn't have a translation for this language.
+/// warning
- But you can help translating it: [Contributing](https://fastapi.tiangolo.com/contributing/){.internal-link target=_blank}.
+The current page still doesn't have a translation for this language.
+
+But you can help translating it: [Contributing](https://fastapi.tiangolo.com/contributing/){.internal-link target=_blank}.
+
+///
diff --git a/docs/nl/docs/environment-variables.md b/docs/nl/docs/environment-variables.md
new file mode 100644
index 000000000..f6b3d285b
--- /dev/null
+++ b/docs/nl/docs/environment-variables.md
@@ -0,0 +1,298 @@
+# Omgevingsvariabelen
+
+/// tip
+
+Als je al weet wat "omgevingsvariabelen" zijn en hoe je ze kunt gebruiken, kun je deze stap gerust overslaan.
+
+///
+
+Een omgevingsvariabele (ook bekend als "**env var**") is een variabele die **buiten** de Python-code leeft, in het **besturingssysteem** en die door je Python-code (of door andere programma's) kan worden gelezen.
+
+Omgevingsvariabelen kunnen nuttig zijn voor het bijhouden van applicatie **instellingen**, als onderdeel van de **installatie** van Python, enz.
+
+## Omgevingsvariabelen maken en gebruiken
+
+Je kunt omgevingsvariabelen **maken** en gebruiken in de **shell (terminal)**, zonder dat je Python nodig hebt:
+
+//// tab | Linux, macOS, Windows Bash
+
++ FastAPI framework, zeer goede prestaties, eenvoudig te leren, snel te programmeren, klaar voor productie +
+ + +--- + +**Documentatie**: https://fastapi.tiangolo.com + +**Broncode**: https://github.com/tiangolo/fastapi + +--- + +FastAPI is een modern, snel (zeer goede prestaties), web framework voor het bouwen van API's in Python, gebruikmakend van standaard Python type-hints. + +De belangrijkste kenmerken zijn: + +* **Snel**: Zeer goede prestaties, vergelijkbaar met **NodeJS** en **Go** (dankzij Starlette en Pydantic). [Een van de snelste beschikbare Python frameworks](#prestaties). +* **Snel te programmeren**: Verhoog de snelheid om functionaliteit te ontwikkelen met ongeveer 200% tot 300%. * +* **Minder bugs**: Verminder ongeveer 40% van de door mensen (ontwikkelaars) veroorzaakte fouten. * +* **Intuïtief**: Buitengewoon goede ondersteuning voor editors. Overal automische code aanvulling. Minder tijd kwijt aan debuggen. +* **Eenvoudig**: Ontworpen om gemakkelijk te gebruiken en te leren. Minder tijd nodig om documentatie te lezen. +* **Kort**: Minimaliseer codeduplicatie. Elke parameterdeclaratie ondersteunt meerdere functionaliteiten. Minder bugs. +* **Robust**: Code gereed voor productie. Met automatische interactieve documentatie. +* **Standards-based**: Gebaseerd op (en volledig verenigbaar met) open standaarden voor API's: OpenAPI (voorheen bekend als Swagger) en JSON Schema. + +* schatting op basis van testen met een intern ontwikkelteam en bouwen van productieapplicaties. + +## Sponsors + + + +{% if sponsors %} +{% for sponsor in sponsors.gold -%} +async def...fastapi dev main.py...email_validator - voor email validatie.
+
+Gebruikt door Starlette:
+
+* httpx - Vereist indien je de `TestClient` wil gebruiken.
+* jinja2 - Vereist als je de standaard templateconfiguratie wil gebruiken.
+* python-multipart - Vereist indien je "parsen" van formulieren wil ondersteunen met `requests.form()`.
+
+Gebruikt door FastAPI / Starlette:
+
+* uvicorn - voor de server die jouw applicatie laadt en bedient.
+* `fastapi-cli` - om het `fastapi` commando te voorzien.
+
+### Zonder `standard` Afhankelijkheden
+
+Indien je de optionele `standard` afhankelijkheden niet wenst te installeren, kan je installeren met `pip install fastapi` in plaats van `pip install "fastapi[standard]"`.
+
+### Bijkomende Optionele Afhankelijkheden
+
+Er zijn nog een aantal bijkomende afhankelijkheden die je eventueel kan installeren.
+
+Bijkomende optionele afhankelijkheden voor Pydantic:
+
+* pydantic-settings - voor het beheren van settings.
+* pydantic-extra-types - voor extra data types die gebruikt kunnen worden met Pydantic.
+
+Bijkomende optionele afhankelijkheden voor FastAPI:
+
+* orjson - Vereist indien je `ORJSONResponse` wil gebruiken.
+* ujson - Vereist indien je `UJSONResponse` wil gebruiken.
+
+## Licentie
+
+Dit project is gelicenseerd onder de voorwaarden van de MIT licentie.
diff --git a/docs/nl/docs/python-types.md b/docs/nl/docs/python-types.md
new file mode 100644
index 000000000..00052037c
--- /dev/null
+++ b/docs/nl/docs/python-types.md
@@ -0,0 +1,597 @@
+# Introductie tot Python Types
+
+Python biedt ondersteuning voor optionele "type hints" (ook wel "type annotaties" genoemd).
+
+Deze **"type hints"** of annotaties zijn een speciale syntax waarmee het type van een variabele kan worden gedeclareerd.
+
+Door types voor je variabelen te declareren, kunnen editors en hulpmiddelen je beter ondersteunen.
+
+Dit is slechts een **korte tutorial/opfrisser** over Python type hints. Het behandelt enkel het minimum dat nodig is om ze te gebruiken met **FastAPI**... en dat is relatief weinig.
+
+**FastAPI** is helemaal gebaseerd op deze type hints, ze geven veel voordelen.
+
+Maar zelfs als je **FastAPI** nooit gebruikt, heb je er baat bij om er iets over te leren.
+
+/// note
+
+Als je een Python expert bent en alles al weet over type hints, sla dan dit hoofdstuk over.
+
+///
+
+## Motivatie
+
+Laten we beginnen met een eenvoudig voorbeeld:
+
+```Python
+{!../../docs_src/python_types/tutorial001.py!}
+```
+
+Het aanroepen van dit programma leidt tot het volgende resultaat:
+
+```
+John Doe
+```
+
+De functie voert het volgende uit:
+
+* Neem een `first_name` en een `last_name`
+* Converteer de eerste letter van elk naar een hoofdletter met `title()`.
+``
+* Voeg samen met een spatie in het midden.
+
+```Python hl_lines="2"
+{!../../docs_src/python_types/tutorial001.py!}
+```
+
+### Bewerk het
+
+Dit is een heel eenvoudig programma.
+
+Maar stel je nu voor dat je het vanaf nul zou moeten maken.
+
+Op een gegeven moment zou je aan de definitie van de functie zijn begonnen, je had de parameters klaar...
+
+Maar dan moet je “die methode die de eerste letter naar hoofdletters converteert” aanroepen.
+
+Was het `upper`? Was het `uppercase`? `first_uppercase`? `capitalize`?
+
+Dan roep je de hulp in van je oude programmeursvriend, (automatische) code aanvulling in je editor.
+
+Je typt de eerste parameter van de functie, `first_name`, dan een punt (`.`) en drukt dan op `Ctrl+Spatie` om de aanvulling te activeren.
+
+Maar helaas krijg je niets bruikbaars:
+
+
+
+### Types toevoegen
+
+Laten we een enkele regel uit de vorige versie aanpassen.
+
+We zullen precies dit fragment, de parameters van de functie, wijzigen van:
+
+```Python
+ first_name, last_name
+```
+
+naar:
+
+```Python
+ first_name: str, last_name: str
+```
+
+Dat is alles.
+
+Dat zijn de "type hints":
+
+```Python hl_lines="1"
+{!../../docs_src/python_types/tutorial002.py!}
+```
+
+Dit is niet hetzelfde als het declareren van standaardwaarden zoals bij:
+
+```Python
+ first_name="john", last_name="doe"
+```
+
+Het is iets anders.
+
+We gebruiken dubbele punten (`:`), geen gelijkheidstekens (`=`).
+
+Het toevoegen van type hints verandert normaal gesproken niet wat er gebeurt in je programma t.o.v. wat er zonder type hints zou gebeuren.
+
+Maar stel je voor dat je weer bezig bent met het maken van een functie, maar deze keer met type hints.
+
+Op hetzelfde moment probeer je de automatische aanvulling te activeren met `Ctrl+Spatie` en je ziet:
+
+
+
+Nu kun je de opties bekijken en er doorheen scrollen totdat je de optie vindt die “een belletje doet rinkelen”:
+
+
+
+### Meer motivatie
+
+Bekijk deze functie, deze heeft al type hints:
+
+```Python hl_lines="1"
+{!../../docs_src/python_types/tutorial003.py!}
+```
+
+Omdat de editor de types van de variabelen kent, krijgt u niet alleen aanvulling, maar ook controles op fouten:
+
+
+
+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!}
+```
+
+## Types declareren
+
+Je hebt net de belangrijkste plek om type hints te declareren gezien. Namelijk als functieparameters.
+
+Dit is ook de belangrijkste plek waar je ze gebruikt met **FastAPI**.
+
+### Eenvoudige types
+
+Je kunt alle standaard Python types declareren, niet alleen `str`.
+
+Je kunt bijvoorbeeld het volgende gebruiken:
+
+* `int`
+* `float`
+* `bool`
+* `bytes`
+
+```Python hl_lines="1"
+{!../../docs_src/python_types/tutorial005.py!}
+```
+
+### Generieke types met typeparameters
+
+Er zijn enkele datastructuren die andere waarden kunnen bevatten, zoals `dict`, `list`, `set` en `tuple` en waar ook de interne waarden hun eigen type kunnen hebben.
+
+Deze types die interne types hebben worden “**generieke**” types genoemd. Het is mogelijk om ze te declareren, zelfs met hun interne types.
+
+Om deze types en de interne types te declareren, kun je de standaard Python module `typing` gebruiken. Deze module is speciaal gemaakt om deze type hints te ondersteunen.
+
+#### Nieuwere versies van Python
+
+De syntax met `typing` is **verenigbaar** met alle versies, van Python 3.6 tot aan de nieuwste, inclusief Python 3.9, Python 3.10, enz.
+
+Naarmate Python zich ontwikkelt, worden **nieuwere versies**, met verbeterde ondersteuning voor deze type annotaties, beschikbaar. In veel gevallen hoef je niet eens de `typing` module te importeren en te gebruiken om de type annotaties te declareren.
+
+Als je een recentere versie van Python kunt kiezen voor je project, kun je profiteren van die extra eenvoud.
+
+In alle documentatie staan voorbeelden die compatibel zijn met elke versie van Python (als er een verschil is).
+
+Bijvoorbeeld “**Python 3.6+**” betekent dat het compatibel is met Python 3.6 of hoger (inclusief 3.7, 3.8, 3.9, 3.10, etc). En “**Python 3.9+**” betekent dat het compatibel is met Python 3.9 of hoger (inclusief 3.10, etc).
+
+Als je de **laatste versies van Python** kunt gebruiken, gebruik dan de voorbeelden voor de laatste versie, die hebben de **beste en eenvoudigste syntax**, bijvoorbeeld “**Python 3.10+**”.
+
+#### List
+
+Laten we bijvoorbeeld een variabele definiëren als een `list` van `str`.
+
+//// tab | Python 3.9+
+
+Declareer de variabele met dezelfde dubbele punt (`:`) syntax.
+
+Als type, vul `list` in.
+
+Doordat de list een type is dat enkele interne types bevat, zet je ze tussen vierkante haakjes:
+
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial006_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+Van `typing`, importeer `List` (met een hoofdletter `L`):
+
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial006.py!}
+```
+
+Declareer de variabele met dezelfde dubbele punt (`:`) syntax.
+
+Zet als type de `List` die je hebt geïmporteerd uit `typing`.
+
+Doordat de list een type is dat enkele interne types bevat, zet je ze tussen vierkante haakjes:
+
+```Python hl_lines="4"
+{!> ../../docs_src/python_types/tutorial006.py!}
+```
+
+////
+
+/// info
+
+De interne types tussen vierkante haakjes worden “typeparameters” genoemd.
+
+In dit geval is `str` de typeparameter die wordt doorgegeven aan `List` (of `list` in Python 3.9 en hoger).
+
+///
+
+Dat betekent: “de variabele `items` is een `list`, en elk van de items in deze list is een `str`”.
+
+/// tip
+
+Als je Python 3.9 of hoger gebruikt, hoef je `List` niet te importeren uit `typing`, je kunt in plaats daarvan hetzelfde reguliere `list` type gebruiken.
+
+///
+
+Door dat te doen, kan je editor ondersteuning bieden, zelfs tijdens het verwerken van items uit de list:
+
+
+
+Zonder types is dat bijna onmogelijk om te bereiken.
+
+Merk op dat de variabele `item` een van de elementen is in de lijst `items`.
+
+Toch weet de editor dat het een `str` is, en biedt daar vervolgens ondersteuning voor aan.
+
+#### Tuple en Set
+
+Je kunt hetzelfde doen om `tuple`s en `set`s te declareren:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial007_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial007.py!}
+```
+
+////
+
+Dit betekent:
+
+* De variabele `items_t` is een `tuple` met 3 items, een `int`, nog een `int`, en een `str`.
+* De variabele `items_s` is een `set`, en elk van de items is van het type `bytes`.
+
+#### Dict
+
+Om een `dict` te definiëren, geef je 2 typeparameters door, gescheiden door komma's.
+
+De eerste typeparameter is voor de sleutels (keys) van de `dict`.
+
+De tweede typeparameter is voor de waarden (values) van het `dict`:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial008_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial008.py!}
+```
+
+////
+
+Dit betekent:
+
+* De variabele `prices` is een `dict`:
+ * De sleutels van dit `dict` zijn van het type `str` (bijvoorbeeld de naam van elk item).
+ * De waarden van dit `dict` zijn van het type `float` (bijvoorbeeld de prijs van elk item).
+
+#### Union
+
+Je kunt een variable declareren die van **verschillende types** kan zijn, bijvoorbeeld een `int` of een `str`.
+
+In Python 3.6 en hoger (inclusief Python 3.10) kun je het `Union`-type van `typing` gebruiken en de mogelijke types die je wilt accepteren, tussen de vierkante haakjes zetten.
+
+In Python 3.10 is er ook een **nieuwe syntax** waarin je de mogelijke types kunt scheiden door een verticale balk (`|`).
+
+//// tab | Python 3.10+
+
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial008b_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial008b.py!}
+```
+
+////
+
+In beide gevallen betekent dit dat `item` een `int` of een `str` kan zijn.
+
+#### Mogelijk `None`
+
+Je kunt declareren dat een waarde een type kan hebben, zoals `str`, maar dat het ook `None` kan zijn.
+
+In Python 3.6 en hoger (inclusief Python 3.10) kun je het declareren door `Optional` te importeren en te gebruiken vanuit de `typing`-module.
+
+```Python hl_lines="1 4"
+{!../../docs_src/python_types/tutorial009.py!}
+```
+
+Door `Optional[str]` te gebruiken in plaats van alleen `str`, kan de editor je helpen fouten te detecteren waarbij je ervan uit zou kunnen gaan dat een waarde altijd een `str` is, terwijl het in werkelijkheid ook `None` zou kunnen zijn.
+
+`Optional[EenType]` is eigenlijk een snelkoppeling voor `Union[EenType, None]`, ze zijn equivalent.
+
+Dit betekent ook dat je in Python 3.10 `EenType | None` kunt gebruiken:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial009_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial009.py!}
+```
+
+////
+
+//// tab | Python 3.8+ alternative
+
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial009b.py!}
+```
+
+////
+
+#### Gebruik van `Union` of `Optional`
+
+Als je een Python versie lager dan 3.10 gebruikt, is dit een tip vanuit mijn **subjectieve** standpunt:
+
+* 🚨 Vermijd het gebruik van `Optional[EenType]`.
+* Gebruik in plaats daarvan **`Union[EenType, None]`** ✨.
+
+Beide zijn gelijkwaardig en onderliggend zijn ze hetzelfde, maar ik zou `Union` aanraden in plaats van `Optional` omdat het woord “**optional**” lijkt te impliceren dat de waarde optioneel is, en het eigenlijk betekent “het kan `None` zijn”, zelfs als het niet optioneel is en nog steeds vereist is.
+
+Ik denk dat `Union[SomeType, None]` explicieter is over wat het betekent.
+
+Het gaat alleen om de woorden en naamgeving. Maar die naamgeving kan invloed hebben op hoe jij en je teamgenoten over de code denken.
+
+Laten we als voorbeeld deze functie nemen:
+
+```Python hl_lines="1 4"
+{!../../docs_src/python_types/tutorial009c.py!}
+```
+
+De parameter `name` is gedefinieerd als `Optional[str]`, maar is **niet optioneel**, je kunt de functie niet aanroepen zonder de parameter:
+
+```Python
+say_hi() # Oh, nee, dit geeft een foutmelding! 😱
+```
+
+De `name` parameter is **nog steeds vereist** (niet *optioneel*) omdat het geen standaardwaarde heeft. Toch accepteert `name` `None` als waarde:
+
+```Python
+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!}
+```
+
+Dan hoef je je geen zorgen te maken over namen als `Optional` en `Union`. 😎
+
+#### Generieke typen
+
+De types die typeparameters in vierkante haakjes gebruiken, worden **Generieke types** of **Generics** genoemd, bijvoorbeeld:
+
+//// tab | Python 3.10+
+
+Je kunt dezelfde ingebouwde types gebruiken als generics (met vierkante haakjes en types erin):
+
+* `list`
+* `tuple`
+* `set`
+* `dict`
+
+Hetzelfde als bij Python 3.8, uit de `typing`-module:
+
+* `Union`
+* `Optional` (hetzelfde als bij Python 3.8)
+* ...en anderen.
+
+In Python 3.10 kun je , als alternatief voor de generieke `Union` en `Optional`, de verticale lijn (`|`) gebruiken om unions van typen te voorzien, dat is veel beter en eenvoudiger.
+
+////
+
+//// tab | Python 3.9+
+
+Je kunt dezelfde ingebouwde types gebruiken als generieke types (met vierkante haakjes en types erin):
+
+* `list`
+* `tuple`
+* `set`
+* `dict`
+
+En hetzelfde als met Python 3.8, vanuit de `typing`-module:
+
+* `Union`
+* `Optional`
+* ...en anderen.
+
+////
+
+//// tab | Python 3.8+
+
+* `List`
+* `Tuple`
+* `Set`
+* `Dict`
+* `Union`
+* `Optional`
+* ...en anderen.
+
+////
+
+### Klassen als types
+
+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!}
+```
+
+Vervolgens kun je een variabele van het type `Persoon` declareren:
+
+```Python hl_lines="6"
+{!../../docs_src/python_types/tutorial010.py!}
+```
+
+Dan krijg je ook nog eens volledige editorondersteuning:
+
+
+
+Merk op dat dit betekent dat "`one_person` een **instantie** is van de klasse `Person`".
+
+Dit betekent niet dat `one_person` de **klasse** is met de naam `Person`.
+
+## Pydantic modellen
+
+Pydantic is een Python-pakket voor het uitvoeren van datavalidatie.
+
+Je declareert de "vorm" van de data als klassen met attributen.
+
+Elk attribuut heeft een type.
+
+Vervolgens maak je een instantie van die klasse met een aantal waarden en het valideert de waarden, converteert ze naar het juiste type (als dat het geval is) en geeft je een object met alle data terug.
+
+Daarnaast krijg je volledige editorondersteuning met dat resulterende object.
+
+Een voorbeeld uit de officiële Pydantic-documentatie:
+
+//// tab | Python 3.10+
+
+```Python
+{!> ../../docs_src/python_types/tutorial011_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python
+{!> ../../docs_src/python_types/tutorial011_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python
+{!> ../../docs_src/python_types/tutorial011.py!}
+```
+
+////
+
+/// info
+
+Om meer te leren over Pydantic, bekijk de documentatie.
+
+///
+
+**FastAPI** is volledig gebaseerd op Pydantic.
+
+Je zult veel meer van dit alles in de praktijk zien in de [Tutorial - Gebruikershandleiding](tutorial/index.md){.internal-link target=_blank}.
+
+/// tip
+
+Pydantic heeft een speciaal gedrag wanneer je `Optional` of `Union[EenType, None]` gebruikt zonder een standaardwaarde, je kunt er meer over lezen in de Pydantic-documentatie over Verplichte optionele velden.
+
+///
+
+## Type Hints met Metadata Annotaties
+
+Python heeft ook een functie waarmee je **extra metadata** in deze type hints kunt toevoegen met behulp van `Annotated`.
+
+//// tab | Python 3.9+
+
+In Python 3.9 is `Annotated` onderdeel van de standaardpakket, dus je kunt het importeren vanuit `typing`.
+
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial013_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+In versies lager dan Python 3.9 importeer je `Annotated` vanuit `typing_extensions`.
+
+Het wordt al geïnstalleerd met **FastAPI**.
+
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial013.py!}
+```
+
+////
+
+Python zelf doet niets met deze `Annotated` en voor editors en andere hulpmiddelen is het type nog steeds een `str`.
+
+Maar je kunt deze ruimte in `Annotated` gebruiken om **FastAPI** te voorzien van extra metadata over hoe je wilt dat je applicatie zich gedraagt.
+
+Het belangrijkste om te onthouden is dat **de eerste *typeparameter*** die je doorgeeft aan `Annotated` het **werkelijke type** is. De rest is gewoon metadata voor andere hulpmiddelen.
+
+Voor nu hoef je alleen te weten dat `Annotated` bestaat en dat het standaard Python is. 😎
+
+Later zul je zien hoe **krachtig** het kan zijn.
+
+/// tip
+
+Het feit dat dit **standaard Python** is, betekent dat je nog steeds de **best mogelijke ontwikkelaarservaring** krijgt in je editor, met de hulpmiddelen die je gebruikt om je code te analyseren en te refactoren, enz. ✨
+
+Daarnaast betekent het ook dat je code zeer verenigbaar zal zijn met veel andere Python-hulpmiddelen en -pakketten. 🚀
+
+///
+
+## Type hints in **FastAPI**
+
+**FastAPI** maakt gebruik van type hints om verschillende dingen te doen.
+
+Met **FastAPI** declareer je parameters met type hints en krijg je:
+
+* **Editor ondersteuning**.
+* **Type checks**.
+
+...en **FastAPI** gebruikt dezelfde declaraties om:
+
+* **Vereisten te definïeren **: van request pad parameters, query parameters, headers, bodies, dependencies, enz.
+* **Data te converteren**: van de request naar het vereiste type.
+* **Data te valideren**: afkomstig van elke request:
+ * **Automatische foutmeldingen** te genereren die naar de client worden geretourneerd wanneer de data ongeldig is.
+* De API met OpenAPI te **documenteren**:
+ * die vervolgens wordt gebruikt door de automatische interactieve documentatie gebruikersinterfaces.
+
+Dit klinkt misschien allemaal abstract. Maak je geen zorgen. Je ziet dit allemaal in actie in de [Tutorial - Gebruikershandleiding](tutorial/index.md){.internal-link target=_blank}.
+
+Het belangrijkste is dat door standaard Python types te gebruiken, op één plek (in plaats van meer klassen, decorators, enz. toe te voegen), **FastAPI** een groot deel van het werk voor je doet.
+
+/// info
+
+Als je de hele tutorial al hebt doorgenomen en terug bent gekomen om meer te weten te komen over types, is een goede bron het "cheat sheet" van `mypy`.
+
+///
diff --git a/docs/nl/mkdocs.yml b/docs/nl/mkdocs.yml
new file mode 100644
index 000000000..de18856f4
--- /dev/null
+++ b/docs/nl/mkdocs.yml
@@ -0,0 +1 @@
+INHERIT: ../en/mkdocs.yml
diff --git a/docs/pl/docs/fastapi-people.md b/docs/pl/docs/fastapi-people.md
deleted file mode 100644
index 6c431b401..000000000
--- a/docs/pl/docs/fastapi-people.md
+++ /dev/null
@@ -1,178 +0,0 @@
-# Ludzie FastAPI
-
-FastAPI posiada wspaniałą społeczność, która jest otwarta dla ludzi z każdego środowiska.
-
-## Twórca - Opienik
-
-Cześć! 👋
-
-To ja:
-
-{% if people %}
-email_validator - dla walidacji adresów email.
+* email-validator - dla walidacji adresów email.
Używane przez Starlette:
diff --git a/docs/pl/docs/tutorial/first-steps.md b/docs/pl/docs/tutorial/first-steps.md
index ce71f8b83..99c425f12 100644
--- a/docs/pl/docs/tutorial/first-steps.md
+++ b/docs/pl/docs/tutorial/first-steps.md
@@ -3,7 +3,7 @@
Najprostszy plik FastAPI może wyglądać tak:
```Python
-{!../../../docs_src/first_steps/tutorial001.py!}
+{!../../docs_src/first_steps/tutorial001.py!}
```
Skopiuj to do pliku `main.py`.
@@ -24,12 +24,15 @@ $ uvicorn main:app --reload
-!!! note
- Polecenie `uvicorn main:app` odnosi się do:
+/// note
- * `main`: plik `main.py` ("moduł" Python).
- * `app`: obiekt utworzony w pliku `main.py` w lini `app = FastAPI()`.
- * `--reload`: sprawia, że serwer uruchamia się ponownie po zmianie kodu. Używany tylko w trakcie tworzenia oprogramowania.
+Polecenie `uvicorn main:app` odnosi się do:
+
+* `main`: plik `main.py` ("moduł" Python).
+* `app`: obiekt utworzony w pliku `main.py` w lini `app = FastAPI()`.
+* `--reload`: sprawia, że serwer uruchamia się ponownie po zmianie kodu. Używany tylko w trakcie tworzenia oprogramowania.
+
+///
Na wyjściu znajduje się linia z czymś w rodzaju:
@@ -131,21 +134,23 @@ Możesz go również użyć do automatycznego generowania kodu dla klientów, kt
### Krok 1: zaimportuj `FastAPI`
```Python hl_lines="1"
-{!../../../docs_src/first_steps/tutorial001.py!}
+{!../../docs_src/first_steps/tutorial001.py!}
```
`FastAPI` jest klasą, która zapewnia wszystkie funkcjonalności Twojego API.
-!!! note "Szczegóły techniczne"
- `FastAPI` jest klasą, która dziedziczy bezpośrednio z `Starlette`.
+/// note | "Szczegóły techniczne"
- Oznacza to, że możesz korzystać ze wszystkich funkcjonalności Starlette również w `FastAPI`.
+`FastAPI` jest klasą, która dziedziczy bezpośrednio z `Starlette`.
+Oznacza to, że możesz korzystać ze wszystkich funkcjonalności Starlette również w `FastAPI`.
+
+///
### Krok 2: utwórz instancję `FastAPI`
```Python hl_lines="3"
-{!../../../docs_src/first_steps/tutorial001.py!}
+{!../../docs_src/first_steps/tutorial001.py!}
```
Zmienna `app` będzie tutaj "instancją" klasy `FastAPI`.
@@ -167,7 +172,7 @@ $ uvicorn main:app --reload
Jeśli stworzysz swoją aplikację, np.:
```Python hl_lines="3"
-{!../../../docs_src/first_steps/tutorial002.py!}
+{!../../docs_src/first_steps/tutorial002.py!}
```
I umieścisz to w pliku `main.py`, to będziesz mógł tak wywołać `uvicorn`:
@@ -200,8 +205,11 @@ https://example.com/items/foo
/items/foo
```
-!!! info
- "Ścieżka" jest zazwyczaj nazywana "path", "endpoint" lub "route'.
+/// info
+
+"Ścieżka" jest zazwyczaj nazywana "path", "endpoint" lub "route'.
+
+///
Podczas budowania API, "ścieżka" jest głównym sposobem na oddzielenie "odpowiedzialności" i „zasobów”.
@@ -243,7 +251,7 @@ Będziemy je również nazywali "**operacjami**".
#### Zdefiniuj *dekorator operacji na ścieżce*
```Python hl_lines="6"
-{!../../../docs_src/first_steps/tutorial001.py!}
+{!../../docs_src/first_steps/tutorial001.py!}
```
`@app.get("/")` mówi **FastAPI** że funkcja poniżej odpowiada za obsługę żądań, które trafiają do:
@@ -251,16 +259,19 @@ Będziemy je również nazywali "**operacjami**".
* ścieżki `/`
* używając operacji get
-!!! info "`@decorator` Info"
- Składnia `@something` jest w Pythonie nazywana "dekoratorem".
+/// info | "`@decorator` Info"
- Umieszczasz to na szczycie funkcji. Jak ładną ozdobną czapkę (chyba stąd wzięła się nazwa).
+Składnia `@something` jest w Pythonie nazywana "dekoratorem".
- "Dekorator" przyjmuje funkcję znajdującą się poniżej jego i coś z nią robi.
+Umieszczasz to na szczycie funkcji. Jak ładną ozdobną czapkę (chyba stąd wzięła się nazwa).
- W naszym przypadku dekorator mówi **FastAPI**, że poniższa funkcja odpowiada **ścieżce** `/` z **operacją** `get`.
+"Dekorator" przyjmuje funkcję znajdującą się poniżej jego i coś z nią robi.
- Jest to "**dekorator operacji na ścieżce**".
+W naszym przypadku dekorator mówi **FastAPI**, że poniższa funkcja odpowiada **ścieżce** `/` z **operacją** `get`.
+
+Jest to "**dekorator operacji na ścieżce**".
+
+///
Możesz również użyć innej operacji:
@@ -275,14 +286,17 @@ Oraz tych bardziej egzotycznych:
* `@app.patch()`
* `@app.trace()`
-!!! tip
- Możesz dowolnie używać każdej operacji (metody HTTP).
+/// tip
- **FastAPI** nie narzuca żadnego konkretnego znaczenia.
+Możesz dowolnie używać każdej operacji (metody HTTP).
- Informacje tutaj są przedstawione jako wskazówka, a nie wymóg.
+**FastAPI** nie narzuca żadnego konkretnego znaczenia.
- Na przykład, używając GraphQL, normalnie wykonujesz wszystkie akcje używając tylko operacji `POST`.
+Informacje tutaj są przedstawione jako wskazówka, a nie wymóg.
+
+Na przykład, używając GraphQL, normalnie wykonujesz wszystkie akcje używając tylko operacji `POST`.
+
+///
### Krok 4: zdefiniuj **funkcję obsługującą ścieżkę**
@@ -293,7 +307,7 @@ To jest nasza "**funkcja obsługująca ścieżkę**":
* **funkcja**: to funkcja poniżej "dekoratora" (poniżej `@app.get("/")`).
```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial001.py!}
+{!../../docs_src/first_steps/tutorial001.py!}
```
Jest to funkcja Python.
@@ -307,16 +321,19 @@ W tym przypadku jest to funkcja "asynchroniczna".
Możesz również zdefiniować to jako normalną funkcję zamiast `async def`:
```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial003.py!}
+{!../../docs_src/first_steps/tutorial003.py!}
```
-!!! note
- Jeśli nie znasz różnicy, sprawdź [Async: *"In a hurry?"*](../async.md#in-a-hurry){.internal-link target=_blank}.
+/// note
+
+Jeśli nie znasz różnicy, sprawdź [Async: *"In a hurry?"*](../async.md#in-a-hurry){.internal-link target=_blank}.
+
+///
### Krok 5: zwróć zawartość
```Python hl_lines="8"
-{!../../../docs_src/first_steps/tutorial001.py!}
+{!../../docs_src/first_steps/tutorial001.py!}
```
Możesz zwrócić `dict`, `list`, pojedynczą wartość jako `str`, `int`, itp.
diff --git a/docs/pl/docs/tutorial/index.md b/docs/pl/docs/tutorial/index.md
index f8c5c6022..66f7c6d62 100644
--- a/docs/pl/docs/tutorial/index.md
+++ b/docs/pl/docs/tutorial/index.md
@@ -52,22 +52,25 @@ $ pip install "fastapi[all]"
...wliczając w to `uvicorn`, który będzie służył jako serwer wykonujacy Twój kod.
-!!! note
- Możesz również wykonać instalację "krok po kroku".
+/// note
- Prawdopodobnie zechcesz to zrobić, kiedy będziesz wdrażać swoją aplikację w środowisku produkcyjnym:
+Możesz również wykonać instalację "krok po kroku".
- ```
- pip install fastapi
- ```
+Prawdopodobnie zechcesz to zrobić, kiedy będziesz wdrażać swoją aplikację w środowisku produkcyjnym:
- Zainstaluj też `uvicorn`, który będzie służył jako serwer:
+```
+pip install fastapi
+```
- ```
- pip install "uvicorn[standard]"
- ```
+Zainstaluj też `uvicorn`, który będzie służył jako serwer:
- Tak samo możesz zainstalować wszystkie dodatkowe biblioteki, których chcesz użyć.
+```
+pip install "uvicorn[standard]"
+```
+
+Tak samo możesz zainstalować wszystkie dodatkowe biblioteki, których chcesz użyć.
+
+///
## Zaawansowany poradnik
diff --git a/docs/pt/docs/advanced/additional-responses.md b/docs/pt/docs/advanced/additional-responses.md
index 7c7d22611..46cf1efc3 100644
--- a/docs/pt/docs/advanced/additional-responses.md
+++ b/docs/pt/docs/advanced/additional-responses.md
@@ -1,9 +1,12 @@
# Retornos Adicionais no OpenAPI
-!!! warning "Aviso"
- Este é um tema bem avançado.
+/// warning | "Aviso"
- Se você está começando com o **FastAPI**, provavelmente você não precisa disso.
+Este é um tema bem avançado.
+
+Se você está começando com o **FastAPI**, provavelmente você não precisa disso.
+
+///
Você pode declarar retornos adicionais, com códigos de status adicionais, media types, descrições, etc.
@@ -24,23 +27,29 @@ 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!}
```
-!!! note "Nota"
- Lembre-se que você deve retornar o `JSONResponse` diretamente.
+/// note | "Nota"
-!!! info "Informação"
- A chave `model` não é parte do OpenAPI.
+Lembre-se que você deve retornar o `JSONResponse` diretamente.
- O **FastAPI** pegará o modelo do Pydantic, gerará o `JSON Schema`, e adicionará no local correto.
+///
- O local correto é:
+/// info | "Informação"
- * Na chave `content`, que tem como valor um outro objeto JSON (`dict`) que contém:
- * Uma chave com o media type, como por exemplo `application/json`, que contém como valor um outro objeto JSON, contendo::
- * Uma chave `schema`, que contém como valor o JSON Schema do modelo, sendo este o local correto.
- * O **FastAPI** adiciona aqui a referência dos esquemas JSON globais que estão localizados em outro lugar, ao invés de incluí-lo diretamente. Deste modo, outras aplicações e clientes podem utilizar estes esquemas JSON diretamente, fornecer melhores ferramentas de geração de código, etc.
+A chave `model` não é parte do OpenAPI.
+
+O **FastAPI** pegará o modelo do Pydantic, gerará o `JSON Schema`, e adicionará no local correto.
+
+O local correto é:
+
+* Na chave `content`, que tem como valor um outro objeto JSON (`dict`) que contém:
+ * Uma chave com o media type, como por exemplo `application/json`, que contém como valor um outro objeto JSON, contendo::
+ * Uma chave `schema`, que contém como valor o JSON Schema do modelo, sendo este o local correto.
+ * O **FastAPI** adiciona aqui a referência dos esquemas JSON globais que estão localizados em outro lugar, ao invés de incluí-lo diretamente. Deste modo, outras aplicações e clientes podem utilizar estes esquemas JSON diretamente, fornecer melhores ferramentas de geração de código, etc.
+
+///
O retorno gerado no OpenAI para esta *operação de caminho* será:
@@ -169,16 +178,22 @@ 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!}
```
-!!! note "Nota"
- Note que você deve retornar a imagem utilizando um `FileResponse` diretamente.
+/// note | "Nota"
-!!! 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`).
+Note que você deve retornar a imagem utilizando um `FileResponse` diretamente.
- Porém se você especificou uma classe de retorno com o valor `None` como media type, o FastAPI utilizará `application/json` para qualquer retorno adicional que possui um modelo associado.
+///
+
+/// info | "Informação"
+
+A menos que você especifique um media type diferente explicitamente em seu parâmetro `responses`, o FastAPI assumirá que o retorno possui o mesmo media type contido na classe principal de retorno (padrão `application/json`).
+
+Porém se você especificou uma classe de retorno com o valor `None` como media type, o FastAPI utilizará `application/json` para qualquer retorno adicional que possui um modelo associado.
+
+///
## Combinando informações
@@ -193,7 +208,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!}
```
Isso será combinado e incluído em seu OpenAPI, e disponibilizado na documentação da sua API:
@@ -229,7 +244,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!}
```
## Mais informações sobre retornos OpenAPI
diff --git a/docs/pt/docs/advanced/additional-status-codes.md b/docs/pt/docs/advanced/additional-status-codes.md
index a7699b324..02bb4c015 100644
--- a/docs/pt/docs/advanced/additional-status-codes.md
+++ b/docs/pt/docs/advanced/additional-status-codes.md
@@ -14,53 +14,75 @@ Mas você também deseja aceitar novos itens. E quando os itens não existiam, e
Para conseguir isso, importe `JSONResponse` e retorne o seu conteúdo diretamente, definindo o `status_code` que você deseja:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="4 25"
- {!> ../../../docs_src/additional_status_codes/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="4 25"
+{!> ../../docs_src/additional_status_codes/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="4 25"
- {!> ../../../docs_src/additional_status_codes/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="4 25"
+{!> ../../docs_src/additional_status_codes/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="4 26"
- {!> ../../../docs_src/additional_status_codes/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip "Dica"
- Faça uso da versão `Annotated` quando possível.
+```Python hl_lines="4 26"
+{!> ../../docs_src/additional_status_codes/tutorial001_an.py!}
+```
- ```Python hl_lines="2 23"
- {!> ../../../docs_src/additional_status_codes/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip "Dica"
- Faça uso da versão `Annotated` quando possível.
+/// tip | "Dica"
- ```Python hl_lines="4 25"
- {!> ../../../docs_src/additional_status_codes/tutorial001.py!}
- ```
+Faça uso da versão `Annotated` quando possível.
-!!! warning "Aviso"
- Quando você retorna um `Response` diretamente, como no exemplo acima, ele será retornado diretamente.
+///
- Ele não será serializado com um modelo, etc.
+```Python hl_lines="2 23"
+{!> ../../docs_src/additional_status_codes/tutorial001_py310.py!}
+```
- Garanta que ele tenha toda informação que você deseja, e que os valores sejam um JSON válido (caso você esteja usando `JSONResponse`).
+////
-!!! note "Detalhes técnicos"
- Você também pode utilizar `from starlette.responses import JSONResponse`.
+//// tab | Python 3.8+ non-Annotated
- O **FastAPI** disponibiliza o `starlette.responses` como `fastapi.responses` apenas por conveniência para você, o programador. Porém a maioria dos retornos disponíveis vem diretamente do Starlette. O mesmo com `status`.
+/// tip | "Dica"
+
+Faça uso da versão `Annotated` quando possível.
+
+///
+
+```Python hl_lines="4 25"
+{!> ../../docs_src/additional_status_codes/tutorial001.py!}
+```
+
+////
+
+/// warning | "Aviso"
+
+Quando você retorna um `Response` diretamente, como no exemplo acima, ele será retornado diretamente.
+
+Ele não será serializado com um modelo, etc.
+
+Garanta que ele tenha toda informação que você deseja, e que os valores sejam um JSON válido (caso você esteja usando `JSONResponse`).
+
+///
+
+/// note | "Detalhes técnicos"
+
+Você também pode utilizar `from starlette.responses import JSONResponse`.
+
+O **FastAPI** disponibiliza o `starlette.responses` como `fastapi.responses` apenas por conveniência para você, o programador. Porém a maioria dos retornos disponíveis vem diretamente do Starlette. O mesmo com `status`.
+
+///
## OpenAPI e documentação da API
diff --git a/docs/pt/docs/advanced/advanced-dependencies.md b/docs/pt/docs/advanced/advanced-dependencies.md
index 58887f9c8..a656390a4 100644
--- a/docs/pt/docs/advanced/advanced-dependencies.md
+++ b/docs/pt/docs/advanced/advanced-dependencies.md
@@ -18,26 +18,35 @@ Não propriamente a classe (que já é um chamável), mas a instância desta cla
Para fazer isso, nós declaramos o método `__call__`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="12"
- {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
- ```
+```Python hl_lines="12"
+{!> ../../docs_src/dependencies/tutorial011_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="11"
- {!> ../../../docs_src/dependencies/tutorial011_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="11"
+{!> ../../docs_src/dependencies/tutorial011_an.py!}
+```
- !!! tip "Dica"
- Prefira utilizar a versão `Annotated` se possível.
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/dependencies/tutorial011.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "Dica"
+
+Prefira utilizar a versão `Annotated` se possível.
+
+///
+
+```Python hl_lines="10"
+{!> ../../docs_src/dependencies/tutorial011.py!}
+```
+
+////
Neste caso, o `__call__` é o que o **FastAPI** utilizará para verificar parâmetros adicionais e sub dependências, e isso é o que será chamado para passar o valor ao parâmetro na sua *função de operação de rota* posteriormente.
@@ -45,26 +54,35 @@ Neste caso, o `__call__` é o que o **FastAPI** utilizará para verificar parâm
E agora, nós podemos utilizar o `__init__` para declarar os parâmetros da instância que podemos utilizar para "parametrizar" a dependência:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="9"
- {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/dependencies/tutorial011_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/dependencies/tutorial011_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="8"
+{!> ../../docs_src/dependencies/tutorial011_an.py!}
+```
- !!! tip "Dica"
- Prefira utilizar a versão `Annotated` se possível.
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/dependencies/tutorial011.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "Dica"
+
+Prefira utilizar a versão `Annotated` se possível.
+
+///
+
+```Python hl_lines="7"
+{!> ../../docs_src/dependencies/tutorial011.py!}
+```
+
+////
Neste caso, o **FastAPI** nunca tocará ou se importará com o `__init__`, nós vamos utilizar diretamente em nosso código.
@@ -72,26 +90,35 @@ Neste caso, o **FastAPI** nunca tocará ou se importará com o `__init__`, nós
Nós poderíamos criar uma instância desta classe com:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="18"
- {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
- ```
+```Python hl_lines="18"
+{!> ../../docs_src/dependencies/tutorial011_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial011_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="17"
+{!> ../../docs_src/dependencies/tutorial011_an.py!}
+```
- !!! tip "Dica"
- Prefira utilizar a versão `Annotated` se possível.
+////
- ```Python hl_lines="16"
- {!> ../../../docs_src/dependencies/tutorial011.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "Dica"
+
+Prefira utilizar a versão `Annotated` se possível.
+
+///
+
+```Python hl_lines="16"
+{!> ../../docs_src/dependencies/tutorial011.py!}
+```
+
+////
E deste modo nós podemos "parametrizar" a nossa dependência, que agora possui `"bar"` dentro dele, como o atributo `checker.fixed_content`.
@@ -107,32 +134,44 @@ checker(q="somequery")
...e passar o que quer que isso retorne como valor da dependência em nossa *função de operação de rota* como o parâmetro `fixed_content_included`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="22"
- {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
- ```
+```Python hl_lines="22"
+{!> ../../docs_src/dependencies/tutorial011_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="21"
- {!> ../../../docs_src/dependencies/tutorial011_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="21"
+{!> ../../docs_src/dependencies/tutorial011_an.py!}
+```
- !!! tip "Dica"
- Prefira utilizar a versão `Annotated` se possível.
+////
- ```Python hl_lines="20"
- {!> ../../../docs_src/dependencies/tutorial011.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-!!! tip "Dica"
- Tudo isso parece não ser natural. E pode não estar muito claro ou aparentar ser útil ainda.
+/// tip | "Dica"
- Estes exemplos são intencionalmente simples, porém mostram como tudo funciona.
+Prefira utilizar a versão `Annotated` se possível.
- Nos capítulos sobre segurança, existem funções utilitárias que são implementadas desta maneira.
+///
- Se você entendeu tudo isso, você já sabe como essas funções utilitárias para segurança funcionam por debaixo dos panos.
+```Python hl_lines="20"
+{!> ../../docs_src/dependencies/tutorial011.py!}
+```
+
+////
+
+/// tip | "Dica"
+
+Tudo isso parece não ser natural. E pode não estar muito claro ou aparentar ser útil ainda.
+
+Estes exemplos são intencionalmente simples, porém mostram como tudo funciona.
+
+Nos capítulos sobre segurança, existem funções utilitárias que são implementadas desta maneira.
+
+Se você entendeu tudo isso, você já sabe como essas funções utilitárias para segurança funcionam por debaixo dos panos.
+
+///
diff --git a/docs/pt/docs/advanced/async-tests.md b/docs/pt/docs/advanced/async-tests.md
index 4ccc0c452..c81d6124b 100644
--- a/docs/pt/docs/advanced/async-tests.md
+++ b/docs/pt/docs/advanced/async-tests.md
@@ -33,13 +33,13 @@ 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
@@ -61,16 +61,19 @@ $ 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!}
```
-!!! tip "Dica"
- Note que a função de teste é `async def` agora, no lugar de apenas `def` como quando estávamos utilizando o `TestClient` anteriormente.
+/// tip | "Dica"
+
+Note que a função de teste é `async def` agora, no lugar de apenas `def` como quando estávamos utilizando o `TestClient` anteriormente.
+
+///
Então podemos criar um `AsyncClient` com a aplicação, e enviar requisições assíncronas para ela utilizando `await`.
-```Python hl_lines="9-10"
-{!../../../docs_src/async_tests/test_main.py!}
+```Python hl_lines="9-12"
+{!../../docs_src/async_tests/test_main.py!}
```
Isso é equivalente a:
@@ -81,15 +84,24 @@ response = client.get('/')
...que nós utilizamos para fazer as nossas requisições utilizando o `TestClient`.
-!!! tip "Dica"
- Note que nós estamos utilizando async/await com o novo `AsyncClient` - a requisição é assíncrona.
+/// tip | "Dica"
-!!! 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.
+Note que nós estamos utilizando async/await com o novo `AsyncClient` - a requisição é assíncrona.
+
+///
+
+/// warning | "Aviso"
+
+Se a sua aplicação depende dos eventos de vida útil (*lifespan*), o `AsyncClient` não acionará estes eventos. Para garantir que eles são acionados, utilize o `LifespanManager` do florimondmanca/asgi-lifespan.
+
+///
## Outras Chamadas de Funções Assíncronas
Como a função de teste agora é assíncrona, você pode chamar (e `esperar`) outras funções `async` além de enviar requisições para a sua aplicação FastAPI em seus testes, exatamente como você as chamaria em qualquer outro lugar do seu código.
-!!! tip "Dica"
- Se você se deparar com um `RuntimeError: Task attached to a different loop` ao integrar funções assíncronas em seus testes (e.g. ao utilizar o MotorClient do MongoDB) Lembre-se de instanciar objetos que precisam de um loop de eventos (*event loop*) apenas em funções assíncronas, e.g. um *"callback"* `'@app.on_event("startup")`.
+/// tip | "Dica"
+
+Se você se deparar com um `RuntimeError: Task attached to a different loop` ao integrar funções assíncronas em seus testes (e.g. ao utilizar o MotorClient do MongoDB) Lembre-se de instanciar objetos que precisam de um loop de eventos (*event loop*) apenas em funções assíncronas, e.g. um *"callback"* `'@app.on_event("startup")`.
+
+///
diff --git a/docs/pt/docs/advanced/behind-a-proxy.md b/docs/pt/docs/advanced/behind-a-proxy.md
index 8ac9102a3..3c65b5a0a 100644
--- a/docs/pt/docs/advanced/behind-a-proxy.md
+++ b/docs/pt/docs/advanced/behind-a-proxy.md
@@ -19,7 +19,7 @@ Nesse caso, o caminho original `/app` seria servido em `/api/v1/app`.
Embora todo o seu código esteja escrito assumindo que existe apenas `/app`.
```Python hl_lines="6"
-{!../../../docs_src/behind_a_proxy/tutorial001.py!}
+{!../../docs_src/behind_a_proxy/tutorial001.py!}
```
E o proxy estaria **"removendo"** o **prefixo do caminho** dinamicamente antes de transmitir a solicitação para o servidor da aplicação (provavelmente Uvicorn via CLI do FastAPI), mantendo sua aplicação convencida de que está sendo servida em `/app`, para que você não precise atualizar todo o seu código para incluir o prefixo `/api/v1`.
@@ -43,8 +43,11 @@ browser --> proxy
proxy --> server
```
-!!! tip "Dica"
- O IP `0.0.0.0` é comumente usado para significar que o programa escuta em todos os IPs disponíveis naquela máquina/servidor.
+/// tip | "Dica"
+
+O IP `0.0.0.0` é comumente usado para significar que o programa escuta em todos os IPs disponíveis naquela máquina/servidor.
+
+///
A interface de documentação também precisaria do OpenAPI schema para declarar que API `server` está localizado em `/api/v1` (atrás do proxy). Por exemplo:
@@ -81,10 +84,13 @@ $ fastapi run main.py --root-path /api/v1
Se você usar Hypercorn, ele também tem a opção `--root-path`.
-!!! note "Detalhes Técnicos"
- A especificação ASGI define um `root_path` para esse caso de uso.
+/// note | "Detalhes Técnicos"
- E a opção de linha de comando `--root-path` fornece esse `root_path`.
+A especificação ASGI define um `root_path` para esse caso de uso.
+
+E a opção de linha de comando `--root-path` fornece esse `root_path`.
+
+///
### Verificando o `root_path` atual
@@ -93,7 +99,7 @@ Você pode obter o `root_path` atual usado pela sua aplicação para cada solici
Aqui estamos incluindo ele na mensagem apenas para fins de demonstração.
```Python hl_lines="8"
-{!../../../docs_src/behind_a_proxy/tutorial001.py!}
+{!../../docs_src/behind_a_proxy/tutorial001.py!}
```
Então, se você iniciar o Uvicorn com:
@@ -122,7 +128,7 @@ A resposta seria algo como:
Alternativamente, se você não tiver uma maneira de fornecer uma opção de linha de comando como `--root-path` ou equivalente, você pode definir o parâmetro `--root-path` ao criar sua aplicação FastAPI:
```Python hl_lines="3"
-{!../../../docs_src/behind_a_proxy/tutorial002.py!}
+{!../../docs_src/behind_a_proxy/tutorial002.py!}
```
Passar o `root_path`h para `FastAPI` seria o equivalente a passar a opção de linha de comando `--root-path` para Uvicorn ou Hypercorn.
@@ -172,8 +178,11 @@ Então, crie um arquivo `traefik.toml` com:
Isso diz ao Traefik para escutar na porta 9999 e usar outro arquivo `routes.toml`.
-!!! tip "Dica"
- Estamos usando a porta 9999 em vez da porta padrão HTTP 80 para que você não precise executá-lo com privilégios de administrador (`sudo`).
+/// tip | "Dica"
+
+Estamos usando a porta 9999 em vez da porta padrão HTTP 80 para que você não precise executá-lo com privilégios de administrador (`sudo`).
+
+///
Agora crie esse outro arquivo `routes.toml`:
@@ -239,8 +248,11 @@ Agora, se você for ao URL com a porta para o Uvicorn: http://127.0.0.1:9999/api/v1/app.
@@ -283,8 +295,11 @@ Isso porque o FastAPI usa esse `root_path` para criar o `server` padrão no Open
## Servidores adicionais
-!!! warning "Aviso"
- Este é um caso de uso mais avançado. Sinta-se à vontade para pular.
+/// warning | "Aviso"
+
+Este é um caso de uso mais avançado. Sinta-se à vontade para pular.
+
+///
Por padrão, o **FastAPI** criará um `server` no OpenAPI schema com o URL para o `root_path`.
@@ -295,7 +310,7 @@ Se você passar uma lista personalizada de `servers` e houver um `root_path` (po
Por exemplo:
```Python hl_lines="4-7"
-{!../../../docs_src/behind_a_proxy/tutorial003.py!}
+{!../../docs_src/behind_a_proxy/tutorial003.py!}
```
Gerará um OpenAPI schema como:
@@ -323,22 +338,28 @@ Gerará um OpenAPI schema como:
}
```
-!!! tip "Dica"
- Perceba o servidor gerado automaticamente com um valor `url` de `/api/v1`, retirado do `root_path`.
+/// tip | "Dica"
+
+Perceba o servidor gerado automaticamente com um valor `url` de `/api/v1`, retirado do `root_path`.
+
+///
Na interface de documentação em http://127.0.0.1:9999/api/v1/docs parecerá:
-!!! tip "Dica"
- A interface de documentação interagirá com o servidor que você selecionar.
+/// tip | "Dica"
+
+A interface de documentação interagirá com o servidor que você selecionar.
+
+///
### Desabilitar servidor automático de `root_path`
Se você não quiser que o **FastAPI** inclua um servidor automático usando o `root_path`, você pode usar o parâmetro `root_path_in_servers=False`:
```Python hl_lines="9"
-{!../../../docs_src/behind_a_proxy/tutorial004.py!}
+{!../../docs_src/behind_a_proxy/tutorial004.py!}
```
e então ele não será incluído no OpenAPI schema.
diff --git a/docs/pt/docs/advanced/events.md b/docs/pt/docs/advanced/events.md
index 12aa93f29..02f5b6d2b 100644
--- a/docs/pt/docs/advanced/events.md
+++ b/docs/pt/docs/advanced/events.md
@@ -32,24 +32,27 @@ 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!}
```
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"
- O `shutdown` aconteceria quando você estivesse **encerrando** a aplicação.
+/// tip | "Dica"
- Talvez você precise inicializar uma nova versão, ou apenas cansou de executá-la. 🤷
+O `shutdown` aconteceria quando você estivesse **encerrando** a aplicação.
+
+Talvez você precise inicializar uma nova versão, ou apenas cansou de executá-la. 🤷
+
+///
### Função _lifespan_
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!}
```
A primeira parte da função, antes do `yield`, será executada **antes** da aplicação inicializar.
@@ -63,7 +66,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!}
```
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:
@@ -87,15 +90,18 @@ 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!}
```
## Eventos alternativos (deprecados)
-!!! warning "Aviso"
- A maneira recomendada para lidar com a *inicialização* e o *encerramento* é usando o parâmetro `lifespan` da aplicação `FastAPI` como descrito acima.
+/// warning | "Aviso"
- Você provavelmente pode pular essa parte.
+A maneira recomendada para lidar com a *inicialização* e o *encerramento* é usando o parâmetro `lifespan` da aplicação `FastAPI` como descrito acima.
+
+Você provavelmente pode pular essa parte.
+
+///
Existe uma forma alternativa para definir a execução dessa lógica durante *inicialização* e durante *encerramento*.
@@ -108,7 +114,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!}
```
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.
@@ -122,22 +128,28 @@ 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!}
```
Aqui, a função de manipulação de evento `shutdown` irá escrever uma linha de texto `"Application shutdown"` no arquivo `log.txt`.
-!!! info "Informação"
- Na função `open()`, o `mode="a"` significa "acrescentar", então, a linha irá ser adicionada depois de qualquer coisa que esteja naquele arquivo, sem sobrescrever o conteúdo anterior.
+/// info | "Informação"
-!!! tip "Dica"
- Perceba que nesse caso nós estamos usando a função padrão do Python `open()` que interage com um arquivo.
+Na função `open()`, o `mode="a"` significa "acrescentar", então, a linha irá ser adicionada depois de qualquer coisa que esteja naquele arquivo, sem sobrescrever o conteúdo anterior.
- Então, isso envolve I/O (input/output), que exige "esperar" que coisas sejam escritas em disco.
+///
- Mas `open()` não usa `async` e `await`.
+/// tip | "Dica"
- Então, nós declaramos uma função de manipulação de evento com o padrão `def` ao invés de `async def`.
+Perceba que nesse caso nós estamos usando a função padrão do Python `open()` que interage com um arquivo.
+
+Então, isso envolve I/O (input/output), que exige "esperar" que coisas sejam escritas em disco.
+
+Mas `open()` não usa `async` e `await`.
+
+Então, nós declaramos uma função de manipulação de evento com o padrão `def` ao invés de `async def`.
+
+///
### `startup` e `shutdown` juntos
@@ -153,10 +165,13 @@ Só um detalhe técnico para nerds curiosos. 🤓
Por baixo, na especificação técnica ASGI, essa é a parte do Protocolo Lifespan, e define eventos chamados `startup` e `shutdown`.
-!!! info "Informação"
- Você pode ler mais sobre o manipulador `lifespan` do Starlette na Documentação do Lifespan Starlette.
+/// info | "Informação"
- Incluindo como manipular estado do lifespan que pode ser usado em outras áreas do seu código.
+Você pode ler mais sobre o manipulador `lifespan` do Starlette na Documentação do Lifespan Starlette.
+
+Incluindo como manipular estado do lifespan que pode ser usado em outras áreas do seu código.
+
+///
## Sub Aplicações
diff --git a/docs/pt/docs/advanced/index.md b/docs/pt/docs/advanced/index.md
index 413d8815f..2569fc914 100644
--- a/docs/pt/docs/advanced/index.md
+++ b/docs/pt/docs/advanced/index.md
@@ -6,10 +6,13 @@ O [Tutorial - Guia de Usuário](../tutorial/index.md){.internal-link target=_bla
Na próxima seção você verá outras opções, configurações, e recursos adicionais.
-!!! tip "Dica"
- As próximas seções **não são necessáriamente "avançadas"**
+/// tip | "Dica"
- E é possível que para seu caso de uso, a solução esteja em uma delas.
+As próximas seções **não são necessáriamente "avançadas"**
+
+E é possível que para seu caso de uso, a solução esteja em uma delas.
+
+///
## Leia o Tutorial primeiro
diff --git a/docs/pt/docs/advanced/openapi-webhooks.md b/docs/pt/docs/advanced/openapi-webhooks.md
index 932fe0d9a..5a0226c74 100644
--- a/docs/pt/docs/advanced/openapi-webhooks.md
+++ b/docs/pt/docs/advanced/openapi-webhooks.md
@@ -22,21 +22,27 @@ Com o **FastAPI**, utilizando o OpenAPI, você pode definir os nomes destes webh
Isto pode facilitar bastante para os seus usuários **implementarem as APIs deles** para receber as requisições dos seus **webhooks**, eles podem inclusive ser capazes de gerar parte do código da API deles.
-!!! info "Informação"
- Webhooks estão disponíveis a partir do OpenAPI 3.1.0, e possui suporte do FastAPI a partir da versão `0.99.0`.
+/// info | "Informação"
+
+Webhooks estão disponíveis a partir do OpenAPI 3.1.0, e possui suporte do FastAPI a partir da versão `0.99.0`.
+
+///
## Uma aplicação com webhooks
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!}
```
Os webhooks que você define aparecerão no esquema do **OpenAPI** e na **página de documentação** gerada automaticamente.
-!!! info "Informação"
- O objeto `app.webhooks` é na verdade apenas um `APIRouter`, o mesmo tipo que você utilizaria ao estruturar a sua aplicação com diversos arquivos.
+/// info | "Informação"
+
+O objeto `app.webhooks` é na verdade apenas um `APIRouter`, o mesmo tipo que você utilizaria ao estruturar a sua aplicação com diversos arquivos.
+
+///
Note que utilizando webhooks você não está de fato declarando uma **rota** (como `/items/`), o texto que informa é apenas um **identificador** do webhook (o nome do evento), por exemplo em `@app.webhooks.post("new-subscription")`, o nome do webhook é `new-subscription`.
diff --git a/docs/pt/docs/advanced/response-change-status-code.md b/docs/pt/docs/advanced/response-change-status-code.md
index 99695c831..2ac5eca18 100644
--- a/docs/pt/docs/advanced/response-change-status-code.md
+++ b/docs/pt/docs/advanced/response-change-status-code.md
@@ -21,7 +21,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!}
```
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-directly.md b/docs/pt/docs/advanced/response-directly.md
new file mode 100644
index 000000000..fd2a0eef1
--- /dev/null
+++ b/docs/pt/docs/advanced/response-directly.md
@@ -0,0 +1,70 @@
+# Retornando uma Resposta Diretamente
+
+Quando você cria uma *operação de rota* no **FastAPI** você pode retornar qualquer dado nela: um dicionário (`dict`), uma lista (`list`), um modelo do Pydantic ou do seu banco de dados, etc.
+
+Por padrão, o **FastAPI** irá converter automaticamente o valor do retorno para JSON utilizando o `jsonable_encoder` explicado em [JSON Compatible Encoder](../tutorial/encoder.md){.internal-link target=_blank}.
+
+Então, por baixo dos panos, ele incluiria esses dados compatíveis com JSON (e.g. um `dict`) dentro de uma `JSONResponse` que é utilizada para enviar uma resposta para o cliente.
+
+Mas você pode retornar a `JSONResponse` diretamente nas suas *operações de rota*.
+
+Pode ser útil para retornar cabeçalhos e cookies personalizados, por exemplo.
+
+## Retornando uma `Response`
+
+Na verdade, você pode retornar qualquer `Response` ou subclasse dela.
+
+/// tip | Dica
+
+A própria `JSONResponse` é uma subclasse de `Response`.
+
+///
+
+E quando você retorna uma `Response`, o **FastAPI** vai repassá-la diretamente.
+
+Ele não vai fazer conversões de dados com modelos do Pydantic, não irá converter a tipagem de nenhum conteúdo, etc.
+
+Isso te dá bastante flexibilidade. Você pode retornar qualquer tipo de dado, sobrescrever qualquer declaração e validação nos dados, etc.
+
+## Utilizando o `jsonable_encoder` em uma `Response`
+
+Como o **FastAPI** não realiza nenhuma mudança na `Response` que você retorna, você precisa garantir que o conteúdo dela está pronto para uso.
+
+Por exemplo, você não pode colocar um modelo do Pydantic em uma `JSONResponse` sem antes convertê-lo em um `dict` com todos os tipos de dados (como `datetime`, `UUID`, etc) convertidos para tipos compatíveis com JSON.
+
+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!}
+```
+
+/// note | Detalhes Técnicos
+
+Você também pode utilizar `from starlette.responses import JSONResponse`.
+
+**FastAPI** utiliza a mesma `starlette.responses` como `fastapi.responses` apenas como uma conveniência para você, desenvolvedor. Mas maior parte das respostas disponíveis vem diretamente do Starlette.
+
+///
+
+## Retornando uma `Response`
+
+O exemplo acima mostra todas as partes que você precisa, mas ainda não é muito útil, já que você poderia ter retornado o `item` diretamente, e o **FastAPI** colocaria em uma `JSONResponse` para você, convertendo em um `dict`, etc. Tudo isso por padrão.
+
+Agora, vamos ver como você pode usar isso para retornar uma resposta personalizada.
+
+Vamos dizer quer retornar uma resposta XML.
+
+Você pode colocar o seu conteúdo XML em uma string, colocar em uma `Response`, e retorná-lo:
+
+```Python hl_lines="1 18"
+{!../../docs_src/response_directly/tutorial002.py!}
+```
+
+## Notas
+
+Quando você retorna uma `Response` diretamente os dados não são validados, convertidos (serializados) ou documentados automaticamente.
+
+Mas você ainda pode documentar como descrito em [Retornos Adicionais no OpenAPI
+](additional-responses.md){.internal-link target=_blank}.
+
+Você pode ver nas próximas seções como usar/declarar essas `Responses` customizadas enquanto mantém a conversão e documentação automática dos dados.
diff --git a/docs/pt/docs/advanced/security/http-basic-auth.md b/docs/pt/docs/advanced/security/http-basic-auth.md
new file mode 100644
index 000000000..26983a103
--- /dev/null
+++ b/docs/pt/docs/advanced/security/http-basic-auth.md
@@ -0,0 +1,192 @@
+# HTTP Basic Auth
+
+Para os casos mais simples, você pode utilizar o HTTP Basic Auth.
+
+No HTTP Basic Auth, a aplicação espera um cabeçalho que contém um usuário e uma senha.
+
+Caso ela não receba, ela retorna um erro HTTP 401 "Unauthorized" (*Não Autorizado*).
+
+E retorna um cabeçalho `WWW-Authenticate` com o valor `Basic`, e um parâmetro opcional `realm`.
+
+Isso sinaliza ao navegador para mostrar o prompt integrado para um usuário e senha.
+
+Então, quando você digitar o usuário e senha, o navegador os envia automaticamente no cabeçalho.
+
+## HTTP Basic Auth Simples
+
+* Importe `HTTPBasic` e `HTTPBasicCredentials`.
+* Crie um "esquema `security`" utilizando `HTTPBasic`.
+* Utilize o `security` com uma dependência em sua *operação de rota*.
+* Isso retorna um objeto do tipo `HTTPBasicCredentials`:
+ * Isto contém o `username` e o `password` enviado.
+
+//// 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 | "Dica"
+
+Prefira utilizar a versão `Annotated` se possível.
+
+///
+
+```Python hl_lines="2 6 10"
+{!> ../../docs_src/security/tutorial006.py!}
+```
+
+////
+
+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:
+
+
+
+## Verifique o usuário
+
+Aqui está um exemplo mais completo.
+
+Utilize uma dependência para verificar se o usuário e a senha estão corretos.
+
+Para isso, utilize o módulo padrão do Python `secrets` para verificar o usuário e senha.
+
+O `secrets.compare_digest()` necessita receber `bytes` ou `str` que possuem apenas caracteres ASCII (os em inglês). Isso significa que não funcionaria com caracteres como o `á`, como em `Sebastián`.
+
+Para lidar com isso, primeiramente nós convertemos o `username` e o `password` para `bytes`, codificando-os com UTF-8.
+
+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!}
+```
+
+////
+
+Isso seria parecido com:
+
+```Python
+if not (credentials.username == "stanleyjobson") or not (credentials.password == "swordfish"):
+ # Return some error
+ ...
+```
+
+Porém, ao utilizar o `secrets.compare_digest()`, isso estará seguro contra um tipo de ataque chamado "timing attacks" (ataques de temporização).
+
+### Ataques de Temporização
+
+Mas o que é um "timing attack" (ataque de temporização)?
+
+Vamos imaginar que alguns invasores estão tentando adivinhar o usuário e a senha.
+
+E eles enviam uma requisição com um usuário `johndoe` e uma senha `love123`.
+
+Então o código Python em sua aplicação seria equivalente a algo como:
+
+```Python
+if "johndoe" == "stanleyjobson" and "love123" == "swordfish":
+ ...
+```
+
+Mas no exato momento que o Python compara o primeiro `j` em `johndoe` contra o primeiro `s` em `stanleyjobson`, ele retornará `False`, porque ele já sabe que aquelas duas strings não são a mesma, pensando que "não existe a necessidade de desperdiçar mais poder computacional comparando o resto das letras". E a sua aplicação dirá "Usuário ou senha incorretos".
+
+Então os invasores vão tentar com o usuário `stanleyjobsox` e a senha `love123`.
+
+E a sua aplicação faz algo como:
+
+```Python
+if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish":
+ ...
+```
+
+O Python terá que comparar todo o `stanleyjobso` tanto em `stanleyjobsox` como em `stanleyjobson` antes de perceber que as strings não são a mesma. Então isso levará alguns microssegundos a mais para retornar "Usuário ou senha incorretos".
+
+#### O tempo para responder ajuda os invasores
+
+Neste ponto, ao perceber que o servidor demorou alguns microssegundos a mais para enviar o retorno "Usuário ou senha incorretos", os invasores irão saber que eles acertaram _alguma coisa_, algumas das letras iniciais estavam certas.
+
+E eles podem tentar de novo sabendo que provavelmente é algo mais parecido com `stanleyjobsox` do que com `johndoe`.
+
+#### Um ataque "profissional"
+
+Claro, os invasores não tentariam tudo isso de forma manual, eles escreveriam um programa para fazer isso, possivelmente com milhares ou milhões de testes por segundo. E obteriam apenas uma letra a mais por vez.
+
+Mas fazendo isso, em alguns minutos ou horas os invasores teriam adivinhado o usuário e senha corretos, com a "ajuda" da nossa aplicação, apenas usando o tempo levado para responder.
+
+#### Corrija com o `secrets.compare_digest()`
+
+Mas em nosso código já estamos utilizando o `secrets.compare_digest()`.
+
+Resumindo, levará o mesmo tempo para comparar `stanleyjobsox` com `stanleyjobson` do que comparar `johndoe` com `stanleyjobson`. E o mesmo para a senha.
+
+Deste modo, ao utilizar `secrets.compare_digest()` no código de sua aplicação, ela estará a salvo contra toda essa gama de ataques de segurança.
+
+
+### Retorne o erro
+
+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!}
+```
+
+////
diff --git a/docs/pt/docs/advanced/security/index.md b/docs/pt/docs/advanced/security/index.md
new file mode 100644
index 000000000..ae63f1c96
--- /dev/null
+++ b/docs/pt/docs/advanced/security/index.md
@@ -0,0 +1,19 @@
+# Segurança Avançada
+
+## Funcionalidades Adicionais
+
+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"
+
+As próximas seções **não são necessariamente "avançadas"**.
+
+E é possível que para o seu caso de uso, a solução está em uma delas.
+
+///
+
+## Leia o Tutorial primeiro
+
+As próximas seções pressupõem que você já leu o principal [Tutorial - Guia de Usuário: Segurança](../../tutorial/security/index.md){.internal-link target=_blank}.
+
+Todas elas são baseadas nos mesmos conceitos, mas permitem algumas funcionalidades extras.
diff --git a/docs/pt/docs/advanced/security/oauth2-scopes.md b/docs/pt/docs/advanced/security/oauth2-scopes.md
new file mode 100644
index 000000000..fa4594c89
--- /dev/null
+++ b/docs/pt/docs/advanced/security/oauth2-scopes.md
@@ -0,0 +1,786 @@
+# Escopos OAuth2
+
+Você pode utilizar escopos do OAuth2 diretamente com o **FastAPI**, eles são integrados para funcionar perfeitamente.
+
+Isso permitiria que você tivesse um sistema de permissionamento mais refinado, seguindo o padrão do OAuth2 integrado na sua aplicação OpenAPI (e as documentações da API).
+
+OAuth2 com escopos é o mecanismo utilizado por muitos provedores de autenticação, como o Facebook, Google, GitHub, Microsoft, Twitter, etc. Eles utilizam isso para prover permissões específicas para os usuários e aplicações.
+
+Toda vez que você "se autentica com" Facebook, Google, GitHub, Microsoft, Twitter, aquela aplicação está utilizando o OAuth2 com escopos.
+
+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"
+
+Isso é uma seção mais ou menos avançada. Se você está apenas começando, você pode pular.
+
+Você não necessariamente precisa de escopos do OAuth2, e você pode lidar com autenticação e autorização da maneira que você achar melhor.
+
+Mas o OAuth2 com escopos pode ser integrado de maneira fácil em sua API (com OpenAPI) e a sua documentação de API.
+
+No entando, você ainda aplica estes escopos, ou qualquer outro requisito de segurança/autorização, conforme necessário, em seu código.
+
+Em muitos casos, OAuth2 com escopos pode ser um exagero.
+
+Mas se você sabe que precisa, ou está curioso, continue lendo.
+
+///
+
+## Escopos OAuth2 e OpenAPI
+
+A especificação OAuth2 define "escopos" como uma lista de strings separadas por espaços.
+
+O conteúdo de cada uma dessas strings pode ter qualquer formato, mas não devem possuir espaços.
+
+Estes escopos representam "permissões".
+
+No OpenAPI (e.g. os documentos da API), você pode definir "esquemas de segurança".
+
+Quando um desses esquemas de segurança utiliza OAuth2, você pode também declarar e utilizar escopos.
+
+Cada "escopo" é apenas uma string (sem espaços).
+
+Eles são normalmente utilizados para declarar permissões de segurança específicas, como por exemplo:
+
+* `users:read` or `users:write` são exemplos comuns.
+* `instagram_basic` é utilizado pelo Facebook / Instagram.
+* `https://www.googleapis.com/auth/drive` é utilizado pelo Google.
+
+/// info | Informação
+
+No OAuth2, um "escopo" é apenas uma string que declara uma permissão específica necessária.
+
+Não importa se ela contém outros caracteres como `:` ou se ela é uma URL.
+
+Estes detalhes são específicos da implementação.
+
+Para o OAuth2, eles são apenas strings.
+
+///
+
+## Visão global
+
+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!}
+```
+
+////
+
+Agora vamos revisar essas mudanças passo a passo.
+
+## Esquema de segurança OAuth2
+
+A primeira mudança é que agora nós estamos declarando o esquema de segurança OAuth2 com dois escopos disponíveis, `me` e `items`.
+
+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!}
+```
+
+////
+
+Pelo motivo de estarmos declarando estes escopos, eles aparecerão nos documentos da API quando você se autenticar/autorizar.
+
+E você poderá selecionar quais escopos você deseja dar acesso: `me` e `items`.
+
+Este é o mesmo mecanismo utilizado quando você adiciona permissões enquanto se autentica com o Facebook, Google, GitHub, etc:
+
+
+
+## Token JWT com escopos
+
+Agora, modifique o *caminho de rota* para retornar os escopos solicitados.
+
+Nós ainda estamos utilizando o mesmo `OAuth2PasswordRequestForm`. Ele inclui a propriedade `scopes` com uma `list` de `str`, com cada escopo que ele recebeu na requisição.
+
+E nós retornamos os escopos como parte do token JWT.
+
+/// danger | Cuidado
+
+Para manter as coisas simples, aqui nós estamos apenas adicionando os escopos recebidos diretamente ao token.
+
+Porém em sua aplicação, por segurança, você deve garantir que você apenas adiciona os escopos que o usuário possui permissão de fato, ou aqueles que você predefiniu.
+
+///
+
+//// 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!}
+```
+
+////
+
+## Declare escopos em *operações de rota* e dependências
+
+Agora nós declaramos que a *operação de rota* para `/users/me/items/` exige o escopo `items`.
+
+Para isso, nós importamos e utilizamos `Security` de `fastapi`.
+
+Você pode utilizar `Security` para declarar dependências (assim como `Depends`), porém o `Security` também recebe o parâmetros `scopes` com uma lista de escopos (strings).
+
+Neste caso, nós passamos a função `get_current_active_user` como dependência para `Security` (da mesma forma que nós faríamos com `Depends`).
+
+Mas nós também passamos uma `list` de escopos, neste caso com apenas um escopo: `items` (poderia ter mais).
+
+E a função de dependência `get_current_active_user` também pode declarar subdependências, não apenas com `Depends`, mas também com `Security`. Ao declarar sua própria função de subdependência (`get_current_user`), e mais requisitos de escopo.
+
+Neste caso, ele requer o escopo `me` (poderia requerer mais de um escopo).
+
+/// note | "Nota"
+
+Você não necessariamente precisa adicionar diferentes escopos em diferentes lugares.
+
+Nós estamos fazendo isso aqui para demonstrar como o **FastAPI** lida com escopos declarados em diferentes níveis.
+
+///
+
+//// 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!}
+```
+
+////
+
+/// info | Informações Técnicas
+
+`Security` é na verdade uma subclasse de `Depends`, e ele possui apenas um parâmetro extra que veremos depois.
+
+Porém ao utilizar `Security` no lugar de `Depends`, o **FastAPI** saberá que ele pode declarar escopos de segurança, utilizá-los internamente, e documentar a API com o OpenAPI.
+
+Mas quando você importa `Query`, `Path`, `Depends`, `Security` entre outros de `fastapi`, eles são na verdade funções que retornam classes especiais.
+
+///
+
+## Utilize `SecurityScopes`
+
+Agora atualize a dependência `get_current_user`.
+
+Este é o usado pelas dependências acima.
+
+Aqui é onde estamos utilizando o mesmo esquema OAuth2 que nós declaramos antes, declarando-o como uma dependência: `oauth2_scheme`.
+
+Porque esta função de dependência não possui nenhum requerimento de escopo, nós podemos utilizar `Depends` com o `oauth2_scheme`. Nós não precisamos utilizar `Security` quando nós não precisamos especificar escopos de segurança.
+
+Nós também declaramos um parâmetro especial do tipo `SecurityScopes`, importado de `fastapi.security`.
+
+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!}
+```
+
+////
+
+## Utilize os `scopes`
+
+O parâmetro `security_scopes` será do tipo `SecurityScopes`.
+
+Ele terá a propriedade `scopes` com uma lista contendo todos os escopos requeridos por ele e todas as dependências que utilizam ele como uma subdependência. Isso significa, todos os "dependentes"... pode soar meio confuso, e isso será explicado novamente mais adiante.
+
+O objeto `security_scopes` (da classe `SecurityScopes`) também oferece um atributo `scope_str` com uma única string, contendo os escopos separados por espaços (nós vamos utilizar isso).
+
+Nós criamos uma `HTTPException` que nós podemos reutilizar (`raise`) mais tarde em diversos lugares.
+
+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!}
+```
+
+////
+
+## Verifique o `username` e o formato dos dados
+
+Nós verificamos que nós obtemos um `username`, e extraímos os escopos.
+
+E depois nós validamos esse dado com o modelo Pydantic (capturando a exceção `ValidationError`), e se nós obtemos um erro ao ler o token JWT ou validando os dados com o Pydantic, nós levantamos a exceção `HTTPException` que criamos anteriormente.
+
+Para isso, nós atualizamos o modelo Pydantic `TokenData` com a nova propriedade `scopes`.
+
+Ao validar os dados com o Pydantic nós podemos garantir que temos, por exemplo, exatamente uma `list` de `str` com os escopos e uma `str` com o `username`.
+
+No lugar de, por exemplo, um `dict`, ou alguma outra coisa, que poderia quebrar a aplicação em algum lugar mais tarde, tornando isso um risco de segurança.
+
+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!}
+```
+
+////
+
+## Verifique os `scopes`
+
+Nós verificamos agora que todos os escopos necessários, por essa dependência e todos os dependentes (incluindo as *operações de rota*) estão incluídas nos escopos fornecidos pelo token recebido, caso contrário, levantamos uma `HTTPException`.
+
+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!}
+```
+
+////
+
+## Árvore de dependência e escopos
+
+Vamos rever novamente essa árvore de dependência e os escopos.
+
+Como a dependência `get_current_active_user` possui uma subdependência em `get_current_user`, o escopo `"me"` declarado em `get_current_active_user` será incluído na lista de escopos necessários em `security_scopes.scopes` passado para `get_current_user`.
+
+A própria *operação de rota* também declara o escopo, `"items"`, então ele também estará na lista de `security_scopes.scopes` passado para o `get_current_user`.
+
+Aqui está como a hierarquia de dependências e escopos parecem:
+
+* A *operação de rota* `read_own_items` possui:
+ * Escopos necessários `["items"]` com a dependência:
+ * `get_current_active_user`:
+ * A função de dependência `get_current_active_user` possui:
+ * Escopos necessários `["me"]` com a dependência:
+ * `get_current_user`:
+ * A função de dependência `get_current_user` possui:
+ * Nenhum escopo necessário.
+ * Uma dependência utilizando `oauth2_scheme`.
+ * Um parâmetro `security_scopes` do tipo `SecurityScopes`:
+ * Este parâmetro `security_scopes` possui uma propriedade `scopes` com uma `list` contendo todos estes escopos declarados acima, então:
+ * `security_scopes.scopes` terá `["me", "items"]` para a *operação de rota* `read_own_items`.
+ * `security_scopes.scopes` terá `["me"]` para a *operação de rota* `read_users_me`, porque ela declarou na dependência `get_current_active_user`.
+ * `security_scopes.scopes` terá `[]` (nada) para a *operação de rota* `read_system_status`, porque ele não declarou nenhum `Security` com `scopes`, e sua dependência, `get_current_user`, não declara nenhum `scopes` também.
+
+/// tip | Dica
+
+A coisa importante e "mágica" aqui é que `get_current_user` terá diferentes listas de `scopes` para validar para cada *operação de rota*.
+
+Tudo depende dos `scopes` declarados em cada *operação de rota* e cada dependência da árvore de dependências para aquela *operação de rota* específica.
+
+///
+
+## Mais detalhes sobre `SecurityScopes`
+
+Você pode utilizar `SecurityScopes` em qualquer lugar, e em diversos lugares. Ele não precisa estar na dependência "raiz".
+
+Ele sempre terá os escopos de segurança declarados nas dependências atuais de `Security` e todos os dependentes para **aquela** *operação de rota* **específica** e **aquela** árvore de dependência **específica**.
+
+Porque o `SecurityScopes` terá todos os escopos declarados por dependentes, você pode utilizá-lo para verificar se o token possui os escopos necessários em uma função de dependência central, e depois declarar diferentes requisitos de escopo em diferentes *operações de rota*.
+
+Todos eles serão validados independentemente para cada *operação de rota*.
+
+## Verifique
+
+Se você abrir os documentos da API, você pode antenticar e especificar quais escopos você quer autorizar.
+
+
+
+Se você não selecionar nenhum escopo, você terá "autenticado", mas quando você tentar acessar `/users/me/` ou `/users/me/items/`, você vai obter um erro dizendo que você não possui as permissões necessárias. Você ainda poderá acessar `/status/`.
+
+E se você selecionar o escopo `me`, mas não o escopo `items`, você poderá acessar `/users/me/`, mas não `/users/me/items/`.
+
+Isso é o que aconteceria se uma aplicação terceira que tentou acessar uma dessas *operações de rota* com um token fornecido por um usuário, dependendo de quantas permissões o usuário forneceu para a aplicação.
+
+## Sobre integrações de terceiros
+
+Neste exemplos nós estamos utilizando o fluxo de senha do OAuth2.
+
+Isso é apropriado quando nós estamos autenticando em nossa própria aplicação, provavelmente com o nosso próprio "*frontend*".
+
+Porque nós podemos confiar nele para receber o `username` e o `password`, pois nós controlamos isso.
+
+Mas se nós estamos construindo uma aplicação OAuth2 que outros poderiam conectar (i.e., se você está construindo um provedor de autenticação equivalente ao Facebook, Google, GitHub, etc.) você deveria utilizar um dos outros fluxos.
+
+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"
+
+É comum que cada provedor de autenticação nomeie os seus fluxos de forma diferente, para torná-lo parte de sua marca.
+
+Mas no final, eles estão implementando o mesmo padrão OAuth2.
+
+///
+
+O **FastAPI** inclui utilitários para todos esses fluxos de autenticação OAuth2 em `fastapi.security.oauth2`.
+
+## `Security` em docoradores de `dependências`
+
+Da mesma forma que você pode definir uma `list` de `Depends` no parâmetro de `dependencias` do decorador (como explicado em [Dependências em decoradores de operações de rota](../../tutorial/dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}), você também pode utilizar `Security` com escopos lá.
diff --git a/docs/pt/docs/advanced/settings.md b/docs/pt/docs/advanced/settings.md
index f6962831f..d32b70ed4 100644
--- a/docs/pt/docs/advanced/settings.md
+++ b/docs/pt/docs/advanced/settings.md
@@ -8,44 +8,51 @@ Por isso é comum prover essas configurações como variáveis de ambiente que s
## Variáveis de Ambiente
-!!! dica
- Se você já sabe o que são variáveis de ambiente e como utilizá-las, sinta-se livre para avançar para o próximo tópico.
+/// dica
+
+Se você já sabe o que são variáveis de ambiente e como utilizá-las, sinta-se livre para avançar para o próximo tópico.
+
+///
Uma variável de ambiente (abreviada em inglês para "env var") é uma variável definida fora do código Python, no sistema operacional, e pode ser lida pelo seu código Python (ou por outros programas).
Você pode criar e utilizar variáveis de ambiente no terminal, sem precisar utilizar Python:
-=== "Linux, macOS, Windows Bash"
+//// tab | Linux, macOS, Windows Bash
-
+
+---
+
+Agora que sabemos a diferença entre os termos **processo** e **programa**, vamos continuar falando sobre implantações.
+
+## Executando na inicialização
+
+Na maioria dos casos, quando você cria uma API web, você quer que ela esteja **sempre em execução**, ininterrupta, para que seus clientes possam sempre acessá-la. Isso é claro, a menos que você tenha um motivo específico para querer que ela seja executada somente em certas situações, mas na maioria das vezes você quer que ela esteja constantemente em execução e **disponível**.
+
+### Em um servidor remoto
+
+Ao configurar um servidor remoto (um servidor em nuvem, uma máquina virtual, etc.), a coisa mais simples que você pode fazer é usar `fastapi run` (que usa Uvicorn) ou algo semelhante, manualmente, da mesma forma que você faz ao desenvolver localmente.
+
+E funcionará e será útil **durante o desenvolvimento**.
+
+Mas se sua conexão com o servidor for perdida, o **processo em execução** provavelmente morrerá.
+
+E se o servidor for reiniciado (por exemplo, após atualizações ou migrações do provedor de nuvem), você provavelmente **não notará**. E por causa disso, você nem saberá que precisa reiniciar o processo manualmente. Então, sua API simplesmente permanecerá inativa. 😱
+
+### Executar automaticamente na inicialização
+
+Em geral, você provavelmente desejará que o programa do servidor (por exemplo, Uvicorn) seja iniciado automaticamente na inicialização do servidor e, sem precisar de nenhuma **intervenção humana**, tenha um processo sempre em execução com sua API (por exemplo, Uvicorn executando seu aplicativo FastAPI).
+
+### Programa separado
+
+Para conseguir isso, você normalmente terá um **programa separado** que garantiria que seu aplicativo fosse executado na inicialização. E em muitos casos, ele também garantiria que outros componentes ou aplicativos também fossem executados, por exemplo, um banco de dados.
+
+### Ferramentas de exemplo para executar na inicialização
+
+Alguns exemplos de ferramentas que podem fazer esse trabalho são:
+
+* Docker
+* Kubernetes
+* Docker Compose
+* Docker em Modo Swarm
+* Systemd
+* Supervisor
+* Gerenciado internamente por um provedor de nuvem como parte de seus serviços
+* Outros...
+
+Darei exemplos mais concretos nos próximos capítulos.
+
+## Reinicializações
+
+Semelhante a garantir que seu aplicativo seja executado na inicialização, você provavelmente também deseja garantir que ele seja **reiniciado** após falhas.
+
+### Nós cometemos erros
+
+Nós, como humanos, cometemos **erros** o tempo todo. O software quase *sempre* tem **bugs** escondidos em lugares diferentes. 🐛
+
+E nós, como desenvolvedores, continuamos aprimorando o código à medida que encontramos esses bugs e implementamos novos recursos (possivelmente adicionando novos bugs também 😅).
+
+### Pequenos erros são tratados automaticamente
+
+Ao criar APIs da web com FastAPI, se houver um erro em nosso código, o FastAPI normalmente o conterá na única solicitação que acionou o erro. 🛡
+
+O cliente receberá um **Erro Interno do Servidor 500** para essa solicitação, mas o aplicativo continuará funcionando para as próximas solicitações em vez de travar completamente.
+
+### Erros maiores - Travamentos
+
+No entanto, pode haver casos em que escrevemos algum código que **trava todo o aplicativo**, fazendo com que o Uvicorn e o Python travem. 💥
+
+E ainda assim, você provavelmente não gostaria que o aplicativo permanecesse inativo porque houve um erro em um lugar, você provavelmente quer que ele **continue em execução** pelo menos para as *operações de caminho* que não estão quebradas.
+
+### Reiniciar após falha
+
+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"
+
+...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.
+
+Então, vamos nos concentrar nos casos principais, onde ele pode travar completamente em alguns casos específicos **no futuro**, e ainda faz sentido reiniciá-lo.
+
+///
+
+Você provavelmente gostaria de ter a coisa responsável por reiniciar seu aplicativo como um **componente externo**, porque a essa altura, o mesmo aplicativo com Uvicorn e Python já havia travado, então não há nada no mesmo código do mesmo aplicativo que possa fazer algo a respeito.
+
+### Ferramentas de exemplo para reiniciar automaticamente
+
+Na maioria dos casos, a mesma ferramenta usada para **executar o programa na inicialização** também é usada para lidar com **reinicializações** automáticas.
+
+Por exemplo, isso poderia ser resolvido por:
+
+* Docker
+* Kubernetes
+* Docker Compose
+* Docker no Modo Swarm
+* Systemd
+* Supervisor
+* Gerenciado internamente por um provedor de nuvem como parte de seus serviços
+* Outros...
+
+## Replicação - Processos e Memória
+
+Com um aplicativo FastAPI, usando um programa de servidor como o comando `fastapi` que executa o Uvicorn, executá-lo uma vez em **um processo** pode atender a vários clientes simultaneamente.
+
+Mas em muitos casos, você desejará executar vários processos de trabalho ao mesmo tempo.
+
+### Processos Múltiplos - Trabalhadores
+
+Se você tiver mais clientes do que um único processo pode manipular (por exemplo, se a máquina virtual não for muito grande) e tiver **vários núcleos** na CPU do servidor, você poderá ter **vários processos** em execução com o mesmo aplicativo ao mesmo tempo e distribuir todas as solicitações entre eles.
+
+Quando você executa **vários processos** do mesmo programa de API, eles são comumente chamados de **trabalhadores**.
+
+### Processos do Trabalhador e Portas
+
+Lembra da documentação [Sobre HTTPS](https.md){.internal-link target=_blank} que diz que apenas um processo pode escutar em uma combinação de porta e endereço IP em um servidor?
+
+Isso ainda é verdade.
+
+Então, para poder ter **vários processos** ao mesmo tempo, tem que haver um **único processo escutando em uma porta** que então transmite a comunicação para cada processo de trabalho de alguma forma.
+
+### Memória por Processo
+
+Agora, quando o programa carrega coisas na memória, por exemplo, um modelo de aprendizado de máquina em uma variável, ou o conteúdo de um arquivo grande em uma variável, tudo isso **consome um pouco da memória (RAM)** do servidor.
+
+E vários processos normalmente **não compartilham nenhuma memória**. Isso significa que cada processo em execução tem suas próprias coisas, variáveis e memória. E se você estiver consumindo uma grande quantidade de memória em seu código, **cada processo** consumirá uma quantidade equivalente de memória.
+
+### Memória do servidor
+
+Por exemplo, se seu código carrega um modelo de Machine Learning com **1 GB de tamanho**, quando você executa um processo com sua API, ele consumirá pelo menos 1 GB de RAM. E se você iniciar **4 processos** (4 trabalhadores), cada um consumirá 1 GB de RAM. Então, no total, sua API consumirá **4 GB de RAM**.
+
+E se o seu servidor remoto ou máquina virtual tiver apenas 3 GB de RAM, tentar carregar mais de 4 GB de RAM causará problemas. 🚨
+
+### Processos Múltiplos - Um Exemplo
+
+Neste exemplo, há um **Processo Gerenciador** que inicia e controla dois **Processos de Trabalhadores**.
+
+Este Processo de Gerenciador provavelmente seria o que escutaria na **porta** no IP. E ele transmitiria toda a comunicação para os processos de trabalho.
+
+Esses processos de trabalho seriam aqueles que executariam seu aplicativo, eles executariam os cálculos principais para receber uma **solicitação** e retornar uma **resposta**, e carregariam qualquer coisa que você colocasse em variáveis na RAM.
+
+fastapi run --workers 4 main.py +INFO Using path main.py +INFO Resolved absolute path /home/user/code/awesomeapp/main.py +INFO Searching for package file structure from directories with __init__.py files +INFO Importing from /home/user/code/awesomeapp + + ╭─ Python module file ─╮ + │ │ + │ 🐍 main.py │ + │ │ + ╰──────────────────────╯ + +INFO Importing module main +INFO Found importable FastAPI app + + ╭─ Importable FastAPI app ─╮ + │ │ + │ from main import app │ + │ │ + ╰──────────────────────────╯ + +INFO Using import string main:app + + ╭─────────── FastAPI CLI - Production mode ───────────╮ + │ │ + │ Serving at: http://0.0.0.0:8000 │ + │ │ + │ API docs: http://0.0.0.0:8000/docs │ + │ │ + │ Running in production mode, for development use: │ + │ │ + │ fastapi dev │ + │ │ + ╰─────────────────────────────────────────────────────╯ + +INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit) +INFO: Started parent process [27365] +INFO: Started server process [27368] +INFO: Waiting for application startup. +INFO: Application startup complete. +INFO: Started server process [27369] +INFO: Waiting for application startup. +INFO: Application startup complete. +INFO: Started server process [27370] +INFO: Waiting for application startup. +INFO: Application startup complete. +INFO: Started server process [27367] +INFO: Waiting for application startup. +INFO: Application startup complete. ++``` + +
+
+Mas você pode desabilitá-lo definindo `syntaxHighlight` como `False`:
+
+```Python hl_lines="3"
+{!../../docs_src/configure_swagger_ui/tutorial001.py!}
+```
+
+...e então o Swagger UI não mostrará mais o destaque de sintaxe:
+
+
+
+## Alterar o tema
+
+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!}
+```
+
+Essa configuração alteraria o tema de cores de destaque de sintaxe:
+
+
+
+## Alterar parâmetros de UI padrão do Swagger
+
+O FastAPI inclui alguns parâmetros de configuração padrão apropriados para a maioria dos casos de uso.
+
+Inclui estas configurações padrão:
+
+```Python
+{!../../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!}
+```
+
+## Outros parâmetros da UI do Swagger
+
+Para ver todas as outras configurações possíveis que você pode usar, leia a documentação oficial dos parâmetros da UI do Swagger.
+
+## Configurações somente JavaScript
+
+A interface do usuário do Swagger também permite que outras configurações sejam objetos **somente JavaScript** (por exemplo, funções JavaScript).
+
+O FastAPI também inclui estas configurações de `predefinições` somente para JavaScript:
+
+```JavaScript
+presets: [
+ SwaggerUIBundle.presets.apis,
+ SwaggerUIBundle.SwaggerUIStandalonePreset
+]
+```
+
+Esses são objetos **JavaScript**, não strings, então você não pode passá-los diretamente do código Python.
+
+Se você precisar usar configurações somente JavaScript como essas, você pode usar um dos métodos acima. Sobrescreva todas as *operações de rotas* do Swagger UI e escreva manualmente qualquer JavaScript que você precisar.
diff --git a/docs/pt/docs/how-to/graphql.md b/docs/pt/docs/how-to/graphql.md
new file mode 100644
index 000000000..2cfd790c5
--- /dev/null
+++ b/docs/pt/docs/how-to/graphql.md
@@ -0,0 +1,62 @@
+# GraphQL
+
+Como o **FastAPI** é baseado no padrão **ASGI**, é muito fácil integrar qualquer biblioteca **GraphQL** também compatível com ASGI.
+
+Você pode combinar *operações de rota* normais do FastAPI com GraphQL na mesma aplicação.
+
+/// tip | "Dica"
+
+**GraphQL** resolve alguns casos de uso muito específicos.
+
+Ele tem **vantagens** e **desvantagens** quando comparado a **web APIs** comuns.
+
+Certifique-se de avaliar se os **benefícios** para o seu caso de uso compensam as **desvantagens**. 🤓
+
+///
+
+## Bibliotecas GraphQL
+
+Aqui estão algumas das bibliotecas **GraphQL** que têm suporte **ASGI**. Você pode usá-las com **FastAPI**:
+
+* Strawberry 🍓
+ * Com docs para FastAPI
+* Ariadne
+ * Com docs para FastAPI
+* Tartiflette
+ * Com Tartiflette ASGI para fornecer integração ASGI
+* Graphene
+ * Com starlette-graphene3
+
+## GraphQL com Strawberry
+
+Se você precisar ou quiser trabalhar com **GraphQL**, **Strawberry** é a biblioteca **recomendada** pois tem o design mais próximo ao design do **FastAPI**, ela é toda baseada em **type annotations**.
+
+Dependendo do seu caso de uso, você pode preferir usar uma biblioteca diferente, mas se você me perguntasse, eu provavelmente sugeriria que você experimentasse o **Strawberry**.
+
+Aqui está uma pequena prévia de como você poderia integrar Strawberry com FastAPI:
+
+```Python hl_lines="3 22 25-26"
+{!../../docs_src/graphql/tutorial001.py!}
+```
+
+Você pode aprender mais sobre Strawberry na documentação do Strawberry.
+
+E também na documentação sobre Strawberry com FastAPI.
+
+## Antigo `GraphQLApp` do Starlette
+
+Versões anteriores do Starlette incluiam uma classe `GraphQLApp` para integrar com Graphene.
+
+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"
+
+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.
+
+///
+
+## Saiba Mais
+
+Você pode aprender mais sobre **GraphQL** na documentação oficial do GraphQL.
+
+Você também pode ler mais sobre cada uma das bibliotecas descritas acima em seus links.
diff --git a/docs/pt/docs/how-to/index.md b/docs/pt/docs/how-to/index.md
index 664e89144..6747b01c7 100644
--- a/docs/pt/docs/how-to/index.md
+++ b/docs/pt/docs/how-to/index.md
@@ -6,6 +6,8 @@ A maioria dessas ideias será mais ou menos **independente**, e na maioria dos c
Se algo parecer interessante e útil para o seu projeto, vá em frente e dê uma olhada. Caso contrário, você pode simplesmente ignorá-lo.
-!!! tip
+/// tip
- Se você deseja **aprender FastAPI** de forma estruturada (recomendado), leia capítulo por capítulo [Tutorial - Guia de Usuário](../tutorial/index.md){.internal-link target=_blank} em vez disso.
+Se você deseja **aprender FastAPI** de forma estruturada (recomendado), leia capítulo por capítulo [Tutorial - Guia de Usuário](../tutorial/index.md){.internal-link target=_blank} em vez disso.
+
+///
diff --git a/docs/pt/docs/index.md b/docs/pt/docs/index.md
index bdaafdefc..f99144617 100644
--- a/docs/pt/docs/index.md
+++ b/docs/pt/docs/index.md
@@ -434,7 +434,7 @@ Para entender mais sobre performance, veja a seção email_validator - para validação de email.
+* email-validator - para validação de email.
Usados por Starlette:
diff --git a/docs/pt/docs/python-types.md b/docs/pt/docs/python-types.md
index 52b2dad8e..05faa860c 100644
--- a/docs/pt/docs/python-types.md
+++ b/docs/pt/docs/python-types.md
@@ -12,16 +12,18 @@ O **FastAPI** é baseado nesses type hints, eles oferecem muitas vantagens e ben
Mas mesmo que você nunca use o **FastAPI**, você se beneficiaria de aprender um pouco sobre eles.
-!!! note "Nota"
- Se você é um especialista em Python e já sabe tudo sobre type hints, pule para o próximo capítulo.
+/// note | "Nota"
+Se você é um especialista em Python e já sabe tudo sobre type hints, pule para o próximo capítulo.
+
+///
## Motivação
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:
@@ -37,7 +39,7 @@ A função faz o seguinte:
* Concatena com um espaço no meio.
```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial001.py!}
+{!../../docs_src/python_types/tutorial001.py!}
```
### Edite-o
@@ -81,7 +83,7 @@ para:
Esses são os "type hints":
```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial002.py!}
+{!../../docs_src/python_types/tutorial002.py!}
```
Isso não é o mesmo que declarar valores padrão como seria com:
@@ -111,7 +113,7 @@ Com isso, você pode rolar, vendo as opções, até encontrar o que "toca uma ca
Marque esta função, ela já possui type hints:
```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial003.py!}
+{!../../docs_src/python_types/tutorial003.py!}
```
Como o editor conhece os tipos de variáveis, você não apenas obtém a conclusão, mas também as verificações de erro:
@@ -121,7 +123,7 @@ Como o editor conhece os tipos de variáveis, você não apenas obtém a conclus
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!}
```
## Tipos de declaração
@@ -142,7 +144,7 @@ Você pode usar, por exemplo:
* `bytes`
```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial005.py!}
+{!../../docs_src/python_types/tutorial005.py!}
```
### Tipos genéricos com parâmetros de tipo
@@ -160,7 +162,7 @@ Por exemplo, vamos definir uma variável para ser uma `lista` de `str`.
Em `typing`, importe `List` (com um `L` maiúsculo):
```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial006.py!}
+{!../../docs_src/python_types/tutorial006.py!}
```
Declare a variável com a mesma sintaxe de dois pontos (`:`).
@@ -170,13 +172,16 @@ Como o tipo, coloque a `List`.
Como a lista é um tipo que contém alguns tipos internos, você os coloca entre colchetes:
```Python hl_lines="4"
-{!../../../docs_src/python_types/tutorial006.py!}
+{!../../docs_src/python_types/tutorial006.py!}
```
-!!! tip "Dica"
- Esses tipos internos entre colchetes são chamados de "parâmetros de tipo".
+/// tip | "Dica"
- Nesse caso, `str` é o parâmetro de tipo passado para `List`.
+Esses tipos internos entre colchetes são chamados de "parâmetros de tipo".
+
+Nesse caso, `str` é o parâmetro de tipo passado para `List`.
+
+///
Isso significa que: "a variável `items` é uma `list`, e cada um dos itens desta lista é uma `str`".
@@ -195,7 +200,7 @@ E, ainda assim, o editor sabe que é um `str` e fornece suporte para isso.
Você faria o mesmo para declarar `tuple`s e `set`s:
```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial007.py!}
+{!../../docs_src/python_types/tutorial007.py!}
```
Isso significa que:
@@ -212,7 +217,7 @@ O primeiro parâmetro de tipo é para as chaves do `dict`.
O segundo parâmetro de tipo é para os valores do `dict`:
```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial008.py!}
+{!../../docs_src/python_types/tutorial008.py!}
```
Isso significa que:
@@ -226,7 +231,7 @@ Isso significa que:
Você também pode usar o `Opcional` para declarar que uma variável tem um tipo, como `str`, mas que é "opcional", o que significa que também pode ser `None`:
```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009.py!}
+{!../../docs_src/python_types/tutorial009.py!}
```
O uso de `Opcional [str]` em vez de apenas `str` permitirá que o editor o ajude a detectar erros, onde você pode estar assumindo que um valor é sempre um `str`, quando na verdade também pode ser `None`.
@@ -251,13 +256,13 @@ Você também pode declarar uma classe como o tipo de uma variável.
Digamos que você tenha uma classe `Person`, com um nome:
```Python hl_lines="1 2 3"
-{!../../../docs_src/python_types/tutorial010.py!}
+{!../../docs_src/python_types/tutorial010.py!}
```
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!}
```
E então, novamente, você recebe todo o suporte do editor:
@@ -279,11 +284,14 @@ E você recebe todo o suporte do editor com esse objeto resultante.
Retirado dos documentos oficiais dos Pydantic:
```Python
-{!../../../docs_src/python_types/tutorial011.py!}
+{!../../docs_src/python_types/tutorial011.py!}
```
-!!! info "Informação"
- Para saber mais sobre o Pydantic, verifique seus documentos .
+/// info | "Informação"
+
+Para saber mais sobre o Pydantic, verifique seus documentos .
+
+///
**FastAPI** é todo baseado em Pydantic.
@@ -311,5 +319,8 @@ Tudo isso pode parecer abstrato. Não se preocupe. Você verá tudo isso em aç
O importante é que, usando tipos padrão de Python, em um único local (em vez de adicionar mais classes, decoradores, etc.), o **FastAPI** fará muito trabalho para você.
-!!! info "Informação"
- Se você já passou por todo o tutorial e voltou para ver mais sobre os tipos, um bom recurso é a "cheat sheet" do `mypy` .
+/// info | "Informação"
+
+Se você já passou por todo o tutorial e voltou para ver mais sobre os tipos, um bom recurso é a "cheat sheet" do `mypy` .
+
+///
diff --git a/docs/pt/docs/reference/apirouter.md b/docs/pt/docs/reference/apirouter.md
deleted file mode 100644
index 7568601c9..000000000
--- a/docs/pt/docs/reference/apirouter.md
+++ /dev/null
@@ -1,24 +0,0 @@
-# Classe `APIRouter`
-
-Aqui está a informação de referência para a classe `APIRouter`, com todos os seus parâmetros, atributos e métodos.
-
-Você pode importar a classe `APIRouter` diretamente do `fastapi`:
-
-```python
-from fastapi import APIRouter
-```
-
-::: fastapi.APIRouter
- options:
- members:
- - websocket
- - include_router
- - get
- - put
- - post
- - delete
- - options
- - head
- - patch
- - trace
- - on_event
diff --git a/docs/pt/docs/reference/background.md b/docs/pt/docs/reference/background.md
deleted file mode 100644
index bfc15aa76..000000000
--- a/docs/pt/docs/reference/background.md
+++ /dev/null
@@ -1,11 +0,0 @@
-# Tarefas em Segundo Plano - `BackgroundTasks`
-
-Você pode declarar um parâmetro em uma *função de operação de rota* ou em uma função de dependência com o tipo `BackgroundTasks`, e então utilizá-lo para agendar a execução de tarefas em segundo plano após o envio da resposta.
-
-Você pode importá-lo diretamente do `fastapi`:
-
-```python
-from fastapi import BackgroundTasks
-```
-
-::: fastapi.BackgroundTasks
diff --git a/docs/pt/docs/reference/exceptions.md b/docs/pt/docs/reference/exceptions.md
deleted file mode 100644
index d6b5d2613..000000000
--- a/docs/pt/docs/reference/exceptions.md
+++ /dev/null
@@ -1,20 +0,0 @@
-# Exceções - `HTTPException` e `WebSocketException`
-
-Essas são as exceções que você pode lançar para mostrar erros ao cliente.
-
-Quando você lança uma exceção, como aconteceria com o Python normal, o restante da execução é abortado. Dessa forma, você pode lançar essas exceções de qualquer lugar do código para abortar uma solicitação e mostrar o erro ao cliente.
-
-Você pode usar:
-
-* `HTTPException`
-* `WebSocketException`
-
-Essas exceções podem ser importadas diretamente do `fastapi`:
-
-```python
-from fastapi import HTTPException, WebSocketException
-```
-
-::: fastapi.HTTPException
-
-::: fastapi.WebSocketException
diff --git a/docs/pt/docs/reference/index.md b/docs/pt/docs/reference/index.md
deleted file mode 100644
index 533a6a996..000000000
--- a/docs/pt/docs/reference/index.md
+++ /dev/null
@@ -1,6 +0,0 @@
-# Referência - API de Código
-
-Aqui está a referência ou API de código, as classes, funções, parâmetros, atributos e todas as partes do FastAPI que você pode usar em suas aplicações.
-
-Se você quer **aprender FastAPI**, é muito melhor ler o
-[FastAPI Tutorial](https://fastapi.tiangolo.com/tutorial/).
diff --git a/docs/pt/docs/tutorial/background-tasks.md b/docs/pt/docs/tutorial/background-tasks.md
index 625fa2b11..2b5f82464 100644
--- a/docs/pt/docs/tutorial/background-tasks.md
+++ b/docs/pt/docs/tutorial/background-tasks.md
@@ -16,7 +16,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!}
```
O **FastAPI** criará o objeto do tipo `BackgroundTasks` para você e o passará como esse parâmetro.
@@ -34,7 +34,7 @@ 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!}
```
## Adicionar a tarefa em segundo plano
@@ -42,7 +42,7 @@ E como a operação de gravação não usa `async` e `await`, definimos a funç
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!}
```
`.add_task()` recebe como argumentos:
@@ -58,7 +58,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!}
```
Neste exemplo, as mensagens serão gravadas no arquivo `log.txt` _após_ o envio da resposta.
diff --git a/docs/pt/docs/tutorial/bigger-applications.md b/docs/pt/docs/tutorial/bigger-applications.md
new file mode 100644
index 000000000..fcc30961f
--- /dev/null
+++ b/docs/pt/docs/tutorial/bigger-applications.md
@@ -0,0 +1,556 @@
+# Aplicações Maiores - Múltiplos Arquivos
+
+Se você está construindo uma aplicação ou uma API web, é raro que você possa colocar tudo em um único arquivo.
+
+**FastAPI** oferece uma ferramenta conveniente para estruturar sua aplicação, mantendo toda a flexibilidade.
+
+/// info | "Informação"
+
+Se você vem do Flask, isso seria o equivalente aos Blueprints do Flask.
+
+///
+
+## Um exemplo de estrutura de arquivos
+
+Digamos que você tenha uma estrutura de arquivos como esta:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+│ ├── dependencies.py
+│ └── routers
+│ │ ├── __init__.py
+│ │ ├── items.py
+│ │ └── users.py
+│ └── internal
+│ ├── __init__.py
+│ └── admin.py
+```
+
+/// tip | "Dica"
+
+Existem vários arquivos `__init__.py` presentes em cada diretório ou subdiretório.
+
+Isso permite a importação de código de um arquivo para outro.
+
+Por exemplo, no arquivo `app/main.py`, você poderia ter uma linha como:
+
+```
+from app.routers import items
+```
+
+///
+
+* O diretório `app` contém todo o código da aplicação. Ele possui um arquivo `app/__init__.py` vazio, o que o torna um "pacote Python" (uma coleção de "módulos Python"): `app`.
+* Dentro dele, o arquivo `app/main.py` está localizado em um pacote Python (diretório com `__init__.py`). Portanto, ele é um "módulo" desse pacote: `app.main`.
+* Existem também um arquivo `app/dependencies.py`, assim como o `app/main.py`, ele é um "módulo": `app.dependencies`.
+* Há um subdiretório `app/routers/` com outro arquivo `__init__.py`, então ele é um "subpacote Python": `app.routers`.
+* O arquivo `app/routers/items.py` está dentro de um pacote, `app/routers/`, portanto, é um "submódulo": `app.routers.items`.
+* O mesmo com `app/routers/users.py`, ele é outro submódulo: `app.routers.users`.
+* Há também um subdiretório `app/internal/` com outro arquivo `__init__.py`, então ele é outro "subpacote Python":`app.internal`.
+* E o arquivo `app/internal/admin.py` é outro submódulo: `app.internal.admin`.
+
+
+
+## Incluir o mesmo roteador várias vezes com `prefixos` diferentes
+
+Você também pode usar `.include_router()` várias vezes com o *mesmo* roteador usando prefixos diferentes.
+
+Isso pode ser útil, por exemplo, para expor a mesma API sob prefixos diferentes, por exemplo, `/api/v1` e `/api/latest`.
+
+Esse é um uso avançado que você pode não precisar, mas está lá caso precise.
+
+## Incluir um `APIRouter` em outro
+
+Da mesma forma que você pode incluir um `APIRouter` em um aplicativo `FastAPI`, você pode incluir um `APIRouter` em outro `APIRouter` usando:
+
+```Python
+router.include_router(other_router)
+```
+
+Certifique-se de fazer isso antes de incluir `router` no aplicativo `FastAPI`, para que as *operações de rota* de `other_router` também sejam incluídas.
diff --git a/docs/pt/docs/tutorial/body-fields.md b/docs/pt/docs/tutorial/body-fields.md
index 8f3313ae9..ab9377fdb 100644
--- a/docs/pt/docs/tutorial/body-fields.md
+++ b/docs/pt/docs/tutorial/body-fields.md
@@ -7,33 +7,42 @@ 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!}
```
-!!! warning "Aviso"
- Note que `Field` é importado diretamente do `pydantic`, não do `fastapi` como todo o resto (`Query`, `Path`, `Body`, etc).
+/// warning | "Aviso"
+
+Note que `Field` é importado diretamente do `pydantic`, não do `fastapi` como todo o resto (`Query`, `Path`, `Body`, etc).
+
+///
## Declare atributos do modelo
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!}
```
`Field` funciona da mesma forma que `Query`, `Path` e `Body`, ele possui todos os mesmos parâmetros, etc.
-!!! note "Detalhes técnicos"
- Na realidade, `Query`, `Path` e outros que você verá em seguida, criam objetos de subclasses de uma classe `Param` comum, que é ela mesma uma subclasse da classe `FieldInfo` do Pydantic.
+/// note | "Detalhes técnicos"
- E `Field` do Pydantic retorna uma instância de `FieldInfo` também.
+Na realidade, `Query`, `Path` e outros que você verá em seguida, criam objetos de subclasses de uma classe `Param` comum, que é ela mesma uma subclasse da classe `FieldInfo` do Pydantic.
- `Body` também retorna objetos de uma subclasse de `FieldInfo` diretamente. E tem outras que você verá mais tarde que são subclasses da classe `Body`.
+E `Field` do Pydantic retorna uma instância de `FieldInfo` também.
- Lembre-se que quando você importa `Query`, `Path`, e outros de `fastapi`, esse são na realidade funções que retornam classes especiais.
+`Body` também retorna objetos de uma subclasse de `FieldInfo` diretamente. E tem outras que você verá mais tarde que são subclasses da classe `Body`.
-!!! tip "Dica"
- Note como cada atributo do modelo com um tipo, valor padrão e `Field` possuem a mesma estrutura que parâmetros de *funções de operações de rota*, com `Field` ao invés de `Path`, `Query` e `Body`.
+Lembre-se que quando você importa `Query`, `Path`, e outros de `fastapi`, esse são na realidade funções que retornam classes especiais.
+
+///
+
+/// tip | "Dica"
+
+Note como cada atributo do modelo com um tipo, valor padrão e `Field` possuem a mesma estrutura que parâmetros de *funções de operações de rota*, com `Field` ao invés de `Path`, `Query` e `Body`.
+
+///
## Adicione informações extras
diff --git a/docs/pt/docs/tutorial/body-multiple-params.md b/docs/pt/docs/tutorial/body-multiple-params.md
index 7d0435a6b..400813a7b 100644
--- a/docs/pt/docs/tutorial/body-multiple-params.md
+++ b/docs/pt/docs/tutorial/body-multiple-params.md
@@ -8,20 +8,27 @@ Primeiro, é claro, você pode misturar `Path`, `Query` e declarações de parâ
E você também pode declarar parâmetros de corpo como opcionais, definindo o valor padrão com `None`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="17-19"
- {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!}
- ```
+```Python hl_lines="17-19"
+{!> ../../docs_src/body_multiple_params/tutorial001_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="19-21"
- {!> ../../../docs_src/body_multiple_params/tutorial001.py!}
- ```
+//// tab | Python 3.8+
-!!! 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.
+```Python hl_lines="19-21"
+{!> ../../docs_src/body_multiple_params/tutorial001.py!}
+```
+
+////
+
+/// note | "Nota"
+
+Repare que, neste caso, o `item` que seria capturado a partir do corpo é opcional. Visto que ele possui `None` como valor padrão.
+
+///
## Múltiplos parâmetros de corpo
@@ -38,17 +45,21 @@ No exemplo anterior, as *operações de rota* esperariam um JSON no corpo conten
Mas você pode também declarar múltiplos parâmetros de corpo, por exemplo, `item` e `user`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!}
- ```
+```Python hl_lines="20"
+{!> ../../docs_src/body_multiple_params/tutorial002_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="22"
- {!> ../../../docs_src/body_multiple_params/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="22"
+{!> ../../docs_src/body_multiple_params/tutorial002.py!}
+```
+
+////
Neste caso, o **FastAPI** perceberá que existe mais de um parâmetro de corpo na função (dois parâmetros que são modelos Pydantic).
@@ -69,9 +80,11 @@ Então, ele usará o nome dos parâmetros como chaves (nome dos campos) no corpo
}
```
-!!! note "Nota"
- Repare que mesmo que o `item` esteja declarado da mesma maneira que antes, agora é esperado que ele esteja dentro do corpo com uma chave `item`.
+/// note | "Nota"
+Repare que mesmo que o `item` esteja declarado da mesma maneira que antes, agora é esperado que ele esteja dentro do corpo com uma chave `item`.
+
+///
O **FastAPI** fará a conversão automática a partir da requisição, assim esse parâmetro `item` receberá seu respectivo conteúdo e o mesmo ocorrerá com `user`.
@@ -87,17 +100,21 @@ Se você declará-lo como é, porque é um valor singular, o **FastAPI** assumir
Mas você pode instruir o **FastAPI** para tratá-lo como outra chave do corpo usando `Body`:
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python hl_lines="22"
- {!> ../../../docs_src/body_multiple_params/tutorial003.py!}
- ```
+```Python hl_lines="22"
+{!> ../../docs_src/body_multiple_params/tutorial003.py!}
+```
-=== "Python 3.10+"
+////
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!}
- ```
+//// tab | Python 3.10+
+
+```Python hl_lines="20"
+{!> ../../docs_src/body_multiple_params/tutorial003_py310.py!}
+```
+
+////
Neste caso, o **FastAPI** esperará um corpo como:
@@ -137,20 +154,27 @@ q: str | None = None
Por exemplo:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="26"
- {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!}
- ```
+```Python hl_lines="26"
+{!> ../../docs_src/body_multiple_params/tutorial004_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004.py!}
- ```
+//// tab | Python 3.8+
-!!! info "Informação"
- `Body` também possui todas as validações adicionais e metadados de parâmetros como em `Query`,`Path` e outras que você verá depois.
+```Python hl_lines="27"
+{!> ../../docs_src/body_multiple_params/tutorial004.py!}
+```
+
+////
+
+/// info | "Informação"
+
+`Body` também possui todas as validações adicionais e metadados de parâmetros como em `Query`,`Path` e outras que você verá depois.
+
+///
## Declare um único parâmetro de corpo indicando sua chave
@@ -166,17 +190,21 @@ item: Item = Body(embed=True)
como em:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="15"
- {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!}
- ```
+```Python hl_lines="15"
+{!> ../../docs_src/body_multiple_params/tutorial005_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="17"
- {!> ../../../docs_src/body_multiple_params/tutorial005.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="17"
+{!> ../../docs_src/body_multiple_params/tutorial005.py!}
+```
+
+////
Neste caso o **FastAPI** esperará um corpo como:
diff --git a/docs/pt/docs/tutorial/body-nested-models.md b/docs/pt/docs/tutorial/body-nested-models.md
index c9d0b8bb6..3aa79d563 100644
--- a/docs/pt/docs/tutorial/body-nested-models.md
+++ b/docs/pt/docs/tutorial/body-nested-models.md
@@ -7,7 +7,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!}
```
Isso fará com que tags seja uma lista de itens mesmo sem declarar o tipo dos elementos desta lista.
@@ -21,7 +21,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!}
```
### Declare a `List` com um parâmetro de tipo
@@ -45,7 +45,7 @@ Portanto, em nosso exemplo, podemos fazer com que `tags` sejam especificamente u
```Python hl_lines="14"
-{!../../../docs_src/body_nested_models/tutorial002.py!}
+{!../../docs_src/body_nested_models/tutorial002.py!}
```
## Tipo "set"
@@ -59,7 +59,7 @@ 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!}
```
Com isso, mesmo que você receba uma requisição contendo dados duplicados, ela será convertida em um conjunto de itens exclusivos.
@@ -83,7 +83,7 @@ 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!}
```
### Use o sub-modelo como um tipo
@@ -91,7 +91,7 @@ Por exemplo, nós podemos definir um modelo `Image`:
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!}
```
Isso significa que o **FastAPI** vai esperar um corpo similar à:
@@ -126,7 +126,7 @@ Para ver todas as opções possíveis, cheque a documentação para osPydantic com todos os seus poderes e benefícios.
-!!! info "Informação"
- Para enviar dados, você deve usar utilizar um dos métodos: `POST` (Mais comum), `PUT`, `DELETE` ou `PATCH`.
+/// info | "Informação"
- Enviar um corpo em uma requisição `GET` não tem um comportamento definido nas especificações, porém é suportado pelo FastAPI, apenas para casos de uso bem complexos/extremos.
+Para enviar dados, você deve usar utilizar um dos métodos: `POST` (Mais comum), `PUT`, `DELETE` ou `PATCH`.
- Como é desencorajado, a documentação interativa com Swagger UI não irá mostrar a documentação para o corpo da requisição para um `GET`, e proxies que intermediarem podem não suportar o corpo da requisição.
+Enviar um corpo em uma requisição `GET` não tem um comportamento definido nas especificações, porém é suportado pelo FastAPI, apenas para casos de uso bem complexos/extremos.
+
+Como é desencorajado, a documentação interativa com Swagger UI não irá mostrar a documentação para o corpo da requisição para um `GET`, e proxies que intermediarem podem não suportar o corpo da requisição.
+
+///
## Importe o `BaseModel` do Pydantic
Primeiro, você precisa importar `BaseModel` do `pydantic`:
```Python hl_lines="4"
-{!../../../docs_src/body/tutorial001.py!}
+{!../../docs_src/body/tutorial001.py!}
```
## Crie seu modelo de dados
@@ -30,7 +33,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!}
```
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.
@@ -60,7 +63,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!}
```
...E declare o tipo como o modelo que você criou, `Item`.
@@ -110,23 +113,26 @@ Mas você terá o mesmo suporte do editor no
-!!! tip "Dica"
- Se você utiliza o PyCharm como editor, você pode utilizar o Plugin do Pydantic para o PyCharm .
+/// tip | "Dica"
- Melhora o suporte do editor para seus modelos Pydantic com::
+Se você utiliza o PyCharm como editor, você pode utilizar o Plugin do Pydantic para o PyCharm .
- * completação automática
- * verificação de tipos
- * refatoração
- * buscas
- * inspeções
+Melhora o suporte do editor para seus modelos Pydantic com::
+
+* completação automática
+* verificação de tipos
+* refatoração
+* buscas
+* inspeções
+
+///
## Use o modelo
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!}
```
## Corpo da requisição + parâmetros de rota
@@ -136,7 +142,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!}
```
## Corpo da requisição + parâmetros de rota + parâmetros de consulta
@@ -146,7 +152,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!}
```
Os parâmetros da função serão reconhecidos conforme abaixo:
@@ -155,10 +161,13 @@ Os parâmetros da função serão reconhecidos conforme abaixo:
* Se o parâmetro é de um **tipo único** (como `int`, `float`, `str`, `bool`, etc) será interpretado como um parâmetro de **consulta**.
* Se o parâmetro é declarado como um **modelo Pydantic**, será interpretado como o **corpo** da requisição.
-!!! note "Observação"
- O FastAPI saberá que o valor de `q` não é obrigatório por causa do valor padrão `= None`.
+/// note | "Observação"
- O `Union` em `Union[str, None]` não é utilizado pelo FastAPI, mas permite ao seu editor de texto lhe dar um suporte melhor e detectar erros.
+O FastAPI saberá que o valor de `q` não é obrigatório por causa do valor padrão `= None`.
+
+O `Union` em `Union[str, None]` não é utilizado pelo FastAPI, mas permite ao seu editor de texto lhe dar um suporte melhor e detectar erros.
+
+///
## Sem o Pydantic
diff --git a/docs/pt/docs/tutorial/cookie-param-models.md b/docs/pt/docs/tutorial/cookie-param-models.md
new file mode 100644
index 000000000..671e0d74f
--- /dev/null
+++ b/docs/pt/docs/tutorial/cookie-param-models.md
@@ -0,0 +1,156 @@
+# Modelos de Parâmetros de Cookie
+
+Se você possui um grupo de **cookies** que estão relacionados, você pode criar um **modelo Pydantic** para declará-los. 🍪
+
+Isso lhe permitiria **reutilizar o modelo** em **diversos lugares** e também declarar validações e metadata para todos os parâmetros de uma vez. 😎
+
+/// note | Nota
+
+Isso é suportado desde a versão `0.115.0` do FastAPI. 🤓
+
+///
+
+/// tip | Dica
+
+Essa mesma técnica se aplica para `Query`, `Cookie`, e `Header`. 😎
+
+///
+
+## Cookies com Modelos Pydantic
+
+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!}
+```
+
+////
+
+O **FastAPI** irá **extrair** os dados para **cada campo** dos **cookies** recebidos na requisição e lhe fornecer o modelo Pydantic que você definiu.
+
+## Verifique os Documentos
+
+Você pode ver os cookies definidos na IU dos documentos em `/docs`:
+
+
+
+
+---
+
+Se você usar o Pycharm, você pode:
+
+* Abrir o menu "Executar".
+* Selecionar a opção "Depurar...".
+* Então um menu de contexto aparece.
+* Selecionar o arquivo para depurar (neste caso, `main.py`).
+
+Em seguida, ele iniciará o servidor com seu código **FastAPI**, parará em seus pontos de interrupção, etc.
+
+Veja como pode parecer:
+
+
diff --git a/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md
index 028bf3d20..179bfefb5 100644
--- a/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md
+++ b/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md
@@ -6,41 +6,57 @@ Antes de nos aprofundarmos no sistema de **Injeção de Dependência**, vamos me
No exemplo anterior, nós retornávamos um `dict` da nossa dependência ("injetável"):
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9"
- {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/dependencies/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="11"
- {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="11"
+{!> ../../docs_src/dependencies/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="12"
- {!> ../../../docs_src/dependencies/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+```Python hl_lines="12"
+{!> ../../docs_src/dependencies/tutorial001_an.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+/// tip | "Dica"
- ```Python hl_lines="11"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python hl_lines="7"
+{!> ../../docs_src/dependencies/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python hl_lines="11"
+{!> ../../docs_src/dependencies/tutorial001.py!}
+```
+
+////
Mas assim obtemos um `dict` como valor do parâmetro `commons` na *função de operação de rota*.
@@ -103,123 +119,165 @@ Isso também se aplica a objetos chamáveis que não recebem nenhum parâmetro.
Então, podemos mudar o "injetável" na dependência `common_parameters` acima para a classe `CommonQueryParams`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="11-15"
- {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!}
- ```
+```Python hl_lines="11-15"
+{!> ../../docs_src/dependencies/tutorial002_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="11-15"
- {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="11-15"
+{!> ../../docs_src/dependencies/tutorial002_an_py39.py!}
+```
- ```Python hl_lines="12-16"
- {!> ../../../docs_src/dependencies/tutorial002_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+```Python hl_lines="12-16"
+{!> ../../docs_src/dependencies/tutorial002_an.py!}
+```
+////
- ```Python hl_lines="9-13"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
+//// tab | Python 3.10+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip | "Dica"
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+Utilize a versão com `Annotated` se possível.
+///
- ```Python hl_lines="11-15"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
- ```
+```Python hl_lines="9-13"
+{!> ../../docs_src/dependencies/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python hl_lines="11-15"
+{!> ../../docs_src/dependencies/tutorial002.py!}
+```
+
+////
Observe o método `__init__` usado para criar uma instância da classe:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="12"
- {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!}
- ```
+```Python hl_lines="12"
+{!> ../../docs_src/dependencies/tutorial002_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="12"
- {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="12"
+{!> ../../docs_src/dependencies/tutorial002_an_py39.py!}
+```
- ```Python hl_lines="13"
- {!> ../../../docs_src/dependencies/tutorial002_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+```Python hl_lines="13"
+{!> ../../docs_src/dependencies/tutorial002_an.py!}
+```
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
+//// tab | Python 3.10+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip | "Dica"
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+Utilize a versão com `Annotated` se possível.
+///
- ```Python hl_lines="12"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
- ```
+```Python hl_lines="10"
+{!> ../../docs_src/dependencies/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python hl_lines="12"
+{!> ../../docs_src/dependencies/tutorial002.py!}
+```
+
+////
...ele possui os mesmos parâmetros que nosso `common_parameters` anterior:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="8"
- {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="8"
+{!> ../../docs_src/dependencies/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="9"
+{!> ../../docs_src/dependencies/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/dependencies/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+```Python hl_lines="10"
+{!> ../../docs_src/dependencies/tutorial001_an.py!}
+```
+////
- ```Python hl_lines="6"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+//// tab | Python 3.10+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip | "Dica"
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+Utilize a versão com `Annotated` se possível.
+///
- ```Python hl_lines="9"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+```Python hl_lines="6"
+{!> ../../docs_src/dependencies/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python hl_lines="9"
+{!> ../../docs_src/dependencies/tutorial001.py!}
+```
+
+////
Esses parâmetros são utilizados pelo **FastAPI** para "definir" a dependência.
@@ -235,43 +293,57 @@ Os dados serão convertidos, validados, documentados no esquema da OpenAPI e etc
Agora você pode declarar sua dependência utilizando essa classe.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!}
- ```
+```Python hl_lines="19"
+{!> ../../docs_src/dependencies/tutorial002_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="19"
+{!> ../../docs_src/dependencies/tutorial002_an_py39.py!}
+```
- ```Python hl_lines="20"
- {!> ../../../docs_src/dependencies/tutorial002_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+```Python hl_lines="20"
+{!> ../../docs_src/dependencies/tutorial002_an.py!}
+```
+////
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
+//// tab | Python 3.10+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip | "Dica"
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+Utilize a versão com `Annotated` se possível.
+///
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
- ```
+```Python hl_lines="17"
+{!> ../../docs_src/dependencies/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python hl_lines="19"
+{!> ../../docs_src/dependencies/tutorial002.py!}
+```
+
+////
O **FastAPI** chama a classe `CommonQueryParams`. Isso cria uma "instância" dessa classe e é a instância que será passada para o parâmetro `commons` na sua função.
@@ -279,21 +351,27 @@ O **FastAPI** chama a classe `CommonQueryParams`. Isso cria uma "instância" des
Perceba como escrevemos `CommonQueryParams` duas vezes no código abaixo:
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python
- commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
- ```
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
-=== "Python 3.8+ non-Annotated"
+////
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+//// tab | Python 3.8+ non-Annotated
+/// tip | "Dica"
- ```Python
- commons: CommonQueryParams = Depends(CommonQueryParams)
- ```
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
O último `CommonQueryParams`, em:
@@ -309,81 +387,107 @@ O último `CommonQueryParams`, em:
Nesse caso, o primeiro `CommonQueryParams`, em:
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python
- commons: Annotated[CommonQueryParams, ...
- ```
+```Python
+commons: Annotated[CommonQueryParams, ...
+```
-=== "Python 3.8+ non-Annotated"
+////
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+//// tab | Python 3.8+ non-Annotated
+/// tip | "Dica"
- ```Python
- commons: CommonQueryParams ...
- ```
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python
+commons: CommonQueryParams ...
+```
+
+////
...não tem nenhum signficado especial para o **FastAPI**. O FastAPI não irá utilizá-lo para conversão dos dados, validação, etc (já que ele utiliza `Depends(CommonQueryParams)` para isso).
Na verdade você poderia escrever apenas:
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python
- commons: Annotated[Any, Depends(CommonQueryParams)]
- ```
+```Python
+commons: Annotated[Any, Depends(CommonQueryParams)]
+```
-=== "Python 3.8+ non-Annotated"
+////
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+//// tab | Python 3.8+ non-Annotated
+/// tip | "Dica"
- ```Python
- commons = Depends(CommonQueryParams)
- ```
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python
+commons = Depends(CommonQueryParams)
+```
+
+////
...como em:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial003_an_py310.py!}
- ```
+```Python hl_lines="19"
+{!> ../../docs_src/dependencies/tutorial003_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial003_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="19"
+{!> ../../docs_src/dependencies/tutorial003_an_py39.py!}
+```
- ```Python hl_lines="20"
- {!> ../../../docs_src/dependencies/tutorial003_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+```Python hl_lines="20"
+{!> ../../docs_src/dependencies/tutorial003_an.py!}
+```
+////
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial003_py310.py!}
- ```
+//// tab | Python 3.10+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip | "Dica"
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+Utilize a versão com `Annotated` se possível.
+///
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial003.py!}
- ```
+```Python hl_lines="17"
+{!> ../../docs_src/dependencies/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python hl_lines="19"
+{!> ../../docs_src/dependencies/tutorial003.py!}
+```
+
+////
Mas declarar o tipo é encorajado por que é a forma que o seu editor de texto sabe o que será passado como valor do parâmetro `commons`.
@@ -393,20 +497,27 @@ Mas declarar o tipo é encorajado por que é a forma que o seu editor de texto s
Mas você pode ver que temos uma repetição do código neste exemplo, escrevendo `CommonQueryParams` duas vezes:
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python
- commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
- ```
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
-=== "Python 3.8+ non-Annotated"
+////
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+//// tab | Python 3.8+ non-Annotated
- ```Python
- commons: CommonQueryParams = Depends(CommonQueryParams)
- ```
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
O **FastAPI** nos fornece um atalho para esses casos, onde a dependência é *especificamente* uma classe que o **FastAPI** irá "chamar" para criar uma instância da própria classe.
@@ -414,84 +525,114 @@ Para esses casos específicos, você pode fazer o seguinte:
Em vez de escrever:
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python
- commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
- ```
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
-=== "Python 3.8+ non-Annotated"
+////
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+//// tab | Python 3.8+ non-Annotated
- ```Python
- commons: CommonQueryParams = Depends(CommonQueryParams)
- ```
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
...escreva:
-=== "Python 3.8+"
+//// tab | Python 3.8+
- ```Python
- commons: Annotated[CommonQueryParams, Depends()]
- ```
+```Python
+commons: Annotated[CommonQueryParams, Depends()]
+```
-=== "Python 3.8 non-Annotated"
+////
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+//// tab | Python 3.8 non-Annotated
+/// tip | "Dica"
- ```Python
- commons: CommonQueryParams = Depends()
- ```
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends()
+```
+
+////
Você declara a dependência como o tipo do parâmetro, e utiliza `Depends()` sem nenhum parâmetro, em vez de ter que escrever a classe *novamente* dentro de `Depends(CommonQueryParams)`.
O mesmo exemplo ficaria então dessa forma:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial004_an_py310.py!}
- ```
+```Python hl_lines="19"
+{!> ../../docs_src/dependencies/tutorial004_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial004_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="19"
+{!> ../../docs_src/dependencies/tutorial004_an_py39.py!}
+```
- ```Python hl_lines="20"
- {!> ../../../docs_src/dependencies/tutorial004_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+```Python hl_lines="20"
+{!> ../../docs_src/dependencies/tutorial004_an.py!}
+```
+////
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial004_py310.py!}
- ```
+//// tab | Python 3.10+ non-Annotated
-=== "Python 3.8+ non-Annotated"
+/// tip | "Dica"
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível.
+Utilize a versão com `Annotated` se possível.
+///
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial004.py!}
- ```
+```Python hl_lines="17"
+{!> ../../docs_src/dependencies/tutorial004_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python hl_lines="19"
+{!> ../../docs_src/dependencies/tutorial004.py!}
+```
+
+////
...e o **FastAPI** saberá o que fazer.
-!!! tip "Dica"
- Se isso parece mais confuso do que útil, não utilize, você não *precisa* disso.
+/// tip | "Dica"
- É apenas um atalho. Por que o **FastAPI** se preocupa em ajudar a minimizar a repetição de código.
+Se isso parece mais confuso do que útil, não utilize, você não *precisa* disso.
+
+É apenas um atalho. Por que o **FastAPI** se preocupa em ajudar a minimizar a repetição de código.
+
+///
diff --git a/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
index 4a297268c..7d7086945 100644
--- a/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
+++ b/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
@@ -14,39 +14,55 @@ O *decorador da operação de rota* recebe um argumento opcional `dependencies`.
Ele deve ser uma lista de `Depends()`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
- ```
+```Python hl_lines="19"
+{!> ../../docs_src/dependencies/tutorial006_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="18"
- {!> ../../../docs_src/dependencies/tutorial006_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8 non-Annotated"
+```Python hl_lines="18"
+{!> ../../docs_src/dependencies/tutorial006_an.py!}
+```
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível
+////
+
+//// tab | Python 3.8 non-Annotated
+
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível
+
+///
+
+```Python hl_lines="17"
+{!> ../../docs_src/dependencies/tutorial006.py!}
+```
+
+////
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial006.py!}
- ```
Essas dependências serão executadas/resolvidas da mesma forma que dependências comuns. Mas o valor delas (se existir algum) não será passado para a sua *função de operação de rota*.
-!!! tip "Dica"
- Alguns editores de texto checam parâmetros de funções não utilizados, e os mostram como erros.
+/// tip | "Dica"
- Utilizando `dependencies` no *decorador da operação de rota* você pode garantir que elas serão executadas enquanto evita errors de editores/ferramentas.
+Alguns editores de texto checam parâmetros de funções não utilizados, e os mostram como erros.
- Isso também pode ser útil para evitar confundir novos desenvolvedores que ao ver um parâmetro não usado no seu código podem pensar que ele é desnecessário.
+Utilizando `dependencies` no *decorador da operação de rota* você pode garantir que elas serão executadas enquanto evita errors de editores/ferramentas.
-!!! info "Informação"
- Neste exemplo utilizamos cabeçalhos personalizados inventados `X-Keys` e `X-Token`.
+Isso também pode ser útil para evitar confundir novos desenvolvedores que ao ver um parâmetro não usado no seu código podem pensar que ele é desnecessário.
- Mas em situações reais, como implementações de segurança, você pode obter mais vantagens em usar as [Ferramentas de segurança integradas (o próximo capítulo)](../security/index.md){.internal-link target=_blank}.
+///
+
+/// info | "Informação"
+
+Neste exemplo utilizamos cabeçalhos personalizados inventados `X-Keys` e `X-Token`.
+
+Mas em situações reais, como implementações de segurança, você pode obter mais vantagens em usar as [Ferramentas de segurança integradas (o próximo capítulo)](../security/index.md){.internal-link target=_blank}.
+
+///
## Erros das dependências e valores de retorno
@@ -56,51 +72,69 @@ Você pode utilizar as mesmas *funções* de dependências que você usaria norm
Dependências podem declarar requisitos de requisições (como cabeçalhos) ou outras subdependências:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="8 13"
- {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
- ```
+```Python hl_lines="8 13"
+{!> ../../docs_src/dependencies/tutorial006_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="7 12"
- {!> ../../../docs_src/dependencies/tutorial006_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8 non-Annotated"
+```Python hl_lines="7 12"
+{!> ../../docs_src/dependencies/tutorial006_an.py!}
+```
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível
+////
- ```Python hl_lines="6 11"
- {!> ../../../docs_src/dependencies/tutorial006.py!}
- ```
+//// tab | Python 3.8 non-Annotated
+
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível
+
+///
+
+```Python hl_lines="6 11"
+{!> ../../docs_src/dependencies/tutorial006.py!}
+```
+
+////
### Levantando exceções
Essas dependências podem levantar exceções, da mesma forma que dependências comuns:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="10 15"
- {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
- ```
+```Python hl_lines="10 15"
+{!> ../../docs_src/dependencies/tutorial006_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9 14"
- {!> ../../../docs_src/dependencies/tutorial006_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8 non-Annotated"
+```Python hl_lines="9 14"
+{!> ../../docs_src/dependencies/tutorial006_an.py!}
+```
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível
+////
- ```Python hl_lines="8 13"
- {!> ../../../docs_src/dependencies/tutorial006.py!}
- ```
+//// tab | Python 3.8 non-Annotated
+
+/// tip | "Dica"
+
+Utilize a versão com `Annotated` se possível
+
+///
+
+```Python hl_lines="8 13"
+{!> ../../docs_src/dependencies/tutorial006.py!}
+```
+
+////
### Valores de retorno
@@ -108,26 +142,37 @@ E elas também podem ou não retornar valores, eles não serão utilizados.
Então, você pode reutilizar uma dependência comum (que retorna um valor) que já seja utilizada em outro lugar, e mesmo que o valor não seja utilizado, a dependência será executada:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="11 16"
- {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
- ```
+```Python hl_lines="11 16"
+{!> ../../docs_src/dependencies/tutorial006_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="10 15"
- {!> ../../../docs_src/dependencies/tutorial006_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8 non-Annotated"
+```Python hl_lines="10 15"
+{!> ../../docs_src/dependencies/tutorial006_an.py!}
+```
- !!! tip "Dica"
- Utilize a versão com `Annotated` se possível
+////
- ```Python hl_lines="9 14"
- {!> ../../../docs_src/dependencies/tutorial006.py!}
- ```
+//// tab | Python 3.8 non-Annotated
+
+/// tip | "Dica"
+
+
+
+///
+
+ Utilize a versão com `Annotated` se possível
+
+```Python hl_lines="9 14"
+{!> ../../docs_src/dependencies/tutorial006.py!}
+```
+
+////
## Dependências para um grupo de *operações de rota*
diff --git a/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md
index 8b4175fc5..d90bebe39 100644
--- a/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md
+++ b/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md
@@ -4,18 +4,24 @@ O FastAPI possui suporte para dependências que realizam .
+/// tip | "Dica"
- Mas se você tiver cabeçalhos personalizados desejando que um cliente em um navegador esteja apto a ver, você precisa adicioná-los às suas configurações CORS ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) usando o parâmetro `expose_headers` documentado em Documentos CORS da Starlette.
+Tenha em mente que cabeçalhos proprietários personalizados podem ser adicionados usando o prefixo 'X-'.
-!!! note "Detalhes técnicos"
- Você também pode usar `from starlette.requests import Request`.
+Mas se você tiver cabeçalhos personalizados desejando que um cliente em um navegador esteja apto a ver, você precisa adicioná-los às suas configurações CORS ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) usando o parâmetro `expose_headers` documentado em Documentos CORS da Starlette.
- **FastAPI** fornece isso como uma conveniência para você, o desenvolvedor. Mas vem diretamente da Starlette.
+///
+
+/// note | "Detalhes técnicos"
+
+Você também pode usar `from starlette.requests import Request`.
+
+**FastAPI** fornece isso como uma conveniência para você, o desenvolvedor. Mas vem diretamente da Starlette.
+
+///
### Antes e depois da `response`
@@ -51,7 +60,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!}
```
## Outros middlewares
diff --git a/docs/pt/docs/tutorial/path-operation-configuration.md b/docs/pt/docs/tutorial/path-operation-configuration.md
index 13a87240f..48753d725 100644
--- a/docs/pt/docs/tutorial/path-operation-configuration.md
+++ b/docs/pt/docs/tutorial/path-operation-configuration.md
@@ -2,8 +2,11 @@
Existem vários parâmetros que você pode passar para o seu *decorador de operação de rota* para configurá-lo.
-!!! warning "Aviso"
- Observe que esses parâmetros são passados diretamente para o *decorador de operação de rota*, não para a sua *função de operação de rota*.
+/// warning | "Aviso"
+
+Observe que esses parâmetros são passados diretamente para o *decorador de operação de rota*, não para a sua *função de operação de rota*.
+
+///
## Código de Status da Resposta
@@ -13,52 +16,67 @@ Você pode passar diretamente o código `int`, como `404`.
Mas se você não se lembrar o que cada código numérico significa, pode usar as constantes de atalho em `status`:
-=== "Python 3.8 and above"
+//// tab | Python 3.8 and above
- ```Python hl_lines="3 17"
- {!> ../../../docs_src/path_operation_configuration/tutorial001.py!}
- ```
+```Python hl_lines="3 17"
+{!> ../../docs_src/path_operation_configuration/tutorial001.py!}
+```
-=== "Python 3.9 and above"
+////
- ```Python hl_lines="3 17"
- {!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!}
- ```
+//// tab | Python 3.9 and above
-=== "Python 3.10 and above"
+```Python hl_lines="3 17"
+{!> ../../docs_src/path_operation_configuration/tutorial001_py39.py!}
+```
- ```Python hl_lines="1 15"
- {!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!}
- ```
+////
+
+//// tab | Python 3.10 and above
+
+```Python hl_lines="1 15"
+{!> ../../docs_src/path_operation_configuration/tutorial001_py310.py!}
+```
+
+////
Esse código de status será usado na resposta e será adicionado ao esquema OpenAPI.
-!!! note "Detalhes Técnicos"
- Você também poderia usar `from starlette import status`.
+/// note | "Detalhes Técnicos"
- **FastAPI** fornece o mesmo `starlette.status` como `fastapi.status` apenas como uma conveniência para você, o desenvolvedor. Mas vem diretamente do Starlette.
+Você também poderia usar `from starlette import status`.
+
+**FastAPI** fornece o mesmo `starlette.status` como `fastapi.status` apenas como uma conveniência para você, o desenvolvedor. Mas vem diretamente do Starlette.
+
+///
## Tags
Você pode adicionar tags para sua *operação de rota*, passe o parâmetro `tags` com uma `list` de `str` (comumente apenas um `str`):
-=== "Python 3.8 and above"
+//// tab | Python 3.8 and above
- ```Python hl_lines="17 22 27"
- {!> ../../../docs_src/path_operation_configuration/tutorial002.py!}
- ```
+```Python hl_lines="17 22 27"
+{!> ../../docs_src/path_operation_configuration/tutorial002.py!}
+```
-=== "Python 3.9 and above"
+////
- ```Python hl_lines="17 22 27"
- {!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!}
- ```
+//// tab | Python 3.9 and above
-=== "Python 3.10 and above"
+```Python hl_lines="17 22 27"
+{!> ../../docs_src/path_operation_configuration/tutorial002_py39.py!}
+```
- ```Python hl_lines="15 20 25"
- {!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!}
- ```
+////
+
+//// tab | Python 3.10 and above
+
+```Python hl_lines="15 20 25"
+{!> ../../docs_src/path_operation_configuration/tutorial002_py310.py!}
+```
+
+////
Eles serão adicionados ao esquema OpenAPI e usados pelas interfaces de documentação automática:
@@ -73,30 +91,36 @@ 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!}
```
## Resumo e descrição
Você pode adicionar um `summary` e uma `description`:
-=== "Python 3.8 and above"
+//// tab | Python 3.8 and above
- ```Python hl_lines="20-21"
- {!> ../../../docs_src/path_operation_configuration/tutorial003.py!}
- ```
+```Python hl_lines="20-21"
+{!> ../../docs_src/path_operation_configuration/tutorial003.py!}
+```
-=== "Python 3.9 and above"
+////
- ```Python hl_lines="20-21"
- {!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!}
- ```
+//// tab | Python 3.9 and above
-=== "Python 3.10 and above"
+```Python hl_lines="20-21"
+{!> ../../docs_src/path_operation_configuration/tutorial003_py39.py!}
+```
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!}
- ```
+////
+
+//// tab | Python 3.10 and above
+
+```Python hl_lines="18-19"
+{!> ../../docs_src/path_operation_configuration/tutorial003_py310.py!}
+```
+
+////
## Descrição do docstring
@@ -104,23 +128,29 @@ Como as descrições tendem a ser longas e cobrir várias linhas, você pode dec
Você pode escrever Markdown na docstring, ele será interpretado e exibido corretamente (levando em conta a indentação da docstring).
-=== "Python 3.8 and above"
+//// tab | Python 3.8 and above
- ```Python hl_lines="19-27"
- {!> ../../../docs_src/path_operation_configuration/tutorial004.py!}
- ```
+```Python hl_lines="19-27"
+{!> ../../docs_src/path_operation_configuration/tutorial004.py!}
+```
-=== "Python 3.9 and above"
+////
- ```Python hl_lines="19-27"
- {!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!}
- ```
+//// tab | Python 3.9 and above
-=== "Python 3.10 and above"
+```Python hl_lines="19-27"
+{!> ../../docs_src/path_operation_configuration/tutorial004_py39.py!}
+```
- ```Python hl_lines="17-25"
- {!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!}
- ```
+////
+
+//// tab | Python 3.10 and above
+
+```Python hl_lines="17-25"
+{!> ../../docs_src/path_operation_configuration/tutorial004_py310.py!}
+```
+
+////
Ela será usada nas documentações interativas:
@@ -131,31 +161,43 @@ Ela será usada nas documentações interativas:
Você pode especificar a descrição da resposta com o parâmetro `response_description`:
-=== "Python 3.8 and above"
+//// tab | Python 3.8 and above
- ```Python hl_lines="21"
- {!> ../../../docs_src/path_operation_configuration/tutorial005.py!}
- ```
+```Python hl_lines="21"
+{!> ../../docs_src/path_operation_configuration/tutorial005.py!}
+```
-=== "Python 3.9 and above"
+////
- ```Python hl_lines="21"
- {!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!}
- ```
+//// tab | Python 3.9 and above
-=== "Python 3.10 and above"
+```Python hl_lines="21"
+{!> ../../docs_src/path_operation_configuration/tutorial005_py39.py!}
+```
- ```Python hl_lines="19"
- {!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!}
- ```
+////
-!!! info "Informação"
- Note que `response_description` se refere especificamente à resposta, a `description` se refere à *operação de rota* em geral.
+//// tab | Python 3.10 and above
-!!! check
- OpenAPI especifica que cada *operação de rota* requer uma descrição de resposta.
+```Python hl_lines="19"
+{!> ../../docs_src/path_operation_configuration/tutorial005_py310.py!}
+```
- Então, se você não fornecer uma, o **FastAPI** irá gerar automaticamente uma de "Resposta bem-sucedida".
+////
+
+/// info | "Informação"
+
+Note que `response_description` se refere especificamente à resposta, a `description` se refere à *operação de rota* em geral.
+
+///
+
+/// check
+
+OpenAPI especifica que cada *operação de rota* requer uma descrição de resposta.
+
+Então, se você não fornecer uma, o **FastAPI** irá gerar automaticamente uma de "Resposta bem-sucedida".
+
+///
@@ -164,7 +206,7 @@ Você pode especificar a descrição da resposta com o parâmetro `response_desc
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!}
```
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 eb0d31dc3..28c55482f 100644
--- a/docs/pt/docs/tutorial/path-params-numeric-validations.md
+++ b/docs/pt/docs/tutorial/path-params-numeric-validations.md
@@ -6,17 +6,21 @@ Do mesmo modo que você pode declarar mais validações e metadados para parâme
Primeiro, importe `Path` de `fastapi`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="1"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
- ```
+```Python hl_lines="1"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="3"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!}
+```
+
+////
## Declare metadados
@@ -24,24 +28,31 @@ Você pode declarar todos os parâmetros da mesma maneira que na `Query`.
Por exemplo para declarar um valor de metadado `title` para o parâmetro de rota `item_id` você pode digitar:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="8"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
- ```
+```Python hl_lines="8"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
- ```
+//// tab | Python 3.8+
-!!! note "Nota"
- Um parâmetro de rota é sempre obrigatório, como se fizesse parte da rota.
+```Python hl_lines="10"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!}
+```
- Então, você deve declará-lo com `...` para marcá-lo como obrigatório.
+////
- Mesmo que você declare-o como `None` ou defina um valor padrão, isso não teria efeito algum, o parâmetro ainda seria obrigatório.
+/// note | "Nota"
+
+Um parâmetro de rota é sempre obrigatório, como se fizesse parte da rota.
+
+Então, você deve declará-lo com `...` para marcá-lo como obrigatório.
+
+Mesmo que você declare-o como `None` ou defina um valor padrão, isso não teria efeito algum, o parâmetro ainda seria obrigatório.
+
+///
## Ordene os parâmetros de acordo com sua necessidade
@@ -60,7 +71,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!}
```
## Ordene os parâmetros de a acordo com sua necessidade, truques
@@ -72,7 +83,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!}
```
## Validações numéricas: maior que ou igual
@@ -82,7 +93,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!}
```
## Validações numéricas: maior que e menor que ou igual
@@ -93,7 +104,7 @@ O mesmo se aplica para:
* `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!}
```
## Validações numéricas: valores do tipo float, maior que e menor que
@@ -107,7 +118,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!}
```
## Recapitulando
@@ -121,18 +132,24 @@ E você também pode declarar validações numéricas:
* `lt`: menor que (`l`ess `t`han)
* `le`: menor que ou igual (`l`ess than or `e`qual)
-!!! info "Informação"
- `Query`, `Path` e outras classes que você verá a frente são subclasses de uma classe comum `Param`.
+/// info | "Informação"
- Todas elas compartilham os mesmos parâmetros para validação adicional e metadados que você viu.
+`Query`, `Path` e outras classes que você verá a frente são subclasses de uma classe comum `Param`.
-!!! note "Detalhes Técnicos"
- Quando você importa `Query`, `Path` e outras de `fastapi`, elas são na verdade funções.
+Todas elas compartilham os mesmos parâmetros para validação adicional e metadados que você viu.
- Que quando chamadas, retornam instâncias de classes de mesmo nome.
+///
- Então, você importa `Query`, que é uma função. E quando você a chama, ela retorna uma instância de uma classe também chamada `Query`.
+/// note | "Detalhes Técnicos"
- Estas funções são assim (ao invés de apenas usar as classes diretamente) para que seu editor não acuse erros sobre seus tipos.
+Quando você importa `Query`, `Path` e outras de `fastapi`, elas são na verdade funções.
- Dessa maneira você pode user seu editor e ferramentas de desenvolvimento sem precisar adicionar configurações customizadas para ignorar estes erros.
+Que quando chamadas, retornam instâncias de classes de mesmo nome.
+
+Então, você importa `Query`, que é uma função. E quando você a chama, ela retorna uma instância de uma classe também chamada `Query`.
+
+Estas funções são assim (ao invés de apenas usar as classes diretamente) para que seu editor não acuse erros sobre seus tipos.
+
+Dessa maneira você pode user seu editor e ferramentas de desenvolvimento sem precisar adicionar configurações customizadas para ignorar estes erros.
+
+///
diff --git a/docs/pt/docs/tutorial/path-params.md b/docs/pt/docs/tutorial/path-params.md
index 27aa9dfcf..a68354a1b 100644
--- a/docs/pt/docs/tutorial/path-params.md
+++ b/docs/pt/docs/tutorial/path-params.md
@@ -3,7 +3,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!}
```
O valor do parâmetro que foi passado à `item_id` será passado para a sua função como o argumento `item_id`.
@@ -19,12 +19,17 @@ Então, se você rodar este exemplo e for até dados
@@ -35,7 +40,12 @@ Se você rodar esse exemplo e abrir o seu navegador em "parsing"
+POST.
+ Mas quando o formulário inclui arquivos, ele é codificado como `multipart/form-data`. Você lerá sobre como lidar com arquivos no próximo capítulo.
-!!! warning "Aviso"
- Você pode declarar vários parâmetros `Form` em uma *operação de caminho*, mas não pode declarar campos `Body` que espera receber como JSON, pois a solicitação terá o corpo codificado usando `application/x-www- form-urlencoded` em vez de `application/json`.
+Se você quiser ler mais sobre essas codificações e campos de formulário, vá para o MDN web docs para POST.
- Esta não é uma limitação do **FastAPI**, é parte do protocolo HTTP.
+///
+
+/// warning | "Aviso"
+
+Você pode declarar vários parâmetros `Form` em uma *operação de caminho*, mas não pode declarar campos `Body` que espera receber como JSON, pois a solicitação terá o corpo codificado usando `application/x-www- form-urlencoded` em vez de `application/json`.
+
+Esta não é uma limitação do **FastAPI**, é parte do protocolo HTTP.
+
+///
## Recapitulando
diff --git a/docs/pt/docs/tutorial/request_files.md b/docs/pt/docs/tutorial/request_files.md
new file mode 100644
index 000000000..39bfe284a
--- /dev/null
+++ b/docs/pt/docs/tutorial/request_files.md
@@ -0,0 +1,418 @@
+# Arquivos de Requisição
+
+Você pode definir arquivos para serem enviados para o cliente utilizando `File`.
+
+/// info
+
+Para receber arquivos compartilhados, primeiro instale `python-multipart`.
+
+E.g. `pip install python-multipart`.
+
+Isso se deve por que arquivos enviados são enviados como "dados de formulário".
+
+///
+
+## Importe `File`
+
+Importe `File` e `UploadFile` do `fastapi`:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="3"
+{!> ../../docs_src/request_files/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="1"
+{!> ../../docs_src/request_files/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | Dica
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python hl_lines="1"
+{!> ../../docs_src/request_files/tutorial001.py!}
+```
+
+////
+
+## Defina os parâmetros de `File`
+
+Cria os parâmetros do arquivo da mesma forma que você faria para `Body` ou `Form`:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="9"
+{!> ../../docs_src/request_files/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="8"
+{!> ../../docs_src/request_files/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | Dica
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python hl_lines="7"
+{!> ../../docs_src/request_files/tutorial001.py!}
+```
+
+////
+
+/// info | Informação
+
+`File` é uma classe que herda diretamente de `Form`.
+
+Mas lembre-se que quando você importa `Query`,`Path`, `File`, entre outros, do `fastapi`, essas são na verdade funções que retornam classes especiais.
+
+///
+
+/// tip | Dica
+
+Para declarar o corpo de arquivos, você precisa utilizar `File`, do contrário os parâmetros seriam interpretados como parâmetros de consulta ou corpo (JSON) da requisição.
+
+///
+
+Os arquivos serão enviados como "form data".
+
+Se você declarar o tipo do seu parâmetro na sua *função de operação de rota* como `bytes`, o **FastAPI** irá ler o arquivo para você e você receberá o conteúdo como `bytes`.
+
+Lembre-se que isso significa que o conteúdo inteiro será armazenado em memória. Isso funciona bem para arquivos pequenos.
+
+Mas existem vários casos em que você pode se beneficiar ao usar `UploadFile`.
+
+## Parâmetros de arquivo com `UploadFile`
+
+Defina um parâmetro de arquivo com o tipo `UploadFile`
+
+//// tab | Python 3.9+
+
+```Python hl_lines="14"
+{!> ../../docs_src/request_files/tutorial001_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="13"
+{!> ../../docs_src/request_files/tutorial001_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | Dica
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python hl_lines="12"
+{!> ../../docs_src/request_files/tutorial001.py!}
+```
+
+////
+
+Utilizando `UploadFile` tem várias vantagens sobre `bytes`:
+
+* Você não precisa utilizar `File()` como o valor padrão do parâmetro.
+* A classe utiliza um arquivo em "spool":
+ * Um arquivo guardado em memória até um tamanho máximo, depois desse limite ele é guardado em disco.
+* Isso significa que a classe funciona bem com arquivos grandes como imagens, vídeos, binários extensos, etc. Sem consumir toda a memória.
+* Você pode obter metadados do arquivo enviado.
+* Ela possui uma interface semelhante a arquivos `async`.
+* Ela expõe um objeto python `SpooledTemporaryFile` que você pode repassar para bibliotecas que esperam um objeto com comportamento de arquivo.
+
+### `UploadFile`
+
+`UploadFile` tem os seguintes atributos:
+
+* `filename`: Uma string (`str`) com o nome original do arquivo enviado (e.g. `myimage.jpg`).
+* `content-type`: Uma `str` com o tipo do conteúdo (tipo MIME / media) (e.g. `image/jpeg`).
+* `file`: Um objeto do tipo `SpooledTemporaryFile` (um objeto file-like). O arquivo propriamente dito que você pode passar diretamente para outras funções ou bibliotecas que esperam um objeto "file-like".
+
+`UploadFile` tem os seguintes métodos `async`. Todos eles chamam os métodos de arquivos por baixo dos panos (usando o objeto `SpooledTemporaryFile` interno).
+
+* `write(data)`: escreve dados (`data`) em `str` ou `bytes` no arquivo.
+* `read(size)`: Lê um número de bytes/caracteres de acordo com a quantidade `size` (`int`).
+* `seek(offset)`: Navega para o byte na posição `offset` (`int`) do arquivo.
+ * E.g., `await myfile.seek(0)` navegaria para o ínicio do arquivo.
+ * Isso é especialmente útil se você executar `await myfile.read()` uma vez e depois precisar ler os conteúdos do arquivo de novo.
+* `close()`: Fecha o arquivo.
+
+Como todos esses métodos são assíncronos (`async`) você precisa esperar ("await") por eles.
+
+Por exemplo, dentro de uma *função de operação de rota* assíncrona você pode obter os conteúdos com:
+
+```Python
+contents = await myfile.read()
+```
+
+Se você estiver dentro de uma *função de operação de rota* definida normalmente com `def`, você pode acessar `UploadFile.file` diretamente, por exemplo:
+
+```Python
+contents = myfile.file.read()
+```
+
+/// note | Detalhes técnicos do `async`
+
+Quando você utiliza métodos assíncronos, o **FastAPI** executa os métodos do arquivo em uma threadpool e espera por eles.
+
+///
+
+/// note | Detalhes técnicos do Starlette
+
+O `UploadFile` do **FastAPI** herda diretamente do `UploadFile` do **Starlette**, mas adiciona algumas funcionalidades necessárias para ser compatível com o **Pydantic**
+
+///
+
+## O que é "Form Data"
+
+A forma como formulários HTML(``) enviam dados para o servidor normalmente utilizam uma codificação "especial" para esses dados, que é diferente do JSON.
+
+O **FastAPI** garante que os dados serão lidos da forma correta, em vez do JSON.
+
+/// note | Detalhes Técnicos
+
+Dados vindos de formulários geralmente tem a codificação com o "media type" `application/x-www-form-urlencoded` quando estes não incluem arquivos.
+
+Mas quando os dados incluem arquivos, eles são codificados como `multipart/form-data`. Se você utilizar `File`, **FastAPI** saberá que deve receber os arquivos da parte correta do corpo da requisição.
+
+Se você quer ler mais sobre essas codificações e campos de formulário, veja a documentação online da MDN sobre POST .
+
+///
+
+/// warning | Aviso
+
+Você pode declarar múltiplos parâmetros `File` e `Form` em uma *operação de rota*, mas você não pode declarar campos `Body`que seriam recebidos como JSON junto desses parâmetros, por que a codificação do corpo da requisição será `multipart/form-data` em vez de `application/json`.
+
+Isso não é uma limitação do **FastAPI**, é uma parte do protocolo HTTP.
+
+///
+
+## Arquivo de upload opcional
+
+Você pode definir um arquivo como opcional utilizando as anotações de tipo padrão e definindo o valor padrão como `None`:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="9 17"
+{!> ../../docs_src/request_files/tutorial001_02_an_py310.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python hl_lines="9 17"
+{!> ../../docs_src/request_files/tutorial001_02_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="10 18"
+{!> ../../docs_src/request_files/tutorial001_02_an.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip | Dica
+
+Utilize a versão com `Annotated`, se possível
+
+///
+
+```Python hl_lines="7 15"
+{!> ../../docs_src/request_files/tutorial001_02_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | Dica
+
+Utilize a versão com `Annotated`, se possível
+
+///
+
+```Python hl_lines="9 17"
+{!> ../../docs_src/request_files/tutorial001_02.py!}
+```
+
+////
+
+## `UploadFile` com Metadados Adicionais
+
+Você também pode utilizar `File()` com `UploadFile`, por exemplo, para definir metadados adicionais:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="9 15"
+{!> ../../docs_src/request_files/tutorial001_03_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="8 14"
+{!> ../../docs_src/request_files/tutorial001_03_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | Dica
+
+Utilize a versão com `Annotated` se possível
+
+///
+
+```Python hl_lines="7 13"
+{!> ../../docs_src/request_files/tutorial001_03.py!}
+```
+
+////
+
+## Envio de Múltiplos Arquivos
+
+É possível enviar múltiplos arquivos ao mesmo tmepo.
+
+Ele ficam associados ao mesmo "campo do formulário" enviado com "form data".
+
+Para usar isso, declare uma lista de `bytes` ou `UploadFile`:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="10 15"
+{!> ../../docs_src/request_files/tutorial002_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="11 16"
+{!> ../../docs_src/request_files/tutorial002_an.py!}
+```
+
+////
+
+//// tab | Python 3.9+ non-Annotated
+
+/// tip | Dica
+
+Utilize a versão com `Annotated` se possível
+
+///
+
+```Python hl_lines="8 13"
+{!> ../../docs_src/request_files/tutorial002_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | Dica
+
+Utilize a versão com `Annotated` se possível
+
+///
+
+```Python hl_lines="10 15"
+{!> ../../docs_src/request_files/tutorial002.py!}
+```
+
+////
+
+Você irá receber, como delcarado uma lista (`list`) de `bytes` ou `UploadFile`s,
+
+/// note | Detalhes Técnicos
+
+Você também poderia utilizar `from starlette.responses import HTMLResponse`.
+
+O **FastAPI** fornece as mesmas `starlette.responses` como `fastapi.responses` apenas como um facilitador para você, desenvolvedor. Mas a maior parte das respostas vem diretamente do Starlette.
+
+///
+
+### Enviando Múltiplos Arquivos com Metadados Adicionais
+
+E da mesma forma que antes, você pode utilizar `File()` para definir parâmetros adicionais, até mesmo para `UploadFile`:
+
+//// tab | Python 3.9+
+
+```Python hl_lines="11 18-20"
+{!> ../../docs_src/request_files/tutorial003_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="12 19-21"
+{!> ../../docs_src/request_files/tutorial003_an.py!}
+```
+
+////
+
+//// tab | Python 3.9+ non-Annotated
+
+/// tip | Dica
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python hl_lines="9 16"
+{!> ../../docs_src/request_files/tutorial003_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | Dica
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python hl_lines="11 18"
+{!> ../../docs_src/request_files/tutorial003.py!}
+```
+
+////
+
+## Recapitulando
+
+Use `File`, `bytes` e `UploadFile` para declarar arquivos que serão enviados na requisição, enviados como dados do formulário.
diff --git a/docs/pt/docs/tutorial/response-status-code.md b/docs/pt/docs/tutorial/response-status-code.md
index 2df17d4ea..bc4a2cd34 100644
--- a/docs/pt/docs/tutorial/response-status-code.md
+++ b/docs/pt/docs/tutorial/response-status-code.md
@@ -9,16 +9,22 @@ Da mesma forma que você pode especificar um modelo de resposta, você também p
* etc.
```Python hl_lines="6"
-{!../../../docs_src/response_status_code/tutorial001.py!}
+{!../../docs_src/response_status_code/tutorial001.py!}
```
-!!! note "Nota"
- Observe que `status_code` é um parâmetro do método "decorador" (get, post, etc). Não da sua função de *operação de caminho*, como todos os parâmetros e corpo.
+/// note | "Nota"
+
+Observe que `status_code` é um parâmetro do método "decorador" (get, post, etc). Não da sua função de *operação de caminho*, como todos os parâmetros e corpo.
+
+///
O parâmetro `status_code` recebe um número com o código de status HTTP.
-!!! info "Informação"
- `status_code` também pode receber um `IntEnum`, como o do Python `http.HTTPStatus`.
+/// info | "Informação"
+
+`status_code` também pode receber um `IntEnum`, como o do Python `http.HTTPStatus`.
+
+///
Dessa forma:
@@ -27,15 +33,21 @@ Dessa forma:
-!!! note "Nota"
- Alguns códigos de resposta (consulte a próxima seção) indicam que a resposta não possui um corpo.
+/// note | "Nota"
- O FastAPI sabe disso e produzirá documentos OpenAPI informando que não há corpo de resposta.
+Alguns códigos de resposta (consulte a próxima seção) indicam que a resposta não possui um corpo.
+
+O FastAPI sabe disso e produzirá documentos OpenAPI informando que não há corpo de resposta.
+
+///
## Sobre os códigos de status HTTP
-!!! note "Nota"
- Se você já sabe o que são códigos de status HTTP, pule para a próxima seção.
+/// note | "Nota"
+
+Se você já sabe o que são códigos de status HTTP, pule para a próxima seção.
+
+///
Em HTTP, você envia um código de status numérico de 3 dígitos como parte da resposta.
@@ -55,15 +67,18 @@ Resumidamente:
* Para erros genéricos do cliente, você pode usar apenas `400`.
* `500` e acima são para erros do servidor. Você quase nunca os usa diretamente. Quando algo der errado em alguma parte do código do seu aplicativo ou servidor, ele retornará automaticamente um desses códigos de status.
-!!! tip "Dica"
- Para saber mais sobre cada código de status e qual código serve para quê, verifique o MDN documentação sobre códigos de status HTTP.
+/// tip | "Dica"
+
+Para saber mais sobre cada código de status e qual código serve para quê, verifique o MDN documentação sobre códigos de status HTTP.
+
+///
## Atalho para lembrar os nomes
Vamos ver o exemplo anterior novamente:
```Python hl_lines="6"
-{!../../../docs_src/response_status_code/tutorial001.py!}
+{!../../docs_src/response_status_code/tutorial001.py!}
```
`201` é o código de status para "Criado".
@@ -73,18 +88,20 @@ 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!}
```
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"
- Você também pode usar `from starlette import status`.
+/// note | "Detalhes técnicos"
- **FastAPI** fornece o mesmo `starlette.status` como `fastapi.status` apenas como uma conveniência para você, o desenvolvedor. Mas vem diretamente da Starlette.
+Você também pode usar `from starlette import status`.
+**FastAPI** fornece o mesmo `starlette.status` como `fastapi.status` apenas como uma conveniência para você, o desenvolvedor. Mas vem diretamente da Starlette.
+
+///
## Alterando o padrão
diff --git a/docs/pt/docs/tutorial/schema-extra-example.md b/docs/pt/docs/tutorial/schema-extra-example.md
index d04dc1a26..2d78e4ef1 100644
--- a/docs/pt/docs/tutorial/schema-extra-example.md
+++ b/docs/pt/docs/tutorial/schema-extra-example.md
@@ -9,15 +9,18 @@ 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!}
```
Essas informações extras serão adicionadas como se encontram no **JSON Schema** de resposta desse modelo e serão usadas na documentação da API.
-!!! tip "Dica"
- Você pode usar a mesma técnica para estender o JSON Schema e adicionar suas próprias informações extras de forma personalizada.
+/// tip | "Dica"
- Por exemplo, você pode usar isso para adicionar metadados para uma interface de usuário de front-end, etc.
+Você pode usar a mesma técnica para estender o JSON Schema e adicionar suas próprias informações extras de forma personalizada.
+
+Por exemplo, você pode usar isso para adicionar metadados para uma interface de usuário de front-end, etc.
+
+///
## `Field` de argumentos adicionais
@@ -26,11 +29,14 @@ 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!}
```
-!!! warning "Atenção"
- Lembre-se de que esses argumentos extras passados não adicionarão nenhuma validação, apenas informações extras, para fins de documentação.
+/// warning | "Atenção"
+
+Lembre-se de que esses argumentos extras passados não adicionarão nenhuma validação, apenas informações extras, para fins de documentação.
+
+///
## `example` e `examples` no OpenAPI
@@ -51,7 +57,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!}
```
### Exemplo na UI da documentação
@@ -74,7 +80,7 @@ Cada `dict` de exemplo específico em `examples` pode conter:
* `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!}
```
### Exemplos na UI da documentação
@@ -85,10 +91,13 @@ Com `examples` adicionado a `Body()`, os `/docs` vão ficar assim:
## Detalhes técnicos
-!!! warning "Atenção"
- Esses são detalhes muito técnicos sobre os padrões **JSON Schema** e **OpenAPI**.
+/// warning | "Atenção"
- Se as ideias explicadas acima já funcionam para você, isso pode ser o suficiente, e você provavelmente não precisa desses detalhes, fique à vontade para pular.
+Esses são detalhes muito técnicos sobre os padrões **JSON Schema** e **OpenAPI**.
+
+Se as ideias explicadas acima já funcionam para você, isso pode ser o suficiente, e você provavelmente não precisa desses detalhes, fique à vontade para pular.
+
+///
Quando você adiciona um exemplo dentro de um modelo Pydantic, usando `schema_extra` ou` Field(example="something") `esse exemplo é adicionado ao **JSON Schema** para esse modelo Pydantic.
diff --git a/docs/pt/docs/tutorial/security/first-steps.md b/docs/pt/docs/tutorial/security/first-steps.md
index 4331a0bc3..9fb94fe67 100644
--- a/docs/pt/docs/tutorial/security/first-steps.md
+++ b/docs/pt/docs/tutorial/security/first-steps.md
@@ -20,12 +20,17 @@ Vamos primeiro usar o código e ver como funciona, e depois voltaremos para ente
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"
+
+
+
+///
+
Primeiro, instale `python-multipart`.
Ex: `pip install python-multipart`.
@@ -52,7 +57,12 @@ Você verá algo deste tipo:
-!!! check "Botão de Autorizar!"
+/// check | "Botão de Autorizar!"
+
+
+
+///
+
Você já tem um novo "botão de autorizar!".
E seu *path operation* tem um pequeno cadeado no canto superior direito que você pode clicar.
@@ -61,7 +71,12 @@ E se você clicar, você terá um pequeno formulário de autorização para digi
-!!! note "Nota"
+/// note | "Nota"
+
+
+
+///
+
Não importa o que você digita no formulário, não vai funcionar ainda. Mas nós vamos chegar lá.
Claro que este não é o frontend para os usuários finais, mas é uma ótima ferramenta automática para documentar interativamente toda sua API.
@@ -104,7 +119,12 @@ Então, vamos rever de um ponto de vista simplificado:
Neste exemplo, nós vamos usar o **OAuth2** com o fluxo de **Senha**, usando um token **Bearer**. Fazemos isso usando a classe `OAuth2PasswordBearer`.
-!!! info "informação"
+/// info | "informação"
+
+
+
+///
+
Um token "bearer" não é a única opção.
Mas é a melhor no nosso caso.
@@ -116,10 +136,15 @@ 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!}
```
-!!! tip "Dica"
+/// tip | "Dica"
+
+
+
+///
+
Esse `tokenUrl="token"` se refere a uma URL relativa que nós não criamos ainda. Como é uma URL relativa, é equivalente a `./token`.
Porque estamos usando uma URL relativa, se sua API estava localizada em `https://example.com/`, então irá referir-se à `https://example.com/token`. Mas se sua API estava localizada em `https://example.com/api/v1/`, então irá referir-se à `https://example.com/api/v1/token`.
@@ -130,7 +155,12 @@ Esse parâmetro não cria um endpoint / *path operation*, mas declara que a URL
Em breve também criaremos o atual path operation.
-!!! info "informação"
+/// info | "informação"
+
+
+
+///
+
Se você é um "Pythonista" muito rigoroso, você pode não gostar do estilo do nome do parâmetro `tokenUrl` em vez de `token_url`.
Isso ocorre porque está utilizando o mesmo nome que está nas especificações do OpenAPI. Então, se você precisa investigar mais sobre qualquer um desses esquemas de segurança, você pode simplesmente copiar e colar para encontrar mais informações sobre isso.
@@ -150,14 +180,19 @@ 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!}
```
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"
+
+
+
+///
+
**FastAPI** saberá que pode usar a classe `OAuth2PasswordBearer` (declarada na dependência) para definir o esquema de segurança na OpenAPI porque herda de `fastapi.security.oauth2.OAuth2`, que por sua vez herda de `fastapi.security.base.Securitybase`.
Todos os utilitários de segurança que se integram com OpenAPI (e na documentação da API automática) herdam de `SecurityBase`, é assim que **FastAPI** pode saber como integrá-los no OpenAPI.
diff --git a/docs/pt/docs/tutorial/security/index.md b/docs/pt/docs/tutorial/security/index.md
index f94a8ab62..2f23aa47e 100644
--- a/docs/pt/docs/tutorial/security/index.md
+++ b/docs/pt/docs/tutorial/security/index.md
@@ -32,9 +32,11 @@ Não é muito popular ou usado nos dias atuais.
OAuth2 não especifica como criptografar a comunicação, ele espera que você tenha sua aplicação em um servidor HTTPS.
-!!! tip "Dica"
- Na seção sobre **deployment** você irá ver como configurar HTTPS de modo gratuito, usando Traefik e Let’s Encrypt.
+/// tip | "Dica"
+Na seção sobre **deployment** você irá ver como configurar HTTPS de modo gratuito, usando Traefik e Let’s Encrypt.
+
+///
## OpenID Connect
@@ -87,10 +89,13 @@ OpenAPI define os seguintes esquemas de segurança:
* Essa descoberta automática é o que é definido na especificação OpenID Connect.
-!!! tip "Dica"
- Integração com outros provedores de autenticação/autorização como Google, Facebook, Twitter, GitHub, etc. é bem possível e relativamente fácil.
+/// tip | "Dica"
- O problema mais complexo é criar um provedor de autenticação/autorização como eles, mas o FastAPI dá a você ferramentas para fazer isso facilmente, enquanto faz o trabalho pesado para você.
+Integração com outros provedores de autenticação/autorização como Google, Facebook, Twitter, GitHub, etc. é bem possível e relativamente fácil.
+
+O problema mais complexo é criar um provedor de autenticação/autorização como eles, mas o FastAPI dá a você ferramentas para fazer isso facilmente, enquanto faz o trabalho pesado para você.
+
+///
## **FastAPI** utilitários
diff --git a/docs/pt/docs/tutorial/static-files.md b/docs/pt/docs/tutorial/static-files.md
index 009158fc6..901fca1d2 100644
--- a/docs/pt/docs/tutorial/static-files.md
+++ b/docs/pt/docs/tutorial/static-files.md
@@ -8,13 +8,16 @@ Você pode servir arquivos estáticos automaticamente de um diretório usando `S
* "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!}
```
-!!! note "Detalhes técnicos"
- Você também pode usar `from starlette.staticfiles import StaticFiles`.
+/// note | "Detalhes técnicos"
- O **FastAPI** fornece o mesmo que `starlette.staticfiles` como `fastapi.staticfiles` apenas como uma conveniência para você, o desenvolvedor. Mas na verdade vem diretamente da Starlette.
+Você também pode usar `from starlette.staticfiles import StaticFiles`.
+
+O **FastAPI** fornece o mesmo que `starlette.staticfiles` como `fastapi.staticfiles` apenas como uma conveniência para você, o desenvolvedor. Mas na verdade vem diretamente da Starlette.
+
+///
### O que é "Montagem"
diff --git a/docs/pt/docs/tutorial/testing.md b/docs/pt/docs/tutorial/testing.md
new file mode 100644
index 000000000..4e28a43c0
--- /dev/null
+++ b/docs/pt/docs/tutorial/testing.md
@@ -0,0 +1,249 @@
+# Testando
+
+Graças ao Starlette, testar aplicativos **FastAPI** é fácil e agradável.
+
+Ele é baseado no HTTPX, que por sua vez é projetado com base em Requests, por isso é muito familiar e intuitivo.
+
+Com ele, você pode usar o pytest diretamente com **FastAPI**.
+
+## Usando `TestClient`
+
+/// info | "Informação"
+
+Para usar o `TestClient`, primeiro instale o `httpx`.
+
+Certifique-se de criar um [ambiente virtual](../virtual-environments.md){.internal-link target=_blank}, ativá-lo e instalá-lo, por exemplo:
+
+```console
+$ pip install httpx
+```
+
+///
+
+Importe `TestClient`.
+
+Crie um `TestClient` passando seu aplicativo **FastAPI** para ele.
+
+Crie funções com um nome que comece com `test_` (essa é a convenção padrão do `pytest`).
+
+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!}
+```
+
+/// tip | "Dica"
+
+Observe que as funções de teste são `def` normais, não `async def`.
+
+E as chamadas para o cliente também são chamadas normais, não usando `await`.
+
+Isso permite que você use `pytest` diretamente sem complicações.
+
+///
+
+/// note | "Detalhes técnicos"
+
+Você também pode usar `from starlette.testclient import TestClient`.
+
+**FastAPI** fornece o mesmo `starlette.testclient` que `fastapi.testclient` apenas como uma conveniência para você, o desenvolvedor. Mas ele vem diretamente da Starlette.
+
+///
+
+/// 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.
+
+///
+
+## Separando testes
+
+Em uma aplicação real, você provavelmente teria seus testes em um arquivo diferente.
+
+E seu aplicativo **FastAPI** também pode ser composto de vários arquivos/módulos, etc.
+
+### Arquivo do aplicativo **FastAPI**
+
+Digamos que você tenha uma estrutura de arquivo conforme descrito em [Aplicativos maiores](bigger-applications.md){.internal-link target=_blank}:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ └── main.py
+```
+
+No arquivo `main.py` você tem seu aplicativo **FastAPI**:
+
+
+```Python
+{!../../docs_src/app_testing/main.py!}
+```
+
+### Arquivo de teste
+
+Então você poderia ter um arquivo `test_main.py` com seus testes. Ele poderia estar no mesmo pacote Python (o mesmo diretório com um arquivo `__init__.py`):
+
+``` hl_lines="5"
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+│ └── test_main.py
+```
+
+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!}
+```
+
+...e ter o código para os testes como antes.
+
+## Testando: exemplo estendido
+
+Agora vamos estender este exemplo e adicionar mais detalhes para ver como testar diferentes partes.
+
+### Arquivo de aplicativo **FastAPI** estendido
+
+Vamos continuar com a mesma estrutura de arquivo de antes:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+│ └── test_main.py
+```
+
+Digamos que agora o arquivo `main.py` com seu aplicativo **FastAPI** tenha algumas outras **operações de rotas**.
+
+Ele tem uma operação `GET` que pode retornar um erro.
+
+Ele tem uma operação `POST` que pode retornar vários erros.
+
+Ambas as *operações de rotas* requerem um cabeçalho `X-Token`.
+
+//// tab | Python 3.10+
+
+```Python
+{!> ../../docs_src/app_testing/app_b_an_py310/main.py!}
+```
+
+////
+
+//// tab | Python 3.9+
+
+```Python
+{!> ../../docs_src/app_testing/app_b_an_py39/main.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python
+{!> ../../docs_src/app_testing/app_b_an/main.py!}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip | "Dica"
+
+Prefira usar a versão `Annotated` se possível.
+
+///
+
+```Python
+{!> ../../docs_src/app_testing/app_b_py310/main.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "Dica"
+
+Prefira usar a versão `Annotated` se possível.
+
+///
+
+```Python
+{!> ../../docs_src/app_testing/app_b/main.py!}
+```
+
+////
+
+### Arquivo de teste estendido
+
+Você pode então atualizar `test_main.py` com os testes estendidos:
+
+```Python
+{!> ../../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.
+
+Depois é só fazer o mesmo nos seus testes.
+
+Por exemplo:
+
+* Para passar um parâmetro *path* ou *query*, adicione-o à própria URL.
+* Para passar um corpo JSON, passe um objeto Python (por exemplo, um `dict`) para o parâmetro `json`.
+* Se você precisar enviar *Dados de Formulário* em vez de JSON, use o parâmetro `data`.
+* Para passar *headers*, use um `dict` no parâmetro `headers`.
+* Para *cookies*, um `dict` no parâmetro `cookies`.
+
+Para mais informações sobre como passar dados para o backend (usando `httpx` ou `TestClient`), consulte a documentação do HTTPX.
+
+/// info | "Informação"
+
+Observe que o `TestClient` recebe dados que podem ser convertidos para JSON, não para modelos Pydantic.
+
+Se você tiver um modelo Pydantic em seu teste e quiser enviar seus dados para o aplicativo durante o teste, poderá usar o `jsonable_encoder` descrito em [Codificador compatível com JSON](encoder.md){.internal-link target=_blank}.
+
+///
+
+## Execute-o
+
+Depois disso, você só precisa instalar o `pytest`.
+
+Certifique-se de criar um [ambiente virtual](../virtual-environments.md){.internal-link target=_blank}, ativá-lo e instalá-lo, por exemplo:
+
+email_validator - для проверки электронной почты.
+* email-validator - для проверки электронной почты.
Используется Starlette:
diff --git a/docs/ru/docs/python-types.md b/docs/ru/docs/python-types.md
index 3c8492c67..e5905304a 100644
--- a/docs/ru/docs/python-types.md
+++ b/docs/ru/docs/python-types.md
@@ -12,15 +12,18 @@ Python имеет поддержку необязательных аннотац
Но даже если вы никогда не используете **FastAPI**, вам будет полезно немного узнать о них.
-!!! note
- Если вы являетесь экспертом в Python и уже знаете всё об аннотациях типов, переходите к следующему разделу.
+/// note
+
+Если вы являетесь экспертом в Python и уже знаете всё об аннотациях типов, переходите к следующему разделу.
+
+///
## Мотивация
Давайте начнем с простого примера:
```Python
-{!../../../docs_src/python_types/tutorial001.py!}
+{!../../docs_src/python_types/tutorial001.py!}
```
Вызов этой программы выводит:
@@ -36,7 +39,7 @@ John Doe
* Соединяет их через пробел.
```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial001.py!}
+{!../../docs_src/python_types/tutorial001.py!}
```
### Отредактируем пример
@@ -80,7 +83,7 @@ John Doe
Это аннотации типов:
```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial002.py!}
+{!../../docs_src/python_types/tutorial002.py!}
```
Это не то же самое, что объявление значений по умолчанию, например:
@@ -110,7 +113,7 @@ John Doe
Проверьте эту функцию, она уже имеет аннотации типов:
```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial003.py!}
+{!../../docs_src/python_types/tutorial003.py!}
```
Поскольку редактор знает типы переменных, вы получаете не только дополнение, но и проверки ошибок:
@@ -120,7 +123,7 @@ John Doe
Теперь вы знаете, что вам нужно исправить, преобразовав `age` в строку с `str(age)`:
```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial004.py!}
+{!../../docs_src/python_types/tutorial004.py!}
```
## Объявление типов
@@ -141,7 +144,7 @@ John Doe
* `bytes`
```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial005.py!}
+{!../../docs_src/python_types/tutorial005.py!}
```
### Generic-типы с параметрами типов
@@ -159,7 +162,7 @@ John Doe
Импортируйте `List` из `typing` (с заглавной `L`):
```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial006.py!}
+{!../../docs_src/python_types/tutorial006.py!}
```
Объявите переменную с тем же синтаксисом двоеточия (`:`).
@@ -169,13 +172,16 @@ John Doe
Поскольку список является типом, содержащим некоторые внутренние типы, вы помещаете их в квадратные скобки:
```Python hl_lines="4"
-{!../../../docs_src/python_types/tutorial006.py!}
+{!../../docs_src/python_types/tutorial006.py!}
```
-!!! tip
- Эти внутренние типы в квадратных скобках называются «параметрами типов».
+/// tip
- В этом случае `str` является параметром типа, передаваемым в `List`.
+Эти внутренние типы в квадратных скобках называются «параметрами типов».
+
+В этом случае `str` является параметром типа, передаваемым в `List`.
+
+///
Это означает: "переменная `items` является `list`, и каждый из элементов этого списка является `str`".
@@ -194,7 +200,7 @@ John Doe
Вы бы сделали то же самое, чтобы объявить `tuple` и `set`:
```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial007.py!}
+{!../../docs_src/python_types/tutorial007.py!}
```
Это означает:
@@ -211,7 +217,7 @@ John Doe
Второй параметр типа предназначен для значений `dict`:
```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial008.py!}
+{!../../docs_src/python_types/tutorial008.py!}
```
Это означает:
@@ -225,7 +231,7 @@ John Doe
Вы также можете использовать `Optional`, чтобы объявить, что переменная имеет тип, например, `str`, но это является «необязательным», что означает, что она также может быть `None`:
```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009.py!}
+{!../../docs_src/python_types/tutorial009.py!}
```
Использование `Optional[str]` вместо просто `str` позволит редактору помочь вам в обнаружении ошибок, в которых вы могли бы предположить, что значение всегда является `str`, хотя на самом деле это может быть и `None`.
@@ -250,13 +256,13 @@ John Doe
Допустим, у вас есть класс `Person` с полем `name`:
```Python hl_lines="1-3"
-{!../../../docs_src/python_types/tutorial010.py!}
+{!../../docs_src/python_types/tutorial010.py!}
```
Тогда вы можете объявить переменную типа `Person`:
```Python hl_lines="6"
-{!../../../docs_src/python_types/tutorial010.py!}
+{!../../docs_src/python_types/tutorial010.py!}
```
И снова вы получаете полную поддержку редактора:
@@ -278,11 +284,14 @@ John Doe
Взято из официальной документации Pydantic:
```Python
-{!../../../docs_src/python_types/tutorial011.py!}
+{!../../docs_src/python_types/tutorial011.py!}
```
-!!! info
- Чтобы узнать больше о Pydantic, читайте его документацию.
+/// info
+
+Чтобы узнать больше о Pydantic, читайте его документацию.
+
+///
**FastAPI** целиком основан на Pydantic.
@@ -310,5 +319,8 @@ John Doe
Важно то, что при использовании стандартных типов Python в одном месте (вместо добавления дополнительных классов, декораторов и т.д.) **FastAPI** сделает за вас большую часть работы.
-!!! info
- Если вы уже прошли всё руководство и вернулись, чтобы узнать больше о типах, хорошим ресурсом является «шпаргалка» от `mypy`.
+/// info
+
+Если вы уже прошли всё руководство и вернулись, чтобы узнать больше о типах, хорошим ресурсом является «шпаргалка» от `mypy`.
+
+///
diff --git a/docs/ru/docs/tutorial/background-tasks.md b/docs/ru/docs/tutorial/background-tasks.md
index 73ba860bc..0f6ce0eb3 100644
--- a/docs/ru/docs/tutorial/background-tasks.md
+++ b/docs/ru/docs/tutorial/background-tasks.md
@@ -16,7 +16,7 @@
Сначала импортируйте `BackgroundTasks`, потом добавьте в функцию параметр с типом `BackgroundTasks`:
```Python hl_lines="1 13"
-{!../../../docs_src/background_tasks/tutorial001.py!}
+{!../../docs_src/background_tasks/tutorial001.py!}
```
**FastAPI** создаст объект класса `BackgroundTasks` для вас и запишет его в параметр.
@@ -34,7 +34,7 @@
Так как операция записи не использует `async` и `await`, мы определим ее как обычную `def`:
```Python hl_lines="6-9"
-{!../../../docs_src/background_tasks/tutorial001.py!}
+{!../../docs_src/background_tasks/tutorial001.py!}
```
## Добавление фоновой задачи
@@ -42,7 +42,7 @@
Внутри функции вызовите метод `.add_task()` у объекта *background tasks* и передайте ему функцию, которую хотите выполнить в фоне:
```Python hl_lines="14"
-{!../../../docs_src/background_tasks/tutorial001.py!}
+{!../../docs_src/background_tasks/tutorial001.py!}
```
`.add_task()` принимает следующие аргументы:
@@ -57,17 +57,21 @@
**FastAPI** знает, что нужно сделать в каждом случае и как переиспользовать тот же объект `BackgroundTasks`, так чтобы все фоновые задачи собрались и запустились вместе в фоне:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="11 13 20 23"
- {!> ../../../docs_src/background_tasks/tutorial002_py310.py!}
- ```
+```Python hl_lines="11 13 20 23"
+{!> ../../docs_src/background_tasks/tutorial002_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="13 15 22 25"
- {!> ../../../docs_src/background_tasks/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="13 15 22 25"
+{!> ../../docs_src/background_tasks/tutorial002.py!}
+```
+
+////
В этом примере сообщения будут записаны в `log.txt` *после* того, как ответ сервера был отправлен.
diff --git a/docs/ru/docs/tutorial/body-fields.md b/docs/ru/docs/tutorial/body-fields.md
index 02a598004..f3b2c6113 100644
--- a/docs/ru/docs/tutorial/body-fields.md
+++ b/docs/ru/docs/tutorial/body-fields.md
@@ -6,50 +6,67 @@
Сначала вы должны импортировать его:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="2"
- {!> ../../../docs_src/body_fields/tutorial001_py310.py!}
- ```
+```Python hl_lines="2"
+{!> ../../docs_src/body_fields/tutorial001_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001.py!}
- ```
+//// tab | Python 3.8+
-!!! warning "Внимание"
- Обратите внимание, что функция `Field` импортируется непосредственно из `pydantic`, а не из `fastapi`, как все остальные функции (`Query`, `Path`, `Body` и т.д.).
+```Python hl_lines="4"
+{!> ../../docs_src/body_fields/tutorial001.py!}
+```
+
+////
+
+/// warning | "Внимание"
+
+Обратите внимание, что функция `Field` импортируется непосредственно из `pydantic`, а не из `fastapi`, как все остальные функции (`Query`, `Path`, `Body` и т.д.).
+
+///
## Объявление атрибутов модели
Вы можете использовать функцию `Field` с атрибутами модели:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9-12"
- {!> ../../../docs_src/body_fields/tutorial001_py310.py!}
- ```
+```Python hl_lines="9-12"
+{!> ../../docs_src/body_fields/tutorial001_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="11-14"
+{!> ../../docs_src/body_fields/tutorial001.py!}
+```
+
+////
Функция `Field` работает так же, как `Query`, `Path` и `Body`, у неё такие же параметры и т.д.
-!!! note "Технические детали"
- На самом деле, `Query`, `Path` и другие функции, которые вы увидите в дальнейшем, создают объекты подклассов общего класса `Param`, который сам по себе является подклассом `FieldInfo` из Pydantic.
+/// note | "Технические детали"
- И `Field` (из Pydantic), и `Body`, оба возвращают объекты подкласса `FieldInfo`.
+На самом деле, `Query`, `Path` и другие функции, которые вы увидите в дальнейшем, создают объекты подклассов общего класса `Param`, который сам по себе является подклассом `FieldInfo` из Pydantic.
- У класса `Body` есть и другие подклассы, с которыми вы ознакомитесь позже.
+И `Field` (из Pydantic), и `Body`, оба возвращают объекты подкласса `FieldInfo`.
- Помните, что когда вы импортируете `Query`, `Path` и другое из `fastapi`, это фактически функции, которые возвращают специальные классы.
+У класса `Body` есть и другие подклассы, с которыми вы ознакомитесь позже.
-!!! tip "Подсказка"
- Обратите внимание, что каждый атрибут модели с типом, значением по умолчанию и `Field` имеет ту же структуру, что и параметр *функции обработки пути* с `Field` вместо `Path`, `Query` и `Body`.
+Помните, что когда вы импортируете `Query`, `Path` и другое из `fastapi`, это фактически функции, которые возвращают специальные классы.
+
+///
+
+/// tip | "Подсказка"
+
+Обратите внимание, что каждый атрибут модели с типом, значением по умолчанию и `Field` имеет ту же структуру, что и параметр *функции обработки пути* с `Field` вместо `Path`, `Query` и `Body`.
+
+///
## Добавление дополнительной информации
@@ -58,9 +75,12 @@
Вы узнаете больше о добавлении дополнительной информации позже в документации, когда будете изучать, как задавать примеры принимаемых данных.
-!!! warning "Внимание"
- Дополнительные ключи, переданные в функцию `Field`, также будут присутствовать в сгенерированной OpenAPI схеме вашего приложения.
- Поскольку эти ключи не являются обязательной частью спецификации OpenAPI, некоторые инструменты OpenAPI, например, [валидатор OpenAPI](https://validator.swagger.io/), могут не работать с вашей сгенерированной схемой.
+/// warning | "Внимание"
+
+Дополнительные ключи, переданные в функцию `Field`, также будут присутствовать в сгенерированной OpenAPI схеме вашего приложения.
+Поскольку эти ключи не являются обязательной частью спецификации OpenAPI, некоторые инструменты OpenAPI, например, [валидатор OpenAPI](https://validator.swagger.io/), могут не работать с вашей сгенерированной схемой.
+
+///
## Резюме
diff --git a/docs/ru/docs/tutorial/body-multiple-params.md b/docs/ru/docs/tutorial/body-multiple-params.md
index ffba1d0f4..53965f0ec 100644
--- a/docs/ru/docs/tutorial/body-multiple-params.md
+++ b/docs/ru/docs/tutorial/body-multiple-params.md
@@ -8,44 +8,63 @@
Вы также можете объявить параметры тела запроса как необязательные, установив значение по умолчанию, равное `None`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="18-20"
- {!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="18-20"
+{!> ../../docs_src/body_multiple_params/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="18-20"
- {!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="18-20"
+{!> ../../docs_src/body_multiple_params/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="19-21"
- {!> ../../../docs_src/body_multiple_params/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip "Заметка"
- Рекомендуется использовать `Annotated` версию, если это возможно.
+```Python hl_lines="19-21"
+{!> ../../docs_src/body_multiple_params/tutorial001_an.py!}
+```
- ```Python hl_lines="17-19"
- {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip "Заметка"
- Рекомендуется использовать версию с `Annotated`, если это возможно.
+/// tip | "Заметка"
- ```Python hl_lines="19-21"
- {!> ../../../docs_src/body_multiple_params/tutorial001.py!}
- ```
+Рекомендуется использовать `Annotated` версию, если это возможно.
-!!! note "Заметка"
- Заметьте, что в данном случае параметр `item`, который будет взят из тела запроса, необязателен. Так как было установлено значение `None` по умолчанию.
+///
+
+```Python hl_lines="17-19"
+{!> ../../docs_src/body_multiple_params/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "Заметка"
+
+Рекомендуется использовать версию с `Annotated`, если это возможно.
+
+///
+
+```Python hl_lines="19-21"
+{!> ../../docs_src/body_multiple_params/tutorial001.py!}
+```
+
+////
+
+/// note | "Заметка"
+
+Заметьте, что в данном случае параметр `item`, который будет взят из тела запроса, необязателен. Так как было установлено значение `None` по умолчанию.
+
+///
## Несколько параметров тела запроса
@@ -62,17 +81,21 @@
Но вы также можете объявить множество параметров тела запроса, например `item` и `user`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!}
- ```
+```Python hl_lines="20"
+{!> ../../docs_src/body_multiple_params/tutorial002_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="22"
- {!> ../../../docs_src/body_multiple_params/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="22"
+{!> ../../docs_src/body_multiple_params/tutorial002.py!}
+```
+
+////
В этом случае **FastAPI** заметит, что в функции есть более одного параметра тела (два параметра, которые являются моделями Pydantic).
@@ -93,9 +116,11 @@
}
```
-!!! note "Внимание"
- Обратите внимание, что хотя параметр `item` был объявлен таким же способом, как и раньше, теперь предпологается, что он находится внутри тела с ключом `item`.
+/// note | "Внимание"
+Обратите внимание, что хотя параметр `item` был объявлен таким же способом, как и раньше, теперь предпологается, что он находится внутри тела с ключом `item`.
+
+///
**FastAPI** сделает автоматические преобразование из запроса, так что параметр `item` получит своё конкретное содержимое, и то же самое происходит с пользователем `user`.
@@ -111,41 +136,57 @@
Но вы можете указать **FastAPI** обрабатывать его, как ещё один ключ тела запроса, используя `Body`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="23"
- {!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!}
- ```
+```Python hl_lines="23"
+{!> ../../docs_src/body_multiple_params/tutorial003_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="23"
- {!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="23"
+{!> ../../docs_src/body_multiple_params/tutorial003_an_py39.py!}
+```
- ```Python hl_lines="24"
- {!> ../../../docs_src/body_multiple_params/tutorial003_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip "Заметка"
- Рекомендуется использовать `Annotated` версию, если это возможно.
+```Python hl_lines="24"
+{!> ../../docs_src/body_multiple_params/tutorial003_an.py!}
+```
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip "Заметка"
- Рекомендуется использовать `Annotated` версию, если это возможно.
+/// tip | "Заметка"
- ```Python hl_lines="22"
- {!> ../../../docs_src/body_multiple_params/tutorial003.py!}
- ```
+Рекомендуется использовать `Annotated` версию, если это возможно.
+
+///
+
+```Python hl_lines="20"
+{!> ../../docs_src/body_multiple_params/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "Заметка"
+
+Рекомендуется использовать `Annotated` версию, если это возможно.
+
+///
+
+```Python hl_lines="22"
+{!> ../../docs_src/body_multiple_params/tutorial003.py!}
+```
+
+////
В этом случае, **FastAPI** будет ожидать тело запроса в формате:
@@ -185,44 +226,63 @@ q: str | None = None
Например:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!}
- ```
+```Python hl_lines="27"
+{!> ../../docs_src/body_multiple_params/tutorial004_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="27"
+{!> ../../docs_src/body_multiple_params/tutorial004_an_py39.py!}
+```
- ```Python hl_lines="28"
- {!> ../../../docs_src/body_multiple_params/tutorial004_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip "Заметка"
- Рекомендуется использовать `Annotated` версию, если это возможно.
+```Python hl_lines="28"
+{!> ../../docs_src/body_multiple_params/tutorial004_an.py!}
+```
- ```Python hl_lines="25"
- {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip "Заметка"
- Рекомендуется использовать `Annotated` версию, если это возможно.
+/// tip | "Заметка"
- ```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004.py!}
- ```
+Рекомендуется использовать `Annotated` версию, если это возможно.
-!!! info "Информация"
- `Body` также имеет все те же дополнительные параметры валидации и метаданных, как у `Query`,`Path` и других, которые вы увидите позже.
+///
+
+```Python hl_lines="25"
+{!> ../../docs_src/body_multiple_params/tutorial004_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "Заметка"
+
+Рекомендуется использовать `Annotated` версию, если это возможно.
+
+///
+
+```Python hl_lines="27"
+{!> ../../docs_src/body_multiple_params/tutorial004.py!}
+```
+
+////
+
+/// info | "Информация"
+
+`Body` также имеет все те же дополнительные параметры валидации и метаданных, как у `Query`,`Path` и других, которые вы увидите позже.
+
+///
## Добавление одного body-параметра
@@ -238,41 +298,57 @@ item: Item = Body(embed=True)
так же, как в этом примере:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="17"
- {!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!}
- ```
+```Python hl_lines="17"
+{!> ../../docs_src/body_multiple_params/tutorial005_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="17"
- {!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="17"
+{!> ../../docs_src/body_multiple_params/tutorial005_an_py39.py!}
+```
- ```Python hl_lines="18"
- {!> ../../../docs_src/body_multiple_params/tutorial005_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip "Заметка"
- Рекомендуется использовать `Annotated` версию, если это возможно.
+```Python hl_lines="18"
+{!> ../../docs_src/body_multiple_params/tutorial005_an.py!}
+```
- ```Python hl_lines="15"
- {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip "Заметка"
- Рекомендуется использовать `Annotated` версию, если это возможно.
+/// tip | "Заметка"
- ```Python hl_lines="17"
- {!> ../../../docs_src/body_multiple_params/tutorial005.py!}
- ```
+Рекомендуется использовать `Annotated` версию, если это возможно.
+
+///
+
+```Python hl_lines="15"
+{!> ../../docs_src/body_multiple_params/tutorial005_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "Заметка"
+
+Рекомендуется использовать `Annotated` версию, если это возможно.
+
+///
+
+```Python hl_lines="17"
+{!> ../../docs_src/body_multiple_params/tutorial005.py!}
+```
+
+////
В этом случае **FastAPI** будет ожидать тело запроса в формате:
diff --git a/docs/ru/docs/tutorial/body-nested-models.md b/docs/ru/docs/tutorial/body-nested-models.md
index 51a32ba56..780946725 100644
--- a/docs/ru/docs/tutorial/body-nested-models.md
+++ b/docs/ru/docs/tutorial/body-nested-models.md
@@ -6,17 +6,21 @@
Вы можете определять атрибут как подтип. Например, тип `list` в Python:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="12"
- {!> ../../../docs_src/body_nested_models/tutorial001_py310.py!}
- ```
+```Python hl_lines="12"
+{!> ../../docs_src/body_nested_models/tutorial001_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="14"
+{!> ../../docs_src/body_nested_models/tutorial001.py!}
+```
+
+////
Это приведёт к тому, что обьект `tags` преобразуется в список, несмотря на то что тип его элементов не объявлен.
@@ -31,7 +35,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!}
```
### Объявление `list` с указанием типов для вложенных элементов
@@ -61,23 +65,29 @@ my_list: List[str]
Таким образом, в нашем примере мы можем явно указать тип данных для поля `tags` как "список строк":
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="12"
- {!> ../../../docs_src/body_nested_models/tutorial002_py310.py!}
- ```
+```Python hl_lines="12"
+{!> ../../docs_src/body_nested_models/tutorial002_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial002_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="14"
+{!> ../../docs_src/body_nested_models/tutorial002_py39.py!}
+```
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial002.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="14"
+{!> ../../docs_src/body_nested_models/tutorial002.py!}
+```
+
+////
## Типы множеств
@@ -87,23 +97,29 @@ my_list: List[str]
Тогда мы можем обьявить поле `tags` как множество строк:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="12"
- {!> ../../../docs_src/body_nested_models/tutorial003_py310.py!}
- ```
+```Python hl_lines="12"
+{!> ../../docs_src/body_nested_models/tutorial003_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial003_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="14"
+{!> ../../docs_src/body_nested_models/tutorial003_py39.py!}
+```
- ```Python hl_lines="1 14"
- {!> ../../../docs_src/body_nested_models/tutorial003.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="1 14"
+{!> ../../docs_src/body_nested_models/tutorial003.py!}
+```
+
+////
С помощью этого, даже если вы получите запрос с повторяющимися данными, они будут преобразованы в множество уникальных элементов.
@@ -125,45 +141,57 @@ my_list: List[str]
Например, мы можем определить модель `Image`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7-9"
- {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!}
- ```
+```Python hl_lines="7-9"
+{!> ../../docs_src/body_nested_models/tutorial004_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="9-11"
- {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="9-11"
+{!> ../../docs_src/body_nested_models/tutorial004_py39.py!}
+```
- ```Python hl_lines="9-11"
- {!> ../../../docs_src/body_nested_models/tutorial004.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9-11"
+{!> ../../docs_src/body_nested_models/tutorial004.py!}
+```
+
+////
### Использование вложенной модели в качестве типа
Также мы можем использовать эту модель как тип атрибута:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="18"
- {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!}
- ```
+```Python hl_lines="18"
+{!> ../../docs_src/body_nested_models/tutorial004_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="20"
+{!> ../../docs_src/body_nested_models/tutorial004_py39.py!}
+```
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial004.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="20"
+{!> ../../docs_src/body_nested_models/tutorial004.py!}
+```
+
+////
Это означает, что **FastAPI** будет ожидать тело запроса, аналогичное этому:
@@ -196,23 +224,29 @@ my_list: List[str]
Например, так как в модели `Image` у нас есть поле `url`, то мы можем объявить его как тип `HttpUrl` из модуля Pydantic вместо типа `str`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="2 8"
- {!> ../../../docs_src/body_nested_models/tutorial005_py310.py!}
- ```
+```Python hl_lines="2 8"
+{!> ../../docs_src/body_nested_models/tutorial005_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="4 10"
- {!> ../../../docs_src/body_nested_models/tutorial005_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="4 10"
+{!> ../../docs_src/body_nested_models/tutorial005_py39.py!}
+```
- ```Python hl_lines="4 10"
- {!> ../../../docs_src/body_nested_models/tutorial005.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="4 10"
+{!> ../../docs_src/body_nested_models/tutorial005.py!}
+```
+
+////
Строка будет проверена на соответствие допустимому URL-адресу и задокументирована в JSON схему / OpenAPI.
@@ -220,23 +254,29 @@ my_list: List[str]
Вы также можете использовать модели Pydantic в качестве типов вложенных в `list`, `set` и т.д:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="18"
- {!> ../../../docs_src/body_nested_models/tutorial006_py310.py!}
- ```
+```Python hl_lines="18"
+{!> ../../docs_src/body_nested_models/tutorial006_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial006_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="20"
+{!> ../../docs_src/body_nested_models/tutorial006_py39.py!}
+```
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial006.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="20"
+{!> ../../docs_src/body_nested_models/tutorial006.py!}
+```
+
+////
Такая реализация будет ожидать (конвертировать, валидировать, документировать и т.д) JSON-содержимое в следующем формате:
@@ -264,33 +304,45 @@ my_list: List[str]
}
```
-!!! info "Информация"
- Заметьте, что теперь у ключа `images` есть список объектов изображений.
+/// info | "Информация"
+
+Заметьте, что теперь у ключа `images` есть список объектов изображений.
+
+///
## Глубоко вложенные модели
Вы можете определять модели с произвольным уровнем вложенности:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7 12 18 21 25"
- {!> ../../../docs_src/body_nested_models/tutorial007_py310.py!}
- ```
+```Python hl_lines="7 12 18 21 25"
+{!> ../../docs_src/body_nested_models/tutorial007_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="9 14 20 23 27"
- {!> ../../../docs_src/body_nested_models/tutorial007_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="9 14 20 23 27"
+{!> ../../docs_src/body_nested_models/tutorial007_py39.py!}
+```
- ```Python hl_lines="9 14 20 23 27"
- {!> ../../../docs_src/body_nested_models/tutorial007.py!}
- ```
+////
-!!! info "Информация"
- Заметьте, что у объекта `Offer` есть список объектов `Item`, которые, в свою очередь, могут содержать необязательный список объектов `Image`
+//// tab | Python 3.8+
+
+```Python hl_lines="9 14 20 23 27"
+{!> ../../docs_src/body_nested_models/tutorial007.py!}
+```
+
+////
+
+/// info | "Информация"
+
+Заметьте, что у объекта `Offer` есть список объектов `Item`, которые, в свою очередь, могут содержать необязательный список объектов `Image`
+
+///
## Тела с чистыми списками элементов
@@ -308,17 +360,21 @@ images: list[Image]
например так:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="13"
- {!> ../../../docs_src/body_nested_models/tutorial008_py39.py!}
- ```
+```Python hl_lines="13"
+{!> ../../docs_src/body_nested_models/tutorial008_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="15"
- {!> ../../../docs_src/body_nested_models/tutorial008.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="15"
+{!> ../../docs_src/body_nested_models/tutorial008.py!}
+```
+
+////
## Универсальная поддержка редактора
@@ -348,26 +404,33 @@ images: list[Image]
В этом случае вы принимаете `dict`, пока у него есть ключи типа `int` со значениями типа `float`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="7"
- {!> ../../../docs_src/body_nested_models/tutorial009_py39.py!}
- ```
+```Python hl_lines="7"
+{!> ../../docs_src/body_nested_models/tutorial009_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/body_nested_models/tutorial009.py!}
- ```
+//// tab | Python 3.8+
-!!! tip "Совет"
- Имейте в виду, что JSON поддерживает только ключи типа `str`.
+```Python hl_lines="9"
+{!> ../../docs_src/body_nested_models/tutorial009.py!}
+```
- Но Pydantic обеспечивает автоматическое преобразование данных.
+////
- Это значит, что даже если пользователи вашего API могут отправлять только строки в качестве ключей, при условии, что эти строки содержат целые числа, Pydantic автоматический преобразует и валидирует эти данные.
+/// tip | "Совет"
- А `dict`, с именем `weights`, который вы получите в качестве ответа Pydantic, действительно будет иметь ключи типа `int` и значения типа `float`.
+Имейте в виду, что JSON поддерживает только ключи типа `str`.
+
+Но Pydantic обеспечивает автоматическое преобразование данных.
+
+Это значит, что даже если пользователи вашего API могут отправлять только строки в качестве ключей, при условии, что эти строки содержат целые числа, Pydantic автоматический преобразует и валидирует эти данные.
+
+А `dict`, с именем `weights`, который вы получите в качестве ответа Pydantic, действительно будет иметь ключи типа `int` и значения типа `float`.
+
+///
## Резюме
diff --git a/docs/ru/docs/tutorial/body-updates.md b/docs/ru/docs/tutorial/body-updates.md
index 4998ab31a..3ecfe52f4 100644
--- a/docs/ru/docs/tutorial/body-updates.md
+++ b/docs/ru/docs/tutorial/body-updates.md
@@ -6,23 +6,29 @@
Вы можете использовать функцию `jsonable_encoder` для преобразования входных данных в JSON, так как нередки случаи, когда работать можно только с простыми типами данных (например, для хранения в NoSQL-базе данных).
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="28-33"
- {!> ../../../docs_src/body_updates/tutorial001_py310.py!}
- ```
+```Python hl_lines="28-33"
+{!> ../../docs_src/body_updates/tutorial001_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="30-35"
- {!> ../../../docs_src/body_updates/tutorial001_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.6+"
+```Python hl_lines="30-35"
+{!> ../../docs_src/body_updates/tutorial001_py39.py!}
+```
- ```Python hl_lines="30-35"
- {!> ../../../docs_src/body_updates/tutorial001.py!}
- ```
+////
+
+//// tab | Python 3.6+
+
+```Python hl_lines="30-35"
+{!> ../../docs_src/body_updates/tutorial001.py!}
+```
+
+////
`PUT` используется для получения данных, которые должны полностью заменить существующие данные.
@@ -48,14 +54,17 @@
Это означает, что можно передавать только те данные, которые необходимо обновить, оставляя остальные нетронутыми.
-!!! note "Технические детали"
- `PATCH` менее распространен и известен, чем `PUT`.
+/// note | "Технические детали"
- А многие команды используют только `PUT`, даже для частичного обновления.
+`PATCH` менее распространен и известен, чем `PUT`.
- Вы можете **свободно** использовать их как угодно, **FastAPI** не накладывает никаких ограничений.
+А многие команды используют только `PUT`, даже для частичного обновления.
- Но в данном руководстве более или менее понятно, как они должны использоваться.
+Вы можете **свободно** использовать их как угодно, **FastAPI** не накладывает никаких ограничений.
+
+Но в данном руководстве более или менее понятно, как они должны использоваться.
+
+///
### Использование параметра `exclude_unset` в Pydantic
@@ -65,23 +74,29 @@
В результате будет сгенерирован словарь, содержащий только те данные, которые были заданы при создании модели `item`, без учета значений по умолчанию. Затем вы можете использовать это для создания словаря только с теми данными, которые были установлены (отправлены в запросе), опуская значения по умолчанию:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="32"
- {!> ../../../docs_src/body_updates/tutorial002_py310.py!}
- ```
+```Python hl_lines="32"
+{!> ../../docs_src/body_updates/tutorial002_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="34"
- {!> ../../../docs_src/body_updates/tutorial002_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.6+"
+```Python hl_lines="34"
+{!> ../../docs_src/body_updates/tutorial002_py39.py!}
+```
- ```Python hl_lines="34"
- {!> ../../../docs_src/body_updates/tutorial002.py!}
- ```
+////
+
+//// tab | Python 3.6+
+
+```Python hl_lines="34"
+{!> ../../docs_src/body_updates/tutorial002.py!}
+```
+
+////
### Использование параметра `update` в Pydantic
@@ -89,23 +104,29 @@
Например, `stored_item_model.copy(update=update_data)`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="33"
- {!> ../../../docs_src/body_updates/tutorial002_py310.py!}
- ```
+```Python hl_lines="33"
+{!> ../../docs_src/body_updates/tutorial002_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="35"
- {!> ../../../docs_src/body_updates/tutorial002_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.6+"
+```Python hl_lines="35"
+{!> ../../docs_src/body_updates/tutorial002_py39.py!}
+```
- ```Python hl_lines="35"
- {!> ../../../docs_src/body_updates/tutorial002.py!}
- ```
+////
+
+//// tab | Python 3.6+
+
+```Python hl_lines="35"
+{!> ../../docs_src/body_updates/tutorial002.py!}
+```
+
+////
### Кратко о частичном обновлении
@@ -122,32 +143,44 @@
* Сохранить данные в своей БД.
* Вернуть обновленную модель.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="28-35"
- {!> ../../../docs_src/body_updates/tutorial002_py310.py!}
- ```
+```Python hl_lines="28-35"
+{!> ../../docs_src/body_updates/tutorial002_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="30-37"
- {!> ../../../docs_src/body_updates/tutorial002_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.6+"
+```Python hl_lines="30-37"
+{!> ../../docs_src/body_updates/tutorial002_py39.py!}
+```
- ```Python hl_lines="30-37"
- {!> ../../../docs_src/body_updates/tutorial002.py!}
- ```
+////
-!!! tip "Подсказка"
- Эту же технику можно использовать и для операции HTTP `PUT`.
+//// tab | Python 3.6+
- Но в приведенном примере используется `PATCH`, поскольку он был создан именно для таких случаев использования.
+```Python hl_lines="30-37"
+{!> ../../docs_src/body_updates/tutorial002.py!}
+```
-!!! note "Технические детали"
- Обратите внимание, что входная модель по-прежнему валидируется.
+////
- Таким образом, если вы хотите получать частичные обновления, в которых могут быть опущены все атрибуты, вам необходимо иметь модель, в которой все атрибуты помечены как необязательные (со значениями по умолчанию или `None`).
+/// tip | "Подсказка"
- Чтобы отличить модели со всеми необязательными значениями для **обновления** от моделей с обязательными значениями для **создания**, можно воспользоваться идеями, описанными в [Дополнительные модели](extra-models.md){.internal-link target=_blank}.
+Эту же технику можно использовать и для операции HTTP `PUT`.
+
+Но в приведенном примере используется `PATCH`, поскольку он был создан именно для таких случаев использования.
+
+///
+
+/// note | "Технические детали"
+
+Обратите внимание, что входная модель по-прежнему валидируется.
+
+Таким образом, если вы хотите получать частичные обновления, в которых могут быть опущены все атрибуты, вам необходимо иметь модель, в которой все атрибуты помечены как необязательные (со значениями по умолчанию или `None`).
+
+Чтобы отличить модели со всеми необязательными значениями для **обновления** от моделей с обязательными значениями для **создания**, можно воспользоваться идеями, описанными в [Дополнительные модели](extra-models.md){.internal-link target=_blank}.
+
+///
diff --git a/docs/ru/docs/tutorial/body.md b/docs/ru/docs/tutorial/body.md
index 5d0e033fd..91b169d07 100644
--- a/docs/ru/docs/tutorial/body.md
+++ b/docs/ru/docs/tutorial/body.md
@@ -8,19 +8,22 @@
Чтобы объявить тело **запроса**, необходимо использовать модели Pydantic, со всей их мощью и преимуществами.
-!!! info "Информация"
- Чтобы отправить данные, необходимо использовать один из методов: `POST` (обычно), `PUT`, `DELETE` или `PATCH`.
+/// info | "Информация"
- Отправка тела с запросом `GET` имеет неопределенное поведение в спецификациях, тем не менее, оно поддерживается FastAPI только для очень сложных/экстремальных случаев использования.
+Чтобы отправить данные, необходимо использовать один из методов: `POST` (обычно), `PUT`, `DELETE` или `PATCH`.
- Поскольку это не рекомендуется, интерактивная документация со Swagger UI не будет отображать информацию для тела при использовании метода GET, а промежуточные прокси-серверы могут не поддерживать такой вариант запроса.
+Отправка тела с запросом `GET` имеет неопределенное поведение в спецификациях, тем не менее, оно поддерживается FastAPI только для очень сложных/экстремальных случаев использования.
+
+Поскольку это не рекомендуется, интерактивная документация со Swagger UI не будет отображать информацию для тела при использовании метода GET, а промежуточные прокси-серверы могут не поддерживать такой вариант запроса.
+
+///
## Импортирование `BaseModel` из Pydantic
Первое, что вам необходимо сделать, это импортировать `BaseModel` из пакета `pydantic`:
```Python hl_lines="4"
-{!../../../docs_src/body/tutorial001.py!}
+{!../../docs_src/body/tutorial001.py!}
```
## Создание вашей собственной модели
@@ -30,7 +33,7 @@
Используйте аннотации типов Python для всех атрибутов:
```Python hl_lines="7-11"
-{!../../../docs_src/body/tutorial001.py!}
+{!../../docs_src/body/tutorial001.py!}
```
Также как и при описании параметров запроса, когда атрибут модели имеет значение по умолчанию, он является необязательным. Иначе он обязателен. Используйте `None`, чтобы сделать его необязательным без использования конкретных значений по умолчанию.
@@ -60,7 +63,7 @@
Чтобы добавить параметр к вашему *обработчику*, объявите его также, как вы объявляли параметры пути или параметры запроса:
```Python hl_lines="18"
-{!../../../docs_src/body/tutorial001.py!}
+{!../../docs_src/body/tutorial001.py!}
```
...и укажите созданную модель в качестве типа параметра, `Item`.
@@ -110,23 +113,26 @@
-!!! tip "Подсказка"
- Если вы используете PyCharm в качестве редактора, то вам стоит попробовать плагин Pydantic PyCharm Plugin.
+/// tip | "Подсказка"
- Он улучшает поддержку редактором моделей Pydantic в части:
+Если вы используете PyCharm в качестве редактора, то вам стоит попробовать плагин Pydantic PyCharm Plugin.
- * автодополнения,
- * проверки типов,
- * рефакторинга,
- * поиска,
- * инспектирования.
+Он улучшает поддержку редактором моделей Pydantic в части:
+
+* автодополнения,
+* проверки типов,
+* рефакторинга,
+* поиска,
+* инспектирования.
+
+///
## Использование модели
Внутри функции вам доступны все атрибуты объекта модели напрямую:
```Python hl_lines="21"
-{!../../../docs_src/body/tutorial002.py!}
+{!../../docs_src/body/tutorial002.py!}
```
## Тело запроса + параметры пути
@@ -136,7 +142,7 @@
**FastAPI** распознает, какие параметры функции соответствуют параметрам пути и должны быть **получены из пути**, а какие параметры функции, объявленные как модели Pydantic, должны быть **получены из тела запроса**.
```Python hl_lines="17-18"
-{!../../../docs_src/body/tutorial003.py!}
+{!../../docs_src/body/tutorial003.py!}
```
## Тело запроса + параметры пути + параметры запроса
@@ -146,7 +152,7 @@
**FastAPI** распознает каждый из них и возьмет данные из правильного источника.
```Python hl_lines="18"
-{!../../../docs_src/body/tutorial004.py!}
+{!../../docs_src/body/tutorial004.py!}
```
Параметры функции распознаются следующим образом:
@@ -155,10 +161,13 @@
* Если аннотация типа параметра содержит **примитивный тип** (`int`, `float`, `str`, `bool` и т.п.), он будет интерпретирован как параметр **запроса**.
* Если аннотация типа параметра представляет собой **модель Pydantic**, он будет интерпретирован как параметр **тела запроса**.
-!!! note "Заметка"
- FastAPI понимает, что значение параметра `q` не является обязательным, потому что имеет значение по умолчанию `= None`.
+/// note | "Заметка"
- Аннотация `Optional` в `Optional[str]` не используется FastAPI, но помогает вашему редактору лучше понимать ваш код и обнаруживать ошибки.
+FastAPI понимает, что значение параметра `q` не является обязательным, потому что имеет значение по умолчанию `= None`.
+
+Аннотация `Optional` в `Optional[str]` не используется FastAPI, но помогает вашему редактору лучше понимать ваш код и обнаруживать ошибки.
+
+///
## Без Pydantic
diff --git a/docs/ru/docs/tutorial/cookie-params.md b/docs/ru/docs/tutorial/cookie-params.md
index 5f99458b6..2a73a5918 100644
--- a/docs/ru/docs/tutorial/cookie-params.md
+++ b/docs/ru/docs/tutorial/cookie-params.md
@@ -6,17 +6,21 @@
Сначала импортируйте `Cookie`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="1"
- {!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
- ```
+```Python hl_lines="1"
+{!> ../../docs_src/cookie_params/tutorial001_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="3"
+{!> ../../docs_src/cookie_params/tutorial001.py!}
+```
+
+////
## Объявление параметров `Cookie`
@@ -24,25 +28,35 @@
Первое значение - это значение по умолчанию, вы можете передать все дополнительные параметры проверки или аннотации:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7"
- {!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
- ```
+```Python hl_lines="7"
+{!> ../../docs_src/cookie_params/tutorial001_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/cookie_params/tutorial001.py!}
- ```
+//// tab | Python 3.8+
-!!! note "Технические детали"
- `Cookie` - это класс, родственный `Path` и `Query`. Он также наследуется от общего класса `Param`.
+```Python hl_lines="9"
+{!> ../../docs_src/cookie_params/tutorial001.py!}
+```
- Но помните, что когда вы импортируете `Query`, `Path`, `Cookie` и другое из `fastapi`, это фактически функции, которые возвращают специальные классы.
+////
-!!! info "Дополнительная информация"
- Для объявления cookies, вам нужно использовать `Cookie`, иначе параметры будут интерпретированы как параметры запроса.
+/// note | "Технические детали"
+
+`Cookie` - это класс, родственный `Path` и `Query`. Он также наследуется от общего класса `Param`.
+
+Но помните, что когда вы импортируете `Query`, `Path`, `Cookie` и другое из `fastapi`, это фактически функции, которые возвращают специальные классы.
+
+///
+
+/// info | "Дополнительная информация"
+
+Для объявления cookies, вам нужно использовать `Cookie`, иначе параметры будут интерпретированы как параметры запроса.
+
+///
## Резюме
diff --git a/docs/ru/docs/tutorial/cors.md b/docs/ru/docs/tutorial/cors.md
index 8c7fbc046..8d415a2c1 100644
--- a/docs/ru/docs/tutorial/cors.md
+++ b/docs/ru/docs/tutorial/cors.md
@@ -47,7 +47,7 @@
* Отдельных HTTP-заголовков или всех вместе, используя `"*"`.
```Python hl_lines="2 6-11 13-19"
-{!../../../docs_src/cors/tutorial001.py!}
+{!../../docs_src/cors/tutorial001.py!}
```
`CORSMiddleware` использует для параметров "запрещающие" значения по умолчанию, поэтому вам нужно явным образом разрешить использование отдельных источников, методов или заголовков, чтобы браузеры могли использовать их в кросс-доменном контексте.
@@ -78,7 +78,10 @@
Для получения более подробной информации о CORS, обратитесь к Документации CORS от Mozilla.
-!!! note "Технические детали"
- Вы также можете использовать `from starlette.middleware.cors import CORSMiddleware`.
+/// note | "Технические детали"
- **FastAPI** предоставляет несколько middleware в `fastapi.middleware` только для вашего удобства как разработчика. Но большинство доступных middleware взяты напрямую из Starlette.
+Вы также можете использовать `from starlette.middleware.cors import CORSMiddleware`.
+
+**FastAPI** предоставляет несколько middleware в `fastapi.middleware` только для вашего удобства как разработчика. Но большинство доступных middleware взяты напрямую из Starlette.
+
+///
diff --git a/docs/ru/docs/tutorial/debugging.md b/docs/ru/docs/tutorial/debugging.md
index 5fc6a2c1f..606a32bfc 100644
--- a/docs/ru/docs/tutorial/debugging.md
+++ b/docs/ru/docs/tutorial/debugging.md
@@ -7,7 +7,7 @@
В вашем FastAPI приложении, импортируйте и вызовите `uvicorn` напрямую:
```Python hl_lines="1 15"
-{!../../../docs_src/debugging/tutorial001.py!}
+{!../../docs_src/debugging/tutorial001.py!}
```
### Описание `__name__ == "__main__"`
@@ -74,8 +74,11 @@ from myapp import app
не будет выполнена.
-!!! info "Информация"
- Для получения дополнительной информации, ознакомьтесь с официальной документацией Python.
+/// info | "Информация"
+
+Для получения дополнительной информации, ознакомьтесь с официальной документацией Python.
+
+///
## Запуск вашего кода с помощью отладчика
diff --git a/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md
index b6ad25daf..161101bb3 100644
--- a/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md
+++ b/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md
@@ -6,41 +6,57 @@
В предыдущем примере мы возвращали `словарь` из нашей зависимости:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9"
- {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/dependencies/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="11"
- {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.6+"
+```Python hl_lines="11"
+{!> ../../docs_src/dependencies/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="12"
- {!> ../../../docs_src/dependencies/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.6+
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+```Python hl_lines="12"
+{!> ../../docs_src/dependencies/tutorial001_an.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.6+ без Annotated"
+//// tab | Python 3.10+ без Annotated
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="11"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="7"
+{!> ../../docs_src/dependencies/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.6+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="11"
+{!> ../../docs_src/dependencies/tutorial001.py!}
+```
+
+////
Но затем мы получаем `словарь` в параметре `commons` *функции операции пути*. И мы знаем, что редакторы не могут обеспечить достаточную поддержку для `словаря`, поскольку они не могут знать их ключи и типы значений.
@@ -101,117 +117,165 @@ fluffy = Cat(name="Mr Fluffy")
Теперь мы можем изменить зависимость `common_parameters`, указанную выше, на класс `CommonQueryParams`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="11-15"
- {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!}
- ```
+```Python hl_lines="11-15"
+{!> ../../docs_src/dependencies/tutorial002_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="11-15"
- {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.6+"
+```Python hl_lines="11-15"
+{!> ../../docs_src/dependencies/tutorial002_an_py39.py!}
+```
- ```Python hl_lines="12-16"
- {!> ../../../docs_src/dependencies/tutorial002_an.py!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.6+
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+```Python hl_lines="12-16"
+{!> ../../docs_src/dependencies/tutorial002_an.py!}
+```
- ```Python hl_lines="9-13"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
+////
-=== "Python 3.6+ без Annotated"
+//// tab | Python 3.10+ без Annotated
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="11-15"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="9-13"
+{!> ../../docs_src/dependencies/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.6+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="11-15"
+{!> ../../docs_src/dependencies/tutorial002.py!}
+```
+
+////
Обратите внимание на метод `__init__`, используемый для создания экземпляра класса:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="12"
- {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!}
- ```
+```Python hl_lines="12"
+{!> ../../docs_src/dependencies/tutorial002_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="12"
- {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.6+"
+```Python hl_lines="12"
+{!> ../../docs_src/dependencies/tutorial002_an_py39.py!}
+```
- ```Python hl_lines="13"
- {!> ../../../docs_src/dependencies/tutorial002_an.py!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.6+
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+```Python hl_lines="13"
+{!> ../../docs_src/dependencies/tutorial002_an.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
+////
-=== "Python 3.6+ без Annotated"
+//// tab | Python 3.10+ без Annotated
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="12"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="10"
+{!> ../../docs_src/dependencies/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.6+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="12"
+{!> ../../docs_src/dependencies/tutorial002.py!}
+```
+
+////
...имеет те же параметры, что и ранее используемая функция `common_parameters`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="8"
- {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="8"
+{!> ../../docs_src/dependencies/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.6+"
+```Python hl_lines="9"
+{!> ../../docs_src/dependencies/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/dependencies/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.6+
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+```Python hl_lines="10"
+{!> ../../docs_src/dependencies/tutorial001_an.py!}
+```
- ```Python hl_lines="6"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.6+ без Annotated"
+//// tab | Python 3.10+ без Annotated
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="9"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="6"
+{!> ../../docs_src/dependencies/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.6+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="9"
+{!> ../../docs_src/dependencies/tutorial001.py!}
+```
+
+////
Эти параметры и будут использоваться **FastAPI** для "решения" зависимости.
@@ -227,41 +291,57 @@ fluffy = Cat(name="Mr Fluffy")
Теперь вы можете объявить свою зависимость, используя этот класс.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!}
- ```
+```Python hl_lines="19"
+{!> ../../docs_src/dependencies/tutorial002_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.6+"
+```Python hl_lines="19"
+{!> ../../docs_src/dependencies/tutorial002_an_py39.py!}
+```
- ```Python hl_lines="20"
- {!> ../../../docs_src/dependencies/tutorial002_an.py!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.6+
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+```Python hl_lines="20"
+{!> ../../docs_src/dependencies/tutorial002_an.py!}
+```
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
+////
-=== "Python 3.6+ без Annotated"
+//// tab | Python 3.10+ без Annotated
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="17"
+{!> ../../docs_src/dependencies/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.6+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="19"
+{!> ../../docs_src/dependencies/tutorial002.py!}
+```
+
+////
**FastAPI** вызывает класс `CommonQueryParams`. При этом создается "экземпляр" этого класса, который будет передан в качестве параметра `commons` в вашу функцию.
@@ -269,20 +349,27 @@ fluffy = Cat(name="Mr Fluffy")
Обратите внимание, что в приведенном выше коде мы два раза пишем `CommonQueryParams`:
-=== "Python 3.6+ без Annotated"
+//// tab | Python 3.6+ без Annotated
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python
- commons: CommonQueryParams = Depends(CommonQueryParams)
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
-=== "Python 3.6+"
+///
- ```Python
- commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
- ```
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
+
+//// tab | Python 3.6+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
Последний параметр `CommonQueryParams`, в:
@@ -298,77 +385,107 @@ fluffy = Cat(name="Mr Fluffy")
В этом случае первый `CommonQueryParams`, в:
-=== "Python 3.6+"
+//// tab | Python 3.6+
- ```Python
- commons: Annotated[CommonQueryParams, ...
- ```
+```Python
+commons: Annotated[CommonQueryParams, ...
+```
-=== "Python 3.6+ без Annotated"
+////
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+//// tab | Python 3.6+ без Annotated
- ```Python
- commons: CommonQueryParams ...
- ```
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python
+commons: CommonQueryParams ...
+```
+
+////
...не имеет никакого специального значения для **FastAPI**. FastAPI не будет использовать его для преобразования данных, валидации и т.д. (поскольку для этого используется `Depends(CommonQueryParams)`).
На самом деле можно написать просто:
-=== "Python 3.6+"
+//// tab | Python 3.6+
- ```Python
- commons: Annotated[Any, Depends(CommonQueryParams)]
- ```
+```Python
+commons: Annotated[Any, Depends(CommonQueryParams)]
+```
-=== "Python 3.6+ без Annotated"
+////
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+//// tab | Python 3.6+ без Annotated
- ```Python
- commons = Depends(CommonQueryParams)
- ```
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python
+commons = Depends(CommonQueryParams)
+```
+
+////
...как тут:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial003_an_py310.py!}
- ```
+```Python hl_lines="19"
+{!> ../../docs_src/dependencies/tutorial003_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial003_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.6+"
+```Python hl_lines="19"
+{!> ../../docs_src/dependencies/tutorial003_an_py39.py!}
+```
- ```Python hl_lines="20"
- {!> ../../../docs_src/dependencies/tutorial003_an.py!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.6+
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+```Python hl_lines="20"
+{!> ../../docs_src/dependencies/tutorial003_an.py!}
+```
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial003_py310.py!}
- ```
+////
-=== "Python 3.6+ без Annotated"
+//// tab | Python 3.10+ без Annotated
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial003.py!}
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="17"
+{!> ../../docs_src/dependencies/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.6+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="19"
+{!> ../../docs_src/dependencies/tutorial003.py!}
+```
+
+////
Но объявление типа приветствуется, так как в этом случае ваш редактор будет знать, что будет передано в качестве параметра `commons`, и тогда он сможет помочь вам с автодополнением, проверкой типов и т.д:
@@ -378,101 +495,141 @@ fluffy = Cat(name="Mr Fluffy")
Но вы видите, что здесь мы имеем некоторое повторение кода, дважды написав `CommonQueryParams`:
-=== "Python 3.6+ без Annotated"
+//// tab | Python 3.6+ без Annotated
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python
- commons: CommonQueryParams = Depends(CommonQueryParams)
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
-=== "Python 3.6+"
+///
- ```Python
- commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
- ```
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
+
+//// tab | Python 3.6+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
Для случаев, когда зависимостью является *конкретный* класс, который **FastAPI** "вызовет" для создания экземпляра этого класса, можно использовать укороченную запись.
Вместо того чтобы писать:
-=== "Python 3.6+"
+//// tab | Python 3.6+
- ```Python
- commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
- ```
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
-=== "Python 3.6+ без Annotated"
+////
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+//// tab | Python 3.6+ без Annotated
- ```Python
- commons: CommonQueryParams = Depends(CommonQueryParams)
- ```
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
...следует написать:
-=== "Python 3.6+"
+//// tab | Python 3.6+
- ```Python
- commons: Annotated[CommonQueryParams, Depends()]
- ```
+```Python
+commons: Annotated[CommonQueryParams, Depends()]
+```
-=== "Python 3.6 без Annotated"
+////
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+//// tab | Python 3.6 без Annotated
- ```Python
- commons: CommonQueryParams = Depends()
- ```
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends()
+```
+
+////
Вы объявляете зависимость как тип параметра и используете `Depends()` без какого-либо параметра, вместо того чтобы *снова* писать полный класс внутри `Depends(CommonQueryParams)`.
Аналогичный пример будет выглядеть следующим образом:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial004_an_py310.py!}
- ```
+```Python hl_lines="19"
+{!> ../../docs_src/dependencies/tutorial004_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial004_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.6+"
+```Python hl_lines="19"
+{!> ../../docs_src/dependencies/tutorial004_an_py39.py!}
+```
- ```Python hl_lines="20"
- {!> ../../../docs_src/dependencies/tutorial004_an.py!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.6+
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+```Python hl_lines="20"
+{!> ../../docs_src/dependencies/tutorial004_an.py!}
+```
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial004_py310.py!}
- ```
+////
-=== "Python 3.6+ без Annotated"
+//// tab | Python 3.10+ без Annotated
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial004.py!}
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="17"
+{!> ../../docs_src/dependencies/tutorial004_py310.py!}
+```
+
+////
+
+//// tab | Python 3.6+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="19"
+{!> ../../docs_src/dependencies/tutorial004.py!}
+```
+
+////
...и **FastAPI** будет знать, что делать.
-!!! tip "Подсказка"
- Если это покажется вам более запутанным, чем полезным, не обращайте внимания, это вам не *нужно*.
+/// tip | "Подсказка"
- Это просто сокращение. Потому что **FastAPI** заботится о том, чтобы помочь вам свести к минимуму повторение кода.
+Если это покажется вам более запутанным, чем полезным, не обращайте внимания, это вам не *нужно*.
+
+Это просто сокращение. Потому что **FastAPI** заботится о том, чтобы помочь вам свести к минимуму повторение кода.
+
+///
diff --git a/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
index 2bd096189..305ce46cb 100644
--- a/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
+++ b/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
@@ -14,40 +14,55 @@
Это должен быть `list` состоящий из `Depends()`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
- ```
+```Python hl_lines="19"
+{!> ../../docs_src/dependencies/tutorial006_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="18"
- {!> ../../../docs_src/dependencies/tutorial006_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8 без Annotated"
+```Python hl_lines="18"
+{!> ../../docs_src/dependencies/tutorial006_an.py!}
+```
- !!! Подсказка
- Рекомендуется использовать версию с Annotated, если возможно.
+////
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial006.py!}
- ```
+//// tab | Python 3.8 без Annotated
+
+/// подсказка
+
+Рекомендуется использовать версию с Annotated, если возможно.
+
+///
+
+```Python hl_lines="17"
+{!> ../../docs_src/dependencies/tutorial006.py!}
+```
+
+////
Зависимости из dependencies выполнятся так же, как и обычные зависимости. Но их значения (если они были) не будут переданы в *функцию операции пути*.
-!!! Подсказка
- Некоторые редакторы кода определяют неиспользуемые параметры функций и подсвечивают их как ошибку.
+/// подсказка
- Использование `dependencies` в *декораторе операции пути* гарантирует выполнение зависимостей, избегая при этом предупреждений редактора кода и других инструментов.
+Некоторые редакторы кода определяют неиспользуемые параметры функций и подсвечивают их как ошибку.
- Это также должно помочь предотвратить путаницу у начинающих разработчиков, которые видят неиспользуемые параметры в коде и могут подумать что в них нет необходимости.
+Использование `dependencies` в *декораторе операции пути* гарантирует выполнение зависимостей, избегая при этом предупреждений редактора кода и других инструментов.
-!!! Дополнительная информация
- В этом примере мы используем выдуманные пользовательские заголовки `X-Key` и `X-Token`.
+Это также должно помочь предотвратить путаницу у начинающих разработчиков, которые видят неиспользуемые параметры в коде и могут подумать что в них нет необходимости.
- Но в реальных проектах, при внедрении системы безопасности, вы получите больше пользы используя интегрированные [средства защиты (следующая глава)](../security/index.md){.internal-link target=_blank}.
+///
+
+/// дополнительная | информация
+
+В этом примере мы используем выдуманные пользовательские заголовки `X-Key` и `X-Token`.
+
+Но в реальных проектах, при внедрении системы безопасности, вы получите больше пользы используя интегрированные [средства защиты (следующая глава)](../security/index.md){.internal-link target=_blank}.
+
+///
## Исключения в dependencies и возвращаемые значения
@@ -57,51 +72,69 @@
Они могут объявлять требования к запросу (например заголовки) или другие подзависимости:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="8 13"
- {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
- ```
+```Python hl_lines="8 13"
+{!> ../../docs_src/dependencies/tutorial006_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="7 12"
- {!> ../../../docs_src/dependencies/tutorial006_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8 без Annotated"
+```Python hl_lines="7 12"
+{!> ../../docs_src/dependencies/tutorial006_an.py!}
+```
- !!! Подсказка
- Рекомендуется использовать версию с Annotated, если возможно.
+////
- ```Python hl_lines="6 11"
- {!> ../../../docs_src/dependencies/tutorial006.py!}
- ```
+//// tab | Python 3.8 без Annotated
+
+/// подсказка
+
+Рекомендуется использовать версию с Annotated, если возможно.
+
+///
+
+```Python hl_lines="6 11"
+{!> ../../docs_src/dependencies/tutorial006.py!}
+```
+
+////
### Вызов исключений
Зависимости из dependencies могут вызывать исключения с помощью `raise`, как и обычные зависимости:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="10 15"
- {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
- ```
+```Python hl_lines="10 15"
+{!> ../../docs_src/dependencies/tutorial006_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9 14"
- {!> ../../../docs_src/dependencies/tutorial006_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8 без Annotated"
+```Python hl_lines="9 14"
+{!> ../../docs_src/dependencies/tutorial006_an.py!}
+```
- !!! Подсказка
- Рекомендуется использовать версию с Annotated, если возможно.
+////
- ```Python hl_lines="8 13"
- {!> ../../../docs_src/dependencies/tutorial006.py!}
- ```
+//// tab | Python 3.8 без Annotated
+
+/// подсказка
+
+Рекомендуется использовать версию с Annotated, если возможно.
+
+///
+
+```Python hl_lines="8 13"
+{!> ../../docs_src/dependencies/tutorial006.py!}
+```
+
+////
### Возвращаемые значения
@@ -109,26 +142,35 @@
Таким образом, вы можете переиспользовать обычную зависимость (возвращающую значение), которую вы уже используете где-то в другом месте, и хотя значение не будет использоваться, зависимость будет выполнена:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="11 16"
- {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
- ```
+```Python hl_lines="11 16"
+{!> ../../docs_src/dependencies/tutorial006_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="10 15"
- {!> ../../../docs_src/dependencies/tutorial006_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8 без Annotated"
+```Python hl_lines="10 15"
+{!> ../../docs_src/dependencies/tutorial006_an.py!}
+```
- !!! Подсказка
- Рекомендуется использовать версию с Annotated, если возможно.
+////
- ```Python hl_lines="9 14"
- {!> ../../../docs_src/dependencies/tutorial006.py!}
- ```
+//// tab | Python 3.8 без Annotated
+
+/// подсказка
+
+Рекомендуется использовать версию с Annotated, если возможно.
+
+///
+
+```Python hl_lines="9 14"
+{!> ../../docs_src/dependencies/tutorial006.py!}
+```
+
+////
## Dependencies для группы *операций путей*
diff --git a/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md
index cd524cf66..99a86e999 100644
--- a/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md
+++ b/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md
@@ -4,18 +4,24 @@ FastAPI поддерживает зависимости, которые выпо
Для этого используйте `yield` вместо `return`, а дополнительный код напишите после него.
-!!! tip "Подсказка"
- Обязательно используйте `yield` один-единственный раз.
+/// tip | "Подсказка"
-!!! note "Технические детали"
- Любая функция, с которой может работать:
+Обязательно используйте `yield` один-единственный раз.
- * `@contextlib.contextmanager` или
- * `@contextlib.asynccontextmanager`
+///
- будет корректно использоваться в качестве **FastAPI**-зависимости.
+/// note | "Технические детали"
- На самом деле, FastAPI использует эту пару декораторов "под капотом".
+Любая функция, с которой может работать:
+
+* `@contextlib.contextmanager` или
+* `@contextlib.asynccontextmanager`
+
+будет корректно использоваться в качестве **FastAPI**-зависимости.
+
+На самом деле, FastAPI использует эту пару декораторов "под капотом".
+
+///
## Зависимость базы данных с помощью `yield`
@@ -24,25 +30,28 @@ FastAPI поддерживает зависимости, которые выпо
Перед созданием ответа будет выполнен только код до и включая `yield`.
```Python hl_lines="2-4"
-{!../../../docs_src/dependencies/tutorial007.py!}
+{!../../docs_src/dependencies/tutorial007.py!}
```
Полученное значение и есть то, что будет внедрено в функцию операции пути и другие зависимости:
```Python hl_lines="4"
-{!../../../docs_src/dependencies/tutorial007.py!}
+{!../../docs_src/dependencies/tutorial007.py!}
```
Код, следующий за оператором `yield`, выполняется после доставки ответа:
```Python hl_lines="5-6"
-{!../../../docs_src/dependencies/tutorial007.py!}
+{!../../docs_src/dependencies/tutorial007.py!}
```
-!!! tip "Подсказка"
- Можно использовать как `async` так и обычные функции.
+/// tip | "Подсказка"
- **FastAPI** это корректно обработает, и в обоих случаях будет делать то же самое, что и с обычными зависимостями.
+Можно использовать как `async` так и обычные функции.
+
+**FastAPI** это корректно обработает, и в обоих случаях будет делать то же самое, что и с обычными зависимостями.
+
+///
## Зависимость с `yield` и `try` одновременно
@@ -55,7 +64,7 @@ FastAPI поддерживает зависимости, которые выпо
Таким же образом можно использовать `finally`, чтобы убедиться, что обязательные шаги при выходе выполнены, независимо от того, было ли исключение или нет.
```Python hl_lines="3 5"
-{!../../../docs_src/dependencies/tutorial007.py!}
+{!../../docs_src/dependencies/tutorial007.py!}
```
## Подзависимости с `yield`
@@ -66,26 +75,35 @@ FastAPI поддерживает зависимости, которые выпо
Например, `dependency_c` может иметь зависимость от `dependency_b`, а `dependency_b` от `dependency_a`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="6 14 22"
- {!> ../../../docs_src/dependencies/tutorial008_an_py39.py!}
- ```
+```Python hl_lines="6 14 22"
+{!> ../../docs_src/dependencies/tutorial008_an_py39.py!}
+```
-=== "Python 3.6+"
+////
- ```Python hl_lines="5 13 21"
- {!> ../../../docs_src/dependencies/tutorial008_an.py!}
- ```
+//// tab | Python 3.6+
-=== "Python 3.6+ без Annotated"
+```Python hl_lines="5 13 21"
+{!> ../../docs_src/dependencies/tutorial008_an.py!}
+```
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+////
- ```Python hl_lines="4 12 20"
- {!> ../../../docs_src/dependencies/tutorial008.py!}
- ```
+//// tab | Python 3.6+ без Annotated
+
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="4 12 20"
+{!> ../../docs_src/dependencies/tutorial008.py!}
+```
+
+////
И все они могут использовать `yield`.
@@ -93,26 +111,35 @@ FastAPI поддерживает зависимости, которые выпо
И, в свою очередь, `dependency_b` нуждается в том, чтобы значение из `dependency_a` (здесь `dep_a`) было доступно для ее завершающего кода.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="18-19 26-27"
- {!> ../../../docs_src/dependencies/tutorial008_an_py39.py!}
- ```
+```Python hl_lines="18-19 26-27"
+{!> ../../docs_src/dependencies/tutorial008_an_py39.py!}
+```
-=== "Python 3.6+"
+////
- ```Python hl_lines="17-18 25-26"
- {!> ../../../docs_src/dependencies/tutorial008_an.py!}
- ```
+//// tab | Python 3.6+
-=== "Python 3.6+ без Annotated"
+```Python hl_lines="17-18 25-26"
+{!> ../../docs_src/dependencies/tutorial008_an.py!}
+```
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+////
- ```Python hl_lines="16-17 24-25"
- {!> ../../../docs_src/dependencies/tutorial008.py!}
- ```
+//// tab | Python 3.6+ без Annotated
+
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="16-17 24-25"
+{!> ../../docs_src/dependencies/tutorial008.py!}
+```
+
+////
Точно так же можно иметь часть зависимостей с `yield`, часть с `return`, и какие-то из них могут зависеть друг от друга.
@@ -122,8 +149,11 @@ FastAPI поддерживает зависимости, которые выпо
**FastAPI** проследит за тем, чтобы все выполнялось в правильном порядке.
-!!! note "Технические детали"
- Это работает благодаря Контекстным менеджерам в Python.
+/// note | "Технические детали"
+
+Это работает благодаря Контекстным менеджерам в Python.
+
+///
**FastAPI** использует их "под капотом" с этой целью.
@@ -147,8 +177,11 @@ FastAPI поддерживает зависимости, которые выпо
Если у вас есть пользовательские исключения, которые вы хотите обрабатывать *до* возврата ответа и, возможно, модифицировать ответ, даже вызывая `HTTPException`, создайте [Cобственный обработчик исключений](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}.
-!!! tip "Подсказка"
- Вы все еще можете вызывать исключения, включая `HTTPException`, *до* `yield`. Но не после.
+/// tip | "Подсказка"
+
+Вы все еще можете вызывать исключения, включая `HTTPException`, *до* `yield`. Но не после.
+
+///
Последовательность выполнения примерно такая, как на этой схеме. Время течет сверху вниз. А каждый столбец - это одна из частей, взаимодействующих с кодом или выполняющих код.
@@ -192,22 +225,31 @@ participant tasks as Background tasks
end
```
-!!! info "Дополнительная информация"
- Клиенту будет отправлен только **один ответ**. Это может быть один из ответов об ошибке или это будет ответ от *операции пути*.
+/// info | "Дополнительная информация"
- После отправки одного из этих ответов никакой другой ответ не может быть отправлен.
+Клиенту будет отправлен только **один ответ**. Это может быть один из ответов об ошибке или это будет ответ от *операции пути*.
-!!! tip "Подсказка"
- На этой диаграмме показано "HttpException", но вы также можете вызвать любое другое исключение, для которого вы создаете [Пользовательский обработчик исключений](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}.
+После отправки одного из этих ответов никакой другой ответ не может быть отправлен.
- Если вы создадите какое-либо исключение, оно будет передано зависимостям с yield, включая `HttpException`, а затем **снова** обработчикам исключений. Если для этого исключения нет обработчика исключений, то оно будет обработано внутренним "ServerErrorMiddleware" по умолчанию, возвращающим код состояния HTTP 500, чтобы уведомить клиента, что на сервере произошла ошибка.
+///
+
+/// tip | "Подсказка"
+
+На этой диаграмме показано "HttpException", но вы также можете вызвать любое другое исключение, для которого вы создаете [Пользовательский обработчик исключений](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}.
+
+Если вы создадите какое-либо исключение, оно будет передано зависимостям с yield, включая `HttpException`, а затем **снова** обработчикам исключений. Если для этого исключения нет обработчика исключений, то оно будет обработано внутренним "ServerErrorMiddleware" по умолчанию, возвращающим код состояния HTTP 500, чтобы уведомить клиента, что на сервере произошла ошибка.
+
+///
## Зависимости с `yield`, `HTTPException` и фоновыми задачами
-!!! warning "Внимание"
- Скорее всего, вам не нужны эти технические подробности, вы можете пропустить этот раздел и продолжить ниже.
+/// warning | "Внимание"
- Эти подробности полезны, главным образом, если вы использовали версию FastAPI до 0.106.0 и использовали ресурсы из зависимостей с `yield` в фоновых задачах.
+Скорее всего, вам не нужны эти технические подробности, вы можете пропустить этот раздел и продолжить ниже.
+
+Эти подробности полезны, главным образом, если вы использовали версию FastAPI до 0.106.0 и использовали ресурсы из зависимостей с `yield` в фоновых задачах.
+
+///
До версии FastAPI 0.106.0 вызывать исключения после `yield` было невозможно, код выхода в зависимостях с `yield` выполнялся *после* отправки ответа, поэтому [Обработчик Ошибок](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank} уже был бы запущен.
@@ -215,10 +257,12 @@ participant tasks as Background tasks
Тем не менее, поскольку это означало бы ожидание ответа в сети, а также ненужное удержание ресурса в зависимости от доходности (например, соединение с базой данных), это было изменено в FastAPI 0.106.0.
-!!! tip "Подсказка"
+/// tip | "Подсказка"
- Кроме того, фоновая задача обычно представляет собой независимый набор логики, который должен обрабатываться отдельно, со своими собственными ресурсами (например, собственным подключением к базе данных).
- Таким образом, вы, вероятно, получите более чистый код.
+Кроме того, фоновая задача обычно представляет собой независимый набор логики, который должен обрабатываться отдельно, со своими собственными ресурсами (например, собственным подключением к базе данных).
+Таким образом, вы, вероятно, получите более чистый код.
+
+///
Если вы полагались на это поведение, то теперь вам следует создавать ресурсы для фоновых задач внутри самой фоновой задачи, а внутри использовать только те данные, которые не зависят от ресурсов зависимостей с `yield`.
@@ -246,10 +290,13 @@ with open("./somefile.txt") as f:
### Использование менеджеров контекста в зависимостях с помощью `yield`
-!!! warning "Внимание"
- Это более или менее "продвинутая" идея.
+/// warning | "Внимание"
- Если вы только начинаете работать с **FastAPI**, то лучше пока пропустить этот пункт.
+Это более или менее "продвинутая" идея.
+
+Если вы только начинаете работать с **FastAPI**, то лучше пока пропустить этот пункт.
+
+///
В Python для создания менеджеров контекста можно создать класс с двумя методами: `__enter__()` и `__exit__()`.
@@ -257,19 +304,22 @@ with open("./somefile.txt") as f:
`with` или `async with` внутри функции зависимости:
```Python hl_lines="1-9 13"
-{!../../../docs_src/dependencies/tutorial010.py!}
+{!../../docs_src/dependencies/tutorial010.py!}
```
-!!! tip "Подсказка"
- Другой способ создания контекстного менеджера - с помощью:
+/// tip | "Подсказка"
- * `@contextlib.contextmanager` или
- * `@contextlib.asynccontextmanager`
+Другой способ создания контекстного менеджера - с помощью:
- используйте их для оформления функции с одним `yield`.
+* `@contextlib.contextmanager` или
+* `@contextlib.asynccontextmanager`
- Это то, что **FastAPI** использует внутри себя для зависимостей с `yield`.
+используйте их для оформления функции с одним `yield`.
- Но использовать декораторы для зависимостей FastAPI не обязательно (да и не стоит).
+Это то, что **FastAPI** использует внутри себя для зависимостей с `yield`.
- FastAPI сделает это за вас на внутреннем уровне.
+Но использовать декораторы для зависимостей FastAPI не обязательно (да и не стоит).
+
+FastAPI сделает это за вас на внутреннем уровне.
+
+///
diff --git a/docs/ru/docs/tutorial/dependencies/global-dependencies.md b/docs/ru/docs/tutorial/dependencies/global-dependencies.md
index eb1b4d7c1..7dbd50ae1 100644
--- a/docs/ru/docs/tutorial/dependencies/global-dependencies.md
+++ b/docs/ru/docs/tutorial/dependencies/global-dependencies.md
@@ -6,26 +6,35 @@
В этом случае они будут применяться ко всем *операциям пути* в приложении:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="16"
- {!> ../../../docs_src/dependencies/tutorial012_an_py39.py!}
- ```
+```Python hl_lines="16"
+{!> ../../docs_src/dependencies/tutorial012_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="16"
- {!> ../../../docs_src/dependencies/tutorial012_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8 non-Annotated"
+```Python hl_lines="16"
+{!> ../../docs_src/dependencies/tutorial012_an.py!}
+```
- !!! tip "Подсказка"
- Рекомендуется использовать 'Annotated' версию, если это возможно.
+////
- ```Python hl_lines="15"
- {!> ../../../docs_src/dependencies/tutorial012.py!}
- ```
+//// tab | Python 3.8 non-Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать 'Annotated' версию, если это возможно.
+
+///
+
+```Python hl_lines="15"
+{!> ../../docs_src/dependencies/tutorial012.py!}
+```
+
+////
Все способы [добавления зависимостей в *декораторах операций пути*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} по-прежнему применимы, но в данном случае зависимости применяются ко всем *операциям пути* приложения.
diff --git a/docs/ru/docs/tutorial/dependencies/index.md b/docs/ru/docs/tutorial/dependencies/index.md
index 9fce46b97..fcd9f46dc 100644
--- a/docs/ru/docs/tutorial/dependencies/index.md
+++ b/docs/ru/docs/tutorial/dependencies/index.md
@@ -29,42 +29,57 @@
Давайте для начала сфокусируемся на зависимостях.
Это просто функция, которая может принимать все те же параметры, что и *функции обработки пути*:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="8-9"
- {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="8-9"
+{!> ../../docs_src/dependencies/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="8-11"
- {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="8-11"
+{!> ../../docs_src/dependencies/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="9-12"
- {!> ../../../docs_src/dependencies/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip "Подсказка"
- Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно.
+```Python hl_lines="9-12"
+{!> ../../docs_src/dependencies/tutorial001_an.py!}
+```
- ```Python hl_lines="6-7"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip "Подсказка"
+/// tip | "Подсказка"
- Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно.
+Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно.
- ```Python hl_lines="8-11"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+///
+
+```Python hl_lines="6-7"
+{!> ../../docs_src/dependencies/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "Подсказка"
+
+Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно.
+
+///
+
+```Python hl_lines="8-11"
+{!> ../../docs_src/dependencies/tutorial001.py!}
+```
+
+////
**И всё.**
@@ -84,91 +99,125 @@
И в конце она возвращает `dict`, содержащий эти значения.
-!!! info "Информация"
+/// info | "Информация"
- **FastAPI** добавил поддержку для `Annotated` (и начал её рекомендовать) в версии 0.95.0.
+**FastAPI** добавил поддержку для `Annotated` (и начал её рекомендовать) в версии 0.95.0.
- Если у вас более старая версия, будут ошибки при попытке использовать `Annotated`.
+ Если у вас более старая версия, будут ошибки при попытке использовать `Annotated`.
- Убедитесь, что вы [Обновили FastAPI версию](../../deployment/versions.md#fastapi_2){.internal-link target=_blank} до, как минимум 0.95.1, перед тем как использовать `Annotated`.
+Убедитесь, что вы [Обновили FastAPI версию](../../deployment/versions.md#fastapi_2){.internal-link target=_blank} до, как минимум 0.95.1, перед тем как использовать `Annotated`.
+
+///
### Import `Depends`
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="3"
- {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="3"
+{!> ../../docs_src/dependencies/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="3"
- {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="3"
+{!> ../../docs_src/dependencies/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="3"
- {!> ../../../docs_src/dependencies/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip "Подсказка"
- Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно.
+```Python hl_lines="3"
+{!> ../../docs_src/dependencies/tutorial001_an.py!}
+```
- ```Python hl_lines="1"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip "Подсказка"
- Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="3"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно.
+
+///
+
+```Python hl_lines="1"
+{!> ../../docs_src/dependencies/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "Подсказка"
+
+Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно.
+
+///
+
+```Python hl_lines="3"
+{!> ../../docs_src/dependencies/tutorial001.py!}
+```
+
+////
### Объявите зависимость в "зависимом"
Точно так же, как вы использовали `Body`, `Query` и т.д. с вашей *функцией обработки пути* для параметров, используйте `Depends` с новым параметром:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="13 18"
- {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="13 18"
+{!> ../../docs_src/dependencies/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="15 20"
- {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="15 20"
+{!> ../../docs_src/dependencies/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="16 21"
- {!> ../../../docs_src/dependencies/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip "Подсказка"
- Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно.
+```Python hl_lines="16 21"
+{!> ../../docs_src/dependencies/tutorial001_an.py!}
+```
- ```Python hl_lines="11 16"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip "Подсказка"
- Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="15 20"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно.
+
+///
+
+```Python hl_lines="11 16"
+{!> ../../docs_src/dependencies/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "Подсказка"
+
+Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно.
+
+///
+
+```Python hl_lines="15 20"
+{!> ../../docs_src/dependencies/tutorial001.py!}
+```
+
+////
`Depends` работает немного иначе. Вы передаёте в `Depends` одиночный параметр, который будет похож на функцию.
@@ -176,8 +225,11 @@
И потом функция берёт параметры так же, как *функция обработки пути*.
-!!! tip "Подсказка"
- В следующей главе вы увидите, какие другие вещи, помимо функций, можно использовать в качестве зависимостей.
+/// tip | "Подсказка"
+
+В следующей главе вы увидите, какие другие вещи, помимо функций, можно использовать в качестве зависимостей.
+
+///
Каждый раз, когда новый запрос приходит, **FastAPI** позаботится о:
@@ -198,10 +250,13 @@ common_parameters --> read_users
Таким образом, вы пишете общий код один раз, и **FastAPI** позаботится о его вызове для ваших *операций с путями*.
-!!! check "Проверка"
- Обратите внимание, что вы не создаёте специальный класс и не передаёте его куда-то в **FastAPI** для регистрации, или что-то в этом роде.
+/// check | "Проверка"
- Вы просто передаёте это в `Depends`, и **FastAPI** знает, что делать дальше.
+Обратите внимание, что вы не создаёте специальный класс и не передаёте его куда-то в **FastAPI** для регистрации, или что-то в этом роде.
+
+Вы просто передаёте это в `Depends`, и **FastAPI** знает, что делать дальше.
+
+///
## Объединяем с `Annotated` зависимостями
@@ -215,29 +270,37 @@ commons: Annotated[dict, Depends(common_parameters)]
Но потому что мы используем `Annotated`, мы можем хранить `Annotated` значение в переменной и использовать его в нескольких местах:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="12 16 21"
- {!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!}
- ```
+```Python hl_lines="12 16 21"
+{!> ../../docs_src/dependencies/tutorial001_02_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="14 18 23"
- {!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="14 18 23"
+{!> ../../docs_src/dependencies/tutorial001_02_an_py39.py!}
+```
- ```Python hl_lines="15 19 24"
- {!> ../../../docs_src/dependencies/tutorial001_02_an.py!}
- ```
+////
-!!! tip "Подсказка"
- Это стандартный синтаксис python и называется "type alias", это не особенность **FastAPI**.
+//// tab | Python 3.8+
- Но потому что **FastAPI** базируется на стандартах Python, включая `Annotated`, вы можете использовать этот трюк в вашем коде. 😎
+```Python hl_lines="15 19 24"
+{!> ../../docs_src/dependencies/tutorial001_02_an.py!}
+```
+////
+
+/// tip | "Подсказка"
+
+Это стандартный синтаксис python и называется "type alias", это не особенность **FastAPI**.
+
+Но потому что **FastAPI** базируется на стандартах Python, включая `Annotated`, вы можете использовать этот трюк в вашем коде. 😎
+
+///
Зависимости продолжат работу как ожидалось, и **лучшая часть** в том, что **информация о типе будет сохранена**. Это означает, что ваш редактор кода будет корректно обрабатывать **автодополнения**, **встроенные ошибки** и так далее. То же самое относится и к инструментам, таким как `mypy`.
@@ -253,8 +316,11 @@ commons: Annotated[dict, Depends(common_parameters)]
Это всё не важно. **FastAPI** знает, что нужно сделать. 😎
-!!! note "Информация"
- Если вам эта тема не знакома, прочтите [Async: *"In a hurry?"*](../../async.md){.internal-link target=_blank} раздел о `async` и `await` в документации.
+/// note | "Информация"
+
+Если вам эта тема не знакома, прочтите [Async: *"In a hurry?"*](../../async.md){.internal-link target=_blank} раздел о `async` и `await` в документации.
+
+///
## Интеграция с OpenAPI
diff --git a/docs/ru/docs/tutorial/dependencies/sub-dependencies.md b/docs/ru/docs/tutorial/dependencies/sub-dependencies.md
index 31f9f43c6..ae0fd0824 100644
--- a/docs/ru/docs/tutorial/dependencies/sub-dependencies.md
+++ b/docs/ru/docs/tutorial/dependencies/sub-dependencies.md
@@ -10,41 +10,57 @@
Можно создать первую зависимость следующим образом:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="8-9"
- {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!}
- ```
+```Python hl_lines="8-9"
+{!> ../../docs_src/dependencies/tutorial005_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="8-9"
- {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.6+"
+```Python hl_lines="8-9"
+{!> ../../docs_src/dependencies/tutorial005_an_py39.py!}
+```
- ```Python hl_lines="9-10"
- {!> ../../../docs_src/dependencies/tutorial005_an.py!}
- ```
+////
-=== "Python 3.10 без Annotated"
+//// tab | Python 3.6+
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+```Python hl_lines="9-10"
+{!> ../../docs_src/dependencies/tutorial005_an.py!}
+```
- ```Python hl_lines="6-7"
- {!> ../../../docs_src/dependencies/tutorial005_py310.py!}
- ```
+////
-=== "Python 3.6 без Annotated"
+//// tab | Python 3.10 без Annotated
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="8-9"
- {!> ../../../docs_src/dependencies/tutorial005.py!}
- ```
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="6-7"
+{!> ../../docs_src/dependencies/tutorial005_py310.py!}
+```
+
+////
+
+//// tab | Python 3.6 без Annotated
+
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="8-9"
+{!> ../../docs_src/dependencies/tutorial005.py!}
+```
+
+////
Она объявляет необязательный параметр запроса `q` как строку, а затем возвращает его.
@@ -54,41 +70,57 @@
Затем можно создать еще одну функцию зависимости, которая в то же время содержит внутри себя первую зависимость (таким образом, она тоже является "зависимой"):
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="13"
- {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!}
- ```
+```Python hl_lines="13"
+{!> ../../docs_src/dependencies/tutorial005_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="13"
- {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.6+"
+```Python hl_lines="13"
+{!> ../../docs_src/dependencies/tutorial005_an_py39.py!}
+```
- ```Python hl_lines="14"
- {!> ../../../docs_src/dependencies/tutorial005_an.py!}
- ```
+////
-=== "Python 3.10 без Annotated"
+//// tab | Python 3.6+
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+```Python hl_lines="14"
+{!> ../../docs_src/dependencies/tutorial005_an.py!}
+```
- ```Python hl_lines="11"
- {!> ../../../docs_src/dependencies/tutorial005_py310.py!}
- ```
+////
-=== "Python 3.6 без Annotated"
+//// tab | Python 3.10 без Annotated
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="13"
- {!> ../../../docs_src/dependencies/tutorial005.py!}
- ```
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```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!}
+```
+
+////
Остановимся на объявленных параметрах:
@@ -101,46 +133,65 @@
Затем мы можем использовать зависимость вместе с:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="23"
- {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!}
- ```
+```Python hl_lines="23"
+{!> ../../docs_src/dependencies/tutorial005_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="23"
- {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.6+"
+```Python hl_lines="23"
+{!> ../../docs_src/dependencies/tutorial005_an_py39.py!}
+```
- ```Python hl_lines="24"
- {!> ../../../docs_src/dependencies/tutorial005_an.py!}
- ```
+////
-=== "Python 3.10 без Annotated"
+//// tab | Python 3.6+
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+```Python hl_lines="24"
+{!> ../../docs_src/dependencies/tutorial005_an.py!}
+```
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial005_py310.py!}
- ```
+////
-=== "Python 3.6 без Annotated"
+//// tab | Python 3.10 без Annotated
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="22"
- {!> ../../../docs_src/dependencies/tutorial005.py!}
- ```
+Предпочтительнее использовать версию с аннотацией, если это возможно.
-!!! info "Дополнительная информация"
- Обратите внимание, что мы объявляем только одну зависимость в *функции операции пути* - `query_or_cookie_extractor`.
+///
- Но **FastAPI** будет знать, что сначала он должен выполнить `query_extractor`, чтобы передать результаты этого в `query_or_cookie_extractor` при его вызове.
+```Python hl_lines="19"
+{!> ../../docs_src/dependencies/tutorial005_py310.py!}
+```
+
+////
+
+//// tab | Python 3.6 без Annotated
+
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="22"
+{!> ../../docs_src/dependencies/tutorial005.py!}
+```
+
+////
+
+/// info | "Дополнительная информация"
+
+Обратите внимание, что мы объявляем только одну зависимость в *функции операции пути* - `query_or_cookie_extractor`.
+
+Но **FastAPI** будет знать, что сначала он должен выполнить `query_extractor`, чтобы передать результаты этого в `query_or_cookie_extractor` при его вызове.
+
+///
```mermaid
graph TB
@@ -161,22 +212,29 @@ query_extractor --> query_or_cookie_extractor --> read_query
В расширенном сценарии, когда вы знаете, что вам нужно, чтобы зависимость вызывалась на каждом шаге (возможно, несколько раз) в одном и том же запросе, вместо использования "кэшированного" значения, вы можете установить параметр `use_cache=False` при использовании `Depends`:
-=== "Python 3.6+"
+//// tab | Python 3.6+
- ```Python hl_lines="1"
- async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]):
- return {"fresh_value": fresh_value}
- ```
+```Python hl_lines="1"
+async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]):
+ return {"fresh_value": fresh_value}
+```
-=== "Python 3.6+ без Annotated"
+////
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+//// tab | Python 3.6+ без Annotated
- ```Python hl_lines="1"
- async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)):
- return {"fresh_value": fresh_value}
- ```
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="1"
+async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)):
+ return {"fresh_value": fresh_value}
+```
+
+////
## Резюме
@@ -186,9 +244,12 @@ query_extractor --> query_or_cookie_extractor --> read_query
Но, тем не менее, эта система очень мощная и позволяет вам объявлять вложенные графы (деревья) зависимостей сколь угодно глубоко.
-!!! tip "Подсказка"
- Все это может показаться не столь полезным на этих простых примерах.
+/// tip | "Подсказка"
- Но вы увидите как это пригодится в главах посвященных безопасности.
+Все это может показаться не столь полезным на этих простых примерах.
- И вы также увидите, сколько кода это вам сэкономит.
+Но вы увидите как это пригодится в главах посвященных безопасности.
+
+И вы также увидите, сколько кода это вам сэкономит.
+
+///
diff --git a/docs/ru/docs/tutorial/encoder.md b/docs/ru/docs/tutorial/encoder.md
index c26b2c941..c9900cb2c 100644
--- a/docs/ru/docs/tutorial/encoder.md
+++ b/docs/ru/docs/tutorial/encoder.md
@@ -20,17 +20,21 @@
Она принимает объект, например, модель Pydantic, и возвращает его версию, совместимую с JSON:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="4 21"
- {!> ../../../docs_src/encoder/tutorial001_py310.py!}
- ```
+```Python hl_lines="4 21"
+{!> ../../docs_src/encoder/tutorial001_py310.py!}
+```
-=== "Python 3.6+"
+////
- ```Python hl_lines="5 22"
- {!> ../../../docs_src/encoder/tutorial001.py!}
- ```
+//// tab | Python 3.6+
+
+```Python hl_lines="5 22"
+{!> ../../docs_src/encoder/tutorial001.py!}
+```
+
+////
В данном примере она преобразует Pydantic модель в `dict`, а `datetime` - в `str`.
@@ -38,5 +42,8 @@
Функция не возвращает большой `str`, содержащий данные в формате JSON (в виде строки). Она возвращает стандартную структуру данных Python (например, `dict`) со значениями и подзначениями, которые совместимы с JSON.
-!!! note "Технические детали"
- `jsonable_encoder` фактически используется **FastAPI** внутри системы для преобразования данных. Однако он полезен и во многих других сценариях.
+/// note | "Технические детали"
+
+`jsonable_encoder` фактически используется **FastAPI** внутри системы для преобразования данных. Однако он полезен и во многих других сценариях.
+
+///
diff --git a/docs/ru/docs/tutorial/extra-data-types.md b/docs/ru/docs/tutorial/extra-data-types.md
index d4727e2d4..82cb0ff7a 100644
--- a/docs/ru/docs/tutorial/extra-data-types.md
+++ b/docs/ru/docs/tutorial/extra-data-types.md
@@ -55,28 +55,36 @@
Вот пример *операции пути* с параметрами, который демонстрирует некоторые из вышеперечисленных типов.
-=== "Python 3.8 и выше"
+//// tab | Python 3.8 и выше
- ```Python hl_lines="1 3 12-16"
- {!> ../../../docs_src/extra_data_types/tutorial001.py!}
- ```
+```Python hl_lines="1 3 12-16"
+{!> ../../docs_src/extra_data_types/tutorial001.py!}
+```
-=== "Python 3.10 и выше"
+////
- ```Python hl_lines="1 2 11-15"
- {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
- ```
+//// tab | Python 3.10 и выше
+
+```Python hl_lines="1 2 11-15"
+{!> ../../docs_src/extra_data_types/tutorial001_py310.py!}
+```
+
+////
Обратите внимание, что параметры внутри функции имеют свой естественный тип данных, и вы, например, можете выполнять обычные манипуляции с датами, такие как:
-=== "Python 3.8 и выше"
+//// tab | Python 3.8 и выше
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/extra_data_types/tutorial001.py!}
- ```
+```Python hl_lines="18-19"
+{!> ../../docs_src/extra_data_types/tutorial001.py!}
+```
-=== "Python 3.10 и выше"
+////
- ```Python hl_lines="17-18"
- {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
- ```
+//// tab | Python 3.10 и выше
+
+```Python hl_lines="17-18"
+{!> ../../docs_src/extra_data_types/tutorial001_py310.py!}
+```
+
+////
diff --git a/docs/ru/docs/tutorial/extra-models.md b/docs/ru/docs/tutorial/extra-models.md
index 78855313d..e7ff3f40f 100644
--- a/docs/ru/docs/tutorial/extra-models.md
+++ b/docs/ru/docs/tutorial/extra-models.md
@@ -8,26 +8,33 @@
* **Модель для вывода** не должна содержать пароль.
* **Модель для базы данных**, возможно, должна содержать хэшированный пароль.
-!!! danger "Внимание"
- Никогда не храните пароли пользователей в чистом виде. Всегда храните "безопасный хэш", который вы затем сможете проверить.
+/// danger | "Внимание"
- Если вам это не знакомо, вы можете узнать про "хэш пароля" в [главах о безопасности](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}.
+Никогда не храните пароли пользователей в чистом виде. Всегда храните "безопасный хэш", который вы затем сможете проверить.
+
+Если вам это не знакомо, вы можете узнать про "хэш пароля" в [главах о безопасности](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}.
+
+///
## Множественные модели
Ниже изложена основная идея того, как могут выглядеть эти модели с полями для паролей, а также описаны места, где они используются:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39"
- {!> ../../../docs_src/extra_models/tutorial001_py310.py!}
- ```
+```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39"
+{!> ../../docs_src/extra_models/tutorial001_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41"
- {!> ../../../docs_src/extra_models/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41"
+{!> ../../docs_src/extra_models/tutorial001.py!}
+```
+
+////
### Про `**user_in.dict()`
@@ -139,8 +146,11 @@ UserInDB(
)
```
-!!! warning "Предупреждение"
- Цель использованных в примере вспомогательных функций - не более чем демонстрация возможных операций с данными, но, конечно, они не обеспечивают настоящую безопасность.
+/// warning | "Предупреждение"
+
+Цель использованных в примере вспомогательных функций - не более чем демонстрация возможных операций с данными, но, конечно, они не обеспечивают настоящую безопасность.
+
+///
## Сократите дублирование
@@ -158,17 +168,21 @@ UserInDB(
В этом случае мы можем определить только различия между моделями (с `password` в чистом виде, с `hashed_password` и без пароля):
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7 13-14 17-18 21-22"
- {!> ../../../docs_src/extra_models/tutorial002_py310.py!}
- ```
+```Python hl_lines="7 13-14 17-18 21-22"
+{!> ../../docs_src/extra_models/tutorial002_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9 15-16 19-20 23-24"
- {!> ../../../docs_src/extra_models/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="9 15-16 19-20 23-24"
+{!> ../../docs_src/extra_models/tutorial002.py!}
+```
+
+////
## `Union` или `anyOf`
@@ -178,20 +192,27 @@ UserInDB(
Для этого используйте стандартные аннотации типов в Python `typing.Union`:
-!!! note "Примечание"
- При объявлении `Union`, сначала указывайте наиболее детальные типы, затем менее детальные. В примере ниже более детальный `PlaneItem` стоит перед `CarItem` в `Union[PlaneItem, CarItem]`.
+/// note | "Примечание"
-=== "Python 3.10+"
+При объявлении `Union`, сначала указывайте наиболее детальные типы, затем менее детальные. В примере ниже более детальный `PlaneItem` стоит перед `CarItem` в `Union[PlaneItem, CarItem]`.
- ```Python hl_lines="1 14-15 18-20 33"
- {!> ../../../docs_src/extra_models/tutorial003_py310.py!}
- ```
+///
-=== "Python 3.8+"
+//// tab | Python 3.10+
- ```Python hl_lines="1 14-15 18-20 33"
- {!> ../../../docs_src/extra_models/tutorial003.py!}
- ```
+```Python hl_lines="1 14-15 18-20 33"
+{!> ../../docs_src/extra_models/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="1 14-15 18-20 33"
+{!> ../../docs_src/extra_models/tutorial003.py!}
+```
+
+////
### `Union` в Python 3.10
@@ -213,17 +234,21 @@ some_variable: PlaneItem | CarItem
Для этого используйте `typing.List` из стандартной библиотеки Python (или просто `list` в Python 3.9 и выше):
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="18"
- {!> ../../../docs_src/extra_models/tutorial004_py39.py!}
- ```
+```Python hl_lines="18"
+{!> ../../docs_src/extra_models/tutorial004_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1 20"
- {!> ../../../docs_src/extra_models/tutorial004.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="1 20"
+{!> ../../docs_src/extra_models/tutorial004.py!}
+```
+
+////
## Ответ с произвольным `dict`
@@ -233,17 +258,21 @@ some_variable: PlaneItem | CarItem
В этом случае вы можете использовать `typing.Dict` (или просто `dict` в Python 3.9 и выше):
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="6"
- {!> ../../../docs_src/extra_models/tutorial005_py39.py!}
- ```
+```Python hl_lines="6"
+{!> ../../docs_src/extra_models/tutorial005_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1 8"
- {!> ../../../docs_src/extra_models/tutorial005.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="1 8"
+{!> ../../docs_src/extra_models/tutorial005.py!}
+```
+
+////
## Резюме
diff --git a/docs/ru/docs/tutorial/first-steps.md b/docs/ru/docs/tutorial/first-steps.md
index 8a0876bb4..b1de217cd 100644
--- a/docs/ru/docs/tutorial/first-steps.md
+++ b/docs/ru/docs/tutorial/first-steps.md
@@ -3,7 +3,7 @@
Самый простой FastAPI файл может выглядеть так:
```Python
-{!../../../docs_src/first_steps/tutorial001.py!}
+{!../../docs_src/first_steps/tutorial001.py!}
```
Скопируйте в файл `main.py`.
@@ -24,12 +24,15 @@ $ uvicorn main:app --reload
-!!! note "Технические детали"
- Команда `uvicorn main:app` обращается к:
+/// note | "Технические детали"
- * `main`: файл `main.py` (модуль Python).
- * `app`: объект, созданный внутри файла `main.py` в строке `app = FastAPI()`.
- * `--reload`: перезапускает сервер после изменения кода. Используйте только для разработки.
+Команда `uvicorn main:app` обращается к:
+
+* `main`: файл `main.py` (модуль Python).
+* `app`: объект, созданный внутри файла `main.py` в строке `app = FastAPI()`.
+* `--reload`: перезапускает сервер после изменения кода. Используйте только для разработки.
+
+///
В окне вывода появится следующая строка:
@@ -131,20 +134,23 @@ OpenAPI описывает схему API. Эта схема содержит о
### Шаг 1: импортируйте `FastAPI`
```Python hl_lines="1"
-{!../../../docs_src/first_steps/tutorial001.py!}
+{!../../docs_src/first_steps/tutorial001.py!}
```
`FastAPI` это класс в Python, который предоставляет всю функциональность для API.
-!!! note "Технические детали"
- `FastAPI` это класс, который наследуется непосредственно от `Starlette`.
+/// note | "Технические детали"
- Вы можете использовать всю функциональность Starlette в `FastAPI`.
+`FastAPI` это класс, который наследуется непосредственно от `Starlette`.
+
+Вы можете использовать всю функциональность Starlette в `FastAPI`.
+
+///
### Шаг 2: создайте экземпляр `FastAPI`
```Python hl_lines="3"
-{!../../../docs_src/first_steps/tutorial001.py!}
+{!../../docs_src/first_steps/tutorial001.py!}
```
Переменная `app` является экземпляром класса `FastAPI`.
@@ -166,7 +172,7 @@ $ uvicorn main:app --reload
Если создать такое приложение:
```Python hl_lines="3"
-{!../../../docs_src/first_steps/tutorial002.py!}
+{!../../docs_src/first_steps/tutorial002.py!}
```
И поместить его в `main.py`, тогда вызов `uvicorn` будет таким:
@@ -199,8 +205,11 @@ https://example.com/items/foo
/items/foo
```
-!!! info "Дополнительная иформация"
- Термин "path" также часто называется "endpoint" или "route".
+/// info | "Дополнительная иформация"
+
+Термин "path" также часто называется "endpoint" или "route".
+
+///
При создании API, "путь" является основным способом разделения "задач" и "ресурсов".
@@ -242,7 +251,7 @@ https://example.com/items/foo
#### Определите *декоратор операции пути (path operation decorator)*
```Python hl_lines="6"
-{!../../../docs_src/first_steps/tutorial001.py!}
+{!../../docs_src/first_steps/tutorial001.py!}
```
Декоратор `@app.get("/")` указывает **FastAPI**, что функция, прямо под ним, отвечает за обработку запросов, поступающих по адресу:
@@ -250,16 +259,19 @@ https://example.com/items/foo
* путь `/`
* использующих get операцию
-!!! info "`@decorator` Дополнительная информация"
- Синтаксис `@something` в Python называется "декоратор".
+/// info | "`@decorator` Дополнительная информация"
- Вы помещаете его над функцией. Как красивую декоративную шляпу (думаю, что оттуда и происходит этот термин).
+Синтаксис `@something` в Python называется "декоратор".
- "Декоратор" принимает функцию ниже и выполняет с ней какое-то действие.
+Вы помещаете его над функцией. Как красивую декоративную шляпу (думаю, что оттуда и происходит этот термин).
- В нашем случае, этот декоратор сообщает **FastAPI**, что функция ниже соответствует **пути** `/` и **операции** `get`.
+"Декоратор" принимает функцию ниже и выполняет с ней какое-то действие.
- Это и есть "**декоратор операции пути**".
+В нашем случае, этот декоратор сообщает **FastAPI**, что функция ниже соответствует **пути** `/` и **операции** `get`.
+
+Это и есть "**декоратор операции пути**".
+
+///
Можно также использовать операции:
@@ -274,14 +286,17 @@ https://example.com/items/foo
* `@app.patch()`
* `@app.trace()`
-!!! tip "Подсказка"
- Вы можете использовать каждую операцию (HTTP-метод) по своему усмотрению.
+/// tip | "Подсказка"
- **FastAPI** не навязывает определенного значения для каждого метода.
+Вы можете использовать каждую операцию (HTTP-метод) по своему усмотрению.
- Информация здесь представлена как рекомендация, а не требование.
+**FastAPI** не навязывает определенного значения для каждого метода.
- Например, при использовании GraphQL обычно все действия выполняются только с помощью POST операций.
+Информация здесь представлена как рекомендация, а не требование.
+
+Например, при использовании GraphQL обычно все действия выполняются только с помощью POST операций.
+
+///
### Шаг 4: определите **функцию операции пути**
@@ -292,7 +307,7 @@ https://example.com/items/foo
* **функция**: функция ниже "декоратора" (ниже `@app.get("/")`).
```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial001.py!}
+{!../../docs_src/first_steps/tutorial001.py!}
```
Это обычная Python функция.
@@ -306,16 +321,19 @@ https://example.com/items/foo
Вы также можете определить ее как обычную функцию вместо `async def`:
```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial003.py!}
+{!../../docs_src/first_steps/tutorial003.py!}
```
-!!! note "Технические детали"
- Если не знаете в чём разница, посмотрите [Конкурентность: *"Нет времени?"*](../async.md#_1){.internal-link target=_blank}.
+/// note | "Технические детали"
+
+Если не знаете в чём разница, посмотрите [Конкурентность: *"Нет времени?"*](../async.md#_1){.internal-link target=_blank}.
+
+///
### Шаг 5: верните результат
```Python hl_lines="8"
-{!../../../docs_src/first_steps/tutorial001.py!}
+{!../../docs_src/first_steps/tutorial001.py!}
```
Вы можете вернуть `dict`, `list`, отдельные значения `str`, `int` и т.д.
diff --git a/docs/ru/docs/tutorial/handling-errors.md b/docs/ru/docs/tutorial/handling-errors.md
index 40b6f9bc4..e7bfb85aa 100644
--- a/docs/ru/docs/tutorial/handling-errors.md
+++ b/docs/ru/docs/tutorial/handling-errors.md
@@ -26,7 +26,7 @@
### Импортируйте `HTTPException`
```Python hl_lines="1"
-{!../../../docs_src/handling_errors/tutorial001.py!}
+{!../../docs_src/handling_errors/tutorial001.py!}
```
### Вызовите `HTTPException` в своем коде
@@ -42,7 +42,7 @@
В данном примере, когда клиент запрашивает элемент по несуществующему ID, возникает исключение со статус-кодом `404`:
```Python hl_lines="11"
-{!../../../docs_src/handling_errors/tutorial001.py!}
+{!../../docs_src/handling_errors/tutorial001.py!}
```
### Возвращаемый ответ
@@ -63,12 +63,15 @@
}
```
-!!! tip "Подсказка"
- При вызове `HTTPException` в качестве параметра `detail` можно передавать любое значение, которое может быть преобразовано в JSON, а не только `str`.
+/// tip | "Подсказка"
- Вы можете передать `dict`, `list` и т.д.
+При вызове `HTTPException` в качестве параметра `detail` можно передавать любое значение, которое может быть преобразовано в JSON, а не только `str`.
- Они автоматически обрабатываются **FastAPI** и преобразуются в JSON.
+Вы можете передать `dict`, `list` и т.д.
+
+Они автоматически обрабатываются **FastAPI** и преобразуются в JSON.
+
+///
## Добавление пользовательских заголовков
@@ -79,7 +82,7 @@
Но в случае, если это необходимо для продвинутого сценария, можно добавить пользовательские заголовки:
```Python hl_lines="14"
-{!../../../docs_src/handling_errors/tutorial002.py!}
+{!../../docs_src/handling_errors/tutorial002.py!}
```
## Установка пользовательских обработчиков исключений
@@ -93,7 +96,7 @@
Можно добавить собственный обработчик исключений с помощью `@app.exception_handler()`:
```Python hl_lines="5-7 13-18 24"
-{!../../../docs_src/handling_errors/tutorial003.py!}
+{!../../docs_src/handling_errors/tutorial003.py!}
```
Здесь, если запросить `/unicorns/yolo`, то *операция пути* вызовет `UnicornException`.
@@ -106,10 +109,13 @@
{"message": "Oops! yolo did something. There goes a rainbow..."}
```
-!!! note "Технические детали"
- Также можно использовать `from starlette.requests import Request` и `from starlette.responses import JSONResponse`.
+/// note | "Технические детали"
- **FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette. То же самое касается и `Request`.
+Также можно использовать `from starlette.requests import Request` и `from starlette.responses import JSONResponse`.
+
+**FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette. То же самое касается и `Request`.
+
+///
## Переопределение стандартных обработчиков исключений
@@ -130,7 +136,7 @@
Обработчик исключения получит объект `Request` и исключение.
```Python hl_lines="2 14-16"
-{!../../../docs_src/handling_errors/tutorial004.py!}
+{!../../docs_src/handling_errors/tutorial004.py!}
```
Теперь, если перейти к `/items/foo`, то вместо стандартной JSON-ошибки с:
@@ -160,8 +166,11 @@ path -> item_id
#### `RequestValidationError` или `ValidationError`
-!!! warning "Внимание"
- Это технические детали, которые можно пропустить, если они не важны для вас сейчас.
+/// warning | "Внимание"
+
+Это технические детали, которые можно пропустить, если они не важны для вас сейчас.
+
+///
`RequestValidationError` является подклассом Pydantic `ValidationError`.
@@ -180,13 +189,16 @@ path -> item_id
Например, для этих ошибок можно вернуть обычный текстовый ответ вместо JSON:
```Python hl_lines="3-4 9-11 22"
-{!../../../docs_src/handling_errors/tutorial004.py!}
+{!../../docs_src/handling_errors/tutorial004.py!}
```
-!!! note "Технические детали"
- Можно также использовать `from starlette.responses import PlainTextResponse`.
+/// note | "Технические детали"
- **FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette.
+Можно также использовать `from starlette.responses import PlainTextResponse`.
+
+**FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette.
+
+///
### Используйте тело `RequestValidationError`
@@ -195,7 +207,7 @@ path -> item_id
Вы можете использовать его при разработке приложения для регистрации тела и его отладки, возврата пользователю и т.д.
```Python hl_lines="14"
-{!../../../docs_src/handling_errors/tutorial005.py!}
+{!../../docs_src/handling_errors/tutorial005.py!}
```
Теперь попробуйте отправить недействительный элемент, например:
@@ -255,7 +267,7 @@ 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!}
```
В этом примере вы просто `выводите в терминал` ошибку с очень выразительным сообщением, но идея вам понятна. Вы можете использовать исключение, а затем просто повторно использовать стандартные обработчики исключений.
diff --git a/docs/ru/docs/tutorial/header-params.md b/docs/ru/docs/tutorial/header-params.md
index 1be4ac707..18e1e60d0 100644
--- a/docs/ru/docs/tutorial/header-params.md
+++ b/docs/ru/docs/tutorial/header-params.md
@@ -6,41 +6,57 @@
Сперва импортируйте `Header`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="3"
- {!> ../../../docs_src/header_params/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="3"
+{!> ../../docs_src/header_params/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="3"
- {!> ../../../docs_src/header_params/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="3"
+{!> ../../docs_src/header_params/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="3"
- {!> ../../../docs_src/header_params/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.8+
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+```Python hl_lines="3"
+{!> ../../docs_src/header_params/tutorial001_an.py!}
+```
- ```Python hl_lines="1"
- {!> ../../../docs_src/header_params/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ без Annotated"
+//// tab | Python 3.10+ без Annotated
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="3"
- {!> ../../../docs_src/header_params/tutorial001.py!}
- ```
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="1"
+{!> ../../docs_src/header_params/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ без Annotated
+
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="3"
+{!> ../../docs_src/header_params/tutorial001.py!}
+```
+
+////
## Объявление параметров `Header`
@@ -48,49 +64,71 @@
Первое значение является значением по умолчанию, вы можете передать все дополнительные параметры валидации или аннотации:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/header_params/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="9"
+{!> ../../docs_src/header_params/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/header_params/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.8+
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+```Python hl_lines="10"
+{!> ../../docs_src/header_params/tutorial001_an.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/header_params/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ без Annotated"
+//// tab | Python 3.10+ без Annotated
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial001.py!}
- ```
+Предпочтительнее использовать версию с аннотацией, если это возможно.
-!!! note "Технические детали"
- `Header` - это "родственный" класс `Path`, `Query` и `Cookie`. Он также наследуется от того же общего класса `Param`.
+///
- Но помните, что когда вы импортируете `Query`, `Path`, `Header` и другие из `fastapi`, на самом деле это функции, которые возвращают специальные классы.
+```Python hl_lines="7"
+{!> ../../docs_src/header_params/tutorial001_py310.py!}
+```
-!!! info "Дополнительная информация"
- Чтобы объявить заголовки, важно использовать `Header`, иначе параметры интерпретируются как query-параметры.
+////
+
+//// tab | Python 3.8+ без Annotated
+
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="9"
+{!> ../../docs_src/header_params/tutorial001.py!}
+```
+
+////
+
+/// note | "Технические детали"
+
+`Header` - это "родственный" класс `Path`, `Query` и `Cookie`. Он также наследуется от того же общего класса `Param`.
+
+Но помните, что когда вы импортируете `Query`, `Path`, `Header` и другие из `fastapi`, на самом деле это функции, которые возвращают специальные классы.
+
+///
+
+/// info | "Дополнительная информация"
+
+Чтобы объявить заголовки, важно использовать `Header`, иначе параметры интерпретируются как query-параметры.
+
+///
## Автоматическое преобразование
@@ -108,44 +146,63 @@
Если по какой-либо причине вам необходимо отключить автоматическое преобразование подчеркиваний в дефисы, установите для параметра `convert_underscores` в `Header` значение `False`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="10"
- {!> ../../../docs_src/header_params/tutorial002_an_py310.py!}
- ```
+```Python hl_lines="10"
+{!> ../../docs_src/header_params/tutorial002_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="11"
- {!> ../../../docs_src/header_params/tutorial002_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="11"
+{!> ../../docs_src/header_params/tutorial002_an_py39.py!}
+```
- ```Python hl_lines="12"
- {!> ../../../docs_src/header_params/tutorial002_an.py!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.8+
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+```Python hl_lines="12"
+{!> ../../docs_src/header_params/tutorial002_an.py!}
+```
- ```Python hl_lines="8"
- {!> ../../../docs_src/header_params/tutorial002_py310.py!}
- ```
+////
-=== "Python 3.8+ без Annotated"
+//// tab | Python 3.10+ без Annotated
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="10"
- {!> ../../../docs_src/header_params/tutorial002.py!}
- ```
+Предпочтительнее использовать версию с аннотацией, если это возможно.
-!!! warning "Внимание"
- Прежде чем установить для `convert_underscores` значение `False`, имейте в виду, что некоторые HTTP-прокси и серверы запрещают использование заголовков с подчеркиванием.
+///
+
+```Python hl_lines="8"
+{!> ../../docs_src/header_params/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ без Annotated
+
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="10"
+{!> ../../docs_src/header_params/tutorial002.py!}
+```
+
+////
+
+/// warning | "Внимание"
+
+Прежде чем установить для `convert_underscores` значение `False`, имейте в виду, что некоторые HTTP-прокси и серверы запрещают использование заголовков с подчеркиванием.
+
+///
## Повторяющиеся заголовки
@@ -157,50 +214,71 @@
Например, чтобы объявить заголовок `X-Token`, который может появляться более одного раза, вы можете написать:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial003_an_py310.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/header_params/tutorial003_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial003_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="9"
+{!> ../../docs_src/header_params/tutorial003_an_py39.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/header_params/tutorial003_an.py!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.8+
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+```Python hl_lines="10"
+{!> ../../docs_src/header_params/tutorial003_an.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/header_params/tutorial003_py310.py!}
- ```
+////
-=== "Python 3.9+ без Annotated"
+//// tab | Python 3.10+ без Annotated
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial003_py39.py!}
- ```
+Предпочтительнее использовать версию с аннотацией, если это возможно.
-=== "Python 3.8+ без Annotated"
+///
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+```Python hl_lines="7"
+{!> ../../docs_src/header_params/tutorial003_py310.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial003.py!}
- ```
+////
+
+//// tab | Python 3.9+ без Annotated
+
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="9"
+{!> ../../docs_src/header_params/tutorial003_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ без Annotated
+
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="9"
+{!> ../../docs_src/header_params/tutorial003.py!}
+```
+
+////
Если вы взаимодействуете с этой *операцией пути*, отправляя два HTTP-заголовка, таких как:
diff --git a/docs/ru/docs/tutorial/index.md b/docs/ru/docs/tutorial/index.md
index ea3a1c37a..4cf45c0ed 100644
--- a/docs/ru/docs/tutorial/index.md
+++ b/docs/ru/docs/tutorial/index.md
@@ -52,22 +52,25 @@ $ pip install "fastapi[all]"
...это также включает `uvicorn`, который вы можете использовать в качестве сервера, который запускает ваш код.
-!!! note "Технические детали"
- Вы также можете установить его по частям.
+/// note | "Технические детали"
- Это то, что вы, вероятно, сделаете, когда захотите развернуть свое приложение в рабочей среде:
+Вы также можете установить его по частям.
- ```
- pip install fastapi
- ```
+Это то, что вы, вероятно, сделаете, когда захотите развернуть свое приложение в рабочей среде:
- Также установите `uvicorn` для работы в качестве сервера:
+```
+pip install fastapi
+```
- ```
- pip install "uvicorn[standard]"
- ```
+Также установите `uvicorn` для работы в качестве сервера:
- И то же самое для каждой из необязательных зависимостей, которые вы хотите использовать.
+```
+pip install "uvicorn[standard]"
+```
+
+И то же самое для каждой из необязательных зависимостей, которые вы хотите использовать.
+
+///
## Продвинутое руководство пользователя
diff --git a/docs/ru/docs/tutorial/metadata.md b/docs/ru/docs/tutorial/metadata.md
index 0c6940d0e..246458f42 100644
--- a/docs/ru/docs/tutorial/metadata.md
+++ b/docs/ru/docs/tutorial/metadata.md
@@ -18,11 +18,14 @@
Вы можете задать их следующим образом:
```Python hl_lines="3-16 19-31"
-{!../../../docs_src/metadata/tutorial001.py!}
+{!../../docs_src/metadata/tutorial001.py!}
```
-!!! tip "Подсказка"
- Вы можете использовать Markdown в поле `description`, и оно будет отображено в выводе.
+/// tip | "Подсказка"
+
+Вы можете использовать Markdown в поле `description`, и оно будет отображено в выводе.
+
+///
С этой конфигурацией автоматическая документация API будут выглядеть так:
@@ -49,23 +52,29 @@
Создайте метаданные для ваших тегов и передайте их в параметре `openapi_tags`:
```Python hl_lines="3-16 18"
-{!../../../docs_src/metadata/tutorial004.py!}
+{!../../docs_src/metadata/tutorial004.py!}
```
Помните, что вы можете использовать Markdown внутри описания, к примеру "login" будет отображен жирным шрифтом (**login**) и "fancy" будет отображаться курсивом (_fancy_).
-!!! tip "Подсказка"
- Вам необязательно добавлять метаданные для всех используемых тегов
+/// tip | "Подсказка"
+
+Вам необязательно добавлять метаданные для всех используемых тегов
+
+///
### Используйте собственные теги
Используйте параметр `tags` с вашими *операциями пути* (и `APIRouter`ами), чтобы присвоить им различные теги:
```Python hl_lines="21 26"
-{!../../../docs_src/metadata/tutorial004.py!}
+{!../../docs_src/metadata/tutorial004.py!}
```
-!!! info "Дополнительная информация"
- Узнайте больше о тегах в [Конфигурации операции пути](path-operation-configuration.md#_3){.internal-link target=_blank}.
+/// info | "Дополнительная информация"
+
+Узнайте больше о тегах в [Конфигурации операции пути](path-operation-configuration.md#_3){.internal-link target=_blank}.
+
+///
### Проверьте документацию
@@ -88,7 +97,7 @@
К примеру, чтобы задать её отображение по адресу `/api/v1/openapi.json`:
```Python hl_lines="3"
-{!../../../docs_src/metadata/tutorial002.py!}
+{!../../docs_src/metadata/tutorial002.py!}
```
Если вы хотите отключить схему OpenAPI полностью, вы можете задать `openapi_url=None`, это также отключит пользовательские интерфейсы документации, которые его использует.
@@ -107,5 +116,5 @@
К примеру, чтобы задать отображение Swagger UI по адресу `/documentation` и отключить ReDoc:
```Python hl_lines="3"
-{!../../../docs_src/metadata/tutorial003.py!}
+{!../../docs_src/metadata/tutorial003.py!}
```
diff --git a/docs/ru/docs/tutorial/path-operation-configuration.md b/docs/ru/docs/tutorial/path-operation-configuration.md
index db99409f4..5f3855af2 100644
--- a/docs/ru/docs/tutorial/path-operation-configuration.md
+++ b/docs/ru/docs/tutorial/path-operation-configuration.md
@@ -2,8 +2,11 @@
Существует несколько параметров, которые вы можете передать вашему *декоратору операций пути* для его настройки.
-!!! warning "Внимание"
- Помните, что эти параметры передаются непосредственно *декоратору операций пути*, а не вашей *функции-обработчику операций пути*.
+/// warning | "Внимание"
+
+Помните, что эти параметры передаются непосредственно *декоратору операций пути*, а не вашей *функции-обработчику операций пути*.
+
+///
## Коды состояния
@@ -13,52 +16,67 @@
Но если вы не помните, для чего нужен каждый числовой код, вы можете использовать сокращенные константы в параметре `status`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="1 15"
- {!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!}
- ```
+```Python hl_lines="1 15"
+{!> ../../docs_src/path_operation_configuration/tutorial001_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="3 17"
- {!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="3 17"
+{!> ../../docs_src/path_operation_configuration/tutorial001_py39.py!}
+```
- ```Python hl_lines="3 17"
- {!> ../../../docs_src/path_operation_configuration/tutorial001.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="3 17"
+{!> ../../docs_src/path_operation_configuration/tutorial001.py!}
+```
+
+////
Этот код состояния будет использован в ответе и будет добавлен в схему OpenAPI.
-!!! note "Технические детали"
- Вы также можете использовать `from starlette import status`.
+/// note | "Технические детали"
- **FastAPI** предоставляет тот же `starlette.status` под псевдонимом `fastapi.status` для удобства разработчика. Но его источник - это непосредственно Starlette.
+Вы также можете использовать `from starlette import status`.
+
+**FastAPI** предоставляет тот же `starlette.status` под псевдонимом `fastapi.status` для удобства разработчика. Но его источник - это непосредственно Starlette.
+
+///
## Теги
Вы можете добавлять теги к вашим *операциям пути*, добавив параметр `tags` с `list` заполненным `str`-значениями (обычно в нём только одна строка):
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="15 20 25"
- {!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!}
- ```
+```Python hl_lines="15 20 25"
+{!> ../../docs_src/path_operation_configuration/tutorial002_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="17 22 27"
- {!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="17 22 27"
+{!> ../../docs_src/path_operation_configuration/tutorial002_py39.py!}
+```
- ```Python hl_lines="17 22 27"
- {!> ../../../docs_src/path_operation_configuration/tutorial002.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="17 22 27"
+{!> ../../docs_src/path_operation_configuration/tutorial002.py!}
+```
+
+////
Они будут добавлены в схему OpenAPI и будут использованы в автоматической документации интерфейса:
@@ -73,30 +91,36 @@
**FastAPI** поддерживает это так же, как и в случае с обычными строками:
```Python hl_lines="1 8-10 13 18"
-{!../../../docs_src/path_operation_configuration/tutorial002b.py!}
+{!../../docs_src/path_operation_configuration/tutorial002b.py!}
```
## Краткое и развёрнутое содержание
Вы можете добавить параметры `summary` и `description`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!}
- ```
+```Python hl_lines="18-19"
+{!> ../../docs_src/path_operation_configuration/tutorial003_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="20-21"
- {!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="20-21"
+{!> ../../docs_src/path_operation_configuration/tutorial003_py39.py!}
+```
- ```Python hl_lines="20-21"
- {!> ../../../docs_src/path_operation_configuration/tutorial003.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="20-21"
+{!> ../../docs_src/path_operation_configuration/tutorial003.py!}
+```
+
+////
## Описание из строк документации
@@ -104,23 +128,29 @@
Вы можете использовать Markdown в строке документации, и он будет интерпретирован и отображён корректно (с учетом отступа в строке документации).
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="17-25"
- {!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!}
- ```
+```Python hl_lines="17-25"
+{!> ../../docs_src/path_operation_configuration/tutorial004_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="19-27"
- {!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="19-27"
+{!> ../../docs_src/path_operation_configuration/tutorial004_py39.py!}
+```
- ```Python hl_lines="19-27"
- {!> ../../../docs_src/path_operation_configuration/tutorial004.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="19-27"
+{!> ../../docs_src/path_operation_configuration/tutorial004.py!}
+```
+
+////
Он будет использован в интерактивной документации:
@@ -130,31 +160,43 @@
Вы можете указать описание ответа с помощью параметра `response_description`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="19"
- {!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!}
- ```
+```Python hl_lines="19"
+{!> ../../docs_src/path_operation_configuration/tutorial005_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="21"
- {!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="21"
+{!> ../../docs_src/path_operation_configuration/tutorial005_py39.py!}
+```
- ```Python hl_lines="21"
- {!> ../../../docs_src/path_operation_configuration/tutorial005.py!}
- ```
+////
-!!! info "Дополнительная информация"
- Помните, что `response_description` относится конкретно к ответу, а `description` относится к *операции пути* в целом.
+//// tab | Python 3.8+
-!!! check "Технические детали"
- OpenAPI указывает, что каждой *операции пути* необходимо описание ответа.
+```Python hl_lines="21"
+{!> ../../docs_src/path_operation_configuration/tutorial005.py!}
+```
- Если вдруг вы не укажете его, то **FastAPI** автоматически сгенерирует это описание с текстом "Successful response".
+////
+
+/// info | "Дополнительная информация"
+
+Помните, что `response_description` относится конкретно к ответу, а `description` относится к *операции пути* в целом.
+
+///
+
+/// check | "Технические детали"
+
+OpenAPI указывает, что каждой *операции пути* необходимо описание ответа.
+
+Если вдруг вы не укажете его, то **FastAPI** автоматически сгенерирует это описание с текстом "Successful response".
+
+///
@@ -163,7 +205,7 @@
Если вам необходимо пометить *операцию пути* как устаревшую, при этом не удаляя её, передайте параметр `deprecated`:
```Python hl_lines="16"
-{!../../../docs_src/path_operation_configuration/tutorial006.py!}
+{!../../docs_src/path_operation_configuration/tutorial006.py!}
```
Он будет четко помечен как устаревший в интерактивной документации:
diff --git a/docs/ru/docs/tutorial/path-params-numeric-validations.md b/docs/ru/docs/tutorial/path-params-numeric-validations.md
index 0baf51fa9..bf42ec725 100644
--- a/docs/ru/docs/tutorial/path-params-numeric-validations.md
+++ b/docs/ru/docs/tutorial/path-params-numeric-validations.md
@@ -6,48 +6,67 @@
Сначала импортируйте `Path` из `fastapi`, а также импортируйте `Annotated`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="1 3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="1 3"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="1 3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="1 3"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="3-4"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.8+
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+```Python hl_lines="3-4"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
+```
- ```Python hl_lines="1"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ без Annotated"
+//// tab | Python 3.10+ без Annotated
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
-!!! info "Информация"
- Поддержка `Annotated` была добавлена в FastAPI начиная с версии 0.95.0 (и с этой версии рекомендуется использовать этот подход).
+///
- Если вы используете более старую версию, вы столкнётесь с ошибками при попытке использовать `Annotated`.
+```Python hl_lines="1"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
+```
- Убедитесь, что вы [обновили версию FastAPI](../deployment/versions.md#fastapi_2){.internal-link target=_blank} как минимум до 0.95.1 перед тем, как использовать `Annotated`.
+////
+
+//// tab | Python 3.8+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="3"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!}
+```
+
+////
+
+/// info | "Информация"
+
+Поддержка `Annotated` была добавлена в FastAPI начиная с версии 0.95.0 (и с этой версии рекомендуется использовать этот подход).
+
+Если вы используете более старую версию, вы столкнётесь с ошибками при попытке использовать `Annotated`.
+
+Убедитесь, что вы [обновили версию FastAPI](../deployment/versions.md#fastapi_2){.internal-link target=_blank} как минимум до 0.95.1 перед тем, как использовать `Annotated`.
+
+///
## Определите метаданные
@@ -55,53 +74,75 @@
Например, чтобы указать значение метаданных `title` для path-параметра `item_id`, вы можете написать:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="10"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="10"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="11"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.8+
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+```Python hl_lines="11"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
+```
- ```Python hl_lines="8"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ без Annotated"
+//// tab | Python 3.10+ без Annotated
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
-!!! note "Примечание"
- Path-параметр всегда является обязательным, поскольку он составляет часть пути.
+///
- Поэтому следует объявить его с помощью `...`, чтобы обозначить, что этот параметр обязательный.
+```Python hl_lines="8"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
+```
- Тем не менее, даже если вы объявите его как `None` или установите для него значение по умолчанию, это ни на что не повлияет и параметр останется обязательным.
+////
+
+//// tab | Python 3.8+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="10"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!}
+```
+
+////
+
+/// note | "Примечание"
+
+Path-параметр всегда является обязательным, поскольку он составляет часть пути.
+
+Поэтому следует объявить его с помощью `...`, чтобы обозначить, что этот параметр обязательный.
+
+Тем не менее, даже если вы объявите его как `None` или установите для него значение по умолчанию, это ни на что не повлияет и параметр останется обязательным.
+
+///
## Задайте нужный вам порядок параметров
-!!! tip "Подсказка"
- Это не имеет большого значения, если вы используете `Annotated`.
+/// tip | "Подсказка"
+
+Это не имеет большого значения, если вы используете `Annotated`.
+
+///
Допустим, вы хотите объявить query-параметр `q` как обязательный параметр типа `str`.
@@ -117,33 +158,45 @@
Поэтому вы можете определить функцию так:
-=== "Python 3.8 без Annotated"
+//// tab | Python 3.8 без Annotated
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="7"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!}
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="7"
+{!> ../../docs_src/path_params_numeric_validations/tutorial002.py!}
+```
+
+////
Но имейте в виду, что если вы используете `Annotated`, вы не столкнётесь с этой проблемой, так как вы не используете `Query()` или `Path()` в качестве значения по умолчанию для параметра функции.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!}
- ```
+```Python hl_lines="10"
+{!> ../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../docs_src/path_params_numeric_validations/tutorial002_an.py!}
+```
+
+////
## Задайте нужный вам порядок параметров, полезные приёмы
-!!! tip "Подсказка"
- Это не имеет большого значения, если вы используете `Annotated`.
+/// tip | "Подсказка"
+
+Это не имеет большого значения, если вы используете `Annotated`.
+
+///
Здесь описан **небольшой приём**, который может оказаться удобным, хотя часто он вам не понадобится.
@@ -161,24 +214,28 @@
Python не будет ничего делать с `*`, но он будет знать, что все следующие параметры являются именованными аргументами (парами ключ-значение), также известными как kwargs, даже если у них нет значений по умолчанию.
```Python hl_lines="7"
-{!../../../docs_src/path_params_numeric_validations/tutorial003.py!}
+{!../../docs_src/path_params_numeric_validations/tutorial003.py!}
```
### Лучше с `Annotated`
Имейте в виду, что если вы используете `Annotated`, то, поскольку вы не используете значений по умолчанию для параметров функции, то у вас не возникнет подобной проблемы и вам не придётся использовать `*`.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!}
- ```
+```Python hl_lines="10"
+{!> ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../docs_src/path_params_numeric_validations/tutorial003_an.py!}
+```
+
+////
## Валидация числовых данных: больше или равно
@@ -186,26 +243,35 @@ Python не будет ничего делать с `*`, но он будет з
В этом примере при указании `ge=1`, параметр `item_id` должен быть больше или равен `1` ("`g`reater than or `e`qual").
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!}
- ```
+```Python hl_lines="10"
+{!> ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ без Annotated"
+```Python hl_lines="9"
+{!> ../../docs_src/path_params_numeric_validations/tutorial004_an.py!}
+```
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!}
- ```
+//// tab | Python 3.8+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="8"
+{!> ../../docs_src/path_params_numeric_validations/tutorial004.py!}
+```
+
+////
## Валидация числовых данных: больше и меньше или равно
@@ -214,26 +280,35 @@ Python не будет ничего делать с `*`, но он будет з
* `gt`: больше (`g`reater `t`han)
* `le`: меньше или равно (`l`ess than or `e`qual)
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!}
- ```
+```Python hl_lines="10"
+{!> ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ без Annotated"
+```Python hl_lines="9"
+{!> ../../docs_src/path_params_numeric_validations/tutorial005_an.py!}
+```
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!}
- ```
+//// tab | Python 3.8+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="9"
+{!> ../../docs_src/path_params_numeric_validations/tutorial005.py!}
+```
+
+////
## Валидация числовых данных: числа с плавающей точкой, больше и меньше
@@ -245,26 +320,35 @@ Python не будет ничего делать с `*`, но он будет з
То же самое справедливо и для lt.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="13"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!}
- ```
+```Python hl_lines="13"
+{!> ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="12"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ без Annotated"
+```Python hl_lines="12"
+{!> ../../docs_src/path_params_numeric_validations/tutorial006_an.py!}
+```
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+////
- ```Python hl_lines="11"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!}
- ```
+//// tab | Python 3.8+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="11"
+{!> ../../docs_src/path_params_numeric_validations/tutorial006.py!}
+```
+
+////
## Резюме
@@ -277,16 +361,22 @@ Python не будет ничего делать с `*`, но он будет з
* `lt`: меньше (`l`ess `t`han)
* `le`: меньше или равно (`l`ess than or `e`qual)
-!!! info "Информация"
- `Query`, `Path` и другие классы, которые мы разберём позже, являются наследниками общего класса `Param`.
+/// info | "Информация"
- Все они используют те же параметры для дополнительной валидации и метаданных, которые вы видели ранее.
+`Query`, `Path` и другие классы, которые мы разберём позже, являются наследниками общего класса `Param`.
-!!! note "Технические детали"
- `Query`, `Path` и другие "классы", которые вы импортируете из `fastapi`, на самом деле являются функциями, которые при вызове возвращают экземпляры одноимённых классов.
+Все они используют те же параметры для дополнительной валидации и метаданных, которые вы видели ранее.
- Объект `Query`, который вы импортируете, является функцией. И при вызове она возвращает экземпляр одноимённого класса `Query`.
+///
- Использование функций (вместо использования классов напрямую) нужно для того, чтобы ваш редактор не подсвечивал ошибки, связанные с их типами.
+/// note | "Технические детали"
- Таким образом вы можете использовать привычный вам редактор и инструменты разработки, не добавляя дополнительных конфигураций для игнорирования подобных ошибок.
+`Query`, `Path` и другие "классы", которые вы импортируете из `fastapi`, на самом деле являются функциями, которые при вызове возвращают экземпляры одноимённых классов.
+
+Объект `Query`, который вы импортируете, является функцией. И при вызове она возвращает экземпляр одноимённого класса `Query`.
+
+Использование функций (вместо использования классов напрямую) нужно для того, чтобы ваш редактор не подсвечивал ошибки, связанные с их типами.
+
+Таким образом вы можете использовать привычный вам редактор и инструменты разработки, не добавляя дополнительных конфигураций для игнорирования подобных ошибок.
+
+///
diff --git a/docs/ru/docs/tutorial/path-params.md b/docs/ru/docs/tutorial/path-params.md
index 1241e0919..d1d76cf7b 100644
--- a/docs/ru/docs/tutorial/path-params.md
+++ b/docs/ru/docs/tutorial/path-params.md
@@ -3,7 +3,7 @@
Вы можете определить "параметры" или "переменные" пути, используя синтаксис форматированных строк Python:
```Python hl_lines="6-7"
-{!../../../docs_src/path_params/tutorial001.py!}
+{!../../docs_src/path_params/tutorial001.py!}
```
Значение параметра пути `item_id` будет передано в функцию в качестве аргумента `item_id`.
@@ -19,13 +19,16 @@
Вы можете объявить тип параметра пути в функции, используя стандартные аннотации типов Python.
```Python hl_lines="7"
-{!../../../docs_src/path_params/tutorial002.py!}
+{!../../docs_src/path_params/tutorial002.py!}
```
Здесь, `item_id` объявлен типом `int`.
-!!! check "Заметка"
- Это обеспечит поддержку редактора внутри функции (проверка ошибок, автодополнение и т.п.).
+/// check | "Заметка"
+
+Это обеспечит поддержку редактора внутри функции (проверка ошибок, автодополнение и т.п.).
+
+///
## Преобразование данных
@@ -35,10 +38,13 @@
{"item_id":3}
```
-!!! check "Заметка"
- Обратите внимание на значение `3`, которое получила (и вернула) функция. Это целочисленный Python `int`, а не строка `"3"`.
+/// check | "Заметка"
- Используя определения типов, **FastAPI** выполняет автоматический "парсинг" запросов.
+Обратите внимание на значение `3`, которое получила (и вернула) функция. Это целочисленный Python `int`, а не строка `"3"`.
+
+Используя определения типов, **FastAPI** выполняет автоматический "парсинг" запросов.
+
+///
## Проверка данных
@@ -63,12 +69,15 @@
Та же ошибка возникнет, если вместо `int` передать `float` , например: http://127.0.0.1:8000/items/4.2
-!!! check "Заметка"
- **FastAPI** обеспечивает проверку типов, используя всё те же определения типов.
+/// check | "Заметка"
- Обратите внимание, что в тексте ошибки явно указано место не прошедшее проверку.
+**FastAPI** обеспечивает проверку типов, используя всё те же определения типов.
- Это очень полезно при разработке и отладке кода, который взаимодействует с API.
+Обратите внимание, что в тексте ошибки явно указано место не прошедшее проверку.
+
+Это очень полезно при разработке и отладке кода, который взаимодействует с API.
+
+///
## Документация
@@ -76,10 +85,13 @@
-!!! check "Заметка"
- Ещё раз, просто используя определения типов, **FastAPI** обеспечивает автоматическую интерактивную документацию (с интеграцией Swagger UI).
+/// check | "Заметка"
- Обратите внимание, что параметр пути объявлен целочисленным.
+Ещё раз, просто используя определения типов, **FastAPI** обеспечивает автоматическую интерактивную документацию (с интеграцией Swagger UI).
+
+Обратите внимание, что параметр пути объявлен целочисленным.
+
+///
## Преимущества стандартизации, альтернативная документация
@@ -111,7 +123,7 @@
```Python hl_lines="6 11"
-{!../../../docs_src/path_params/tutorial003.py!}
+{!../../docs_src/path_params/tutorial003.py!}
```
Иначе путь для `/users/{user_id}` также будет соответствовать `/users/me`, "подразумевая", что он получает параметр `user_id` со значением `"me"`.
@@ -119,7 +131,7 @@
Аналогично, вы не можете переопределить операцию с путем:
```Python hl_lines="6 11"
-{!../../../docs_src/path_params/tutorial003b.py!}
+{!../../docs_src/path_params/tutorial003b.py!}
```
Первый будет выполняться всегда, так как путь совпадает первым.
@@ -137,21 +149,27 @@
Затем создайте атрибуты класса с фиксированными допустимыми значениями:
```Python hl_lines="1 6-9"
-{!../../../docs_src/path_params/tutorial005.py!}
+{!../../docs_src/path_params/tutorial005.py!}
```
-!!! info "Дополнительная информация"
- Перечисления (enum) доступны в Python начиная с версии 3.4.
+/// info | "Дополнительная информация"
-!!! tip "Подсказка"
- Если интересно, то "AlexNet", "ResNet" и "LeNet" - это названия моделей машинного обучения.
+Перечисления (enum) доступны в Python начиная с версии 3.4.
+
+///
+
+/// tip | "Подсказка"
+
+Если интересно, то "AlexNet", "ResNet" и "LeNet" - это названия моделей машинного обучения.
+
+///
### Определение *параметра пути*
Определите *параметр пути*, используя в аннотации типа класс перечисления (`ModelName`), созданный ранее:
```Python hl_lines="16"
-{!../../../docs_src/path_params/tutorial005.py!}
+{!../../docs_src/path_params/tutorial005.py!}
```
### Проверьте документацию
@@ -169,7 +187,7 @@
Вы можете сравнить это значение с *элементом перечисления* класса `ModelName`:
```Python hl_lines="17"
-{!../../../docs_src/path_params/tutorial005.py!}
+{!../../docs_src/path_params/tutorial005.py!}
```
#### Получение *значения перечисления*
@@ -177,11 +195,14 @@
Можно получить фактическое значение (в данном случае - `str`) с помощью `model_name.value` или в общем случае `your_enum_member.value`:
```Python hl_lines="20"
-{!../../../docs_src/path_params/tutorial005.py!}
+{!../../docs_src/path_params/tutorial005.py!}
```
-!!! tip "Подсказка"
- Значение `"lenet"` также можно получить с помощью `ModelName.lenet.value`.
+/// tip | "Подсказка"
+
+Значение `"lenet"` также можно получить с помощью `ModelName.lenet.value`.
+
+///
#### Возврат *элементов перечисления*
@@ -190,7 +211,7 @@
Они будут преобразованы в соответствующие значения (в данном случае - строки) перед их возвратом клиенту:
```Python hl_lines="18 21 23"
-{!../../../docs_src/path_params/tutorial005.py!}
+{!../../docs_src/path_params/tutorial005.py!}
```
Вы отправите клиенту такой JSON-ответ:
@@ -230,13 +251,16 @@ OpenAPI не поддерживает способов объявления *п
Можете использовать так:
```Python hl_lines="6"
-{!../../../docs_src/path_params/tutorial004.py!}
+{!../../docs_src/path_params/tutorial004.py!}
```
-!!! tip "Подсказка"
- Возможно, вам понадобится, чтобы параметр содержал `/home/johndoe/myfile.txt` с ведущим слэшем (`/`).
+/// tip | "Подсказка"
- В этом случае URL будет таким: `/files//home/johndoe/myfile.txt`, с двойным слэшем (`//`) между `files` и `home`.
+Возможно, вам понадобится, чтобы параметр содержал `/home/johndoe/myfile.txt` с ведущим слэшем (`/`).
+
+В этом случае URL будет таким: `/files//home/johndoe/myfile.txt`, с двойным слэшем (`//`) между `files` и `home`.
+
+///
## Резюме
Используя **FastAPI** вместе со стандартными объявлениями типов Python (короткими и интуитивно понятными), вы получаете:
diff --git a/docs/ru/docs/tutorial/query-params-str-validations.md b/docs/ru/docs/tutorial/query-params-str-validations.md
index 108aefefc..0054af6ed 100644
--- a/docs/ru/docs/tutorial/query-params-str-validations.md
+++ b/docs/ru/docs/tutorial/query-params-str-validations.md
@@ -4,24 +4,31 @@
Давайте рассмотрим следующий пример:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!}
- ```
+```Python hl_lines="7"
+{!> ../../docs_src/query_params_str_validations/tutorial001_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../docs_src/query_params_str_validations/tutorial001.py!}
+```
+
+////
Query-параметр `q` имеет тип `Union[str, None]` (или `str | None` в Python 3.10). Это означает, что входной параметр будет типа `str`, но может быть и `None`. Ещё параметр имеет значение по умолчанию `None`, из-за чего FastAPI определит параметр как необязательный.
-!!! note "Технические детали"
- FastAPI определит параметр `q` как необязательный, потому что его значение по умолчанию `= None`.
+/// note | "Технические детали"
- `Union` в `Union[str, None]` позволит редактору кода оказать вам лучшую поддержку и найти ошибки.
+FastAPI определит параметр `q` как необязательный, потому что его значение по умолчанию `= None`.
+
+`Union` в `Union[str, None]` позволит редактору кода оказать вам лучшую поддержку и найти ошибки.
+
+///
## Расширенная валидация
@@ -34,23 +41,27 @@ Query-параметр `q` имеет тип `Union[str, None]` (или `str | N
* `Query` из пакета `fastapi`:
* `Annotated` из пакета `typing` (или из `typing_extensions` для Python ниже 3.9)
-=== "Python 3.10+"
+//// tab | Python 3.10+
- В Python 3.9 или выше, `Annotated` является частью стандартной библиотеки, таким образом вы можете импортировать его из `typing`.
+В Python 3.9 или выше, `Annotated` является частью стандартной библиотеки, таким образом вы можете импортировать его из `typing`.
- ```Python hl_lines="1 3"
- {!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!}
- ```
+```Python hl_lines="1 3"
+{!> ../../docs_src/query_params_str_validations/tutorial002_an_py310.py!}
+```
-=== "Python 3.8+"
+////
- В версиях Python ниже Python 3.9 `Annotation` импортируется из `typing_extensions`.
+//// tab | Python 3.8+
- Эта библиотека будет установлена вместе с FastAPI.
+В версиях Python ниже Python 3.9 `Annotation` импортируется из `typing_extensions`.
- ```Python hl_lines="3-4"
- {!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!}
- ```
+Эта библиотека будет установлена вместе с FastAPI.
+
+```Python hl_lines="3-4"
+{!> ../../docs_src/query_params_str_validations/tutorial002_an.py!}
+```
+
+////
## `Annotated` как тип для query-параметра `q`
@@ -60,31 +71,39 @@ Query-параметр `q` имеет тип `Union[str, None]` (или `str | N
У нас была аннотация следующего типа:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python
- q: str | None = None
- ```
+```Python
+q: str | None = None
+```
-=== "Python 3.8+"
+////
- ```Python
- q: Union[str, None] = None
- ```
+//// tab | Python 3.8+
+
+```Python
+q: Union[str, None] = None
+```
+
+////
Вот что мы получим, если обернём это в `Annotated`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python
- q: Annotated[str | None] = None
- ```
+```Python
+q: Annotated[str | None] = None
+```
-=== "Python 3.8+"
+////
- ```Python
- q: Annotated[Union[str, None]] = None
- ```
+//// tab | Python 3.8+
+
+```Python
+q: Annotated[Union[str, None]] = None
+```
+
+////
Обе эти версии означают одно и тоже. `q` - это параметр, который может быть `str` или `None`, и по умолчанию он будет принимать `None`.
@@ -94,17 +113,21 @@ Query-параметр `q` имеет тип `Union[str, None]` (или `str | N
Теперь, когда у нас есть `Annotated`, где мы можем добавить больше метаданных, добавим `Query` со значением параметра `max_length` равным 50:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/query_params_str_validations/tutorial002_an_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="10"
+{!> ../../docs_src/query_params_str_validations/tutorial002_an.py!}
+```
+
+////
Обратите внимание, что значение по умолчанию всё ещё `None`, так что параметр остаётся необязательным.
@@ -120,22 +143,29 @@ Query-параметр `q` имеет тип `Union[str, None]` (или `str | N
В предыдущих версиях FastAPI (ниже 0.95.0) необходимо было использовать `Query` как значение по умолчанию для query-параметра. Так было вместо размещения его в `Annotated`, так что велика вероятность, что вам встретится такой код. Сейчас объясню.
-!!! tip "Подсказка"
- При написании нового кода и везде где это возможно, используйте `Annotated`, как было описано ранее. У этого способа есть несколько преимуществ (о них дальше) и никаких недостатков. 🍰
+/// tip | "Подсказка"
+
+При написании нового кода и везде где это возможно, используйте `Annotated`, как было описано ранее. У этого способа есть несколько преимуществ (о них дальше) и никаких недостатков. 🍰
+
+///
Вот как вы могли бы использовать `Query()` в качестве значения по умолчанию параметра вашей функции, установив для параметра `max_length` значение 50:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!}
- ```
+```Python hl_lines="7"
+{!> ../../docs_src/query_params_str_validations/tutorial002_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../docs_src/query_params_str_validations/tutorial002.py!}
+```
+
+////
В таком случае (без использования `Annotated`), мы заменили значение по умолчанию с `None` на `Query()` в функции. Теперь нам нужно установить значение по умолчанию для query-параметра `Query(default=None)`, что необходимо для тех же целей, как когда ранее просто указывалось значение по умолчанию (по крайней мере, для FastAPI).
@@ -165,22 +195,25 @@ q: str | None = None
Но он явно объявляет его как query-параметр.
-!!! info "Дополнительная информация"
- Запомните, важной частью объявления параметра как необязательного является:
+/// info | "Дополнительная информация"
- ```Python
- = None
- ```
+Запомните, важной частью объявления параметра как необязательного является:
- или:
+```Python
+= None
+```
- ```Python
- = Query(default=None)
- ```
+или:
- так как `None` указан в качестве значения по умолчанию, параметр будет **необязательным**.
+```Python
+= Query(default=None)
+```
- `Union[str, None]` позволит редактору кода оказать вам лучшую поддержку. Но это не то, на что обращает внимание FastAPI для определения необязательности параметра.
+так как `None` указан в качестве значения по умолчанию, параметр будет **необязательным**.
+
+`Union[str, None]` позволит редактору кода оказать вам лучшую поддержку. Но это не то, на что обращает внимание FastAPI для определения необязательности параметра.
+
+///
Теперь, мы можем указать больше параметров для `Query`. В данном случае, параметр `max_length` применяется к строкам:
@@ -232,81 +265,113 @@ q: str = Query(default="rick")
Вы также можете добавить параметр `min_length`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial003_an_py310.py!}
- ```
+```Python hl_lines="10"
+{!> ../../docs_src/query_params_str_validations/tutorial003_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial003_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="10"
+{!> ../../docs_src/query_params_str_validations/tutorial003_an_py39.py!}
+```
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial003_an.py!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.8+
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+```Python hl_lines="11"
+{!> ../../docs_src/query_params_str_validations/tutorial003_an.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!}
- ```
+////
-=== "Python 3.8+ без Annotated"
+//// tab | Python 3.10+ без Annotated
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial003.py!}
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="7"
+{!> ../../docs_src/query_params_str_validations/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="10"
+{!> ../../docs_src/query_params_str_validations/tutorial003.py!}
+```
+
+////
## Регулярные выражения
Вы можете определить регулярное выражение, которому должен соответствовать параметр:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial004_an_py310.py!}
- ```
+```Python hl_lines="11"
+{!> ../../docs_src/query_params_str_validations/tutorial004_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial004_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="11"
+{!> ../../docs_src/query_params_str_validations/tutorial004_an_py39.py!}
+```
- ```Python hl_lines="12"
- {!> ../../../docs_src/query_params_str_validations/tutorial004_an.py!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.8+
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+```Python hl_lines="12"
+{!> ../../docs_src/query_params_str_validations/tutorial004_an.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!}
- ```
+////
-=== "Python 3.8+ без Annotated"
+//// tab | Python 3.10+ без Annotated
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial004.py!}
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="9"
+{!> ../../docs_src/query_params_str_validations/tutorial004_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="11"
+{!> ../../docs_src/query_params_str_validations/tutorial004.py!}
+```
+
+////
Данное регулярное выражение проверяет, что полученное значение параметра:
@@ -324,29 +389,41 @@ q: str = Query(default="rick")
Например, вы хотите для параметра запроса `q` указать, что он должен состоять минимум из 3 символов (`min_length=3`) и иметь значение по умолчанию `"fixedquery"`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial005_an_py39.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/query_params_str_validations/tutorial005_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial005_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ без Annotated"
+```Python hl_lines="8"
+{!> ../../docs_src/query_params_str_validations/tutorial005_an.py!}
+```
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial005.py!}
- ```
+//// tab | Python 3.8+ без Annotated
-!!! note "Технические детали"
- Наличие значения по умолчанию делает параметр необязательным.
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="7"
+{!> ../../docs_src/query_params_str_validations/tutorial005.py!}
+```
+
+////
+
+/// note | "Технические детали"
+
+Наличие значения по умолчанию делает параметр необязательным.
+
+///
## Обязательный параметр
@@ -364,75 +441,103 @@ q: Union[str, None] = None
Но у нас query-параметр определён как `Query`. Например:
-=== "Annotated"
+//// tab | Annotated
- ```Python
- q: Annotated[Union[str, None], Query(min_length=3)] = None
- ```
+```Python
+q: Annotated[Union[str, None], Query(min_length=3)] = None
+```
-=== "без Annotated"
+////
- ```Python
- q: Union[str, None] = Query(default=None, min_length=3)
- ```
+//// tab | без Annotated
+
+```Python
+q: Union[str, None] = Query(default=None, min_length=3)
+```
+
+////
В таком случае, чтобы сделать query-параметр `Query` обязательным, вы можете просто не указывать значение по умолчанию:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial006_an_py39.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/query_params_str_validations/tutorial006_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial006_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ без Annotated"
+```Python hl_lines="8"
+{!> ../../docs_src/query_params_str_validations/tutorial006_an.py!}
+```
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial006.py!}
- ```
+//// tab | Python 3.8+ без Annotated
- !!! tip "Подсказка"
- Обратите внимание, что даже когда `Query()` используется как значение по умолчанию для параметра функции, мы не передаём `default=None` в `Query()`.
+/// tip | "Подсказка"
- Лучше будет использовать версию с `Annotated`. 😉
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="7"
+{!> ../../docs_src/query_params_str_validations/tutorial006.py!}
+```
+
+/// tip | "Подсказка"
+
+Обратите внимание, что даже когда `Query()` используется как значение по умолчанию для параметра функции, мы не передаём `default=None` в `Query()`.
+
+Лучше будет использовать версию с `Annotated`. 😉
+
+///
+
+////
### Обязательный параметр с Ellipsis (`...`)
Альтернативный способ указать обязательность параметра запроса - это указать параметр `default` через многоточие `...`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial006b_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ без Annotated"
+```Python hl_lines="8"
+{!> ../../docs_src/query_params_str_validations/tutorial006b_an.py!}
+```
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial006b.py!}
- ```
+//// tab | Python 3.8+ без Annotated
-!!! info "Дополнительная информация"
- Если вы ранее не сталкивались с `...`: это специальное значение, часть языка Python и называется "Ellipsis".
+/// tip | "Подсказка"
- Используется в Pydantic и FastAPI для определения, что значение требуется обязательно.
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="7"
+{!> ../../docs_src/query_params_str_validations/tutorial006b.py!}
+```
+
+////
+
+/// info | "Дополнительная информация"
+
+Если вы ранее не сталкивались с `...`: это специальное значение, часть языка Python и называется "Ellipsis".
+
+Используется в Pydantic и FastAPI для определения, что значение требуется обязательно.
+
+///
Таким образом, **FastAPI** определяет, что параметр является обязательным.
@@ -442,72 +547,103 @@ q: Union[str, None] = None
Чтобы этого добиться, вам нужно определить `None` как валидный тип для параметра запроса, но также указать `default=...`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py310.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/query_params_str_validations/tutorial006c_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="9"
+{!> ../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial006c_an.py!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.8+
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+```Python hl_lines="10"
+{!> ../../docs_src/query_params_str_validations/tutorial006c_an.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!}
- ```
+////
-=== "Python 3.8+ без Annotated"
+//// tab | Python 3.10+ без Annotated
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial006c.py!}
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
-!!! tip "Подсказка"
- Pydantic, мощь которого используется в FastAPI для валидации и сериализации, имеет специальное поведение для `Optional` или `Union[Something, None]` без значения по умолчанию. Вы можете узнать об этом больше в документации Pydantic, раздел Обязательные Опциональные поля.
+///
+
+```Python hl_lines="7"
+{!> ../../docs_src/query_params_str_validations/tutorial006c_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="9"
+{!> ../../docs_src/query_params_str_validations/tutorial006c.py!}
+```
+
+////
+
+/// tip | "Подсказка"
+
+Pydantic, мощь которого используется в FastAPI для валидации и сериализации, имеет специальное поведение для `Optional` или `Union[Something, None]` без значения по умолчанию. Вы можете узнать об этом больше в документации Pydantic, раздел Обязательные Опциональные поля.
+
+///
### Использование Pydantic's `Required` вместо Ellipsis (`...`)
Если вас смущает `...`, вы можете использовать `Required` из Pydantic:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="4 10"
- {!> ../../../docs_src/query_params_str_validations/tutorial006d_an_py39.py!}
- ```
+```Python hl_lines="4 10"
+{!> ../../docs_src/query_params_str_validations/tutorial006d_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="2 9"
- {!> ../../../docs_src/query_params_str_validations/tutorial006d_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ без Annotated"
+```Python hl_lines="2 9"
+{!> ../../docs_src/query_params_str_validations/tutorial006d_an.py!}
+```
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+////
- ```Python hl_lines="2 8"
- {!> ../../../docs_src/query_params_str_validations/tutorial006d.py!}
- ```
+//// tab | Python 3.8+ без Annotated
-!!! tip "Подсказка"
- Запомните, когда вам необходимо объявить query-параметр обязательным, вы можете просто не указывать параметр `default`. Таким образом, вам редко придётся использовать `...` или `Required`.
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="2 8"
+{!> ../../docs_src/query_params_str_validations/tutorial006d.py!}
+```
+
+////
+
+/// tip | "Подсказка"
+
+Запомните, когда вам необходимо объявить query-параметр обязательным, вы можете просто не указывать параметр `default`. Таким образом, вам редко придётся использовать `...` или `Required`.
+
+///
## Множество значений для query-параметра
@@ -515,50 +651,71 @@ q: Union[str, None] = None
Например, query-параметр `q` может быть указан в URL несколько раз. И если вы ожидаете такой формат запроса, то можете указать это следующим образом:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial011_an_py310.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/query_params_str_validations/tutorial011_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial011_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="9"
+{!> ../../docs_src/query_params_str_validations/tutorial011_an_py39.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial011_an.py!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.8+
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+```Python hl_lines="10"
+{!> ../../docs_src/query_params_str_validations/tutorial011_an.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial011_py310.py!}
- ```
+////
-=== "Python 3.9+ без Annotated"
+//// tab | Python 3.10+ без Annotated
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!}
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
-=== "Python 3.8+ без Annotated"
+///
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+```Python hl_lines="7"
+{!> ../../docs_src/query_params_str_validations/tutorial011_py310.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial011.py!}
- ```
+////
+
+//// tab | Python 3.9+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="9"
+{!> ../../docs_src/query_params_str_validations/tutorial011_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="9"
+{!> ../../docs_src/query_params_str_validations/tutorial011.py!}
+```
+
+////
Затем, получив такой URL:
@@ -579,8 +736,11 @@ http://localhost:8000/items/?q=foo&q=bar
}
```
-!!! tip "Подсказка"
- Чтобы объявить query-параметр типом `list`, как в примере выше, вам нужно явно использовать `Query`, иначе он будет интерпретирован как тело запроса.
+/// tip | "Подсказка"
+
+Чтобы объявить query-параметр типом `list`, как в примере выше, вам нужно явно использовать `Query`, иначе он будет интерпретирован как тело запроса.
+
+///
Интерактивная документация API будет обновлена соответствующим образом, где будет разрешено множество значений:
@@ -590,35 +750,49 @@ http://localhost:8000/items/?q=foo&q=bar
Вы также можете указать тип `list` со списком значений по умолчанию на случай, если вам их не предоставят:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial012_an_py39.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/query_params_str_validations/tutorial012_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial012_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.9+ без Annotated"
+```Python hl_lines="10"
+{!> ../../docs_src/query_params_str_validations/tutorial012_an.py!}
+```
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!}
- ```
+//// tab | Python 3.9+ без Annotated
-=== "Python 3.8+ без Annotated"
+/// tip | "Подсказка"
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+Рекомендуется использовать версию с `Annotated` если возможно.
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial012.py!}
- ```
+///
+
+```Python hl_lines="7"
+{!> ../../docs_src/query_params_str_validations/tutorial012_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="9"
+{!> ../../docs_src/query_params_str_validations/tutorial012.py!}
+```
+
+////
Если вы перейдёте по ссылке:
@@ -641,31 +815,43 @@ http://localhost:8000/items/
Вы также можете использовать `list` напрямую вместо `List[str]` (или `list[str]` в Python 3.9+):
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial013_an_py39.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/query_params_str_validations/tutorial013_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial013_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ без Annotated"
+```Python hl_lines="8"
+{!> ../../docs_src/query_params_str_validations/tutorial013_an.py!}
+```
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial013.py!}
- ```
+//// tab | Python 3.8+ без Annotated
-!!! note "Технические детали"
- Запомните, что в таком случае, FastAPI не будет проверять содержимое списка.
+/// tip | "Подсказка"
- Например, для List[int] список будет провалидирован (и задокументирован) на содержание только целочисленных элементов. Но для простого `list` такой проверки не будет.
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="7"
+{!> ../../docs_src/query_params_str_validations/tutorial013.py!}
+```
+
+////
+
+/// note | "Технические детали"
+
+Запомните, что в таком случае, FastAPI не будет проверять содержимое списка.
+
+Например, для List[int] список будет провалидирован (и задокументирован) на содержание только целочисленных элементов. Но для простого `list` такой проверки не будет.
+
+///
## Больше метаданных
@@ -673,86 +859,121 @@ http://localhost:8000/items/
Указанная информация будет включена в генерируемую OpenAPI документацию и использована в пользовательском интерфейсе и внешних инструментах.
-!!! note "Технические детали"
- Имейте в виду, что разные инструменты могут иметь разные уровни поддержки OpenAPI.
+/// note | "Технические детали"
- Некоторые из них могут не отображать (на данный момент) всю заявленную дополнительную информацию, хотя в большинстве случаев отсутствующая функция уже запланирована к разработке.
+Имейте в виду, что разные инструменты могут иметь разные уровни поддержки OpenAPI.
+
+Некоторые из них могут не отображать (на данный момент) всю заявленную дополнительную информацию, хотя в большинстве случаев отсутствующая функция уже запланирована к разработке.
+
+///
Вы можете указать название query-параметра, используя параметр `title`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial007_an_py310.py!}
- ```
+```Python hl_lines="10"
+{!> ../../docs_src/query_params_str_validations/tutorial007_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial007_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="10"
+{!> ../../docs_src/query_params_str_validations/tutorial007_an_py39.py!}
+```
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial007_an.py!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.8+
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+```Python hl_lines="11"
+{!> ../../docs_src/query_params_str_validations/tutorial007_an.py!}
+```
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!}
- ```
+////
-=== "Python 3.8+ без Annotated"
+//// tab | Python 3.10+ без Annotated
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial007.py!}
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="8"
+{!> ../../docs_src/query_params_str_validations/tutorial007_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="10"
+{!> ../../docs_src/query_params_str_validations/tutorial007.py!}
+```
+
+////
Добавить описание, используя параметр `description`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="14"
- {!> ../../../docs_src/query_params_str_validations/tutorial008_an_py310.py!}
- ```
+```Python hl_lines="14"
+{!> ../../docs_src/query_params_str_validations/tutorial008_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="14"
- {!> ../../../docs_src/query_params_str_validations/tutorial008_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="14"
+{!> ../../docs_src/query_params_str_validations/tutorial008_an_py39.py!}
+```
- ```Python hl_lines="15"
- {!> ../../../docs_src/query_params_str_validations/tutorial008_an.py!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.8+
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+```Python hl_lines="15"
+{!> ../../docs_src/query_params_str_validations/tutorial008_an.py!}
+```
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!}
- ```
+////
-=== "Python 3.8+ без Annotated"
+//// tab | Python 3.10+ без Annotated
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="13"
- {!> ../../../docs_src/query_params_str_validations/tutorial008.py!}
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="11"
+{!> ../../docs_src/query_params_str_validations/tutorial008_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="13"
+{!> ../../docs_src/query_params_str_validations/tutorial008.py!}
+```
+
+////
## Псевдонимы параметров
@@ -772,41 +993,57 @@ http://127.0.0.1:8000/items/?item-query=foobaritems
Тогда вы можете объявить `псевдоним`, и этот псевдоним будет использоваться для поиска значения параметра запроса:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial009_an_py310.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/query_params_str_validations/tutorial009_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial009_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="9"
+{!> ../../docs_src/query_params_str_validations/tutorial009_an_py39.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial009_an.py!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.8+
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+```Python hl_lines="10"
+{!> ../../docs_src/query_params_str_validations/tutorial009_an.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!}
- ```
+////
-=== "Python 3.8+ без Annotated"
+//// tab | Python 3.10+ без Annotated
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial009.py!}
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="7"
+{!> ../../docs_src/query_params_str_validations/tutorial009_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="9"
+{!> ../../docs_src/query_params_str_validations/tutorial009.py!}
+```
+
+////
## Устаревшие параметры
@@ -816,41 +1053,57 @@ http://127.0.0.1:8000/items/?item-query=foobaritems
Тогда для `Query` укажите параметр `deprecated=True`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="19"
- {!> ../../../docs_src/query_params_str_validations/tutorial010_an_py310.py!}
- ```
+```Python hl_lines="19"
+{!> ../../docs_src/query_params_str_validations/tutorial010_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="19"
- {!> ../../../docs_src/query_params_str_validations/tutorial010_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="19"
+{!> ../../docs_src/query_params_str_validations/tutorial010_an_py39.py!}
+```
- ```Python hl_lines="20"
- {!> ../../../docs_src/query_params_str_validations/tutorial010_an.py!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.8+
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+```Python hl_lines="20"
+{!> ../../docs_src/query_params_str_validations/tutorial010_an.py!}
+```
- ```Python hl_lines="16"
- {!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!}
- ```
+////
-=== "Python 3.8+ без Annotated"
+//// tab | Python 3.10+ без Annotated
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="18"
- {!> ../../../docs_src/query_params_str_validations/tutorial010.py!}
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="16"
+{!> ../../docs_src/query_params_str_validations/tutorial010_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="18"
+{!> ../../docs_src/query_params_str_validations/tutorial010.py!}
+```
+
+////
В документации это будет отображено следующим образом:
@@ -860,41 +1113,57 @@ http://127.0.0.1:8000/items/?item-query=foobaritems
Чтобы исключить query-параметр из генерируемой OpenAPI схемы (а также из системы автоматической генерации документации), укажите в `Query` параметр `include_in_schema=False`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial014_an_py310.py!}
- ```
+```Python hl_lines="10"
+{!> ../../docs_src/query_params_str_validations/tutorial014_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial014_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="10"
+{!> ../../docs_src/query_params_str_validations/tutorial014_an_py39.py!}
+```
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial014_an.py!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.8+
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+```Python hl_lines="11"
+{!> ../../docs_src/query_params_str_validations/tutorial014_an.py!}
+```
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!}
- ```
+////
-=== "Python 3.8+ без Annotated"
+//// tab | Python 3.10+ без Annotated
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial014.py!}
- ```
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="8"
+{!> ../../docs_src/query_params_str_validations/tutorial014_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать версию с `Annotated` если возможно.
+
+///
+
+```Python hl_lines="10"
+{!> ../../docs_src/query_params_str_validations/tutorial014.py!}
+```
+
+////
## Резюме
diff --git a/docs/ru/docs/tutorial/query-params.md b/docs/ru/docs/tutorial/query-params.md
index f6e18f971..edf06746b 100644
--- a/docs/ru/docs/tutorial/query-params.md
+++ b/docs/ru/docs/tutorial/query-params.md
@@ -3,7 +3,7 @@
Когда вы объявляете параметры функции, которые не являются параметрами пути, они автоматически интерпретируются как "query"-параметры.
```Python hl_lines="9"
-{!../../../docs_src/query_params/tutorial001.py!}
+{!../../docs_src/query_params/tutorial001.py!}
```
Query-параметры представляют из себя набор пар ключ-значение, которые идут после знака `?` в URL-адресе, разделенные символами `&`.
@@ -63,38 +63,49 @@ http://127.0.0.1:8000/items/?skip=20
Аналогично, вы можете объявлять необязательные query-параметры, установив их значение по умолчанию, равное `None`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params/tutorial002_py310.py!}
- ```
+```Python hl_lines="7"
+{!> ../../docs_src/query_params/tutorial002_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../docs_src/query_params/tutorial002.py!}
+```
+
+////
В этом случае, параметр `q` будет не обязательным и будет иметь значение `None` по умолчанию.
-!!! check "Важно"
- Также обратите внимание, что **FastAPI** достаточно умён чтобы заметить, что параметр `item_id` является path-параметром, а `q` нет, поэтому, это параметр запроса.
+/// check | "Важно"
+
+Также обратите внимание, что **FastAPI** достаточно умён чтобы заметить, что параметр `item_id` является path-параметром, а `q` нет, поэтому, это параметр запроса.
+
+///
## Преобразование типа параметра запроса
Вы также можете объявлять параметры с типом `bool`, которые будут преобразованы соответственно:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params/tutorial003_py310.py!}
- ```
+```Python hl_lines="7"
+{!> ../../docs_src/query_params/tutorial003_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params/tutorial003.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../docs_src/query_params/tutorial003.py!}
+```
+
+////
В этом случае, если вы сделаете запрос:
@@ -137,17 +148,21 @@ http://127.0.0.1:8000/items/foo?short=yes
Они будут обнаружены по именам:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="6 8"
- {!> ../../../docs_src/query_params/tutorial004_py310.py!}
- ```
+```Python hl_lines="6 8"
+{!> ../../docs_src/query_params/tutorial004_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="8 10"
- {!> ../../../docs_src/query_params/tutorial004.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="8 10"
+{!> ../../docs_src/query_params/tutorial004.py!}
+```
+
+////
## Обязательные query-параметры
@@ -158,7 +173,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!}
```
Здесь параметр запроса `needy` является обязательным параметром с типом данных `str`.
@@ -203,17 +218,21 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
Конечно, вы можете определить некоторые параметры как обязательные, некоторые - со значением по умполчанию, а некоторые - полностью необязательные:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params/tutorial006_py310.py!}
- ```
+```Python hl_lines="8"
+{!> ../../docs_src/query_params/tutorial006_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params/tutorial006.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="10"
+{!> ../../docs_src/query_params/tutorial006.py!}
+```
+
+////
В этом примере, у нас есть 3 параметра запроса:
@@ -221,5 +240,8 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
* `skip`, типа `int` и со значением по умолчанию `0`.
* `limit`, необязательный `int`.
-!!! tip "Подсказка"
- Вы можете использовать класс `Enum` также, как ранее применяли его с [Path-параметрами](path-params.md#_7){.internal-link target=_blank}.
+/// tip | "Подсказка"
+
+Вы можете использовать класс `Enum` также, как ранее применяли его с [Path-параметрами](path-params.md#_7){.internal-link target=_blank}.
+
+///
diff --git a/docs/ru/docs/tutorial/request-files.md b/docs/ru/docs/tutorial/request-files.md
index 79b3bd067..34b9c94fa 100644
--- a/docs/ru/docs/tutorial/request-files.md
+++ b/docs/ru/docs/tutorial/request-files.md
@@ -2,70 +2,97 @@
Используя класс `File`, мы можем позволить клиентам загружать файлы.
-!!! info "Дополнительная информация"
- Чтобы получать загруженные файлы, сначала установите `python-multipart`.
+/// info | "Дополнительная информация"
- Например: `pip install python-multipart`.
+Чтобы получать загруженные файлы, сначала установите `python-multipart`.
- Это связано с тем, что загружаемые файлы передаются как данные формы.
+Например: `pip install python-multipart`.
+
+Это связано с тем, что загружаемые файлы передаются как данные формы.
+
+///
## Импорт `File`
Импортируйте `File` и `UploadFile` из модуля `fastapi`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="3"
- {!> ../../../docs_src/request_files/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="3"
+{!> ../../docs_src/request_files/tutorial001_an_py39.py!}
+```
-=== "Python 3.6+"
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/request_files/tutorial001_an.py!}
- ```
+//// tab | Python 3.6+
-=== "Python 3.6+ без Annotated"
+```Python hl_lines="1"
+{!> ../../docs_src/request_files/tutorial001_an.py!}
+```
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/request_files/tutorial001.py!}
- ```
+//// tab | Python 3.6+ без Annotated
+
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="1"
+{!> ../../docs_src/request_files/tutorial001.py!}
+```
+
+////
## Определите параметры `File`
Создайте параметры `File` так же, как вы это делаете для `Body` или `Form`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="9"
- {!> ../../../docs_src/request_files/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/request_files/tutorial001_an_py39.py!}
+```
-=== "Python 3.6+"
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/request_files/tutorial001_an.py!}
- ```
+//// tab | Python 3.6+
-=== "Python 3.6+ без Annotated"
+```Python hl_lines="8"
+{!> ../../docs_src/request_files/tutorial001_an.py!}
+```
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/request_files/tutorial001.py!}
- ```
+//// tab | Python 3.6+ без Annotated
-!!! info "Дополнительная информация"
- `File` - это класс, который наследуется непосредственно от `Form`.
+/// tip | "Подсказка"
- Но помните, что когда вы импортируете `Query`, `Path`, `File` и другие из `fastapi`, на самом деле это функции, которые возвращают специальные классы.
+Предпочтительнее использовать версию с аннотацией, если это возможно.
-!!! tip "Подсказка"
- Для объявления тела файла необходимо использовать `File`, поскольку в противном случае параметры будут интерпретироваться как параметры запроса или параметры тела (JSON).
+///
+
+```Python hl_lines="7"
+{!> ../../docs_src/request_files/tutorial001.py!}
+```
+
+////
+
+/// info | "Дополнительная информация"
+
+`File` - это класс, который наследуется непосредственно от `Form`.
+
+Но помните, что когда вы импортируете `Query`, `Path`, `File` и другие из `fastapi`, на самом деле это функции, которые возвращают специальные классы.
+
+///
+
+/// tip | "Подсказка"
+
+Для объявления тела файла необходимо использовать `File`, поскольку в противном случае параметры будут интерпретироваться как параметры запроса или параметры тела (JSON).
+
+///
Файлы будут загружены как данные формы.
@@ -79,26 +106,35 @@
Определите параметр файла с типом `UploadFile`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="14"
- {!> ../../../docs_src/request_files/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="14"
+{!> ../../docs_src/request_files/tutorial001_an_py39.py!}
+```
-=== "Python 3.6+"
+////
- ```Python hl_lines="13"
- {!> ../../../docs_src/request_files/tutorial001_an.py!}
- ```
+//// tab | Python 3.6+
-=== "Python 3.6+ без Annotated"
+```Python hl_lines="13"
+{!> ../../docs_src/request_files/tutorial001_an.py!}
+```
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+////
- ```Python hl_lines="12"
- {!> ../../../docs_src/request_files/tutorial001.py!}
- ```
+//// tab | Python 3.6+ без Annotated
+
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="12"
+{!> ../../docs_src/request_files/tutorial001.py!}
+```
+
+////
Использование `UploadFile` имеет ряд преимуществ перед `bytes`:
@@ -141,11 +177,17 @@ contents = await myfile.read()
contents = myfile.file.read()
```
-!!! note "Технические детали `async`"
- При использовании методов `async` **FastAPI** запускает файловые методы в пуле потоков и ожидает их.
+/// note | "Технические детали `async`"
-!!! note "Технические детали Starlette"
- **FastAPI** наследует `UploadFile` непосредственно из **Starlette**, но добавляет некоторые детали для совместимости с **Pydantic** и другими частями FastAPI.
+При использовании методов `async` **FastAPI** запускает файловые методы в пуле потоков и ожидает их.
+
+///
+
+/// note | "Технические детали Starlette"
+
+**FastAPI** наследует `UploadFile` непосредственно из **Starlette**, но добавляет некоторые детали для совместимости с **Pydantic** и другими частями FastAPI.
+
+///
## Про данные формы ("Form Data")
@@ -153,82 +195,113 @@ contents = myfile.file.read()
**FastAPI** позаботится о том, чтобы считать эти данные из нужного места, а не из JSON.
-!!! note "Технические детали"
- Данные из форм обычно кодируются с использованием "media type" `application/x-www-form-urlencoded` когда он не включает файлы.
+/// note | "Технические детали"
- Но когда форма включает файлы, она кодируется как multipart/form-data. Если вы используете `File`, **FastAPI** будет знать, что ему нужно получить файлы из нужной части тела.
+Данные из форм обычно кодируются с использованием "media type" `application/x-www-form-urlencoded` когда он не включает файлы.
- Если вы хотите узнать больше об этих кодировках и полях форм, перейдите по ссылке MDN web docs for POST.
+Но когда форма включает файлы, она кодируется как multipart/form-data. Если вы используете `File`, **FastAPI** будет знать, что ему нужно получить файлы из нужной части тела.
-!!! warning "Внимание"
- В операции *функции операции пути* можно объявить несколько параметров `File` и `Form`, но нельзя также объявлять поля `Body`, которые предполагается получить в виде JSON, поскольку тело запроса будет закодировано с помощью `multipart/form-data`, а не `application/json`.
+Если вы хотите узнать больше об этих кодировках и полях форм, перейдите по ссылке MDN web docs for POST.
- Это не является ограничением **FastAPI**, это часть протокола HTTP.
+///
+
+/// warning | "Внимание"
+
+В операции *функции операции пути* можно объявить несколько параметров `File` и `Form`, но нельзя также объявлять поля `Body`, которые предполагается получить в виде JSON, поскольку тело запроса будет закодировано с помощью `multipart/form-data`, а не `application/json`.
+
+Это не является ограничением **FastAPI**, это часть протокола HTTP.
+
+///
## Необязательная загрузка файлов
Вы можете сделать загрузку файла необязательной, используя стандартные аннотации типов и установив значение по умолчанию `None`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9 17"
- {!> ../../../docs_src/request_files/tutorial001_02_an_py310.py!}
- ```
+```Python hl_lines="9 17"
+{!> ../../docs_src/request_files/tutorial001_02_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="9 17"
- {!> ../../../docs_src/request_files/tutorial001_02_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.6+"
+```Python hl_lines="9 17"
+{!> ../../docs_src/request_files/tutorial001_02_an_py39.py!}
+```
- ```Python hl_lines="10 18"
- {!> ../../../docs_src/request_files/tutorial001_02_an.py!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.6+
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+```Python hl_lines="10 18"
+{!> ../../docs_src/request_files/tutorial001_02_an.py!}
+```
- ```Python hl_lines="7 15"
- {!> ../../../docs_src/request_files/tutorial001_02_py310.py!}
- ```
+////
-=== "Python 3.6+ без Annotated"
+//// tab | Python 3.10+ без Annotated
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+/// tip | "Подсказка"
- ```Python hl_lines="9 17"
- {!> ../../../docs_src/request_files/tutorial001_02.py!}
- ```
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="7 15"
+{!> ../../docs_src/request_files/tutorial001_02_py310.py!}
+```
+
+////
+
+//// tab | Python 3.6+ без Annotated
+
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="9 17"
+{!> ../../docs_src/request_files/tutorial001_02.py!}
+```
+
+////
## `UploadFile` с дополнительными метаданными
Вы также можете использовать `File()` вместе с `UploadFile`, например, для установки дополнительных метаданных:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="9 15"
- {!> ../../../docs_src/request_files/tutorial001_03_an_py39.py!}
- ```
+```Python hl_lines="9 15"
+{!> ../../docs_src/request_files/tutorial001_03_an_py39.py!}
+```
-=== "Python 3.6+"
+////
- ```Python hl_lines="8 14"
- {!> ../../../docs_src/request_files/tutorial001_03_an.py!}
- ```
+//// tab | Python 3.6+
-=== "Python 3.6+ без Annotated"
+```Python hl_lines="8 14"
+{!> ../../docs_src/request_files/tutorial001_03_an.py!}
+```
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+////
- ```Python hl_lines="7 13"
- {!> ../../../docs_src/request_files/tutorial001_03.py!}
- ```
+//// tab | Python 3.6+ без Annotated
+
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="7 13"
+{!> ../../docs_src/request_files/tutorial001_03.py!}
+```
+
+////
## Загрузка нескольких файлов
@@ -238,76 +311,107 @@ contents = myfile.file.read()
Для этого необходимо объявить список `bytes` или `UploadFile`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="10 15"
- {!> ../../../docs_src/request_files/tutorial002_an_py39.py!}
- ```
+```Python hl_lines="10 15"
+{!> ../../docs_src/request_files/tutorial002_an_py39.py!}
+```
-=== "Python 3.6+"
+////
- ```Python hl_lines="11 16"
- {!> ../../../docs_src/request_files/tutorial002_an.py!}
- ```
+//// tab | Python 3.6+
-=== "Python 3.9+ без Annotated"
+```Python hl_lines="11 16"
+{!> ../../docs_src/request_files/tutorial002_an.py!}
+```
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+////
- ```Python hl_lines="8 13"
- {!> ../../../docs_src/request_files/tutorial002_py39.py!}
- ```
+//// tab | Python 3.9+ без Annotated
-=== "Python 3.6+ без Annotated"
+/// tip | "Подсказка"
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+Предпочтительнее использовать версию с аннотацией, если это возможно.
- ```Python hl_lines="10 15"
- {!> ../../../docs_src/request_files/tutorial002.py!}
- ```
+///
+
+```Python hl_lines="8 13"
+{!> ../../docs_src/request_files/tutorial002_py39.py!}
+```
+
+////
+
+//// tab | Python 3.6+ без Annotated
+
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="10 15"
+{!> ../../docs_src/request_files/tutorial002.py!}
+```
+
+////
Вы получите, как и было объявлено, список `list` из `bytes` или `UploadFile`.
-!!! note "Technical Details"
- Можно также использовать `from starlette.responses import HTMLResponse`.
+/// note | "Technical Details"
- **FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette.
+Можно также использовать `from starlette.responses import HTMLResponse`.
+
+**FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette.
+
+///
### Загрузка нескольких файлов с дополнительными метаданными
Так же, как и раньше, вы можете использовать `File()` для задания дополнительных параметров, даже для `UploadFile`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="11 18-20"
- {!> ../../../docs_src/request_files/tutorial003_an_py39.py!}
- ```
+```Python hl_lines="11 18-20"
+{!> ../../docs_src/request_files/tutorial003_an_py39.py!}
+```
-=== "Python 3.6+"
+////
- ```Python hl_lines="12 19-21"
- {!> ../../../docs_src/request_files/tutorial003_an.py!}
- ```
+//// tab | Python 3.6+
-=== "Python 3.9+ без Annotated"
+```Python hl_lines="12 19-21"
+{!> ../../docs_src/request_files/tutorial003_an.py!}
+```
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+////
- ```Python hl_lines="9 16"
- {!> ../../../docs_src/request_files/tutorial003_py39.py!}
- ```
+//// tab | Python 3.9+ без Annotated
-=== "Python 3.6+ без Annotated"
+/// tip | "Подсказка"
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+Предпочтительнее использовать версию с аннотацией, если это возможно.
- ```Python hl_lines="11 18"
- {!> ../../../docs_src/request_files/tutorial003.py!}
- ```
+///
+
+```Python hl_lines="9 16"
+{!> ../../docs_src/request_files/tutorial003_py39.py!}
+```
+
+////
+
+//// tab | Python 3.6+ без Annotated
+
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="11 18"
+{!> ../../docs_src/request_files/tutorial003.py!}
+```
+
+////
## Резюме
diff --git a/docs/ru/docs/tutorial/request-forms-and-files.md b/docs/ru/docs/tutorial/request-forms-and-files.md
index a08232ca7..9b449bcd9 100644
--- a/docs/ru/docs/tutorial/request-forms-and-files.md
+++ b/docs/ru/docs/tutorial/request-forms-and-files.md
@@ -2,67 +2,91 @@
Вы можете определять файлы и поля формы одновременно, используя `File` и `Form`.
-!!! info "Дополнительная информация"
- Чтобы получать загруженные файлы и/или данные форм, сначала установите `python-multipart`.
+/// info | "Дополнительная информация"
- Например: `pip install python-multipart`.
+Чтобы получать загруженные файлы и/или данные форм, сначала установите `python-multipart`.
+
+Например: `pip install python-multipart`.
+
+///
## Импортируйте `File` и `Form`
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="3"
- {!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="3"
+{!> ../../docs_src/request_forms_and_files/tutorial001_an_py39.py!}
+```
-=== "Python 3.6+"
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!}
- ```
+//// tab | Python 3.6+
-=== "Python 3.6+ без Annotated"
+```Python hl_lines="1"
+{!> ../../docs_src/request_forms_and_files/tutorial001_an.py!}
+```
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/request_forms_and_files/tutorial001.py!}
- ```
+//// tab | Python 3.6+ без Annotated
+
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="1"
+{!> ../../docs_src/request_forms_and_files/tutorial001.py!}
+```
+
+////
## Определите параметры `File` и `Form`
Создайте параметры файла и формы таким же образом, как для `Body` или `Query`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="10-12"
- {!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="10-12"
+{!> ../../docs_src/request_forms_and_files/tutorial001_an_py39.py!}
+```
-=== "Python 3.6+"
+////
- ```Python hl_lines="9-11"
- {!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!}
- ```
+//// tab | Python 3.6+
-=== "Python 3.6+ без Annotated"
+```Python hl_lines="9-11"
+{!> ../../docs_src/request_forms_and_files/tutorial001_an.py!}
+```
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/request_forms_and_files/tutorial001.py!}
- ```
+//// tab | Python 3.6+ без Annotated
+
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="8"
+{!> ../../docs_src/request_forms_and_files/tutorial001.py!}
+```
+
+////
Файлы и поля формы будут загружены в виде данных формы, и вы получите файлы и поля формы.
Вы можете объявить некоторые файлы как `bytes`, а некоторые - как `UploadFile`.
-!!! warning "Внимание"
- Вы можете объявить несколько параметров `File` и `Form` в операции *path*, но вы не можете также объявить поля `Body`, которые вы ожидаете получить в виде JSON, так как запрос будет иметь тело, закодированное с помощью `multipart/form-data` вместо `application/json`.
+/// warning | "Внимание"
- Это не ограничение **Fast API**, это часть протокола HTTP.
+Вы можете объявить несколько параметров `File` и `Form` в операции *path*, но вы не можете также объявить поля `Body`, которые вы ожидаете получить в виде JSON, так как запрос будет иметь тело, закодированное с помощью `multipart/form-data` вместо `application/json`.
+
+Это не ограничение **Fast API**, это часть протокола HTTP.
+
+///
## Резюме
diff --git a/docs/ru/docs/tutorial/request-forms.md b/docs/ru/docs/tutorial/request-forms.md
index fa2bcb7cb..93b44437b 100644
--- a/docs/ru/docs/tutorial/request-forms.md
+++ b/docs/ru/docs/tutorial/request-forms.md
@@ -2,60 +2,81 @@
Когда вам нужно получить поля формы вместо JSON, вы можете использовать `Form`.
-!!! info "Дополнительная информация"
- Чтобы использовать формы, сначала установите `python-multipart`.
+/// info | "Дополнительная информация"
- Например, выполните команду `pip install python-multipart`.
+Чтобы использовать формы, сначала установите `python-multipart`.
+
+Например, выполните команду `pip install python-multipart`.
+
+///
## Импорт `Form`
Импортируйте `Form` из `fastapi`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="3"
- {!> ../../../docs_src/request_forms/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="3"
+{!> ../../docs_src/request_forms/tutorial001_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/request_forms/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ без Annotated"
+```Python hl_lines="1"
+{!> ../../docs_src/request_forms/tutorial001_an.py!}
+```
- !!! tip "Подсказка"
- Рекомендуется использовать 'Annotated' версию, если это возможно.
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/request_forms/tutorial001.py!}
- ```
+//// tab | Python 3.8+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать 'Annotated' версию, если это возможно.
+
+///
+
+```Python hl_lines="1"
+{!> ../../docs_src/request_forms/tutorial001.py!}
+```
+
+////
## Определение параметров `Form`
Создайте параметры формы так же, как это делается для `Body` или `Query`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="9"
- {!> ../../../docs_src/request_forms/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/request_forms/tutorial001_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="8"
- {!> ../../../docs_src/request_forms/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ без Annotated"
+```Python hl_lines="8"
+{!> ../../docs_src/request_forms/tutorial001_an.py!}
+```
- !!! tip "Подсказка"
- Рекомендуется использовать 'Annotated' версию, если это возможно.
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/request_forms/tutorial001.py!}
- ```
+//// tab | Python 3.8+ без Annotated
+
+/// tip | "Подсказка"
+
+Рекомендуется использовать 'Annotated' версию, если это возможно.
+
+///
+
+```Python hl_lines="7"
+{!> ../../docs_src/request_forms/tutorial001.py!}
+```
+
+////
Например, в одном из способов использования спецификации OAuth2 (называемом "потоком пароля") требуется отправить `username` и `password` в виде полей формы.
@@ -63,11 +84,17 @@
Вы можете настроить `Form` точно так же, как настраиваете и `Body` ( `Query`, `Path`, `Cookie`), включая валидации, примеры, псевдонимы (например, `user-name` вместо `username`) и т.д.
-!!! info "Дополнительная информация"
- `Form` - это класс, который наследуется непосредственно от `Body`.
+/// info | "Дополнительная информация"
-!!! tip "Подсказка"
- Вам необходимо явно указывать параметр `Form` при объявлении каждого поля, иначе поля будут интерпретироваться как параметры запроса или параметры тела (JSON).
+`Form` - это класс, который наследуется непосредственно от `Body`.
+
+///
+
+/// tip | "Подсказка"
+
+Вам необходимо явно указывать параметр `Form` при объявлении каждого поля, иначе поля будут интерпретироваться как параметры запроса или параметры тела (JSON).
+
+///
## О "полях формы"
@@ -75,17 +102,23 @@
**FastAPI** гарантирует правильное чтение этих данных из соответствующего места, а не из JSON.
-!!! note "Технические детали"
- Данные из форм обычно кодируются с использованием "типа медиа" `application/x-www-form-urlencoded`.
+/// note | "Технические детали"
- Но когда форма содержит файлы, она кодируется как `multipart/form-data`. Вы узнаете о работе с файлами в следующей главе.
+Данные из форм обычно кодируются с использованием "типа медиа" `application/x-www-form-urlencoded`.
- Если вы хотите узнать больше про кодировки и поля формы, ознакомьтесь с документацией MDN для `POST` на веб-сайте.
+Но когда форма содержит файлы, она кодируется как `multipart/form-data`. Вы узнаете о работе с файлами в следующей главе.
-!!! warning "Предупреждение"
- Вы можете объявлять несколько параметров `Form` в *операции пути*, но вы не можете одновременно с этим объявлять поля `Body`, которые вы ожидаете получить в виде JSON, так как запрос будет иметь тело, закодированное с использованием `application/x-www-form-urlencoded`, а не `application/json`.
+Если вы хотите узнать больше про кодировки и поля формы, ознакомьтесь с документацией MDN для `POST` на веб-сайте.
- Это не ограничение **FastAPI**, это часть протокола HTTP.
+///
+
+/// warning | "Предупреждение"
+
+Вы можете объявлять несколько параметров `Form` в *операции пути*, но вы не можете одновременно с этим объявлять поля `Body`, которые вы ожидаете получить в виде JSON, так как запрос будет иметь тело, закодированное с использованием `application/x-www-form-urlencoded`, а не `application/json`.
+
+Это не ограничение **FastAPI**, это часть протокола HTTP.
+
+///
## Резюме
diff --git a/docs/ru/docs/tutorial/response-model.md b/docs/ru/docs/tutorial/response-model.md
index 9b9b60dd5..363e64676 100644
--- a/docs/ru/docs/tutorial/response-model.md
+++ b/docs/ru/docs/tutorial/response-model.md
@@ -4,23 +4,29 @@
FastAPI позволяет использовать **аннотации типов** таким же способом, как и для ввода данных в **параметры** функции, вы можете использовать модели Pydantic, списки, словари, скалярные типы (такие, как int, bool и т.д.).
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="16 21"
- {!> ../../../docs_src/response_model/tutorial001_01_py310.py!}
- ```
+```Python hl_lines="16 21"
+{!> ../../docs_src/response_model/tutorial001_01_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="18 23"
- {!> ../../../docs_src/response_model/tutorial001_01_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="18 23"
+{!> ../../docs_src/response_model/tutorial001_01_py39.py!}
+```
- ```Python hl_lines="18 23"
- {!> ../../../docs_src/response_model/tutorial001_01.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="18 23"
+{!> ../../docs_src/response_model/tutorial001_01.py!}
+```
+
+////
FastAPI будет использовать этот возвращаемый тип для:
@@ -53,35 +59,47 @@ FastAPI будет использовать этот возвращаемый т
* `@app.delete()`
* и др.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001_py310.py!}
- ```
+```Python hl_lines="17 22 24-27"
+{!> ../../docs_src/response_model/tutorial001_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="17 22 24-27"
+{!> ../../docs_src/response_model/tutorial001_py39.py!}
+```
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001.py!}
- ```
+////
-!!! note "Технические детали"
- Помните, что параметр `response_model` является параметром именно декоратора http-методов (`get`, `post`, и т.п.). Не следует его указывать для *функций операций пути*, как вы бы поступили с другими параметрами или с телом запроса.
+//// tab | Python 3.8+
+
+```Python hl_lines="17 22 24-27"
+{!> ../../docs_src/response_model/tutorial001.py!}
+```
+
+////
+
+/// note | "Технические детали"
+
+Помните, что параметр `response_model` является параметром именно декоратора http-методов (`get`, `post`, и т.п.). Не следует его указывать для *функций операций пути*, как вы бы поступили с другими параметрами или с телом запроса.
+
+///
`response_model` принимает те же типы, которые можно указать для какого-либо поля в модели Pydantic. Таким образом, это может быть как одиночная модель Pydantic, так и `список (list)` моделей Pydantic. Например, `List[Item]`.
FastAPI будет использовать значение `response_model` для того, чтобы автоматически генерировать документацию, производить валидацию и т.п. А также для **конвертации и фильтрации выходных данных** в объявленный тип.
-!!! tip "Подсказка"
- Если вы используете анализаторы типов со строгой проверкой (например, mypy), можно указать `Any` в качестве типа возвращаемого значения функции.
+/// tip | "Подсказка"
- Таким образом вы информируете ваш редактор кода, что намеренно возвращаете данные неопределенного типа. Но возможности FastAPI, такие как автоматическая генерация документации, валидация, фильтрация и т.д. все так же будут работать, просто используя параметр `response_model`.
+Если вы используете анализаторы типов со строгой проверкой (например, mypy), можно указать `Any` в качестве типа возвращаемого значения функции.
+
+Таким образом вы информируете ваш редактор кода, что намеренно возвращаете данные неопределенного типа. Но возможности FastAPI, такие как автоматическая генерация документации, валидация, фильтрация и т.д. все так же будут работать, просто используя параметр `response_model`.
+
+///
### Приоритет `response_model`
@@ -95,36 +113,47 @@ FastAPI будет использовать значение `response_model` д
Здесь мы объявили модель `UserIn`, которая хранит пользовательский пароль в открытом виде:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7 9"
- {!> ../../../docs_src/response_model/tutorial002_py310.py!}
- ```
+```Python hl_lines="7 9"
+{!> ../../docs_src/response_model/tutorial002_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9 11"
- {!> ../../../docs_src/response_model/tutorial002.py!}
- ```
+//// tab | Python 3.8+
-!!! info "Информация"
- Чтобы использовать `EmailStr`, прежде необходимо установить `email_validator`.
- Используйте `pip install email-validator`
- или `pip install pydantic[email]`.
+```Python hl_lines="9 11"
+{!> ../../docs_src/response_model/tutorial002.py!}
+```
+
+////
+
+/// info | "Информация"
+
+Чтобы использовать `EmailStr`, прежде необходимо установить `email-validator`.
+Используйте `pip install email-validator`
+или `pip install pydantic[email]`.
+
+///
Далее мы используем нашу модель в аннотациях типа как для аргумента функции, так и для выходного значения:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="16"
- {!> ../../../docs_src/response_model/tutorial002_py310.py!}
- ```
+```Python hl_lines="16"
+{!> ../../docs_src/response_model/tutorial002_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="18"
- {!> ../../../docs_src/response_model/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="18"
+{!> ../../docs_src/response_model/tutorial002.py!}
+```
+
+////
Теперь всякий раз, когда клиент создает пользователя с паролем, API будет возвращать его пароль в ответе.
@@ -132,52 +161,67 @@ FastAPI будет использовать значение `response_model` д
Но что если мы захотим использовать эту модель для какой-либо другой *операции пути*? Мы можем, сами того не желая, отправить пароль любому другому пользователю.
-!!! danger "Осторожно"
- Никогда не храните пароли пользователей в открытом виде, а также никогда не возвращайте их в ответе, как в примере выше. В противном случае - убедитесь, что вы хорошо продумали и учли все возможные риски такого подхода и вам известно, что вы делаете.
+/// danger | "Осторожно"
+
+Никогда не храните пароли пользователей в открытом виде, а также никогда не возвращайте их в ответе, как в примере выше. В противном случае - убедитесь, что вы хорошо продумали и учли все возможные риски такого подхода и вам известно, что вы делаете.
+
+///
## Создание модели для ответа
Вместо этого мы можем создать входную модель, хранящую пароль в открытом виде и выходную модель без пароля:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9 11 16"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
+```Python hl_lines="9 11 16"
+{!> ../../docs_src/response_model/tutorial003_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9 11 16"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="9 11 16"
+{!> ../../docs_src/response_model/tutorial003.py!}
+```
+
+////
В таком случае, даже несмотря на то, что наша *функция операции пути* возвращает тот же самый объект пользователя с паролем, полученным на вход:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
+```Python hl_lines="24"
+{!> ../../docs_src/response_model/tutorial003_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="24"
+{!> ../../docs_src/response_model/tutorial003.py!}
+```
+
+////
...мы указали в `response_model` модель `UserOut`, в которой отсутствует поле, содержащее пароль - и он будет исключен из ответа:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
+```Python hl_lines="22"
+{!> ../../docs_src/response_model/tutorial003_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="22"
+{!> ../../docs_src/response_model/tutorial003.py!}
+```
+
+////
Таким образом **FastAPI** позаботится о фильтрации ответа и исключит из него всё, что не указано в выходной модели (при помощи Pydantic).
@@ -201,17 +245,21 @@ FastAPI будет использовать значение `response_model` д
И в таких случаях мы можем использовать классы и наследование, чтобы пользоваться преимуществами **аннотаций типов** и получать более полную статическую проверку типов. Но при этом все так же получать **фильтрацию ответа** от FastAPI.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7-10 13-14 18"
- {!> ../../../docs_src/response_model/tutorial003_01_py310.py!}
- ```
+```Python hl_lines="7-10 13-14 18"
+{!> ../../docs_src/response_model/tutorial003_01_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9-13 15-16 20"
- {!> ../../../docs_src/response_model/tutorial003_01.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="9-13 15-16 20"
+{!> ../../docs_src/response_model/tutorial003_01.py!}
+```
+
+////
Таким образом, мы получаем поддержку редактора кода и mypy в части типов, сохраняя при этом фильтрацию данных от FastAPI.
@@ -254,7 +302,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!}
```
Это поддерживается FastAPI по-умолчанию, т.к. аннотация проставлена в классе (или подклассе) `Response`.
@@ -266,7 +314,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма
Вы также можете указать подкласс `Response` в аннотации типа:
```Python hl_lines="8-9"
-{!> ../../../docs_src/response_model/tutorial003_03.py!}
+{!> ../../docs_src/response_model/tutorial003_03.py!}
```
Это сработает, потому что `RedirectResponse` является подклассом `Response` и FastAPI автоматически обработает этот простейший случай.
@@ -277,17 +325,21 @@ FastAPI совместно с Pydantic выполнит некоторую ма
То же самое произошло бы, если бы у вас было что-то вроде Union различных типов и один или несколько из них не являлись бы допустимыми типами для Pydantic. Например, такой вариант приведет к ошибке 💥:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="8"
- {!> ../../../docs_src/response_model/tutorial003_04_py310.py!}
- ```
+```Python hl_lines="8"
+{!> ../../docs_src/response_model/tutorial003_04_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/response_model/tutorial003_04.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="10"
+{!> ../../docs_src/response_model/tutorial003_04.py!}
+```
+
+////
...такой код вызовет ошибку, потому что в аннотации указан неподдерживаемый Pydantic тип. А также этот тип не является классом или подклассом `Response`.
@@ -299,17 +351,21 @@ FastAPI совместно с Pydantic выполнит некоторую ма
В таком случае, вы можете отключить генерацию модели ответа, указав `response_model=None`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7"
- {!> ../../../docs_src/response_model/tutorial003_05_py310.py!}
- ```
+```Python hl_lines="7"
+{!> ../../docs_src/response_model/tutorial003_05_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/response_model/tutorial003_05.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../docs_src/response_model/tutorial003_05.py!}
+```
+
+////
Тогда FastAPI не станет генерировать модель ответа и вы сможете сохранить такую аннотацию типа, которая вам требуется, никак не влияя на работу FastAPI. 🤓
@@ -317,23 +373,29 @@ FastAPI совместно с Pydantic выполнит некоторую ма
Модель ответа может иметь значения по умолчанию, например:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9 11-12"
- {!> ../../../docs_src/response_model/tutorial004_py310.py!}
- ```
+```Python hl_lines="9 11-12"
+{!> ../../docs_src/response_model/tutorial004_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="11 13-14"
- {!> ../../../docs_src/response_model/tutorial004_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="11 13-14"
+{!> ../../docs_src/response_model/tutorial004_py39.py!}
+```
- ```Python hl_lines="11 13-14"
- {!> ../../../docs_src/response_model/tutorial004.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="11 13-14"
+{!> ../../docs_src/response_model/tutorial004.py!}
+```
+
+////
* `description: Union[str, None] = None` (или `str | None = None` в Python 3.10), где `None` является значением по умолчанию.
* `tax: float = 10.5`, где `10.5` является значением по умолчанию.
@@ -347,23 +409,29 @@ FastAPI совместно с Pydantic выполнит некоторую ма
Установите для *декоратора операции пути* параметр `response_model_exclude_unset=True`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial004_py310.py!}
- ```
+```Python hl_lines="22"
+{!> ../../docs_src/response_model/tutorial004_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial004_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="24"
+{!> ../../docs_src/response_model/tutorial004_py39.py!}
+```
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial004.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="24"
+{!> ../../docs_src/response_model/tutorial004.py!}
+```
+
+////
и тогда значения по умолчанию не будут включены в ответ. В нем будут только те поля, значения которых фактически были установлены.
@@ -376,16 +444,22 @@ FastAPI совместно с Pydantic выполнит некоторую ма
}
```
-!!! info "Информация"
- "Под капотом" FastAPI использует метод `.dict()` у объектов моделей Pydantic с параметром `exclude_unset`, чтобы достичь такого эффекта.
+/// info | "Информация"
-!!! info "Информация"
- Вы также можете использовать:
+"Под капотом" FastAPI использует метод `.dict()` у объектов моделей Pydantic с параметром `exclude_unset`, чтобы достичь такого эффекта.
- * `response_model_exclude_defaults=True`
- * `response_model_exclude_none=True`
+///
- как описано в документации Pydantic для параметров `exclude_defaults` и `exclude_none`.
+/// info | "Информация"
+
+Вы также можете использовать:
+
+* `response_model_exclude_defaults=True`
+* `response_model_exclude_none=True`
+
+как описано в документации Pydantic для параметров `exclude_defaults` и `exclude_none`.
+
+///
#### Если значение поля отличается от значения по-умолчанию
@@ -420,10 +494,13 @@ FastAPI достаточно умен (на самом деле, это засл
И поэтому, они также будут включены в JSON ответа.
-!!! tip "Подсказка"
- Значением по умолчанию может быть что угодно, не только `None`.
+/// tip | "Подсказка"
- Им может быть и список (`[]`), значение 10.5 типа `float`, и т.п.
+Значением по умолчанию может быть что угодно, не только `None`.
+
+Им может быть и список (`[]`), значение 10.5 типа `float`, и т.п.
+
+///
### `response_model_include` и `response_model_exclude`
@@ -433,45 +510,59 @@ FastAPI достаточно умен (на самом деле, это засл
Это можно использовать как быстрый способ исключить данные из ответа, не создавая отдельную модель Pydantic.
-!!! tip "Подсказка"
- Но по-прежнему рекомендуется следовать изложенным выше советам и использовать несколько моделей вместо данных параметров.
+/// tip | "Подсказка"
- Потому как JSON схема OpenAPI, генерируемая вашим приложением (а также документация) все еще будет содержать все поля, даже если вы использовали `response_model_include` или `response_model_exclude` и исключили некоторые атрибуты.
+Но по-прежнему рекомендуется следовать изложенным выше советам и использовать несколько моделей вместо данных параметров.
- То же самое применимо к параметру `response_model_by_alias`.
+Потому как JSON схема OpenAPI, генерируемая вашим приложением (а также документация) все еще будет содержать все поля, даже если вы использовали `response_model_include` или `response_model_exclude` и исключили некоторые атрибуты.
-=== "Python 3.10+"
+То же самое применимо к параметру `response_model_by_alias`.
- ```Python hl_lines="29 35"
- {!> ../../../docs_src/response_model/tutorial005_py310.py!}
- ```
+///
-=== "Python 3.8+"
+//// tab | Python 3.10+
- ```Python hl_lines="31 37"
- {!> ../../../docs_src/response_model/tutorial005.py!}
- ```
+```Python hl_lines="29 35"
+{!> ../../docs_src/response_model/tutorial005_py310.py!}
+```
-!!! tip "Подсказка"
- При помощи кода `{"name","description"}` создается объект множества (`set`) с двумя строковыми значениями.
+////
- Того же самого можно достичь используя `set(["name", "description"])`.
+//// tab | Python 3.8+
+
+```Python hl_lines="31 37"
+{!> ../../docs_src/response_model/tutorial005.py!}
+```
+
+////
+
+/// tip | "Подсказка"
+
+При помощи кода `{"name","description"}` создается объект множества (`set`) с двумя строковыми значениями.
+
+Того же самого можно достичь используя `set(["name", "description"])`.
+
+///
#### Что если использовать `list` вместо `set`?
Если вы забыли про `set` и использовали структуру `list` или `tuple`, FastAPI автоматически преобразует этот объект в `set`, чтобы обеспечить корректную работу:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="29 35"
- {!> ../../../docs_src/response_model/tutorial006_py310.py!}
- ```
+```Python hl_lines="29 35"
+{!> ../../docs_src/response_model/tutorial006_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="31 37"
- {!> ../../../docs_src/response_model/tutorial006.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="31 37"
+{!> ../../docs_src/response_model/tutorial006.py!}
+```
+
+////
## Резюме
diff --git a/docs/ru/docs/tutorial/response-status-code.md b/docs/ru/docs/tutorial/response-status-code.md
index b2f9b7704..48808bea7 100644
--- a/docs/ru/docs/tutorial/response-status-code.md
+++ b/docs/ru/docs/tutorial/response-status-code.md
@@ -9,16 +9,22 @@
* и других.
```Python hl_lines="6"
-{!../../../docs_src/response_status_code/tutorial001.py!}
+{!../../docs_src/response_status_code/tutorial001.py!}
```
-!!! note "Примечание"
- Обратите внимание, что `status_code` является атрибутом метода-декоратора (`get`, `post` и т.д.), а не *функции-обработчика пути* в отличие от всех остальных параметров и тела запроса.
+/// note | "Примечание"
+
+Обратите внимание, что `status_code` является атрибутом метода-декоратора (`get`, `post` и т.д.), а не *функции-обработчика пути* в отличие от всех остальных параметров и тела запроса.
+
+///
Параметр `status_code` принимает число, обозначающее HTTP код статуса ответа.
-!!! info "Информация"
- В качестве значения параметра `status_code` также может использоваться `IntEnum`, например, из библиотеки `http.HTTPStatus` в Python.
+/// info | "Информация"
+
+В качестве значения параметра `status_code` также может использоваться `IntEnum`, например, из библиотеки `http.HTTPStatus` в Python.
+
+///
Это позволит:
@@ -27,15 +33,21 @@
-!!! note "Примечание"
- Некоторые коды статуса ответа (см. следующий раздел) указывают на то, что ответ не имеет тела.
+/// note | "Примечание"
- FastAPI знает об этом и создаст документацию OpenAPI, в которой будет указано, что тело ответа отсутствует.
+Некоторые коды статуса ответа (см. следующий раздел) указывают на то, что ответ не имеет тела.
+
+FastAPI знает об этом и создаст документацию OpenAPI, в которой будет указано, что тело ответа отсутствует.
+
+///
## Об HTTP кодах статуса ответа
-!!! note "Примечание"
- Если вы уже знаете, что представляют собой HTTP коды статуса ответа, можете перейти к следующему разделу.
+/// note | "Примечание"
+
+Если вы уже знаете, что представляют собой HTTP коды статуса ответа, можете перейти к следующему разделу.
+
+///
В протоколе HTTP числовой код состояния из 3 цифр отправляется как часть ответа.
@@ -54,15 +66,18 @@
* Для общих ошибок со стороны клиента можно просто использовать код `400`.
* `5XX` – статус-коды, сообщающие о серверной ошибке. Они почти никогда не используются разработчиками напрямую. Когда что-то идет не так в какой-то части кода вашего приложения или на сервере, он автоматически вернёт один из 5XX кодов.
-!!! tip "Подсказка"
- Чтобы узнать больше о HTTP кодах статуса и о том, для чего каждый из них предназначен, ознакомьтесь с документацией MDN об HTTP кодах статуса ответа.
+/// tip | "Подсказка"
+
+Чтобы узнать больше о HTTP кодах статуса и о том, для чего каждый из них предназначен, ознакомьтесь с документацией MDN об HTTP кодах статуса ответа.
+
+///
## Краткие обозначения для запоминания названий кодов
Рассмотрим предыдущий пример еще раз:
```Python hl_lines="6"
-{!../../../docs_src/response_status_code/tutorial001.py!}
+{!../../docs_src/response_status_code/tutorial001.py!}
```
`201` – это код статуса "Создано".
@@ -72,17 +87,20 @@
Для удобства вы можете использовать переменные из `fastapi.status`.
```Python hl_lines="1 6"
-{!../../../docs_src/response_status_code/tutorial002.py!}
+{!../../docs_src/response_status_code/tutorial002.py!}
```
Они содержат те же числовые значения, но позволяют использовать подсказки редактора для выбора кода статуса:
-!!! note "Технические детали"
- Вы также можете использовать `from starlette import status` вместо `from fastapi import status`.
+/// note | "Технические детали"
- **FastAPI** позволяет использовать как `starlette.status`, так и `fastapi.status` исключительно для удобства разработчиков. Но поставляется fastapi.status непосредственно из Starlette.
+Вы также можете использовать `from starlette import status` вместо `from fastapi import status`.
+
+**FastAPI** позволяет использовать как `starlette.status`, так и `fastapi.status` исключительно для удобства разработчиков. Но поставляется fastapi.status непосредственно из Starlette.
+
+///
## Изменение кода статуса по умолчанию
diff --git a/docs/ru/docs/tutorial/schema-extra-example.md b/docs/ru/docs/tutorial/schema-extra-example.md
index e1011805a..daa264afc 100644
--- a/docs/ru/docs/tutorial/schema-extra-example.md
+++ b/docs/ru/docs/tutorial/schema-extra-example.md
@@ -8,24 +8,31 @@
Вы можете объявить ключ `example` для модели Pydantic, используя класс `Config` и переменную `schema_extra`, как описано в Pydantic документации: Настройка схемы:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="13-21"
- {!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!}
- ```
+```Python hl_lines="13-21"
+{!> ../../docs_src/schema_extra_example/tutorial001_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="15-23"
- {!> ../../../docs_src/schema_extra_example/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="15-23"
+{!> ../../docs_src/schema_extra_example/tutorial001.py!}
+```
+
+////
Эта дополнительная информация будет включена в **JSON Schema** выходных данных для этой модели, и она будет использоваться в документации к API.
-!!! tip Подсказка
- Вы можете использовать тот же метод для расширения JSON-схемы и добавления своей собственной дополнительной информации.
+/// tip | Подсказка
- Например, вы можете использовать это для добавления дополнительной информации для пользовательского интерфейса в вашем веб-приложении и т.д.
+Вы можете использовать тот же метод для расширения JSON-схемы и добавления своей собственной дополнительной информации.
+
+Например, вы можете использовать это для добавления дополнительной информации для пользовательского интерфейса в вашем веб-приложении и т.д.
+
+///
## Дополнительные аргументы поля `Field`
@@ -33,20 +40,27 @@
Вы можете использовать это, чтобы добавить аргумент `example` для каждого поля:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="2 8-11"
- {!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!}
- ```
+```Python hl_lines="2 8-11"
+{!> ../../docs_src/schema_extra_example/tutorial002_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="4 10-13"
- {!> ../../../docs_src/schema_extra_example/tutorial002.py!}
- ```
+//// tab | Python 3.8+
-!!! warning Внимание
- Имейте в виду, что эти дополнительные переданные аргументы не добавляют никакой валидации, только дополнительную информацию для документации.
+```Python hl_lines="4 10-13"
+{!> ../../docs_src/schema_extra_example/tutorial002.py!}
+```
+
+////
+
+/// warning | Внимание
+
+Имейте в виду, что эти дополнительные переданные аргументы не добавляют никакой валидации, только дополнительную информацию для документации.
+
+///
## Использование `example` и `examples` в OpenAPI
@@ -66,41 +80,57 @@
Здесь мы передаём аргумент `example`, как пример данных ожидаемых в параметре `Body()`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="22-27"
- {!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!}
- ```
+```Python hl_lines="22-27"
+{!> ../../docs_src/schema_extra_example/tutorial003_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="22-27"
- {!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="22-27"
+{!> ../../docs_src/schema_extra_example/tutorial003_an_py39.py!}
+```
- ```Python hl_lines="23-28"
- {!> ../../../docs_src/schema_extra_example/tutorial003_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip Заметка
- Рекомендуется использовать версию с `Annotated`, если это возможно.
+```Python hl_lines="23-28"
+{!> ../../docs_src/schema_extra_example/tutorial003_an.py!}
+```
- ```Python hl_lines="18-23"
- {!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip Заметка
- Рекомендуется использовать версию с `Annotated`, если это возможно.
+/// tip | Заметка
- ```Python hl_lines="20-25"
- {!> ../../../docs_src/schema_extra_example/tutorial003.py!}
- ```
+Рекомендуется использовать версию с `Annotated`, если это возможно.
+
+///
+
+```Python hl_lines="18-23"
+{!> ../../docs_src/schema_extra_example/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | Заметка
+
+Рекомендуется использовать версию с `Annotated`, если это возможно.
+
+///
+
+```Python hl_lines="20-25"
+{!> ../../docs_src/schema_extra_example/tutorial003.py!}
+```
+
+////
### Аргумент "example" в UI документации
@@ -121,41 +151,57 @@
* `value`: Это конкретный пример, который отображается, например, в виде типа `dict`.
* `externalValue`: альтернатива параметру `value`, URL-адрес, указывающий на пример. Хотя это может не поддерживаться таким же количеством инструментов разработки и тестирования API, как параметр `value`.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="23-49"
- {!> ../../../docs_src/schema_extra_example/tutorial004_an_py310.py!}
- ```
+```Python hl_lines="23-49"
+{!> ../../docs_src/schema_extra_example/tutorial004_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="23-49"
- {!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="23-49"
+{!> ../../docs_src/schema_extra_example/tutorial004_an_py39.py!}
+```
- ```Python hl_lines="24-50"
- {!> ../../../docs_src/schema_extra_example/tutorial004_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip Заметка
- Рекомендуется использовать версию с `Annotated`, если это возможно.
+```Python hl_lines="24-50"
+{!> ../../docs_src/schema_extra_example/tutorial004_an.py!}
+```
- ```Python hl_lines="19-45"
- {!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip Заметка
- Рекомендуется использовать версию с `Annotated`, если это возможно.
+/// tip | Заметка
- ```Python hl_lines="21-47"
- {!> ../../../docs_src/schema_extra_example/tutorial004.py!}
- ```
+Рекомендуется использовать версию с `Annotated`, если это возможно.
+
+///
+
+```Python hl_lines="19-45"
+{!> ../../docs_src/schema_extra_example/tutorial004_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | Заметка
+
+Рекомендуется использовать версию с `Annotated`, если это возможно.
+
+///
+
+```Python hl_lines="21-47"
+{!> ../../docs_src/schema_extra_example/tutorial004.py!}
+```
+
+////
### Аргумент "examples" в UI документации
@@ -165,10 +211,13 @@
## Технические Детали
-!!! warning Внимание
- Эти технические детали относятся к стандартам **JSON Schema** и **OpenAPI**.
+/// warning | Внимание
- Если предложенные выше идеи уже работают для вас, возможно этого будет достаточно и эти детали вам не потребуются, можете спокойно их пропустить.
+Эти технические детали относятся к стандартам **JSON Schema** и **OpenAPI**.
+
+Если предложенные выше идеи уже работают для вас, возможно этого будет достаточно и эти детали вам не потребуются, можете спокойно их пропустить.
+
+///
Когда вы добавляете пример внутрь модели Pydantic, используя `schema_extra` или `Field(example="something")`, этот пример добавляется в **JSON Schema** для данной модели Pydantic.
diff --git a/docs/ru/docs/tutorial/security/first-steps.md b/docs/ru/docs/tutorial/security/first-steps.md
index fdeccc01a..c98ce2c60 100644
--- a/docs/ru/docs/tutorial/security/first-steps.md
+++ b/docs/ru/docs/tutorial/security/first-steps.md
@@ -20,36 +20,47 @@
Скопируйте пример в файл `main.py`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python
- {!> ../../../docs_src/security/tutorial001_an_py39.py!}
- ```
+```Python
+{!> ../../docs_src/security/tutorial001_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python
- {!> ../../../docs_src/security/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ без Annotated"
+```Python
+{!> ../../docs_src/security/tutorial001_an.py!}
+```
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+////
- ```Python
- {!> ../../../docs_src/security/tutorial001.py!}
- ```
+//// tab | Python 3.8+ без Annotated
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python
+{!> ../../docs_src/security/tutorial001.py!}
+```
+
+////
## Запуск
-!!! info "Дополнительная информация"
- Вначале, установите библиотеку `python-multipart`.
+/// info | "Дополнительная информация"
- А именно: `pip install python-multipart`.
+Вначале, установите библиотеку `python-multipart`.
- Это связано с тем, что **OAuth2** использует "данные формы" для передачи `имени пользователя` и `пароля`.
+А именно: `pip install python-multipart`.
+
+Это связано с тем, что **OAuth2** использует "данные формы" для передачи `имени пользователя` и `пароля`.
+
+///
Запустите ваш сервер:
@@ -71,17 +82,23 @@ $ uvicorn main:app --reload
-!!! check "Кнопка авторизации!"
- У вас уже появилась новая кнопка "Authorize".
+/// check | "Кнопка авторизации!"
- А у *операции пути* теперь появился маленький замочек в правом верхнем углу, на который можно нажать.
+У вас уже появилась новая кнопка "Authorize".
+
+А у *операции пути* теперь появился маленький замочек в правом верхнем углу, на который можно нажать.
+
+///
При нажатии на нее появляется небольшая форма авторизации, в которую нужно ввести `имя пользователя` и `пароль` (и другие необязательные поля):
-!!! note "Технические детали"
- Неважно, что вы введете в форму, она пока не будет работать. Но мы к этому еще придем.
+/// note | "Технические детали"
+
+Неважно, что вы введете в форму, она пока не будет работать. Но мы к этому еще придем.
+
+///
Конечно, это не фронтенд для конечных пользователей, но это отличный автоматический инструмент для интерактивного документирования всех ваших API.
@@ -123,51 +140,69 @@ OAuth2 был разработан для того, чтобы бэкэнд ил
В данном примере мы будем использовать **OAuth2**, с аутентификацией по паролю, используя токен **Bearer**. Для этого мы используем класс `OAuth2PasswordBearer`.
-!!! info "Дополнительная информация"
- Токен "bearer" - не единственный вариант, но для нашего случая он является наилучшим.
+/// info | "Дополнительная информация"
- И это может быть лучшим вариантом для большинства случаев использования, если только вы не являетесь экспертом в области OAuth2 и точно знаете, почему вам лучше подходит какой-то другой вариант.
+Токен "bearer" - не единственный вариант, но для нашего случая он является наилучшим.
- В этом случае **FastAPI** также предоставляет инструменты для его реализации.
+И это может быть лучшим вариантом для большинства случаев использования, если только вы не являетесь экспертом в области OAuth2 и точно знаете, почему вам лучше подходит какой-то другой вариант.
+
+В этом случае **FastAPI** также предоставляет инструменты для его реализации.
+
+///
При создании экземпляра класса `OAuth2PasswordBearer` мы передаем в него параметр `tokenUrl`. Этот параметр содержит URL, который клиент (фронтенд, работающий в браузере пользователя) будет использовать для отправки `имени пользователя` и `пароля` с целью получения токена.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="8"
- {!> ../../../docs_src/security/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="8"
+{!> ../../docs_src/security/tutorial001_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="7"
- {!> ../../../docs_src/security/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ без Annotated"
+```Python hl_lines="7"
+{!> ../../docs_src/security/tutorial001_an.py!}
+```
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+////
- ```Python hl_lines="6"
- {!> ../../../docs_src/security/tutorial001.py!}
- ```
+//// tab | Python 3.8+ без Annotated
-!!! tip "Подсказка"
- Здесь `tokenUrl="token"` ссылается на относительный URL `token`, который мы еще не создали. Поскольку это относительный URL, он эквивалентен `./token`.
+/// tip | "Подсказка"
- Поскольку мы используем относительный URL, если ваш API расположен по адресу `https://example.com/`, то он будет ссылаться на `https://example.com/token`. Если же ваш API расположен по адресу `https://example.com/api/v1/`, то он будет ссылаться на `https://example.com/api/v1/token`.
+Предпочтительнее использовать версию с аннотацией, если это возможно.
- Использование относительного URL важно для того, чтобы ваше приложение продолжало работать даже в таких сложных случаях, как оно находится [за прокси-сервером](../../advanced/behind-a-proxy.md){.internal-link target=_blank}.
+///
+
+```Python hl_lines="6"
+{!> ../../docs_src/security/tutorial001.py!}
+```
+
+////
+
+/// tip | "Подсказка"
+
+Здесь `tokenUrl="token"` ссылается на относительный URL `token`, который мы еще не создали. Поскольку это относительный URL, он эквивалентен `./token`.
+
+Поскольку мы используем относительный URL, если ваш API расположен по адресу `https://example.com/`, то он будет ссылаться на `https://example.com/token`. Если же ваш API расположен по адресу `https://example.com/api/v1/`, то он будет ссылаться на `https://example.com/api/v1/token`.
+
+Использование относительного URL важно для того, чтобы ваше приложение продолжало работать даже в таких сложных случаях, как оно находится [за прокси-сервером](../../advanced/behind-a-proxy.md){.internal-link target=_blank}.
+
+///
Этот параметр не создает конечную точку / *операцию пути*, а объявляет, что URL `/token` будет таким, который клиент должен использовать для получения токена. Эта информация используется в OpenAPI, а затем в интерактивных системах документации API.
Вскоре мы создадим и саму операцию пути.
-!!! info "Дополнительная информация"
- Если вы очень строгий "питонист", то вам может не понравиться стиль названия параметра `tokenUrl` вместо `token_url`.
+/// info | "Дополнительная информация"
- Это связано с тем, что тут используется то же имя, что и в спецификации OpenAPI. Таким образом, если вам необходимо более подробно изучить какую-либо из этих схем безопасности, вы можете просто использовать копирование/вставку, чтобы найти дополнительную информацию о ней.
+Если вы очень строгий "питонист", то вам может не понравиться стиль названия параметра `tokenUrl` вместо `token_url`.
+
+Это связано с тем, что тут используется то же имя, что и в спецификации OpenAPI. Таким образом, если вам необходимо более подробно изучить какую-либо из этих схем безопасности, вы можете просто использовать копирование/вставку, чтобы найти дополнительную информацию о ней.
+
+///
Переменная `oauth2_scheme` является экземпляром `OAuth2PasswordBearer`, но она также является "вызываемой".
@@ -183,35 +218,47 @@ oauth2_scheme(some, parameters)
Теперь вы можете передать ваш `oauth2_scheme` в зависимость с помощью `Depends`.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="12"
- {!> ../../../docs_src/security/tutorial001_an_py39.py!}
- ```
+```Python hl_lines="12"
+{!> ../../docs_src/security/tutorial001_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="11"
- {!> ../../../docs_src/security/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ без Annotated"
+```Python hl_lines="11"
+{!> ../../docs_src/security/tutorial001_an.py!}
+```
- !!! tip "Подсказка"
- Предпочтительнее использовать версию с аннотацией, если это возможно.
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/security/tutorial001.py!}
- ```
+//// tab | Python 3.8+ без Annotated
+
+/// tip | "Подсказка"
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="10"
+{!> ../../docs_src/security/tutorial001.py!}
+```
+
+////
Эта зависимость будет предоставлять `строку`, которая присваивается параметру `token` в *функции операции пути*.
**FastAPI** будет знать, что он может использовать эту зависимость для определения "схемы безопасности" в схеме OpenAPI (и автоматической документации по API).
-!!! info "Технические детали"
- **FastAPI** будет знать, что он может использовать класс `OAuth2PasswordBearer` (объявленный в зависимости) для определения схемы безопасности в OpenAPI, поскольку он наследуется от `fastapi.security.oauth2.OAuth2`, который, в свою очередь, наследуется от `fastapi.security.base.SecurityBase`.
+/// info | "Технические детали"
- Все утилиты безопасности, интегрируемые в OpenAPI (и автоматическая документация по API), наследуются от `SecurityBase`, поэтому **FastAPI** может знать, как интегрировать их в OpenAPI.
+**FastAPI** будет знать, что он может использовать класс `OAuth2PasswordBearer` (объявленный в зависимости) для определения схемы безопасности в OpenAPI, поскольку он наследуется от `fastapi.security.oauth2.OAuth2`, который, в свою очередь, наследуется от `fastapi.security.base.SecurityBase`.
+
+Все утилиты безопасности, интегрируемые в OpenAPI (и автоматическая документация по API), наследуются от `SecurityBase`, поэтому **FastAPI** может знать, как интегрировать их в OpenAPI.
+
+///
## Что он делает
diff --git a/docs/ru/docs/tutorial/security/index.md b/docs/ru/docs/tutorial/security/index.md
index d5fe4e76f..bd512fde3 100644
--- a/docs/ru/docs/tutorial/security/index.md
+++ b/docs/ru/docs/tutorial/security/index.md
@@ -32,9 +32,11 @@ OAuth2 включает в себя способы аутентификации
OAuth2 не указывает, как шифровать сообщение, он ожидает, что ваше приложение будет обслуживаться по протоколу HTTPS.
-!!! tip "Подсказка"
- В разделе **Развертывание** вы увидите [как настроить протокол HTTPS бесплатно, используя Traefik и Let's Encrypt.](https://fastapi.tiangolo.com/ru/deployment/https/)
+/// tip | "Подсказка"
+В разделе **Развертывание** вы увидите [как настроить протокол HTTPS бесплатно, используя Traefik и Let's Encrypt.](https://fastapi.tiangolo.com/ru/deployment/https/)
+
+///
## OpenID Connect
@@ -87,10 +89,13 @@ OpenAPI может использовать следующие схемы авт
* Это автоматическое обнаружение определено в спецификации OpenID Connect.
-!!! tip "Подсказка"
- Интеграция сторонних сервисов для аутентификации/авторизации таких как Google, Facebook, Twitter, GitHub и т.д. осуществляется достаточно легко.
+/// tip | "Подсказка"
- Самой сложной проблемой является создание такого провайдера аутентификации/авторизации, но **FastAPI** предоставляет вам инструменты, позволяющие легко это сделать, выполняя при этом всю тяжелую работу за вас.
+Интеграция сторонних сервисов для аутентификации/авторизации таких как Google, Facebook, Twitter, GitHub и т.д. осуществляется достаточно легко.
+
+Самой сложной проблемой является создание такого провайдера аутентификации/авторизации, но **FastAPI** предоставляет вам инструменты, позволяющие легко это сделать, выполняя при этом всю тяжелую работу за вас.
+
+///
## Преимущества **FastAPI**
diff --git a/docs/ru/docs/tutorial/static-files.md b/docs/ru/docs/tutorial/static-files.md
index afe2075d9..4734554f3 100644
--- a/docs/ru/docs/tutorial/static-files.md
+++ b/docs/ru/docs/tutorial/static-files.md
@@ -8,13 +8,16 @@
* "Примонтируйте" экземпляр `StaticFiles()` с указанием определенной директории.
```Python hl_lines="2 6"
-{!../../../docs_src/static_files/tutorial001.py!}
+{!../../docs_src/static_files/tutorial001.py!}
```
-!!! note "Технические детали"
- Вы также можете использовать `from starlette.staticfiles import StaticFiles`.
+/// note | "Технические детали"
- **FastAPI** предоставляет `starlette.staticfiles` под псевдонимом `fastapi.staticfiles`, просто для вашего удобства, как разработчика. Но на самом деле это берётся напрямую из библиотеки Starlette.
+Вы также можете использовать `from starlette.staticfiles import StaticFiles`.
+
+**FastAPI** предоставляет `starlette.staticfiles` под псевдонимом `fastapi.staticfiles`, просто для вашего удобства, как разработчика. Но на самом деле это берётся напрямую из библиотеки Starlette.
+
+///
### Что такое "Монтирование"
diff --git a/docs/ru/docs/tutorial/testing.md b/docs/ru/docs/tutorial/testing.md
index 4772660df..ae045bbbe 100644
--- a/docs/ru/docs/tutorial/testing.md
+++ b/docs/ru/docs/tutorial/testing.md
@@ -8,10 +8,13 @@
## Использование класса `TestClient`
-!!! info "Информация"
- Для использования класса `TestClient` необходимо установить библиотеку `httpx`.
+/// info | "Информация"
- Например, так: `pip install httpx`.
+Для использования класса `TestClient` необходимо установить библиотеку `httpx`.
+
+Например, так: `pip install httpx`.
+
+///
Импортируйте `TestClient`.
@@ -24,23 +27,32 @@
Напишите простое утверждение с `assert` дабы проверить истинность Python-выражения (это тоже стандарт `pytest`).
```Python hl_lines="2 12 15-18"
-{!../../../docs_src/app_testing/tutorial001.py!}
+{!../../docs_src/app_testing/tutorial001.py!}
```
-!!! tip "Подсказка"
- Обратите внимание, что тестирующая функция является обычной `def`, а не асинхронной `async def`.
+/// tip | "Подсказка"
- И вызов клиента также осуществляется без `await`.
+Обратите внимание, что тестирующая функция является обычной `def`, а не асинхронной `async def`.
- Это позволяет вам использовать `pytest` без лишних усложнений.
+И вызов клиента также осуществляется без `await`.
-!!! note "Технические детали"
- Также можно написать `from starlette.testclient import TestClient`.
+Это позволяет вам использовать `pytest` без лишних усложнений.
- **FastAPI** предоставляет тот же самый `starlette.testclient` как `fastapi.testclient`. Это всего лишь небольшое удобство для Вас, как разработчика.
+///
-!!! tip "Подсказка"
- Если для тестирования Вам, помимо запросов к приложению FastAPI, необходимо вызывать асинхронные функции (например, для подключения к базе данных с помощью асинхронного драйвера), то ознакомьтесь со страницей [Асинхронное тестирование](../advanced/async-tests.md){.internal-link target=_blank} в расширенном руководстве.
+/// note | "Технические детали"
+
+Также можно написать `from starlette.testclient import TestClient`.
+
+**FastAPI** предоставляет тот же самый `starlette.testclient` как `fastapi.testclient`. Это всего лишь небольшое удобство для Вас, как разработчика.
+
+///
+
+/// tip | "Подсказка"
+
+Если для тестирования Вам, помимо запросов к приложению FastAPI, необходимо вызывать асинхронные функции (например, для подключения к базе данных с помощью асинхронного драйвера), то ознакомьтесь со страницей [Асинхронное тестирование](../advanced/async-tests.md){.internal-link target=_blank} в расширенном руководстве.
+
+///
## Разделение тестов и приложения
@@ -63,7 +75,7 @@
```Python
-{!../../../docs_src/app_testing/main.py!}
+{!../../docs_src/app_testing/main.py!}
```
### Файл тестов
@@ -81,7 +93,7 @@
Так как оба файла находятся в одной директории, для импорта объекта приложения из файла `main` в файл `test_main` Вы можете использовать относительный импорт:
```Python hl_lines="3"
-{!../../../docs_src/app_testing/test_main.py!}
+{!../../docs_src/app_testing/test_main.py!}
```
...и писать дальше тесты, как и раньше.
@@ -110,48 +122,64 @@
Обе *операции пути* требуют наличия в запросе заголовка `X-Token`.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python
- {!> ../../../docs_src/app_testing/app_b_an_py310/main.py!}
- ```
+```Python
+{!> ../../docs_src/app_testing/app_b_an_py310/main.py!}
+```
-=== "Python 3.9+"
+////
- ```Python
- {!> ../../../docs_src/app_testing/app_b_an_py39/main.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python
+{!> ../../docs_src/app_testing/app_b_an_py39/main.py!}
+```
- ```Python
- {!> ../../../docs_src/app_testing/app_b_an/main.py!}
- ```
+////
-=== "Python 3.10+ без Annotated"
+//// tab | Python 3.8+
- !!! tip "Подсказка"
- По возможности используйте версию с `Annotated`.
+```Python
+{!> ../../docs_src/app_testing/app_b_an/main.py!}
+```
- ```Python
- {!> ../../../docs_src/app_testing/app_b_py310/main.py!}
- ```
+////
-=== "Python 3.8+ без Annotated"
+//// tab | Python 3.10+ без Annotated
- !!! tip "Подсказка"
- По возможности используйте версию с `Annotated`.
+/// tip | "Подсказка"
- ```Python
- {!> ../../../docs_src/app_testing/app_b/main.py!}
- ```
+По возможности используйте версию с `Annotated`.
+
+///
+
+```Python
+{!> ../../docs_src/app_testing/app_b_py310/main.py!}
+```
+
+////
+
+//// tab | Python 3.8+ без Annotated
+
+/// tip | "Подсказка"
+
+По возможности используйте версию с `Annotated`.
+
+///
+
+```Python
+{!> ../../docs_src/app_testing/app_b/main.py!}
+```
+
+////
### Расширенный файл тестов
Теперь обновим файл `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.
@@ -168,10 +196,13 @@
Для получения дополнительной информации о передаче данных на бэкенд с помощью `httpx` или `TestClient` ознакомьтесь с документацией HTTPX.
-!!! info "Информация"
- Обратите внимание, что `TestClient` принимает данные, которые можно конвертировать в JSON, но не модели Pydantic.
+/// info | "Информация"
- Если в Ваших тестах есть модели Pydantic и Вы хотите отправить их в тестируемое приложение, то можете использовать функцию `jsonable_encoder`, описанную на странице [Кодировщик совместимый с JSON](encoder.md){.internal-link target=_blank}.
+Обратите внимание, что `TestClient` принимает данные, которые можно конвертировать в JSON, но не модели Pydantic.
+
+Если в Ваших тестах есть модели Pydantic и Вы хотите отправить их в тестируемое приложение, то можете использовать функцию `jsonable_encoder`, описанную на странице [Кодировщик совместимый с JSON](encoder.md){.internal-link target=_blank}.
+
+///
## Запуск тестов
diff --git a/docs/tr/docs/advanced/index.md b/docs/tr/docs/advanced/index.md
index c0a566d12..6c057162e 100644
--- a/docs/tr/docs/advanced/index.md
+++ b/docs/tr/docs/advanced/index.md
@@ -6,10 +6,13 @@
İlerleyen bölümlerde diğer seçenekler, konfigürasyonlar ve ek özellikleri göreceğiz.
-!!! tip "İpucu"
- Sonraki bölümler **mutlaka "gelişmiş" olmak zorunda değildir**.
+/// tip | "İpucu"
- Kullanım şeklinize bağlı olarak, çözümünüz bu bölümlerden birinde olabilir.
+Sonraki bölümler **mutlaka "gelişmiş" olmak zorunda değildir**.
+
+Kullanım şeklinize bağlı olarak, çözümünüz bu bölümlerden birinde olabilir.
+
+///
## Önce Öğreticiyi Okuyun
diff --git a/docs/tr/docs/advanced/security/index.md b/docs/tr/docs/advanced/security/index.md
index 89a431687..227674bd4 100644
--- a/docs/tr/docs/advanced/security/index.md
+++ b/docs/tr/docs/advanced/security/index.md
@@ -4,10 +4,13 @@
[Tutorial - User Guide: Security](../../tutorial/security/index.md){.internal-link target=_blank} sayfasında ele alınanların dışında güvenlikle ilgili bazı ek özellikler vardır.
-!!! tip "İpucu"
- Sonraki bölümler **mutlaka "gelişmiş" olmak zorunda değildir**.
+/// tip | "İpucu"
- Kullanım şeklinize bağlı olarak, çözümünüz bu bölümlerden birinde olabilir.
+Sonraki bölümler **mutlaka "gelişmiş" olmak zorunda değildir**.
+
+Kullanım şeklinize bağlı olarak, çözümünüz bu bölümlerden birinde olabilir.
+
+///
## Önce Öğreticiyi Okuyun
diff --git a/docs/tr/docs/advanced/testing-websockets.md b/docs/tr/docs/advanced/testing-websockets.md
index cdd5b7ae5..aa8a040d0 100644
--- a/docs/tr/docs/advanced/testing-websockets.md
+++ b/docs/tr/docs/advanced/testing-websockets.md
@@ -5,8 +5,11 @@ 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!}
```
-!!! note "Not"
- Daha fazla detay için Starlette'in Websockets'i Test Etmek dokümantasyonunu inceleyin.
+/// 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 54a6f20e2..bc8da16df 100644
--- a/docs/tr/docs/advanced/wsgi.md
+++ b/docs/tr/docs/advanced/wsgi.md
@@ -13,7 +13,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!}
```
## Kontrol Edelim
diff --git a/docs/tr/docs/alternatives.md b/docs/tr/docs/alternatives.md
index 462d8b304..bd668ca45 100644
--- a/docs/tr/docs/alternatives.md
+++ b/docs/tr/docs/alternatives.md
@@ -30,11 +30,17 @@ Django REST framework'ü, Django'nun API kabiliyetlerini arttırmak için arka p
**Otomatik API dökümantasyonu**nun ilk örneklerinden biri olduğu için, **FastAPI** arayışına ilham veren ilk fikirlerden biri oldu.
-!!! note "Not"
- Django REST Framework'ü, aynı zamanda **FastAPI**'ın dayandığı Starlette ve Uvicorn'un da yaratıcısı olan Tom Christie tarafından geliştirildi.
+/// note | "Not"
-!!! check "**FastAPI**'a nasıl ilham verdi?"
- Kullanıcılar için otomatik API dökümantasyonu sunan bir web arayüzüne sahip olmalı.
+Django REST Framework'ü, aynı zamanda **FastAPI**'ın dayandığı Starlette ve Uvicorn'un da yaratıcısı olan Tom Christie tarafından geliştirildi.
+
+///
+
+/// check | "**FastAPI**'a nasıl ilham verdi?"
+
+Kullanıcılar için otomatik API dökümantasyonu sunan bir web arayüzüne sahip olmalı.
+
+///
### Flask
@@ -50,10 +56,13 @@ Uygulama parçalarının böyle ayrılıyor oluşu ve istenilen özelliklerle ge
Flask'ın basitliği göz önünde bulundurulduğu zaman, API geliştirmek için iyi bir seçim gibi görünüyordu. Sıradaki şey ise Flask için bir "Django REST Framework"!
-!!! check "**FastAPI**'a nasıl ilham verdi?"
- Gereken araçları ve parçaları birleştirip eşleştirmeyi kolaylaştıracak bir mikro framework olmalı.
+/// check | "**FastAPI**'a nasıl ilham verdi?"
- Basit ve kullanması kolay bir yönlendirme sistemine sahip olmalı.
+Gereken araçları ve parçaları birleştirip eşleştirmeyi kolaylaştıracak bir mikro framework olmalı.
+
+Basit ve kullanması kolay bir yönlendirme sistemine sahip olmalı.
+
+///
### Requests
@@ -89,10 +98,13 @@ def read_url():
`requests.get(...)` ile `@app.get(...)` arasındaki benzerliklere bakın.
-!!! check "**FastAPI**'a nasıl ilham verdi?"
- * Basit ve sezgisel bir API'ya sahip olmalı.
- * HTTP metot isimlerini (işlemlerini) anlaşılır olacak bir şekilde, direkt kullanmalı.
- * Mantıklı varsayılan değerlere ve buna rağmen güçlü bir özelleştirme desteğine sahip olmalı.
+/// check | "**FastAPI**'a nasıl ilham verdi?"
+
+* Basit ve sezgisel bir API'ya sahip olmalı.
+* HTTP metot isimlerini (işlemlerini) anlaşılır olacak bir şekilde, direkt kullanmalı.
+* Mantıklı varsayılan değerlere ve buna rağmen güçlü bir özelleştirme desteğine sahip olmalı.
+
+///
### Swagger / OpenAPI
@@ -106,15 +118,18 @@ Swagger bir noktada Linux Foundation'a verildi ve adı OpenAPI olarak değiştir
İşte bu yüzden versiyon 2.0 hakkında konuşurken "Swagger", versiyon 3 ve üzeri için ise "OpenAPI" adını kullanmak daha yaygın.
-!!! check "**FastAPI**'a nasıl ilham verdi?"
- API spesifikasyonları için özel bir şema yerine bir açık standart benimseyip kullanmalı.
+/// check | "**FastAPI**'a nasıl ilham verdi?"
- Ayrıca standarda bağlı kullanıcı arayüzü araçlarını entegre etmeli:
+API spesifikasyonları için özel bir şema yerine bir açık standart benimseyip kullanmalı.
- * Swagger UI
- * ReDoc
+Ayrıca standarda bağlı kullanıcı arayüzü araçlarını entegre etmeli:
- Yukarıdaki ikisi oldukça popüler ve istikrarlı olduğu için seçildi, ancak hızlı bir araştırma yaparak **FastAPI** ile kullanabileceğiniz pek çok OpenAPI alternatifi arayüz bulabilirsiniz.
+* Swagger UI
+* ReDoc
+
+Yukarıdaki ikisi oldukça popüler ve istikrarlı olduğu için seçildi, ancak hızlı bir araştırma yaparak **FastAPI** ile kullanabileceğiniz pek çok OpenAPI alternatifi arayüz bulabilirsiniz.
+
+///
### Flask REST framework'leri
@@ -132,8 +147,11 @@ Marshmallow bu özellikleri sağlamak için geliştirilmişti. Benim de geçmiş
Ama... Python'un tip belirteçleri gelmeden önce oluşturulmuştu. Yani her şemayı tanımlamak için Marshmallow'un sunduğu spesifik araçları ve sınıfları kullanmanız gerekiyordu.
-!!! check "**FastAPI**'a nasıl ilham verdi?"
- Kod kullanarak otomatik olarak veri tipini ve veri doğrulamayı belirten "şemalar" tanımlamalı.
+/// check | "**FastAPI**'a nasıl ilham verdi?"
+
+Kod kullanarak otomatik olarak veri tipini ve veri doğrulamayı belirten "şemalar" tanımlamalı.
+
+///
### Webargs
@@ -145,11 +163,17 @@ Veri doğrulama için arka planda Marshmallow kullanıyor, hatta aynı geliştir
Webargs da harika bir araç ve onu da geçmişte henüz **FastAPI** yokken çok kullandım.
-!!! info "Bilgi"
- Webargs aynı Marshmallow geliştirileri tarafından oluşturuldu.
+/// info | "Bilgi"
-!!! check "**FastAPI**'a nasıl ilham verdi?"
- Gelen istek verisi için otomatik veri doğrulamaya sahip olmalı.
+Webargs aynı Marshmallow geliştirileri tarafından oluşturuldu.
+
+///
+
+/// check | "**FastAPI**'a nasıl ilham verdi?"
+
+Gelen istek verisi için otomatik veri doğrulamaya sahip olmalı.
+
+///
### APISpec
@@ -167,11 +191,17 @@ Fakat sonrasında yine mikro sözdizimi problemiyle karşılaşıyoruz. Python m
Editör bu konuda pek yardımcı olamaz. Üstelik eğer parametreleri ya da Marshmallow şemalarını değiştirip YAML kodunu güncellemeyi unutursak artık döküman geçerliliğini yitiriyor.
-!!! info "Bilgi"
- APISpec de aynı Marshmallow geliştiricileri tarafından oluşturuldu.
+/// info | "Bilgi"
-!!! check "**FastAPI**'a nasıl ilham verdi?"
- API'lar için açık standart desteği olmalı (OpenAPI gibi).
+APISpec de aynı Marshmallow geliştiricileri tarafından oluşturuldu.
+
+///
+
+/// check | "**FastAPI**'a nasıl ilham verdi?"
+
+API'lar için açık standart desteği olmalı (OpenAPI gibi).
+
+///
### Flask-apispec
@@ -193,11 +223,17 @@ Bunu kullanmak, bir kaç NestJS (and Angular)
@@ -213,24 +249,33 @@ Ama TypeScript verileri kod JavaScript'e derlendikten sonra korunmadığından,
İç içe geçen derin modelleri pek iyi işleyemiyor. Yani eğer istekteki JSON gövdesi derin bir JSON objesiyse düzgün bir şekilde dökümante edilip doğrulanamıyor.
-!!! check "**FastAPI**'a nasıl ilham oldu?"
- Güzel bir editör desteği için Python tiplerini kullanmalı.
+/// check | "**FastAPI**'a nasıl ilham oldu?"
- Güçlü bir bağımlılık enjeksiyon sistemine sahip olmalı. Kod tekrarını minimuma indirecek bir yol bulmalı.
+Güzel bir editör desteği için Python tiplerini kullanmalı.
+
+Güçlü bir bağımlılık enjeksiyon sistemine sahip olmalı. Kod tekrarını minimuma indirecek bir yol bulmalı.
+
+///
### Sanic
Sanic, `asyncio`'ya dayanan son derece hızlı Python kütüphanelerinden biriydi. Flask'a epey benzeyecek şekilde geliştirilmişti.
-!!! note "Teknik detaylar"
- İçerisinde standart Python `asyncio` döngüsü yerine `uvloop` kullanıldı. Hızının asıl kaynağı buydu.
+/// note | "Teknik detaylar"
- Uvicorn ve Starlette'e ilham kaynağı olduğu oldukça açık, şu anda ikisi de açık karşılaştırmalarda Sanicten daha hızlı gözüküyor.
+İçerisinde standart Python `asyncio` döngüsü yerine `uvloop` kullanıldı. Hızının asıl kaynağı buydu.
-!!! check "**FastAPI**'a nasıl ilham oldu?"
- Uçuk performans sağlayacak bir yol bulmalı.
+Uvicorn ve Starlette'e ilham kaynağı olduğu oldukça açık, şu anda ikisi de açık karşılaştırmalarda Sanicten daha hızlı gözüküyor.
- Tam da bu yüzden **FastAPI** Starlette'e dayanıyor, çünkü Starlette şu anda kullanılabilir en hızlı framework. (üçüncü parti karşılaştırmalı testlerine göre)
+///
+
+/// check | "**FastAPI**'a nasıl ilham oldu?"
+
+Uçuk performans sağlayacak bir yol bulmalı.
+
+Tam da bu yüzden **FastAPI** Starlette'e dayanıyor, çünkü Starlette şu anda kullanılabilir en hızlı framework. (üçüncü parti karşılaştırmalı testlerine göre)
+
+///
### Falcon
@@ -240,12 +285,15 @@ Falcon ise bir diğer yüksek performanslı Python framework'ü. Minimal olacak
Yani veri doğrulama, veri dönüştürme ve dökümantasyonun hepsi kodda yer almalı, otomatik halledemiyoruz. Ya da Falcon üzerine bir framework olarak uygulanmaları gerekiyor, aynı Hug'da olduğu gibi. Bu ayrım Falcon'un tasarımından esinlenen, istek ve cevap objelerini parametre olarak işleyen diğer kütüphanelerde de yer alıyor.
-!!! check "**FastAPI**'a nasıl ilham oldu?"
- Harika bir performans'a sahip olmanın yollarını bulmalı.
+/// check | "**FastAPI**'a nasıl ilham oldu?"
- Hug ile birlikte (Hug zaten Falcon'a dayandığından) **FastAPI**'ın fonksiyonlarda `cevap` parametresi belirtmesinde ilham kaynağı oldu.
+Harika bir performans'a sahip olmanın yollarını bulmalı.
- FastAPI'da opsiyonel olmasına rağmen, daha çok header'lar, çerezler ve alternatif durum kodları belirlemede kullanılıyor.
+Hug ile birlikte (Hug zaten Falcon'a dayandığından) **FastAPI**'ın fonksiyonlarda `cevap` parametresi belirtmesinde ilham kaynağı oldu.
+
+FastAPI'da opsiyonel olmasına rağmen, daha çok header'lar, çerezler ve alternatif durum kodları belirlemede kullanılıyor.
+
+///
### Molten
@@ -263,10 +311,13 @@ Biraz daha detaylı ayarlamalara gerek duyuyor. Ayrıca Yol'lar fonksiyonun üstünde endpoint'i işleyen dekoratörler yerine farklı yerlerde tanımlanan fonksiyonlarla belirlenir. Bu Flask (ve Starlette) yerine daha çok Django'nun yaklaşımına daha yakın bir metot. Bu, kodda nispeten birbiriyle sıkı ilişkili olan şeyleri ayırmaya sebep oluyor.
-!!! check "**FastAPI**'a nasıl ilham oldu?"
- Model özelliklerinin "standart" değerlerini kullanarak veri tipleri için ekstra veri doğrulama koşulları tanımlamalı. Bu editör desteğini geliştiriyor ve daha önceden Pydantic'te yoktu.
+/// check | "**FastAPI**'a nasıl ilham oldu?"
- Bu aslında Pydantic'in de aynı doğrulama stiline geçmesinde ilham kaynağı oldu. Şu anda bütün bu özellikler Pydantic'in yapısında yer alıyor.
+Model özelliklerinin "standart" değerlerini kullanarak veri tipleri için ekstra veri doğrulama koşulları tanımlamalı. Bu editör desteğini geliştiriyor ve daha önceden Pydantic'te yoktu.
+
+Bu aslında Pydantic'in de aynı doğrulama stiline geçmesinde ilham kaynağı oldu. Şu anda bütün bu özellikler Pydantic'in yapısında yer alıyor.
+
+///
### Hug
@@ -282,15 +333,21 @@ Ayrıca ilginç ve çok rastlanmayan bir özelliği vardı: aynı framework'ü k
Senkron çalışan Python web framework'lerinin standardına (WSGI) dayandığından dolayı Websocket'leri ve diğer şeyleri işleyemiyor, ancak yine de yüksek performansa sahip.
-!!! info "Bilgi"
- Hug, Python dosyalarında bulunan dahil etme satırlarını otomatik olarak sıralayan harika bir araç olan `isort`'un geliştiricisi Timothy Crosley tarafından geliştirildi.
+/// info | "Bilgi"
-!!! check "**FastAPI**'a nasıl ilham oldu?"
- Hug, APIStar'ın çeşitli kısımlarında esin kaynağı oldu ve APIStar'la birlikte en umut verici bulduğum araçlardan biriydi.
+Hug, Python dosyalarında bulunan dahil etme satırlarını otomatik olarak sıralayan harika bir araç olan `isort`'un geliştiricisi Timothy Crosley tarafından geliştirildi.
- **FastAPI**, Python tip belirteçlerini kullanarak parametre belirlemede ve API'ı otomatık tanımlayan bir şema üretmede de Hug'a esinlendi.
+///
- **FastAPI**'ın header ve çerez tanımlamak için fonksiyonlarda `response` parametresini belirtmesinde de Hug'dan ilham alındı.
+/// check | "**FastAPI**'a nasıl ilham oldu?"
+
+Hug, APIStar'ın çeşitli kısımlarında esin kaynağı oldu ve APIStar'la birlikte en umut verici bulduğum araçlardan biriydi.
+
+**FastAPI**, Python tip belirteçlerini kullanarak parametre belirlemede ve API'ı otomatık tanımlayan bir şema üretmede de Hug'a esinlendi.
+
+**FastAPI**'ın header ve çerez tanımlamak için fonksiyonlarda `response` parametresini belirtmesinde de Hug'dan ilham alındı.
+
+///
### APIStar (<= 0.5)
@@ -316,23 +373,29 @@ Geliştiricinin Starlette'e odaklanması gerekince proje de artık bir API web f
Artık APIStar, OpenAPI özelliklerini doğrulamak için bir dizi araç sunan bir proje haline geldi.
-!!! info "Bilgi"
- APIStar, aşağıdaki projeleri de üreten Tom Christie tarafından geliştirildi:
+/// info | "Bilgi"
- * Django REST Framework
- * **FastAPI**'ın da dayandığı Starlette
- * Starlette ve **FastAPI** tarafından da kullanılan Uvicorn
+APIStar, aşağıdaki projeleri de üreten Tom Christie tarafından geliştirildi:
-!!! check "**FastAPI**'a nasıl ilham oldu?"
- Var oldu.
+* Django REST Framework
+* **FastAPI**'ın da dayandığı Starlette
+* Starlette ve **FastAPI** tarafından da kullanılan Uvicorn
- Aynı Python veri tipleriyle birden fazla şeyi belirleme (veri doğrulama, veri dönüştürme ve dökümantasyon), bir yandan da harika bir editör desteği sunma, benim muhteşem bulduğum bir fikirdi.
+///
- Uzunca bir süre boyunca benzer bir framework arayıp pek çok farklı alternatifi denedikten sonra, APIStar en iyi seçenekti.
+/// check | "**FastAPI**'a nasıl ilham oldu?"
- Sonra APIStar bir sunucu olmayı bıraktı ve Starlette oluşturuldu. Starlette, böyle bir sunucu sistemi için daha iyi bir temel sunuyordu. Bu da **FastAPI**'ın son esin kaynağıydı.
+Var oldu.
- Ben bu önceki araçlardan öğrendiklerime dayanarak **FastAPI**'ın özelliklerini arttırıp geliştiriyor, tip desteği sistemi ve diğer kısımları iyileştiriyorum ancak yine de **FastAPI**'ı APIStar'ın "ruhani varisi" olarak görüyorum.
+Aynı Python veri tipleriyle birden fazla şeyi belirleme (veri doğrulama, veri dönüştürme ve dökümantasyon), bir yandan da harika bir editör desteği sunma, benim muhteşem bulduğum bir fikirdi.
+
+Uzunca bir süre boyunca benzer bir framework arayıp pek çok farklı alternatifi denedikten sonra, APIStar en iyi seçenekti.
+
+Sonra APIStar bir sunucu olmayı bıraktı ve Starlette oluşturuldu. Starlette, böyle bir sunucu sistemi için daha iyi bir temel sunuyordu. Bu da **FastAPI**'ın son esin kaynağıydı.
+
+Ben bu önceki araçlardan öğrendiklerime dayanarak **FastAPI**'ın özelliklerini arttırıp geliştiriyor, tip desteği sistemi ve diğer kısımları iyileştiriyorum ancak yine de **FastAPI**'ı APIStar'ın "ruhani varisi" olarak görüyorum.
+
+///
## **FastAPI** Tarafından Kullanılanlar
@@ -344,10 +407,13 @@ Tip belirteçleri kullanıyor olması onu aşırı sezgisel yapıyor.
Marshmallow ile karşılaştırılabilir. Ancak karşılaştırmalarda Marshmallowdan daha hızlı görünüyor. Aynı Python tip belirteçlerine dayanıyor ve editör desteği de harika.
-!!! check "**FastAPI** nerede kullanıyor?"
- Bütün veri doğrulama, veri dönüştürme ve JSON Şemasına bağlı otomatik model dökümantasyonunu halletmek için!
+/// check | "**FastAPI** nerede kullanıyor?"
- **FastAPI** yaptığı her şeyin yanı sıra bu JSON Şema verisini alıp daha sonra OpenAPI'ya yerleştiriyor.
+Bütün veri doğrulama, veri dönüştürme ve JSON Şemasına bağlı otomatik model dökümantasyonunu halletmek için!
+
+**FastAPI** yaptığı her şeyin yanı sıra bu JSON Şema verisini alıp daha sonra OpenAPI'ya yerleştiriyor.
+
+///
### Starlette
@@ -376,18 +442,23 @@ Ancak otomatik veri doğrulama, veri dönüştürme ve dökümantasyon sağlamyo
Bu, **FastAPI**'ın onun üzerine tamamen Python tip belirteçlerine bağlı olarak eklediği (Pydantic ile) ana şeylerden biri. **FastAPI** bunun yanında artı olarak bağımlılık enjeksiyonu sistemi, güvenlik araçları, OpenAPI şema üretimi ve benzeri özellikler de ekliyor.
-!!! note "Teknik Detaylar"
- ASGI, Django'nun ana ekibi tarafından geliştirilen yeni bir "standart". Bir "Python standardı" (PEP) olma sürecinde fakat henüz bir standart değil.
+/// note | "Teknik Detaylar"
- Bununla birlikte, halihazırda birçok araç tarafından bir "standart" olarak kullanılmakta. Bu, Uvicorn'u farklı ASGI sunucularıyla (Daphne veya Hypercorn gibi) değiştirebileceğiniz veya `python-socketio` gibi ASGI ile uyumlu araçları ekleyebileciğiniz için birlikte çalışılabilirliği büyük ölçüde arttırıyor.
+ASGI, Django'nun ana ekibi tarafından geliştirilen yeni bir "standart". Bir "Python standardı" (PEP) olma sürecinde fakat henüz bir standart değil.
-!!! check "**FastAPI** nerede kullanıyor?"
+Bununla birlikte, halihazırda birçok araç tarafından bir "standart" olarak kullanılmakta. Bu, Uvicorn'u farklı ASGI sunucularıyla (Daphne veya Hypercorn gibi) değiştirebileceğiniz veya `python-socketio` gibi ASGI ile uyumlu araçları ekleyebileciğiniz için birlikte çalışılabilirliği büyük ölçüde arttırıyor.
- Tüm temel web kısımlarında üzerine özellikler eklenerek kullanılmakta.
+///
- `FastAPI` sınıfının kendisi direkt olarak `Starlette` sınıfını miras alıyor!
+/// check | "**FastAPI** nerede kullanıyor?"
- Yani, Starlette ile yapabileceğiniz her şeyi, Starlette'in bir nevi güçlendirilmiş hali olan **FastAPI** ile doğrudan yapabilirsiniz.
+Tüm temel web kısımlarında üzerine özellikler eklenerek kullanılmakta.
+
+`FastAPI` sınıfının kendisi direkt olarak `Starlette` sınıfını miras alıyor!
+
+Yani, Starlette ile yapabileceğiniz her şeyi, Starlette'in bir nevi güçlendirilmiş hali olan **FastAPI** ile doğrudan yapabilirsiniz.
+
+///
### Uvicorn
@@ -397,12 +468,15 @@ Bir web framework'ünden ziyade bir sunucudur, yani yollara bağlı yönlendirme
Starlette ve **FastAPI** için tavsiye edilen sunucu Uvicorndur.
-!!! check "**FastAPI** neden tavsiye ediyor?"
- **FastAPI** uygulamalarını çalıştırmak için ana web sunucusu Uvicorn!
+/// check | "**FastAPI** neden tavsiye ediyor?"
- Gunicorn ile birleştirdiğinizde asenkron ve çoklu işlem destekleyen bir sunucu elde ediyorsunuz!
+**FastAPI** uygulamalarını çalıştırmak için ana web sunucusu Uvicorn!
- Daha fazla detay için [Deployment](deployment/index.md){.internal-link target=_blank} bölümünü inceleyebilirsiniz.
+Gunicorn ile birleştirdiğinizde asenkron ve çoklu işlem destekleyen bir sunucu elde ediyorsunuz!
+
+Daha fazla detay için [Deployment](deployment/index.md){.internal-link target=_blank} bölümünü inceleyebilirsiniz.
+
+///
## Karşılaştırma ve Hız
diff --git a/docs/tr/docs/async.md b/docs/tr/docs/async.md
index c7bedffd1..0d463a2f0 100644
--- a/docs/tr/docs/async.md
+++ b/docs/tr/docs/async.md
@@ -21,8 +21,11 @@ async def read_results():
return results
```
-!!! note "Not"
- Sadece `async def` ile tanımlanan fonksiyonlar içinde `await` kullanabilirsiniz.
+/// note | "Not"
+
+Sadece `async def` ile tanımlanan fonksiyonlar içinde `await` kullanabilirsiniz.
+
+///
---
@@ -363,12 +366,15 @@ FastAPI'ye (Starlette aracılığıyla) güç veren ve bu kadar etkileyici bir p
## Çok Teknik Detaylar
-!!! warning
- Muhtemelen burayı atlayabilirsiniz.
+/// warning
- Bunlar, **FastAPI**'nin altta nasıl çalıştığına dair çok teknik ayrıntılardır.
+Muhtemelen burayı atlayabilirsiniz.
- Biraz teknik bilginiz varsa (co-routines, threads, blocking, vb)ve FastAPI'nin "async def" ile normal "def" arasındaki farkı nasıl işlediğini merak ediyorsanız, devam edin.
+Bunlar, **FastAPI**'nin altta nasıl çalıştığına dair çok teknik ayrıntılardır.
+
+Biraz teknik bilginiz varsa (co-routines, threads, blocking, vb)ve FastAPI'nin "async def" ile normal "def" arasındaki farkı nasıl işlediğini merak ediyorsanız, devam edin.
+
+///
### Path fonksiyonu
diff --git a/docs/tr/docs/external-links.md b/docs/tr/docs/external-links.md
deleted file mode 100644
index 209ab922c..000000000
--- a/docs/tr/docs/external-links.md
+++ /dev/null
@@ -1,33 +0,0 @@
-# Harici Bağlantılar ve Makaleler
-
-**FastAPI** sürekli büyüyen harika bir topluluğa sahiptir.
-
-**FastAPI** ile alakalı birçok yazı, makale, araç ve proje bulunmaktadır.
-
-Bunlardan bazılarının tamamlanmamış bir listesi aşağıda bulunmaktadır.
-
-!!! tip "İpucu"
- Eğer **FastAPI** ile alakalı henüz burada listelenmemiş bir makale, proje, araç veya başka bir şeyiniz varsa, bunu eklediğiniz bir Pull Request oluşturabilirsiniz.
-
-{% for section_name, section_content in external_links.items() %}
-
-## {{ section_name }}
-
-{% for lang_name, lang_content in section_content.items() %}
-
-### {{ lang_name }}
-
-{% for item in lang_content %}
-
-* {{ item.title }} by {{ item.author }}.
-
-{% endfor %}
-{% endfor %}
-{% endfor %}
-
-## Projeler
-
-`fastapi` konulu en son GitHub projeleri:
-
-email_validator - email doğrulaması için.
+* email-validator - email doğrulaması için.
* pydantic-settings - ayar yönetimi için.
* pydantic-extra-types - Pydantic ile birlikte kullanılabilecek ek tipler için.
diff --git a/docs/tr/docs/newsletter.md b/docs/tr/docs/newsletter.md
deleted file mode 100644
index 22ca1b1e2..000000000
--- a/docs/tr/docs/newsletter.md
+++ /dev/null
@@ -1,5 +0,0 @@
-# FastAPI ve Arkadaşları Bülteni
-
-
-
-
diff --git a/docs/tr/docs/python-types.md b/docs/tr/docs/python-types.md
index ac3111136..9584a5732 100644
--- a/docs/tr/docs/python-types.md
+++ b/docs/tr/docs/python-types.md
@@ -12,15 +12,18 @@ Bu pythonda tip belirteçleri için **hızlı bir başlangıç / bilgi tazeleme
**FastAPI** kullanmayacak olsanız bile tür belirteçleri hakkında bilgi edinmenizde fayda var.
-!!! note "Not"
- Python uzmanıysanız ve tip belirteçleri ilgili her şeyi zaten biliyorsanız, sonraki bölüme geçin.
+/// note | "Not"
+
+Python uzmanıysanız ve tip belirteçleri ilgili her şeyi zaten biliyorsanız, sonraki bölüme geçin.
+
+///
## Motivasyon
Basit bir örnek ile başlayalım:
```Python
-{!../../../docs_src/python_types/tutorial001.py!}
+{!../../docs_src/python_types/tutorial001.py!}
```
Programın çıktısı:
@@ -36,7 +39,7 @@ Fonksiyon sırayla şunları yapar:
* 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!}
```
### Düzenle
@@ -80,7 +83,7 @@ Bu kadar.
İşte bunlar "tip belirteçleri":
```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial002.py!}
+{!../../docs_src/python_types/tutorial002.py!}
```
Bu, aşağıdaki gibi varsayılan değerleri bildirmekle aynı şey değildir:
@@ -110,7 +113,7 @@ 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!}
```
Editör değişkenlerin tiplerini bildiğinden, yalnızca otomatik tamamlama değil, hata kontrolleri de sağlar:
@@ -120,7 +123,7 @@ 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!}
```
## Tip bildirme
@@ -141,7 +144,7 @@ Yalnızca `str` değil, tüm standart Python tiplerinin bildirebilirsiniz.
* `bytes`
```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial005.py!}
+{!../../docs_src/python_types/tutorial005.py!}
```
### Tip parametreleri ile Generic tipler
@@ -159,7 +162,7 @@ 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!}
```
Değişkenin tipini yine iki nokta üstüste (`:`) ile belirleyin.
@@ -169,13 +172,16 @@ tip olarak `List` kullanın.
Liste, bazı dahili tipleri içeren bir tür olduğundan, bunları köşeli parantez içine alırsınız:
```Python hl_lines="4"
-{!../../../docs_src/python_types/tutorial006.py!}
+{!../../docs_src/python_types/tutorial006.py!}
```
-!!! tip "Ipucu"
- Köşeli parantez içindeki bu dahili tiplere "tip parametreleri" denir.
+/// tip | "Ipucu"
- Bu durumda `str`, `List`e iletilen tür parametresidir.
+Köşeli parantez içindeki bu dahili tiplere "tip parametreleri" denir.
+
+Bu durumda `str`, `List`e iletilen tür parametresidir.
+
+///
Bunun anlamı şudur: "`items` değişkeni bir `list`tir ve bu listedeki öğelerin her biri bir `str`dir".
@@ -194,7 +200,7 @@ 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!}
```
Bu şu anlama geliyor:
@@ -211,7 +217,7 @@ 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!}
```
Bu şu anlama gelir:
@@ -225,7 +231,7 @@ Bu şu anlama gelir:
`Optional` bir değişkenin `str`gibi bir tipi olabileceğini ama isteğe bağlı olarak tipinin `None` olabileceğini belirtir:
```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009.py!}
+{!../../docs_src/python_types/tutorial009.py!}
```
`str` yerine `Optional[str]` kullanmak editorün bu değerin her zaman `str` tipinde değil bazen `None` tipinde de olabileceğini belirtir ve hataları tespit etmemizde yardımcı olur.
@@ -250,13 +256,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!}
```
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!}
```
Ve yine bütün editör desteğini alırsınız:
@@ -278,11 +284,14 @@ Ve ortaya çıkan nesne üzerindeki bütün editör desteğini alırsınız.
Resmi Pydantic dokümanlarından alınmıştır:
```Python
-{!../../../docs_src/python_types/tutorial011.py!}
+{!../../docs_src/python_types/tutorial011.py!}
```
-!!! info
- Daha fazla şey öğrenmek için Pydantic'i takip edin.
+/// info
+
+Daha fazla şey öğrenmek için Pydantic'i takip edin.
+
+///
**FastAPI** tamamen Pydantic'e dayanmaktadır.
@@ -310,5 +319,8 @@ Bütün bunlar kulağa soyut gelebilir. Merak etme. Tüm bunları çalışırken
Önemli olan, standart Python türlerini tek bir yerde kullanarak (daha fazla sınıf, dekoratör vb. eklemek yerine), **FastAPI**'nin bizim için işi yapmasını sağlamak.
-!!! info
- Tüm öğreticiyi zaten okuduysanız ve türler hakkında daha fazla bilgi için geri döndüyseniz, iyi bir kaynak: the "cheat sheet" from `mypy`.
+/// info
+
+Tüm öğreticiyi zaten okuduysanız ve türler hakkında daha fazla bilgi için geri döndüyseniz, iyi bir kaynak: the "cheat sheet" from `mypy`.
+
+///
diff --git a/docs/tr/docs/tutorial/cookie-params.md b/docs/tr/docs/tutorial/cookie-params.md
index 4a66f26eb..895cf9b03 100644
--- a/docs/tr/docs/tutorial/cookie-params.md
+++ b/docs/tr/docs/tutorial/cookie-params.md
@@ -6,41 +6,57 @@
Öncelikle, `Cookie`'yi projenize dahil edin:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="3"
+{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="3"
+{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip "İpucu"
- Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın.
+```Python hl_lines="3"
+{!> ../../docs_src/cookie_params/tutorial001_an.py!}
+```
- ```Python hl_lines="1"
- {!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip "İpucu"
- Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın.
+/// tip | "İpucu"
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001.py!}
- ```
+Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın.
+
+///
+
+```Python hl_lines="1"
+{!> ../../docs_src/cookie_params/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "İpucu"
+
+Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın.
+
+///
+
+```Python hl_lines="3"
+{!> ../../docs_src/cookie_params/tutorial001.py!}
+```
+
+////
## `Cookie` Parametrelerini Tanımlayın
@@ -48,49 +64,71 @@
İlk değer varsayılan değerdir; tüm ekstra doğrulama veya belirteç parametrelerini kullanabilirsiniz:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="9"
+{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/cookie_params/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip "İpucu"
- Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın.
+```Python hl_lines="10"
+{!> ../../docs_src/cookie_params/tutorial001_an.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip "İpucu"
- Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın.
+/// tip | "İpucu"
- ```Python hl_lines="9"
- {!> ../../../docs_src/cookie_params/tutorial001.py!}
- ```
+Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın.
-!!! note "Teknik Detaylar"
- `Cookie` sınıfı `Path` ve `Query` sınıflarının kardeşidir. Diğerleri gibi `Param` sınıfını miras alan bir sınıftır.
+///
- Ancak `fastapi`'dan projenize dahil ettiğiniz `Query`, `Path`, `Cookie` ve diğerleri aslında özel sınıflar döndüren birer fonksiyondur.
+```Python hl_lines="7"
+{!> ../../docs_src/cookie_params/tutorial001_py310.py!}
+```
-!!! info "Bilgi"
- Çerez tanımlamak için `Cookie` sınıfını kullanmanız gerekmektedir, aksi taktirde parametreler sorgu parametreleri olarak yorumlanır.
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "İpucu"
+
+Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın.
+
+///
+
+```Python hl_lines="9"
+{!> ../../docs_src/cookie_params/tutorial001.py!}
+```
+
+////
+
+/// note | "Teknik Detaylar"
+
+`Cookie` sınıfı `Path` ve `Query` sınıflarının kardeşidir. Diğerleri gibi `Param` sınıfını miras alan bir sınıftır.
+
+Ancak `fastapi`'dan projenize dahil ettiğiniz `Query`, `Path`, `Cookie` ve diğerleri aslında özel sınıflar döndüren birer fonksiyondur.
+
+///
+
+/// info | "Bilgi"
+
+Çerez tanımlamak için `Cookie` sınıfını kullanmanız gerekmektedir, aksi taktirde parametreler sorgu parametreleri olarak yorumlanır.
+
+///
## Özet
diff --git a/docs/tr/docs/tutorial/first-steps.md b/docs/tr/docs/tutorial/first-steps.md
index e66f73034..335fcaece 100644
--- a/docs/tr/docs/tutorial/first-steps.md
+++ b/docs/tr/docs/tutorial/first-steps.md
@@ -3,7 +3,7 @@
En sade FastAPI dosyası şu şekilde görünür:
```Python
-{!../../../docs_src/first_steps/tutorial001.py!}
+{!../../docs_src/first_steps/tutorial001.py!}
```
Yukarıdaki içeriği bir `main.py` dosyasına kopyalayalım.
@@ -24,12 +24,15 @@ $ uvicorn main:app --reload
-!!! note "Not"
- `uvicorn main:app` komutunu şu şekilde açıklayabiliriz:
+/// note | "Not"
- * `main`: dosya olan `main.py` (yani Python "modülü").
- * `app`: ise `main.py` dosyasının içerisinde `app = FastAPI()` satırında oluşturduğumuz `FastAPI` nesnesi.
- * `--reload`: kod değişikliklerinin ardından sunucuyu otomatik olarak yeniden başlatır. Bu parameteyi sadece geliştirme aşamasında kullanmalıyız.
+`uvicorn main:app` komutunu şu şekilde açıklayabiliriz:
+
+* `main`: dosya olan `main.py` (yani Python "modülü").
+* `app`: ise `main.py` dosyasının içerisinde `app = FastAPI()` satırında oluşturduğumuz `FastAPI` nesnesi.
+* `--reload`: kod değişikliklerinin ardından sunucuyu otomatik olarak yeniden başlatır. Bu parameteyi sadece geliştirme aşamasında kullanmalıyız.
+
+///
Çıktı olarak şöyle bir satır ile karşılaşacaksınız:
@@ -131,20 +134,23 @@ 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!}
```
`FastAPI`, API'niz için tüm işlevselliği sağlayan bir Python sınıfıdır.
-!!! note "Teknik Detaylar"
- `FastAPI` doğrudan `Starlette`'i miras alan bir sınıftır.
+/// note | "Teknik Detaylar"
- Starlette'in tüm işlevselliğini `FastAPI` ile de kullanabilirsiniz.
+`FastAPI` doğrudan `Starlette`'i miras alan bir sınıftır.
+
+Starlette'in tüm işlevselliğini `FastAPI` ile de kullanabilirsiniz.
+
+///
### Adım 2: Bir `FastAPI` "Örneği" Oluşturalım
```Python hl_lines="3"
-{!../../../docs_src/first_steps/tutorial001.py!}
+{!../../docs_src/first_steps/tutorial001.py!}
```
Burada `app` değişkeni `FastAPI` sınıfının bir örneği olacaktır.
@@ -166,7 +172,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!}
```
Ve bunu `main.py` dosyasına yerleştirirseniz eğer `uvicorn` komutunu şu şekilde çalıştırabilirsiniz:
@@ -199,8 +205,11 @@ https://example.com/items/foo
/items/foo
```
-!!! info "Bilgi"
- "Yol" genellikle "endpoint" veya "route" olarak adlandırılır.
+/// info | "Bilgi"
+
+"Yol" genellikle "endpoint" veya "route" olarak adlandırılır.
+
+///
Bir API oluştururken, "yol", "kaynaklar" ile "endişeleri" ayırmanın ana yöntemidir.
@@ -242,7 +251,7 @@ Biz de onları "**operasyonlar**" olarak adlandıracağız.
#### Bir *Yol Operasyonu Dekoratörü* Tanımlayalım
```Python hl_lines="6"
-{!../../../docs_src/first_steps/tutorial001.py!}
+{!../../docs_src/first_steps/tutorial001.py!}
```
`@app.get("/")` dekoratörü, **FastAPI**'a hemen altındaki fonksiyonun aşağıdaki durumlardan sorumlu olduğunu söyler:
@@ -250,16 +259,19 @@ Biz de onları "**operasyonlar**" olarak adlandıracağız.
* get operasyonu ile
* `/` yoluna gelen istekler
-!!! info "`@decorator` Bilgisi"
- Python'da `@something` sözdizimi "dekoratör" olarak adlandırılır.
+/// info | "`@decorator` Bilgisi"
- Dekoratörler, dekoratif bir şapka gibi (sanırım terim buradan geliyor) fonksiyonların üzerlerine yerleştirilirler.
+Python'da `@something` sözdizimi "dekoratör" olarak adlandırılır.
- Bir "dekoratör" hemen altında bulunan fonksiyonu alır ve o fonksiyon ile bazı işlemler gerçekleştirir.
+Dekoratörler, dekoratif bir şapka gibi (sanırım terim buradan geliyor) fonksiyonların üzerlerine yerleştirilirler.
- Bizim durumumuzda, kullandığımız dekoratör, **FastAPI**'a altındaki fonksiyonun `/` yoluna gelen `get` metodlu isteklerden sorumlu olduğunu söyler.
+Bir "dekoratör" hemen altında bulunan fonksiyonu alır ve o fonksiyon ile bazı işlemler gerçekleştirir.
- Bu bir **yol operasyonu dekoratörüdür**.
+Bizim durumumuzda, kullandığımız dekoratör, **FastAPI**'a altındaki fonksiyonun `/` yoluna gelen `get` metodlu isteklerden sorumlu olduğunu söyler.
+
+Bu bir **yol operasyonu dekoratörüdür**.
+
+///
Ayrıca diğer operasyonları da kullanabilirsiniz:
@@ -274,14 +286,17 @@ Daha az kullanılanları da kullanabilirsiniz:
* `@app.patch()`
* `@app.trace()`
-!!! tip "İpucu"
- Her işlemi (HTTP metod) istediğiniz gibi kullanmakta özgürsünüz.
+/// tip | "İpucu"
- **FastAPI** herhangi bir özel amacı veya anlamı olması konusunda ısrarcı olmaz.
+Her işlemi (HTTP metod) istediğiniz gibi kullanmakta özgürsünüz.
- Buradaki bilgiler bir gereklilik değil, bir kılavuz olarak sunulmaktadır.
+**FastAPI** herhangi bir özel amacı veya anlamı olması konusunda ısrarcı olmaz.
- Mesela GraphQL kullanırkan genelde tüm işlemleri yalnızca `POST` operasyonunu kullanarak gerçekleştirirsiniz.
+Buradaki bilgiler bir gereklilik değil, bir kılavuz olarak sunulmaktadır.
+
+Mesela GraphQL kullanırkan genelde tüm işlemleri yalnızca `POST` operasyonunu kullanarak gerçekleştirirsiniz.
+
+///
### Adım 4: **Yol Operasyonu Fonksiyonunu** Tanımlayın
@@ -292,7 +307,7 @@ Aşağıdaki, bizim **yol operasyonu fonksiyonumuzdur**:
* **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!}
```
Bu bir Python fonksiyonudur.
@@ -306,16 +321,19 @@ 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!}
```
-!!! note "Not"
- Eğer farkı bilmiyorsanız, [Async: *"Aceleniz mi var?"*](../async.md#in-a-hurry){.internal-link target=_blank} sayfasını kontrol edebilirsiniz.
+/// note | "Not"
+
+Eğer farkı bilmiyorsanız, [Async: *"Aceleniz mi var?"*](../async.md#in-a-hurry){.internal-link target=_blank} sayfasını kontrol edebilirsiniz.
+
+///
### Adım 5: İçeriği Geri Döndürün
```Python hl_lines="8"
-{!../../../docs_src/first_steps/tutorial001.py!}
+{!../../docs_src/first_steps/tutorial001.py!}
```
Bir `dict`, `list` veya `str`, `int` gibi tekil değerler döndürebilirsiniz.
diff --git a/docs/tr/docs/tutorial/path-params.md b/docs/tr/docs/tutorial/path-params.md
index c19023645..9017d99ab 100644
--- a/docs/tr/docs/tutorial/path-params.md
+++ b/docs/tr/docs/tutorial/path-params.md
@@ -3,7 +3,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!}
```
Yol parametresi olan `item_id`'nin değeri, fonksiyonunuza `item_id` argümanı olarak aktarılacaktır.
@@ -19,13 +19,16 @@ Eğer bu örneği çalıştırıp Dönüşümü
@@ -35,10 +38,13 @@ Eğer bu örneği çalıştırıp tarayıcınızda "ayrıştırma"POST sayfasını ziyaret edebilirsiniz.
+Ancak form içerisinde dosyalar yer aldığında `multipart/form-data` olarak kodlanır. Bir sonraki bölümde dosyaların işlenmesi hakkında bilgi edineceksiniz.
-!!! warning "Uyarı"
- *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.
+Form kodlama türleri ve form alanları hakkında daha fazla bilgi edinmek istiyorsanız MDN web docs for POST sayfasını ziyaret edebilirsiniz.
- Bu **FastAPI**'ın getirdiği bir kısıtlama değildir, HTTP protokolünün bir parçasıdır.
+///
+
+/// warning | "Uyarı"
+
+*Yol operasyonları* içerisinde birden fazla `Form` parametresi tanımlayabilirsiniz ancak bunlarla birlikte JSON verisi kabul eden `Body` alanları tanımlayamazsınız çünkü bu durumda istek gövdesi `application/json` yerine `application/x-www-form-urlencoded` ile kodlanmış olur.
+
+Bu **FastAPI**'ın getirdiği bir kısıtlama değildir, HTTP protokolünün bir parçasıdır.
+
+///
## Özet
diff --git a/docs/tr/docs/tutorial/static-files.md b/docs/tr/docs/tutorial/static-files.md
index 00c833686..8bff59744 100644
--- a/docs/tr/docs/tutorial/static-files.md
+++ b/docs/tr/docs/tutorial/static-files.md
@@ -8,13 +8,16 @@
* 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!}
```
-!!! note "Teknik Detaylar"
- Projenize dahil etmek için `from starlette.staticfiles import StaticFiles` kullanabilirsiniz.
+/// note | "Teknik Detaylar"
- **FastAPI**, geliştiricilere kolaylık sağlamak amacıyla `starlette.staticfiles`'ı `fastapi.staticfiles` olarak sağlar. Ancak `StaticFiles` sınıfı aslında doğrudan Starlette'den gelir.
+Projenize dahil etmek için `from starlette.staticfiles import StaticFiles` kullanabilirsiniz.
+
+**FastAPI**, geliştiricilere kolaylık sağlamak amacıyla `starlette.staticfiles`'ı `fastapi.staticfiles` olarak sağlar. Ancak `StaticFiles` sınıfı aslında doğrudan Starlette'den gelir.
+
+///
### Bağlama (Mounting) Nedir?
diff --git a/docs/uk/docs/alternatives.md b/docs/uk/docs/alternatives.md
index 16cc0d875..eb48d6be7 100644
--- a/docs/uk/docs/alternatives.md
+++ b/docs/uk/docs/alternatives.md
@@ -30,12 +30,17 @@
Це був один із перших прикладів **автоматичної документації API**, і саме це була одна з перших ідей, яка надихнула на «пошук» **FastAPI**.
-!!! note "Примітка"
- Django REST Framework створив Том Крісті. Той самий творець Starlette і Uvicorn, на яких базується **FastAPI**.
+/// note | "Примітка"
+Django REST Framework створив Том Крісті. Той самий творець Starlette і Uvicorn, на яких базується **FastAPI**.
-!!! check "Надихнуло **FastAPI** на"
- Мати автоматичний веб-інтерфейс документації API.
+///
+
+/// check | "Надихнуло **FastAPI** на"
+
+Мати автоматичний веб-інтерфейс документації API.
+
+///
### Flask
@@ -51,11 +56,13 @@ Flask — це «мікрофреймворк», він не включає ін
Враховуючи простоту Flask, він здавався хорошим підходом для створення API. Наступним, що знайшов, був «Django REST Framework» для Flask.
-!!! check "Надихнуло **FastAPI** на"
- Бути мікрофреймоворком. Зробити легким комбінування та поєднання необхідних інструментів та частин.
+/// check | "Надихнуло **FastAPI** на"
- Мати просту та легку у використанні систему маршрутизації.
+Бути мікрофреймоворком. Зробити легким комбінування та поєднання необхідних інструментів та частин.
+ Мати просту та легку у використанні систему маршрутизації.
+
+///
### Requests
@@ -91,11 +98,13 @@ def read_url():
Зверніть увагу на схожість у `requests.get(...)` і `@app.get(...)`.
-!!! check "Надихнуло **FastAPI** на"
- * Майте простий та інтуїтивно зрозумілий API.
- * Використовуйте імена (операції) методів HTTP безпосередньо, простим та інтуїтивно зрозумілим способом.
- * Розумні параметри за замовчуванням, але потужні налаштування.
+/// check | "Надихнуло **FastAPI** на"
+* Майте простий та інтуїтивно зрозумілий API.
+ * Використовуйте імена (операції) методів HTTP безпосередньо, простим та інтуїтивно зрозумілим способом.
+ * Розумні параметри за замовчуванням, але потужні налаштування.
+
+///
### Swagger / OpenAPI
@@ -109,15 +118,18 @@ def read_url():
Тому, коли говорять про версію 2.0, прийнято говорити «Swagger», а про версію 3+ «OpenAPI».
-!!! check "Надихнуло **FastAPI** на"
- Прийняти і використовувати відкритий стандарт для специфікацій API замість спеціальної схеми.
+/// check | "Надихнуло **FastAPI** на"
- Інтегрувати інструменти інтерфейсу на основі стандартів:
+Прийняти і використовувати відкритий стандарт для специфікацій API замість спеціальної схеми.
- * Інтерфейс Swagger
- * ReDoc
+ Інтегрувати інструменти інтерфейсу на основі стандартів:
- Ці два було обрано через те, що вони досить популярні та стабільні, але, виконавши швидкий пошук, ви можете знайти десятки додаткових альтернативних інтерфейсів для OpenAPI (які можна використовувати з **FastAPI**).
+ * Інтерфейс Swagger
+ * ReDoc
+
+ Ці два було обрано через те, що вони досить популярні та стабільні, але, виконавши швидкий пошук, ви можете знайти десятки додаткових альтернативних інтерфейсів для OpenAPI (які можна використовувати з **FastAPI**).
+
+///
### Фреймворки REST для Flask
@@ -135,8 +147,11 @@ Marshmallow створено для забезпечення цих функці
Але він був створений до того, як існували підказки типу Python. Отже, щоб визначити кожну схему, вам потрібно використовувати спеціальні утиліти та класи, надані Marshmallow.
-!!! check "Надихнуло **FastAPI** на"
- Використовувати код для автоматичного визначення "схем", які надають типи даних і перевірку.
+/// check | "Надихнуло **FastAPI** на"
+
+Використовувати код для автоматичного визначення "схем", які надають типи даних і перевірку.
+
+///
### Webargs
@@ -148,11 +163,17 @@ Webargs — це інструмент, створений, щоб забезпе
Це чудовий інструмент, і я також часто використовував його, перш ніж створити **FastAPI**.
-!!! info "Інформація"
- Webargs був створений тими ж розробниками Marshmallow.
+/// info | "Інформація"
-!!! check "Надихнуло **FastAPI** на"
- Мати автоматичну перевірку даних вхідного запиту.
+Webargs був створений тими ж розробниками Marshmallow.
+
+///
+
+/// check | "Надихнуло **FastAPI** на"
+
+Мати автоматичну перевірку даних вхідного запиту.
+
+///
### APISpec
@@ -172,12 +193,17 @@ Marshmallow і Webargs забезпечують перевірку, аналіз
Редактор тут нічим не може допомогти. І якщо ми змінимо параметри чи схеми Marshmallow і забудемо також змінити цю строку документа YAML, згенерована схема буде застарілою.
-!!! info "Інформація"
- APISpec був створений тими ж розробниками Marshmallow.
+/// info | "Інформація"
+APISpec був створений тими ж розробниками Marshmallow.
-!!! check "Надихнуло **FastAPI** на"
- Підтримувати відкритий стандарт API, OpenAPI.
+///
+
+/// check | "Надихнуло **FastAPI** на"
+
+Підтримувати відкритий стандарт API, OpenAPI.
+
+///
### Flask-apispec
@@ -199,11 +225,17 @@ Marshmallow і Webargs забезпечують перевірку, аналіз
І ці самі генератори повного стеку були основою [**FastAPI** генераторів проектів](project-generation.md){.internal-link target=_blank}.
-!!! info "Інформація"
- Flask-apispec був створений тими ж розробниками Marshmallow.
+/// info | "Інформація"
-!!! check "Надихнуло **FastAPI** на"
- Створення схеми OpenAPI автоматично з того самого коду, який визначає серіалізацію та перевірку.
+Flask-apispec був створений тими ж розробниками Marshmallow.
+
+///
+
+/// check | "Надихнуло **FastAPI** на"
+
+Створення схеми OpenAPI автоматично з того самого коду, який визначає серіалізацію та перевірку.
+
+///
### NestJS (та Angular)
@@ -219,24 +251,33 @@ Marshmallow і Webargs забезпечують перевірку, аналіз
Він не дуже добре обробляє вкладені моделі. Отже, якщо тіло JSON у запиті є об’єктом JSON із внутрішніми полями, які, у свою чергу, є вкладеними об’єктами JSON, його неможливо належним чином задокументувати та перевірити.
-!!! check "Надихнуло **FastAPI** на"
- Використовувати типи Python, щоб мати чудову підтримку редактора.
+/// check | "Надихнуло **FastAPI** на"
- Мати потужну систему впровадження залежностей. Знайдіть спосіб звести до мінімуму повторення коду.
+Використовувати типи Python, щоб мати чудову підтримку редактора.
+
+ Мати потужну систему впровадження залежностей. Знайдіть спосіб звести до мінімуму повторення коду.
+
+///
### Sanic
Це був один із перших надзвичайно швидких фреймворків Python на основі `asyncio`. Він був дуже схожий на Flask.
-!!! note "Технічні деталі"
- Він використовував `uvloop` замість стандартного циклу Python `asyncio`. Ось що зробило його таким швидким.
+/// note | "Технічні деталі"
- Це явно надихнуло Uvicorn і Starlette, які зараз швидші за Sanic у відкритих тестах.
+Він використовував `uvloop` замість стандартного циклу Python `asyncio`. Ось що зробило його таким швидким.
-!!! check "Надихнуло **FastAPI** на"
- Знайти спосіб отримати божевільну продуктивність.
+ Це явно надихнуло Uvicorn і Starlette, які зараз швидші за Sanic у відкритих тестах.
- Ось чому **FastAPI** базується на Starlette, оскільки це найшвидша доступна структура (перевірена тестами сторонніх розробників).
+///
+
+/// check | "Надихнуло **FastAPI** на"
+
+Знайти спосіб отримати божевільну продуктивність.
+
+ Ось чому **FastAPI** базується на Starlette, оскільки це найшвидша доступна структура (перевірена тестами сторонніх розробників).
+
+///
### Falcon
@@ -246,12 +287,15 @@ Falcon — ще один високопродуктивний фреймворк
Таким чином, перевірка даних, серіалізація та документація повинні виконуватися в коді, а не автоматично. Або вони повинні бути реалізовані як фреймворк поверх Falcon, як Hug. Така сама відмінність спостерігається в інших фреймворках, натхненних дизайном Falcon, що мають один об’єкт запиту та один об’єкт відповіді як параметри.
-!!! check "Надихнуло **FastAPI** на"
- Знайти способи отримати чудову продуктивність.
+/// check | "Надихнуло **FastAPI** на"
- Разом із Hug (оскільки Hug базується на Falcon) надихнув **FastAPI** оголосити параметр `response` у функціях.
+Знайти способи отримати чудову продуктивність.
- Хоча у FastAPI це необов’язково, і використовується в основному для встановлення заголовків, файлів cookie та альтернативних кодів стану.
+ Разом із Hug (оскільки Hug базується на Falcon) надихнув **FastAPI** оголосити параметр `response` у функціях.
+
+ Хоча у FastAPI це необов’язково, і використовується в основному для встановлення заголовків, файлів cookie та альтернативних кодів стану.
+
+///
### Molten
@@ -269,10 +313,13 @@ Falcon — ще один високопродуктивний фреймворк
Маршрути оголошуються в одному місці з використанням функцій, оголошених в інших місцях (замість використання декораторів, які можна розмістити безпосередньо поверх функції, яка обробляє кінцеву точку). Це ближче до того, як це робить Django, ніж до Flask (і Starlette). Він розділяє в коді речі, які відносно тісно пов’язані.
-!!! check "Надихнуло **FastAPI** на"
- Визначити додаткові перевірки для типів даних, використовуючи значення "за замовчуванням" атрибутів моделі. Це покращує підтримку редактора, а раніше вона була недоступна в Pydantic.
+/// check | "Надихнуло **FastAPI** на"
- Це фактично надихнуло оновити частини Pydantic, щоб підтримувати той самий стиль оголошення перевірки (всі ці функції вже доступні в Pydantic).
+Визначити додаткові перевірки для типів даних, використовуючи значення "за замовчуванням" атрибутів моделі. Це покращує підтримку редактора, а раніше вона була недоступна в Pydantic.
+
+ Це фактично надихнуло оновити частини Pydantic, щоб підтримувати той самий стиль оголошення перевірки (всі ці функції вже доступні в Pydantic).
+
+///
### Hug
@@ -288,15 +335,21 @@ Hug був одним із перших фреймворків, який реа
Оскільки він заснований на попередньому стандарті для синхронних веб-фреймворків Python (WSGI), він не може працювати з Websockets та іншими речами, хоча він також має високу продуктивність.
-!!! info "Інформація"
- Hug створив Тімоті Крослі, той самий творець `isort`, чудовий інструмент для автоматичного сортування імпорту у файлах Python.
+/// info | "Інформація"
-!!! check "Надихнуло **FastAPI** на"
- Hug надихнув частину APIStar і був одним із найбільш перспективних інструментів, поряд із APIStar.
+Hug створив Тімоті Крослі, той самий творець `isort`, чудовий інструмент для автоматичного сортування імпорту у файлах Python.
- Hug надихнув **FastAPI** на використання підказок типу Python для оголошення параметрів і автоматичного створення схеми, що визначає API.
+///
- Hug надихнув **FastAPI** оголосити параметр `response` у функціях для встановлення заголовків і файлів cookie.
+/// check | "Надихнуло **FastAPI** на"
+
+Hug надихнув частину APIStar і був одним із найбільш перспективних інструментів, поряд із APIStar.
+
+ Hug надихнув **FastAPI** на використання підказок типу Python для оголошення параметрів і автоматичного створення схеми, що визначає API.
+
+ Hug надихнув **FastAPI** оголосити параметр `response` у функціях для встановлення заголовків і файлів cookie.
+
+///
### APIStar (<= 0,5)
@@ -322,21 +375,27 @@ Hug був одним із перших фреймворків, який реа
Тепер APIStar — це набір інструментів для перевірки специфікацій OpenAPI, а не веб-фреймворк.
-!!! info "Інформація"
- APIStar створив Том Крісті. Той самий хлопець, який створив:
+/// info | "Інформація"
- * Django REST Framework
- * Starlette (на якому базується **FastAPI**)
- * Uvicorn (використовується Starlette і **FastAPI**)
+APIStar створив Том Крісті. Той самий хлопець, який створив:
-!!! check "Надихнуло **FastAPI** на"
- Існувати.
+ * Django REST Framework
+ * Starlette (на якому базується **FastAPI**)
+ * Uvicorn (використовується Starlette і **FastAPI**)
- Ідею оголошення кількох речей (перевірки даних, серіалізації та документації) за допомогою тих самих типів Python, які в той же час забезпечували чудову підтримку редактора, я вважав геніальною ідеєю.
+///
- І після тривалого пошуку подібної структури та тестування багатьох різних альтернатив, APIStar став найкращим доступним варіантом.
+/// check | "Надихнуло **FastAPI** на"
- Потім APIStar перестав існувати як сервер, і було створено Starlette, який став новою кращою основою для такої системи. Це стало останнім джерелом натхнення для створення **FastAPI**. Я вважаю **FastAPI** «духовним спадкоємцем» APIStar, удосконалюючи та розширюючи функції, систему введення тексту та інші частини на основі досвіду, отриманого від усіх цих попередніх інструментів.
+Існувати.
+
+ Ідею оголошення кількох речей (перевірки даних, серіалізації та документації) за допомогою тих самих типів Python, які в той же час забезпечували чудову підтримку редактора, я вважав геніальною ідеєю.
+
+ І після тривалого пошуку подібної структури та тестування багатьох різних альтернатив, APIStar став найкращим доступним варіантом.
+
+ Потім APIStar перестав існувати як сервер, і було створено Starlette, який став новою кращою основою для такої системи. Це стало останнім джерелом натхнення для створення **FastAPI**. Я вважаю **FastAPI** «духовним спадкоємцем» APIStar, удосконалюючи та розширюючи функції, систему введення тексту та інші частини на основі досвіду, отриманого від усіх цих попередніх інструментів.
+
+///
## Використовується **FastAPI**
@@ -348,10 +407,13 @@ Pydantic — це бібліотека для визначення переві
Його можна порівняти з Marshmallow. Хоча він швидший за Marshmallow у тестах. Оскільки він базується на тих самих підказках типу Python, підтримка редактора чудова.
-!!! check "**FastAPI** використовує його для"
- Виконання перевірки всіх даних, серіалізації даних і автоматичної документацію моделі (на основі схеми JSON).
+/// check | "**FastAPI** використовує його для"
- Потім **FastAPI** бере ці дані схеми JSON і розміщує їх у OpenAPI, окремо від усіх інших речей, які він робить.
+Виконання перевірки всіх даних, серіалізації даних і автоматичної документацію моделі (на основі схеми JSON).
+
+ Потім **FastAPI** бере ці дані схеми JSON і розміщує їх у OpenAPI, окремо від усіх інших речей, які він робить.
+
+///
### Starlette
@@ -380,17 +442,23 @@ Starlette надає всі основні функції веб-мікрофр
Це одна з головних речей, які **FastAPI** додає зверху, все на основі підказок типу Python (з використанням Pydantic). Це, а також система впровадження залежностей, утиліти безпеки, створення схеми OpenAPI тощо.
-!!! note "Технічні деталі"
- ASGI — це новий «стандарт», який розробляється членами основної команди Django. Це ще не «стандарт Python» (PEP), хоча вони в процесі цього.
+/// note | "Технічні деталі"
- Тим не менш, він уже використовується як «стандарт» кількома інструментами. Це значно покращує сумісність, оскільки ви можете переключити Uvicorn на будь-який інший сервер ASGI (наприклад, Daphne або Hypercorn), або ви можете додати інструменти, сумісні з ASGI, як-от `python-socketio`.
+ASGI — це новий «стандарт», який розробляється членами основної команди Django. Це ще не «стандарт Python» (PEP), хоча вони в процесі цього.
-!!! check "**FastAPI** використовує його для"
- Керування всіма основними веб-частинами. Додавання функцій зверху.
+ Тим не менш, він уже використовується як «стандарт» кількома інструментами. Це значно покращує сумісність, оскільки ви можете переключити Uvicorn на будь-який інший сервер ASGI (наприклад, Daphne або Hypercorn), або ви можете додати інструменти, сумісні з ASGI, як-от `python-socketio`.
- Сам клас `FastAPI` безпосередньо успадковує клас `Starlette`.
+///
- Отже, усе, що ви можете робити зі Starlette, ви можете робити це безпосередньо за допомогою **FastAPI**, оскільки це, по суті, Starlette на стероїдах.
+/// check | "**FastAPI** використовує його для"
+
+Керування всіма основними веб-частинами. Додавання функцій зверху.
+
+ Сам клас `FastAPI` безпосередньо успадковує клас `Starlette`.
+
+ Отже, усе, що ви можете робити зі Starlette, ви можете робити це безпосередньо за допомогою **FastAPI**, оскільки це, по суті, Starlette на стероїдах.
+
+///
### Uvicorn
@@ -400,12 +468,15 @@ Uvicorn — це блискавичний сервер ASGI, побудован
Це рекомендований сервер для Starlette і **FastAPI**.
-!!! check "**FastAPI** рекомендує це як"
- Основний веб-сервер для запуску програм **FastAPI**.
+/// check | "**FastAPI** рекомендує це як"
- Ви можете поєднати його з Gunicorn, щоб мати асинхронний багатопроцесний сервер.
+Основний веб-сервер для запуску програм **FastAPI**.
- Додаткову інформацію див. у розділі [Розгортання](deployment/index.md){.internal-link target=_blank}.
+ Ви можете поєднати його з Gunicorn, щоб мати асинхронний багатопроцесний сервер.
+
+ Додаткову інформацію див. у розділі [Розгортання](deployment/index.md){.internal-link target=_blank}.
+
+///
## Орієнтири та швидкість
diff --git a/docs/uk/docs/fastapi-people.md b/docs/uk/docs/fastapi-people.md
deleted file mode 100644
index c6a6451d8..000000000
--- a/docs/uk/docs/fastapi-people.md
+++ /dev/null
@@ -1,183 +0,0 @@
----
-hide:
- - navigation
----
-
-# Люди FastAPI
-
-FastAPI має дивовижну спільноту, яка вітає людей різного походження.
-
-## Творець – Супроводжувач
-
-Привіт! 👋
-
-Це я:
-
-{% if people %}
-email_validator - для валідації електронної пошти.
+* email-validator - для валідації електронної пошти.
* pydantic-settings - для управління налаштуваннями.
* pydantic-extra-types - для додаткових типів, що можуть бути використані з Pydantic.
diff --git a/docs/uk/docs/python-types.md b/docs/uk/docs/python-types.md
index d0adadff3..573b5372c 100644
--- a/docs/uk/docs/python-types.md
+++ b/docs/uk/docs/python-types.md
@@ -12,15 +12,18 @@ Python підтримує додаткові "підказки типу" ("type
Але навіть якщо ви ніколи не використаєте **FastAPI**, вам буде корисно дізнатись трохи про них.
-!!! note
- Якщо ви експерт у Python і ви вже знаєте усе про анотації типів - перейдіть до наступного розділу.
+/// note
+
+Якщо ви експерт у Python і ви вже знаєте усе про анотації типів - перейдіть до наступного розділу.
+
+///
## Мотивація
Давайте почнемо з простого прикладу:
```Python
-{!../../../docs_src/python_types/tutorial001.py!}
+{!../../docs_src/python_types/tutorial001.py!}
```
Виклик цієї програми виводить:
@@ -36,7 +39,7 @@ John Doe
* Конкатенує їх разом із пробілом по середині.
```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial001.py!}
+{!../../docs_src/python_types/tutorial001.py!}
```
### Редагуйте це
@@ -80,7 +83,7 @@ John Doe
Це "type hints":
```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial002.py!}
+{!../../docs_src/python_types/tutorial002.py!}
```
Це не те саме, що оголошення значень за замовчуванням, як це було б з:
@@ -110,7 +113,7 @@ John Doe
Перевірте цю функцію, вона вже має анотацію типу:
```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial003.py!}
+{!../../docs_src/python_types/tutorial003.py!}
```
Оскільки редактор знає типи змінних, ви не тільки отримаєте автозаповнення, ви також отримаєте перевірку помилок:
@@ -120,7 +123,7 @@ John Doe
Тепер ви знаєте, щоб виправити це, вам потрібно перетворити `age` у строку з допомогою `str(age)`:
```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial004.py!}
+{!../../docs_src/python_types/tutorial004.py!}
```
## Оголошення типів
@@ -141,7 +144,7 @@ John Doe
* `bytes`
```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial005.py!}
+{!../../docs_src/python_types/tutorial005.py!}
```
### Generic-типи з параметрами типів
@@ -164,45 +167,55 @@ John Doe
Наприклад, давайте визначимо змінну, яка буде `list` із `str`.
-=== "Python 3.8 і вище"
+//// tab | Python 3.8 і вище
- З модуля `typing`, імпортуємо `List` (з великої літери `L`):
+З модуля `typing`, імпортуємо `List` (з великої літери `L`):
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial006.py!}
- ```
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial006.py!}
+```
- Оголосимо змінну з тим самим синтаксисом двокрапки (`:`).
+Оголосимо змінну з тим самим синтаксисом двокрапки (`:`).
- Як тип вкажемо `List`, який ви імпортували з `typing`.
+Як тип вкажемо `List`, який ви імпортували з `typing`.
- Оскільки список є типом, який містить деякі внутрішні типи, ви поміщаєте їх у квадратні дужки:
+Оскільки список є типом, який містить деякі внутрішні типи, ви поміщаєте їх у квадратні дужки:
- ```Python hl_lines="4"
- {!> ../../../docs_src/python_types/tutorial006.py!}
- ```
+```Python hl_lines="4"
+{!> ../../docs_src/python_types/tutorial006.py!}
+```
-=== "Python 3.9 і вище"
+////
- Оголосимо змінну з тим самим синтаксисом двокрапки (`:`).
+//// tab | Python 3.9 і вище
- Як тип вкажемо `list`.
+Оголосимо змінну з тим самим синтаксисом двокрапки (`:`).
- Оскільки список є типом, який містить деякі внутрішні типи, ви поміщаєте їх у квадратні дужки:
+Як тип вкажемо `list`.
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial006_py39.py!}
- ```
+Оскільки список є типом, який містить деякі внутрішні типи, ви поміщаєте їх у квадратні дужки:
-!!! info
- Ці внутрішні типи в квадратних дужках називаються "параметрами типу".
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial006_py39.py!}
+```
- У цьому випадку, `str` це параметр типу переданий у `List` (або `list` у Python 3.9 і вище).
+////
+
+/// info
+
+Ці внутрішні типи в квадратних дужках називаються "параметрами типу".
+
+У цьому випадку, `str` це параметр типу переданий у `List` (або `list` у Python 3.9 і вище).
+
+///
Це означає: "змінна `items` це `list`, і кожен з елементів у цьому списку - `str`".
-!!! tip
- Якщо ви використовуєте Python 3.9 і вище, вам не потрібно імпортувати `List` з `typing`, ви можете використовувати натомість тип `list`.
+/// tip
+
+Якщо ви використовуєте Python 3.9 і вище, вам не потрібно імпортувати `List` з `typing`, ви можете використовувати натомість тип `list`.
+
+///
Зробивши це, ваш редактор може надати підтримку навіть під час обробки елементів зі списку:
@@ -218,17 +231,21 @@ John Doe
Ви повинні зробити те ж саме, щоб оголосити `tuple` і `set`:
-=== "Python 3.8 і вище"
+//// tab | Python 3.8 і вище
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial007.py!}
- ```
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial007.py!}
+```
-=== "Python 3.9 і вище"
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial007_py39.py!}
- ```
+//// tab | Python 3.9 і вище
+
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial007_py39.py!}
+```
+
+////
Це означає:
@@ -243,17 +260,21 @@ John Doe
Другий параметр типу для значення у `dict`:
-=== "Python 3.8 і вище"
+//// tab | Python 3.8 і вище
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial008.py!}
- ```
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial008.py!}
+```
-=== "Python 3.9 і вище"
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial008_py39.py!}
- ```
+//// tab | Python 3.9 і вище
+
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial008_py39.py!}
+```
+
+////
Це означає:
@@ -269,17 +290,21 @@ John Doe
У Python 3.10 також є **альтернативний синтаксис**, у якому ви можете розділити можливі типи за допомогою вертикальної смуги (`|`).
-=== "Python 3.8 і вище"
+//// tab | Python 3.8 і вище
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial008b.py!}
- ```
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial008b.py!}
+```
-=== "Python 3.10 і вище"
+////
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial008b_py310.py!}
- ```
+//// tab | Python 3.10 і вище
+
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial008b_py310.py!}
+```
+
+////
В обох випадках це означає, що `item` може бути `int` або `str`.
@@ -290,7 +315,7 @@ John Doe
У Python 3.6 і вище (включаючи Python 3.10) ви можете оголосити його, імпортувавши та використовуючи `Optional` з модуля `typing`.
```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009.py!}
+{!../../docs_src/python_types/tutorial009.py!}
```
Використання `Optional[str]` замість просто `str` дозволить редактору допомогти вам виявити помилки, коли ви могли б вважати, що значенням завжди є `str`, хоча насправді воно також може бути `None`.
@@ -299,69 +324,81 @@ John Doe
Це також означає, що в Python 3.10 ви можете використовувати `Something | None`:
-=== "Python 3.8 і вище"
+//// tab | Python 3.8 і вище
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial009.py!}
- ```
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial009.py!}
+```
-=== "Python 3.8 і вище - альтернатива"
+////
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial009b.py!}
- ```
+//// tab | Python 3.8 і вище - альтернатива
-=== "Python 3.10 і вище"
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial009b.py!}
+```
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial009_py310.py!}
- ```
+////
+
+//// tab | Python 3.10 і вище
+
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial009_py310.py!}
+```
+
+////
#### Generic типи
Ці типи, які приймають параметри типу у квадратних дужках, називаються **Generic types** or **Generics**, наприклад:
-=== "Python 3.8 і вище"
+//// tab | Python 3.8 і вище
- * `List`
- * `Tuple`
- * `Set`
- * `Dict`
- * `Union`
- * `Optional`
- * ...та інші.
+* `List`
+* `Tuple`
+* `Set`
+* `Dict`
+* `Union`
+* `Optional`
+* ...та інші.
-=== "Python 3.9 і вище"
+////
- Ви можете використовувати ті самі вбудовані типи, як generic (з квадратними дужками та типами всередині):
+//// tab | Python 3.9 і вище
- * `list`
- * `tuple`
- * `set`
- * `dict`
+Ви можете використовувати ті самі вбудовані типи, як generic (з квадратними дужками та типами всередині):
- І те саме, що й у Python 3.8, із модуля `typing`:
+* `list`
+* `tuple`
+* `set`
+* `dict`
- * `Union`
- * `Optional`
- * ...та інші.
+І те саме, що й у Python 3.8, із модуля `typing`:
-=== "Python 3.10 і вище"
+* `Union`
+* `Optional`
+* ...та інші.
- Ви можете використовувати ті самі вбудовані типи, як generic (з квадратними дужками та типами всередині):
+////
- * `list`
- * `tuple`
- * `set`
- * `dict`
+//// tab | Python 3.10 і вище
- І те саме, що й у Python 3.8, із модуля `typing`:
+Ви можете використовувати ті самі вбудовані типи, як generic (з квадратними дужками та типами всередині):
- * `Union`
- * `Optional` (так само як у Python 3.8)
- * ...та інші.
+* `list`
+* `tuple`
+* `set`
+* `dict`
- У Python 3.10, як альтернатива використанню `Union` та `Optional`, ви можете використовувати вертикальну смугу (`|`) щоб оголосити об'єднання типів.
+І те саме, що й у Python 3.8, із модуля `typing`:
+
+* `Union`
+* `Optional` (так само як у Python 3.8)
+* ...та інші.
+
+У Python 3.10, як альтернатива використанню `Union` та `Optional`, ви можете використовувати вертикальну смугу (`|`) щоб оголосити об'єднання типів.
+
+////
### Класи як типи
@@ -370,13 +407,13 @@ John Doe
Скажімо, у вас є клас `Person` з імʼям:
```Python hl_lines="1-3"
-{!../../../docs_src/python_types/tutorial010.py!}
+{!../../docs_src/python_types/tutorial010.py!}
```
Потім ви можете оголосити змінну типу `Person`:
```Python hl_lines="6"
-{!../../../docs_src/python_types/tutorial010.py!}
+{!../../docs_src/python_types/tutorial010.py!}
```
І знову ж таки, ви отримуєте всю підтримку редактора:
@@ -397,26 +434,35 @@ John Doe
Приклад з документації Pydantic:
-=== "Python 3.8 і вище"
+//// tab | Python 3.8 і вище
- ```Python
- {!> ../../../docs_src/python_types/tutorial011.py!}
- ```
+```Python
+{!> ../../docs_src/python_types/tutorial011.py!}
+```
-=== "Python 3.9 і вище"
+////
- ```Python
- {!> ../../../docs_src/python_types/tutorial011_py39.py!}
- ```
+//// tab | Python 3.9 і вище
-=== "Python 3.10 і вище"
+```Python
+{!> ../../docs_src/python_types/tutorial011_py39.py!}
+```
- ```Python
- {!> ../../../docs_src/python_types/tutorial011_py310.py!}
- ```
+////
-!!! info
- Щоб дізнатись більше про Pydantic, перегляньте його документацію.
+//// tab | Python 3.10 і вище
+
+```Python
+{!> ../../docs_src/python_types/tutorial011_py310.py!}
+```
+
+////
+
+/// info
+
+Щоб дізнатись більше про Pydantic, перегляньте його документацію.
+
+///
**FastAPI** повністю базується на Pydantic.
@@ -444,5 +490,8 @@ John Doe
Важливо те, що за допомогою стандартних типів Python в одному місці (замість того, щоб додавати більше класів, декораторів тощо), **FastAPI** зробить багато роботи за вас.
-!!! info
- Якщо ви вже пройшли весь навчальний посібник і повернулися, щоб дізнатися більше про типи, ось хороший ресурс "шпаргалка" від `mypy`.
+/// info
+
+Якщо ви вже пройшли весь навчальний посібник і повернулися, щоб дізнатися більше про типи, ось хороший ресурс "шпаргалка" від `mypy`.
+
+///
diff --git a/docs/uk/docs/tutorial/body-fields.md b/docs/uk/docs/tutorial/body-fields.md
index eee993cbe..b1f645932 100644
--- a/docs/uk/docs/tutorial/body-fields.md
+++ b/docs/uk/docs/tutorial/body-fields.md
@@ -6,98 +6,139 @@
Спочатку вам потрібно імпортувати це:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="4"
+{!> ../../docs_src/body_fields/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="4"
+{!> ../../docs_src/body_fields/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Варто користуватись `Annotated` версією, якщо це можливо.
+```Python hl_lines="4"
+{!> ../../docs_src/body_fields/tutorial001_an.py!}
+```
- ```Python hl_lines="2"
- {!> ../../../docs_src/body_fields/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Варто користуватись `Annotated` версією, якщо це можливо.
+/// tip
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001.py!}
- ```
+Варто користуватись `Annotated` версією, якщо це можливо.
-!!! warning
- Зверніть увагу, що `Field` імпортується прямо з `pydantic`, а не з `fastapi`, як всі інші (`Query`, `Path`, `Body` тощо).
+///
+
+```Python hl_lines="2"
+{!> ../../docs_src/body_fields/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Варто користуватись `Annotated` версією, якщо це можливо.
+
+///
+
+```Python hl_lines="4"
+{!> ../../docs_src/body_fields/tutorial001.py!}
+```
+
+////
+
+/// warning
+
+Зверніть увагу, що `Field` імпортується прямо з `pydantic`, а не з `fastapi`, як всі інші (`Query`, `Path`, `Body` тощо).
+
+///
## Оголошення атрибутів моделі
Ви можете використовувати `Field` з атрибутами моделі:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="11-14"
+{!> ../../docs_src/body_fields/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="11-14"
+{!> ../../docs_src/body_fields/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="12-15"
- {!> ../../../docs_src/body_fields/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Варто користуватись `Annotated` версією, якщо це можливо..
+```Python hl_lines="12-15"
+{!> ../../docs_src/body_fields/tutorial001_an.py!}
+```
- ```Python hl_lines="9-12"
- {!> ../../../docs_src/body_fields/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Варто користуватись `Annotated` версією, якщо це можливо..
+/// tip
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001.py!}
- ```
+Варто користуватись `Annotated` версією, якщо це можливо..
+
+///
+
+```Python hl_lines="9-12"
+{!> ../../docs_src/body_fields/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Варто користуватись `Annotated` версією, якщо це можливо..
+
+///
+
+```Python hl_lines="11-14"
+{!> ../../docs_src/body_fields/tutorial001.py!}
+```
+
+////
`Field` працює так само, як `Query`, `Path` і `Body`, у нього такі самі параметри тощо.
-!!! note "Технічні деталі"
- Насправді, `Query`, `Path` та інші, що ви побачите далі, створюють об'єкти підкласів загального класу `Param`, котрий сам є підкласом класу `FieldInfo` з Pydantic.
+/// note | "Технічні деталі"
- І `Field` від Pydantic також повертає екземпляр `FieldInfo`.
+Насправді, `Query`, `Path` та інші, що ви побачите далі, створюють об'єкти підкласів загального класу `Param`, котрий сам є підкласом класу `FieldInfo` з Pydantic.
- `Body` також безпосередньо повертає об'єкти підкласу `FieldInfo`. І є інші підкласи, які ви побачите пізніше, що є підкласами класу Body.
+І `Field` від Pydantic також повертає екземпляр `FieldInfo`.
- Пам'ятайте, що коли ви імпортуєте 'Query', 'Path' та інше з 'fastapi', вони фактично є функціями, які повертають спеціальні класи.
+`Body` також безпосередньо повертає об'єкти підкласу `FieldInfo`. І є інші підкласи, які ви побачите пізніше, що є підкласами класу Body.
-!!! tip
- Зверніть увагу, що кожен атрибут моделі із типом, значенням за замовчуванням та `Field` має ту саму структуру, що й параметр *функції обробки шляху*, з `Field` замість `Path`, `Query` і `Body`.
+Пам'ятайте, що коли ви імпортуєте 'Query', 'Path' та інше з 'fastapi', вони фактично є функціями, які повертають спеціальні класи.
+
+///
+
+/// tip
+
+Зверніть увагу, що кожен атрибут моделі із типом, значенням за замовчуванням та `Field` має ту саму структуру, що й параметр *функції обробки шляху*, з `Field` замість `Path`, `Query` і `Body`.
+
+///
## Додавання додаткової інформації
@@ -105,9 +146,12 @@
Ви дізнаєтеся більше про додавання додаткової інформації пізніше у документації, коли вивчатимете визначення прикладів.
-!!! warning
- Додаткові ключі, передані в `Field`, також будуть присутні у згенерованій схемі OpenAPI для вашого додатка.
- Оскільки ці ключі не обов'язково можуть бути частиною специфікації OpenAPI, деякі інструменти OpenAPI, наприклад, [OpenAPI валідатор](https://validator.swagger.io/), можуть не працювати з вашою згенерованою схемою.
+/// warning
+
+Додаткові ключі, передані в `Field`, також будуть присутні у згенерованій схемі OpenAPI для вашого додатка.
+Оскільки ці ключі не обов'язково можуть бути частиною специфікації OpenAPI, деякі інструменти OpenAPI, наприклад, [OpenAPI валідатор](https://validator.swagger.io/), можуть не працювати з вашою згенерованою схемою.
+
+///
## Підсумок
diff --git a/docs/uk/docs/tutorial/body.md b/docs/uk/docs/tutorial/body.md
index 11e94e929..1e4188831 100644
--- a/docs/uk/docs/tutorial/body.md
+++ b/docs/uk/docs/tutorial/body.md
@@ -8,28 +8,35 @@
Щоб оголосити тіло **запиту**, ви використовуєте Pydantic моделі з усією їх потужністю та перевагами.
-!!! info
- Щоб надіслати дані, ви повинні використовувати один із: `POST` (більш поширений), `PUT`, `DELETE` або `PATCH`.
+/// info
- Надсилання тіла із запитом `GET` має невизначену поведінку в специфікаціях, проте воно підтримується FastAPI лише для дуже складних/екстремальних випадків використання.
+Щоб надіслати дані, ви повинні використовувати один із: `POST` (більш поширений), `PUT`, `DELETE` або `PATCH`.
- Оскільки це не рекомендується, інтерактивна документація з Swagger UI не відображатиме документацію для тіла запиту під час використання `GET`, і проксі-сервери в середині можуть не підтримувати її.
+Надсилання тіла із запитом `GET` має невизначену поведінку в специфікаціях, проте воно підтримується FastAPI лише для дуже складних/екстремальних випадків використання.
+
+Оскільки це не рекомендується, інтерактивна документація з Swagger UI не відображатиме документацію для тіла запиту під час використання `GET`, і проксі-сервери в середині можуть не підтримувати її.
+
+///
## Імпортуйте `BaseModel` від Pydantic
Спочатку вам потрібно імпортувати `BaseModel` з `pydantic`:
-=== "Python 3.8 і вище"
+//// tab | Python 3.8 і вище
- ```Python hl_lines="4"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
+```Python hl_lines="4"
+{!> ../../docs_src/body/tutorial001.py!}
+```
-=== "Python 3.10 і вище"
+////
- ```Python hl_lines="2"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
+//// tab | Python 3.10 і вище
+
+```Python hl_lines="2"
+{!> ../../docs_src/body/tutorial001_py310.py!}
+```
+
+////
## Створіть свою модель даних
@@ -37,17 +44,21 @@
Використовуйте стандартні типи Python для всіх атрибутів:
-=== "Python 3.8 і вище"
+//// tab | Python 3.8 і вище
- ```Python hl_lines="7-11"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
+```Python hl_lines="7-11"
+{!> ../../docs_src/body/tutorial001.py!}
+```
-=== "Python 3.10 і вище"
+////
- ```Python hl_lines="5-9"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
+//// tab | Python 3.10 і вище
+
+```Python hl_lines="5-9"
+{!> ../../docs_src/body/tutorial001_py310.py!}
+```
+
+////
Так само, як і при оголошенні параметрів запиту, коли атрибут моделі має значення за замовчуванням, він не є обов’язковим. В іншому випадку це потрібно. Використовуйте `None`, щоб зробити його необов'язковим.
@@ -75,17 +86,21 @@
Щоб додати модель даних до вашої *операції шляху*, оголосіть її так само, як ви оголосили параметри шляху та запиту:
-=== "Python 3.8 і вище"
+//// tab | Python 3.8 і вище
- ```Python hl_lines="18"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
+```Python hl_lines="18"
+{!> ../../docs_src/body/tutorial001.py!}
+```
-=== "Python 3.10 і вище"
+////
- ```Python hl_lines="16"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
+//// tab | Python 3.10 і вище
+
+```Python hl_lines="16"
+{!> ../../docs_src/body/tutorial001_py310.py!}
+```
+
+////
...і вкажіть її тип як модель, яку ви створили, `Item`.
@@ -134,32 +149,39 @@
-!!! tip
- Якщо ви використовуєте PyCharm як ваш редактор, ви можете використати Pydantic PyCharm Plugin.
+/// tip
- Він покращує підтримку редакторів для моделей Pydantic за допомогою:
+Якщо ви використовуєте PyCharm як ваш редактор, ви можете використати Pydantic PyCharm Plugin.
- * автозаповнення
- * перевірки типу
- * рефакторингу
- * пошуку
- * інспекції
+Він покращує підтримку редакторів для моделей Pydantic за допомогою:
+
+* автозаповнення
+* перевірки типу
+* рефакторингу
+* пошуку
+* інспекції
+
+///
## Використовуйте модель
Усередині функції ви можете отримати прямий доступ до всіх атрибутів об’єкта моделі:
-=== "Python 3.8 і вище"
+//// tab | Python 3.8 і вище
- ```Python hl_lines="21"
- {!> ../../../docs_src/body/tutorial002.py!}
- ```
+```Python hl_lines="21"
+{!> ../../docs_src/body/tutorial002.py!}
+```
-=== "Python 3.10 і вище"
+////
- ```Python hl_lines="19"
- {!> ../../../docs_src/body/tutorial002_py310.py!}
- ```
+//// tab | Python 3.10 і вище
+
+```Python hl_lines="19"
+{!> ../../docs_src/body/tutorial002_py310.py!}
+```
+
+////
## Тіло запиту + параметри шляху
@@ -167,17 +189,21 @@
**FastAPI** розпізнає, що параметри функції, які відповідають параметрам шляху, мають бути **взяті з шляху**, а параметри функції, які оголошуються як моделі Pydantic, **взяті з тіла запиту**.
-=== "Python 3.8 і вище"
+//// tab | Python 3.8 і вище
- ```Python hl_lines="17-18"
- {!> ../../../docs_src/body/tutorial003.py!}
- ```
+```Python hl_lines="17-18"
+{!> ../../docs_src/body/tutorial003.py!}
+```
-=== "Python 3.10 і вище"
+////
- ```Python hl_lines="15-16"
- {!> ../../../docs_src/body/tutorial003_py310.py!}
- ```
+//// tab | Python 3.10 і вище
+
+```Python hl_lines="15-16"
+{!> ../../docs_src/body/tutorial003_py310.py!}
+```
+
+////
## Тіло запиту + шлях + параметри запиту
@@ -185,17 +211,21 @@
**FastAPI** розпізнає кожен з них і візьме дані з потрібного місця.
-=== "Python 3.8 і вище"
+//// tab | Python 3.8 і вище
- ```Python hl_lines="18"
- {!> ../../../docs_src/body/tutorial004.py!}
- ```
+```Python hl_lines="18"
+{!> ../../docs_src/body/tutorial004.py!}
+```
-=== "Python 3.10 і вище"
+////
- ```Python hl_lines="16"
- {!> ../../../docs_src/body/tutorial004_py310.py!}
- ```
+//// tab | Python 3.10 і вище
+
+```Python hl_lines="16"
+{!> ../../docs_src/body/tutorial004_py310.py!}
+```
+
+////
Параметри функції будуть розпізнаватися наступним чином:
@@ -203,10 +233,13 @@
* Якщо параметр має **сингулярний тип** (наприклад, `int`, `float`, `str`, `bool` тощо), він буде інтерпретуватися як параметр **запиту**.
* Якщо параметр оголошується як тип **Pydantic моделі**, він інтерпретується як **тіло** запиту.
-!!! note
- FastAPI буде знати, що значення "q" не є обов'язковим через значення за замовчуванням "= None".
+/// note
- `Optional` у `Optional[str]` не використовується FastAPI, але дозволить вашому редактору надати вам кращу підтримку та виявляти помилки.
+FastAPI буде знати, що значення "q" не є обов'язковим через значення за замовчуванням "= None".
+
+`Optional` у `Optional[str]` не використовується FastAPI, але дозволить вашому редактору надати вам кращу підтримку та виявляти помилки.
+
+///
## Без Pydantic
diff --git a/docs/uk/docs/tutorial/cookie-params.md b/docs/uk/docs/tutorial/cookie-params.md
index 199b93839..40ca4f6e6 100644
--- a/docs/uk/docs/tutorial/cookie-params.md
+++ b/docs/uk/docs/tutorial/cookie-params.md
@@ -6,41 +6,57 @@
Спочатку імпортуйте `Cookie`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="3"
+{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="3"
+{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Бажано використовувати `Annotated` версію, якщо це можливо.
+```Python hl_lines="3"
+{!> ../../docs_src/cookie_params/tutorial001_an.py!}
+```
- ```Python hl_lines="1"
- {!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Бажано використовувати `Annotated` версію, якщо це можливо.
+/// tip
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001.py!}
- ```
+Бажано використовувати `Annotated` версію, якщо це можливо.
+
+///
+
+```Python hl_lines="1"
+{!> ../../docs_src/cookie_params/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Бажано використовувати `Annotated` версію, якщо це можливо.
+
+///
+
+```Python hl_lines="3"
+{!> ../../docs_src/cookie_params/tutorial001.py!}
+```
+
+////
## Визначення параметрів `Cookie`
@@ -48,48 +64,70 @@
Перше значення це значення за замовчуванням, ви можете також передати всі додаткові параметри валідації чи анотації:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="9"
+{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/cookie_params/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Бажано використовувати `Annotated` версію, якщо це можливо.
+```Python hl_lines="10"
+{!> ../../docs_src/cookie_params/tutorial001_an.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Бажано використовувати `Annotated` версію, якщо це можливо.
+/// tip
- ```Python hl_lines="9"
- {!> ../../../docs_src/cookie_params/tutorial001.py!}
- ```
+Бажано використовувати `Annotated` версію, якщо це можливо.
-!!! note "Технічні Деталі"
- `Cookie` це "сестра" класів `Path` і `Query`. Вони наслідуються від одного батьківського класу `Param`.
- Але пам'ятайте, що коли ви імпортуєте `Query`, `Path`, `Cookie` та інше з `fastapi`, це фактично функції, що повертають спеціальні класи.
+///
-!!! info
- Для визначення cookies ви маєте використовувати `Cookie`, тому що в іншому випадку параметри будуть інтерпритовані, як параметри запиту.
+```Python hl_lines="7"
+{!> ../../docs_src/cookie_params/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Бажано використовувати `Annotated` версію, якщо це можливо.
+
+///
+
+```Python hl_lines="9"
+{!> ../../docs_src/cookie_params/tutorial001.py!}
+```
+
+////
+
+/// note | "Технічні Деталі"
+
+`Cookie` це "сестра" класів `Path` і `Query`. Вони наслідуються від одного батьківського класу `Param`.
+Але пам'ятайте, що коли ви імпортуєте `Query`, `Path`, `Cookie` та інше з `fastapi`, це фактично функції, що повертають спеціальні класи.
+
+///
+
+/// info
+
+Для визначення cookies ви маєте використовувати `Cookie`, тому що в іншому випадку параметри будуть інтерпритовані, як параметри запиту.
+
+///
## Підсумки
diff --git a/docs/uk/docs/tutorial/encoder.md b/docs/uk/docs/tutorial/encoder.md
index 49321ff11..39dca9be8 100644
--- a/docs/uk/docs/tutorial/encoder.md
+++ b/docs/uk/docs/tutorial/encoder.md
@@ -20,17 +20,21 @@
Вона приймає об'єкт, такий як Pydantic model, і повертає його версію, сумісну з JSON:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="4 21"
- {!> ../../../docs_src/encoder/tutorial001_py310.py!}
- ```
+```Python hl_lines="4 21"
+{!> ../../docs_src/encoder/tutorial001_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="5 22"
- {!> ../../../docs_src/encoder/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="5 22"
+{!> ../../docs_src/encoder/tutorial001.py!}
+```
+
+////
У цьому прикладі вона конвертує Pydantic model у `dict`, а `datetime` у `str`.
@@ -38,5 +42,8 @@
Вона не повертає велику строку `str`, яка містить дані у форматі JSON (як строка). Вона повертає стандартну структуру даних Python (наприклад `dict`) із значеннями та підзначеннями, які є сумісними з JSON.
-!!! note "Примітка"
- `jsonable_encoder` фактично використовується **FastAPI** внутрішньо для перетворення даних. Проте вона корисна в багатьох інших сценаріях.
+/// note | "Примітка"
+
+`jsonable_encoder` фактично використовується **FastAPI** внутрішньо для перетворення даних. Проте вона корисна в багатьох інших сценаріях.
+
+///
diff --git a/docs/uk/docs/tutorial/extra-data-types.md b/docs/uk/docs/tutorial/extra-data-types.md
index 01852803a..5e6c364e4 100644
--- a/docs/uk/docs/tutorial/extra-data-types.md
+++ b/docs/uk/docs/tutorial/extra-data-types.md
@@ -55,76 +55,108 @@
Ось приклад *path operation* з параметрами, використовуючи деякі з вищезазначених типів.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="1 3 12-16"
- {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="1 3 12-16"
+{!> ../../docs_src/extra_data_types/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="1 3 12-16"
- {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="1 3 12-16"
+{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="1 3 13-17"
- {!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Бажано використовувати `Annotated` версію, якщо це можливо.
+```Python hl_lines="1 3 13-17"
+{!> ../../docs_src/extra_data_types/tutorial001_an.py!}
+```
- ```Python hl_lines="1 2 11-15"
- {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Бажано використовувати `Annotated` версію, якщо це можливо.
+/// tip
- ```Python hl_lines="1 2 12-16"
- {!> ../../../docs_src/extra_data_types/tutorial001.py!}
- ```
+Бажано використовувати `Annotated` версію, якщо це можливо.
+
+///
+
+```Python hl_lines="1 2 11-15"
+{!> ../../docs_src/extra_data_types/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Бажано використовувати `Annotated` версію, якщо це можливо.
+
+///
+
+```Python hl_lines="1 2 12-16"
+{!> ../../docs_src/extra_data_types/tutorial001.py!}
+```
+
+////
Зверніть увагу, що параметри всередині функції мають свій звичайний тип даних, і ви можете, наприклад, виконувати звичайні маніпуляції з датами, такі як:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="18-19"
+{!> ../../docs_src/extra_data_types/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="18-19"
+{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="19-20"
- {!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Бажано використовувати `Annotated` версію, якщо це можливо.
+```Python hl_lines="19-20"
+{!> ../../docs_src/extra_data_types/tutorial001_an.py!}
+```
- ```Python hl_lines="17-18"
- {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Бажано використовувати `Annotated` версію, якщо це можливо.
+/// tip
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/extra_data_types/tutorial001.py!}
- ```
+Бажано використовувати `Annotated` версію, якщо це можливо.
+
+///
+
+```Python hl_lines="17-18"
+{!> ../../docs_src/extra_data_types/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Бажано використовувати `Annotated` версію, якщо це можливо.
+
+///
+
+```Python hl_lines="18-19"
+{!> ../../docs_src/extra_data_types/tutorial001.py!}
+```
+
+////
diff --git a/docs/uk/docs/tutorial/first-steps.md b/docs/uk/docs/tutorial/first-steps.md
index 725677e42..6f79c0d1d 100644
--- a/docs/uk/docs/tutorial/first-steps.md
+++ b/docs/uk/docs/tutorial/first-steps.md
@@ -3,7 +3,7 @@
Найпростіший файл FastAPI може виглядати так:
```Python
-{!../../../docs_src/first_steps/tutorial001.py!}
+{!../../docs_src/first_steps/tutorial001.py!}
```
Скопіюйте це до файлу `main.py`.
@@ -158,20 +158,23 @@ OpenAPI описує схему для вашого API. І ця схема вк
### Крок 1: імпортуємо `FastAPI`
```Python hl_lines="1"
-{!../../../docs_src/first_steps/tutorial001.py!}
+{!../../docs_src/first_steps/tutorial001.py!}
```
`FastAPI` це клас у Python, який надає всю функціональність для API.
-!!! note "Технічні деталі"
- `FastAPI` це клас, який успадковується безпосередньо від `Starlette`.
+/// note | "Технічні деталі"
- Ви також можете використовувати всю функціональність Starlette у `FastAPI`.
+`FastAPI` це клас, який успадковується безпосередньо від `Starlette`.
+
+Ви також можете використовувати всю функціональність Starlette у `FastAPI`.
+
+///
### Крок 2: створюємо екземпляр `FastAPI`
```Python hl_lines="3"
-{!../../../docs_src/first_steps/tutorial001.py!}
+{!../../docs_src/first_steps/tutorial001.py!}
```
Змінна `app` є екземпляром класу `FastAPI`.
@@ -195,8 +198,11 @@ https://example.com/items/foo
/items/foo
```
-!!! info "Додаткова інформація"
- "Шлях" (path) також зазвичай називають "ендпоінтом" (endpoint) або "маршрутом" (route).
+/// info | "Додаткова інформація"
+
+"Шлях" (path) також зазвичай називають "ендпоінтом" (endpoint) або "маршрутом" (route).
+
+///
При створенні API, "шлях" є основним способом розділення "завдань" і "ресурсів".
#### Operation
@@ -237,23 +243,26 @@ https://example.com/items/foo
#### Визначте декоратор операції шляху (path operation decorator)
```Python hl_lines="6"
-{!../../../docs_src/first_steps/tutorial001.py!}
+{!../../docs_src/first_steps/tutorial001.py!}
```
Декоратор `@app.get("/")` вказує **FastAPI**, що функція нижче, відповідає за обробку запитів, які надходять до неї:
* шлях `/`
* використовуючи get операцію
-!!! info "`@decorator` Додаткова інформація"
- Синтаксис `@something` у Python називається "декоратором".
+/// info | "`@decorator` Додаткова інформація"
- Ви розташовуєте його над функцією. Як гарний декоративний капелюх (мабуть, звідти походить термін).
+Синтаксис `@something` у Python називається "декоратором".
- "Декоратор" приймає функцію нижче і виконує з нею якусь дію.
+Ви розташовуєте його над функцією. Як гарний декоративний капелюх (мабуть, звідти походить термін).
- У нашому випадку, цей декоратор повідомляє **FastAPI**, що функція нижче відповідає **шляху** `/` і **операції** `get`.
+"Декоратор" приймає функцію нижче і виконує з нею якусь дію.
- Це і є "декоратор операції шляху (path operation decorator)".
+У нашому випадку, цей декоратор повідомляє **FastAPI**, що функція нижче відповідає **шляху** `/` і **операції** `get`.
+
+Це і є "декоратор операції шляху (path operation decorator)".
+
+///
Можна також використовувати операції:
@@ -268,15 +277,17 @@ https://example.com/items/foo
* `@app.patch()`
* `@app.trace()`
-!!! tip "Порада"
- Ви можете використовувати кожну операцію (HTTP-метод) на свій розсуд.
+/// tip | "Порада"
- **FastAPI** не нав'язує жодного певного значення для кожного методу.
+Ви можете використовувати кожну операцію (HTTP-метод) на свій розсуд.
- Наведена тут інформація є рекомендацією, а не обов'язковою вимогою.
+**FastAPI** не нав'язує жодного певного значення для кожного методу.
- Наприклад, під час використання GraphQL зазвичай усі дії виконуються тільки за допомогою `POST` операцій.
+Наведена тут інформація є рекомендацією, а не обов'язковою вимогою.
+Наприклад, під час використання GraphQL зазвичай усі дії виконуються тільки за допомогою `POST` операцій.
+
+///
### Крок 4: визначте **функцію операції шляху (path operation function)**
@@ -287,7 +298,7 @@ https://example.com/items/foo
* **функція**: це функція, яка знаходиться нижче "декоратора" (нижче `@app.get("/")`).
```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial001.py!}
+{!../../docs_src/first_steps/tutorial001.py!}
```
Це звичайна функція Python.
@@ -301,16 +312,19 @@ FastAPI викликатиме її щоразу, коли отримає зап
Ви також можете визначити її як звичайну функцію замість `async def`:
```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial003.py!}
+{!../../docs_src/first_steps/tutorial003.py!}
```
-!!! note "Примітка"
- Якщо не знаєте в чому різниця, подивіться [Конкурентність: *"Поспішаєш?"*](../async.md#in-a-hurry){.internal-link target=_blank}.
+/// note | "Примітка"
+
+Якщо не знаєте в чому різниця, подивіться [Конкурентність: *"Поспішаєш?"*](../async.md#in-a-hurry){.internal-link target=_blank}.
+
+///
### Крок 5: поверніть результат
```Python hl_lines="8"
-{!../../../docs_src/first_steps/tutorial001.py!}
+{!../../docs_src/first_steps/tutorial001.py!}
```
Ви можете повернути `dict`, `list`, а також окремі значення `str`, `int`, ітд.
diff --git a/docs/uk/docs/tutorial/index.md b/docs/uk/docs/tutorial/index.md
index e5bae74bc..92c3e77a3 100644
--- a/docs/uk/docs/tutorial/index.md
+++ b/docs/uk/docs/tutorial/index.md
@@ -52,22 +52,25 @@ $ pip install "fastapi[all]"
...який також включає `uvicorn`, який ви можете використовувати як сервер, який запускає ваш код.
-!!! note
- Ви також можете встановити його частина за частиною.
+/// note
- Це те, що ви, ймовірно, зробили б, коли захочете розгорнути свою програму у виробничому середовищі:
+Ви також можете встановити його частина за частиною.
- ```
- pip install fastapi
- ```
+Це те, що ви, ймовірно, зробили б, коли захочете розгорнути свою програму у виробничому середовищі:
- Також встановіть `uvicorn`, щоб він працював як сервер:
+```
+pip install fastapi
+```
- ```
- pip install "uvicorn[standard]"
- ```
+Також встановіть `uvicorn`, щоб він працював як сервер:
- І те саме для кожної з опціональних залежностей, які ви хочете використовувати.
+```
+pip install "uvicorn[standard]"
+```
+
+І те саме для кожної з опціональних залежностей, які ви хочете використовувати.
+
+///
## Розширений посібник користувача
diff --git a/docs/ur/docs/benchmarks.md b/docs/ur/docs/benchmarks.md
index 9fc793e6f..8d583de2f 100644
--- a/docs/ur/docs/benchmarks.md
+++ b/docs/ur/docs/benchmarks.md
@@ -1,5 +1,4 @@
# بینچ مارکس
-
انڈیپنڈنٹ ٹیک امپور بینچ مارک **FASTAPI** Uvicorn کے تحت چلنے والی ایپلی کیشنز کو ایک تیز رفتار Python فریم ورک میں سے ایک ، صرف Starlette اور Uvicorn کے نیچے ( FASTAPI کے ذریعہ اندرونی طور پر استعمال کیا جاتا ہے ) (*)
لیکن جب بینچ مارک اور موازنہ کی جانچ پڑتال کرتے ہو تو آپ کو مندرجہ ذیل بات ذہن میں رکھنی چاہئے.
@@ -14,39 +13,39 @@
درجہ بندی کی طرح ہے:
-email_validator - cho email validation.
+* email-validator - cho email validation.
Sử dụng Starlette:
diff --git a/docs/vi/docs/python-types.md b/docs/vi/docs/python-types.md
index 84d14de55..275b0eb39 100644
--- a/docs/vi/docs/python-types.md
+++ b/docs/vi/docs/python-types.md
@@ -12,15 +12,18 @@ Bằng việc khai báo kiểu dữ liệu cho các biến của bạn, các tr
Nhưng thậm chí nếu bạn không bao giờ sử dụng **FastAPI**, bạn sẽ được lợi từ việc học một ít về chúng.
-!!! note
- Nếu bạn là một chuyên gia về Python, và bạn đã biết mọi thứ về gợi ý kiểu dữ liệu, bỏ qua và đi tới chương tiếp theo.
+/// note
+
+Nếu bạn là một chuyên gia về Python, và bạn đã biết mọi thứ về gợi ý kiểu dữ liệu, bỏ qua và đi tới chương tiếp theo.
+
+///
## Động lực
Hãy bắt đầu với một ví dụ đơn giản:
```Python
-{!../../../docs_src/python_types/tutorial001.py!}
+{!../../docs_src/python_types/tutorial001.py!}
```
Kết quả khi gọi chương trình này:
@@ -36,7 +39,7 @@ Hàm thực hiện như sau:
* 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!}
```
### Sửa đổi
@@ -80,7 +83,7 @@ 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!}
```
Đó không giống như khai báo những giá trị mặc định giống như:
@@ -110,7 +113,7 @@ 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!}
```
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:
@@ -120,7 +123,7 @@ 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!}
```
## Khai báo các kiểu dữ liệu
@@ -141,7 +144,7 @@ Bạn có thể sử dụng, ví dụ:
* `bytes`
```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial005.py!}
+{!../../docs_src/python_types/tutorial005.py!}
```
### Các kiểu dữ liệu tổng quát với tham số kiểu dữ liệu
@@ -170,45 +173,55 @@ Nếu bạn có thể sử dụng **phiên bản cuối cùng của Python**, s
Ví dụ, hãy định nghĩa một biến là `list` các `str`.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- Khai báo biến với cùng dấu hai chấm (`:`).
+Khai báo biến với cùng dấu hai chấm (`:`).
- Tương tự kiểu dữ liệu `list`.
+Tương tự kiểu dữ liệu `list`.
- Như danh sách là một kiểu dữ liệu chứa một vài kiểu dữ liệu có sẵn, bạn đặt chúng trong các dấu ngoặc vuông:
+Như danh sách là một kiểu dữ liệu chứa một vài kiểu dữ liệu có sẵn, bạn đặt chúng trong các dấu ngoặc vuông:
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial006_py39.py!}
- ```
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial006_py39.py!}
+```
-=== "Python 3.8+"
+////
- Từ `typing`, import `List` (với chữ cái `L` viết hoa):
+//// tab | Python 3.8+
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial006.py!}
- ```
+Từ `typing`, import `List` (với chữ cái `L` viết hoa):
- Khai báo biến với cùng dấu hai chấm (`:`).
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial006.py!}
+```
- Tương tự như kiểu dữ liệu, `List` bạn import từ `typing`.
+Khai báo biến với cùng dấu hai chấm (`:`).
- Như danh sách là một kiểu dữ liệu chứa các kiểu dữ liệu có sẵn, bạn đặt chúng bên trong dấu ngoặc vuông:
+Tương tự như kiểu dữ liệu, `List` bạn import từ `typing`.
- ```Python hl_lines="4"
- {!> ../../../docs_src/python_types/tutorial006.py!}
- ```
+Như danh sách là một kiểu dữ liệu chứa các kiểu dữ liệu có sẵn, bạn đặt chúng bên trong dấu ngoặc vuông:
-!!! info
- Các kiểu dữ liệu có sẵn bên trong dấu ngoặc vuông được gọi là "tham số kiểu dữ liệu".
+```Python hl_lines="4"
+{!> ../../docs_src/python_types/tutorial006.py!}
+```
- Trong trường hợp này, `str` là tham số kiểu dữ liệu được truyền tới `List` (hoặc `list` trong Python 3.9 trở lên).
+////
+
+/// info
+
+Các kiểu dữ liệu có sẵn bên trong dấu ngoặc vuông được gọi là "tham số kiểu dữ liệu".
+
+Trong trường hợp này, `str` là tham số kiểu dữ liệu được truyền tới `List` (hoặc `list` trong Python 3.9 trở lên).
+
+///
Có nghĩa là: "biến `items` là một `list`, và mỗi phần tử trong danh sách này là một `str`".
-!!! tip
- Nếu bạn sử dụng Python 3.9 hoặc lớn hơn, bạn không phải import `List` từ `typing`, bạn có thể sử dụng `list` để thay thế.
+/// tip
+
+Nếu bạn sử dụng Python 3.9 hoặc lớn hơn, bạn không phải import `List` từ `typing`, bạn có thể sử dụng `list` để thay thế.
+
+///
Bằng cách này, trình soạn thảo của bạn có thể hỗ trợ trong khi xử lí các phần tử trong danh sách:
@@ -224,17 +237,21 @@ Và do vậy, trình soạn thảo biết nó là một `str`, và cung cấp s
Bạn sẽ làm điều tương tự để khai báo các `tuple` và các `set`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial007_py39.py!}
- ```
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial007_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial007.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial007.py!}
+```
+
+////
Điều này có nghĩa là:
@@ -249,17 +266,21 @@ Tham số kiểu dữ liệu đầu tiên dành cho khóa của `dict`.
Tham số kiểu dữ liệu thứ hai dành cho giá trị của `dict`.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial008_py39.py!}
- ```
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial008_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial008.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial008.py!}
+```
+
+////
Điều này có nghĩa là:
@@ -278,17 +299,21 @@ In Python 3.10 there's also a **new syntax** where you can put the possible type
Trong Python 3.10 cũng có một **cú pháp mới** mà bạn có thể đặt những kiểu giá trị khả thi phân cách bởi một dấu sổ dọc (`|`).
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial008b_py310.py!}
- ```
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial008b_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial008b.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial008b.py!}
+```
+
+////
Trong cả hai trường hợp có nghĩa là `item` có thể là một `int` hoặc `str`.
@@ -299,7 +324,7 @@ Bạn có thể khai báo một giá trị có thể có một kiểu dữ liệ
Trong Python 3.6 hoặc lớn hơn (bao gồm Python 3.10) bạn có thể khai báo nó bằng các import và sử dụng `Optional` từ mô đun `typing`.
```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009.py!}
+{!../../docs_src/python_types/tutorial009.py!}
```
Sử dụng `Optional[str]` thay cho `str` sẽ cho phép trình soạn thảo giúp bạn phát hiện các lỗi mà bạn có thể gặp như một giá trị luôn là một `str`, trong khi thực tế nó rất có thể là `None`.
@@ -308,23 +333,29 @@ Sử dụng `Optional[str]` thay cho `str` sẽ cho phép trình soạn thảo g
Điều này cũng có nghĩa là trong Python 3.10, bạn có thể sử dụng `Something | None`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial009_py310.py!}
- ```
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial009_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial009.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ alternative"
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial009.py!}
+```
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial009b.py!}
- ```
+////
+
+//// tab | Python 3.8+ alternative
+
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial009b.py!}
+```
+
+////
#### Sử dụng `Union` hay `Optional`
@@ -344,7 +375,7 @@ 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!}
```
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ố:
@@ -362,7 +393,7 @@ 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!}
```
Và sau đó, bạn sẽ không phải lo rằng những cái tên như `Optional` và `Union`. 😎
@@ -372,47 +403,53 @@ Và sau đó, bạn sẽ không phải lo rằng những cái tên như `Optiona
Những kiểu dữ liệu này lấy tham số kiểu dữ liệu trong dấu ngoặc vuông được gọi là **Kiểu dữ liệu tổng quát**, cho ví dụ:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- Bạn có thể sử dụng các kiểu dữ liệu có sẵn như là kiểu dữ liệu tổng quát (với ngoặc vuông và kiểu dữ liệu bên trong):
+Bạn có thể sử dụng các kiểu dữ liệu có sẵn như là kiểu dữ liệu tổng quát (với ngoặc vuông và kiểu dữ liệu bên trong):
- * `list`
- * `tuple`
- * `set`
- * `dict`
+* `list`
+* `tuple`
+* `set`
+* `dict`
- Và tương tự với Python 3.6, từ mô đun `typing`:
+Và tương tự với Python 3.6, từ mô đun `typing`:
- * `Union`
- * `Optional` (tương tự như Python 3.6)
- * ...và các kiểu dữ liệu khác.
+* `Union`
+* `Optional` (tương tự như Python 3.6)
+* ...và các kiểu dữ liệu khác.
- Trong Python 3.10, thay vì sử dụng `Union` và `Optional`, bạn có thể sử dụng sổ dọc ('|') để khai báo hợp của các kiểu dữ liệu, điều đó tốt hơn và đơn giản hơn nhiều.
+Trong Python 3.10, thay vì sử dụng `Union` và `Optional`, bạn có thể sử dụng sổ dọc ('|') để khai báo hợp của các kiểu dữ liệu, điều đó tốt hơn và đơn giản hơn nhiều.
-=== "Python 3.9+"
+////
- Bạn có thể sử dụng các kiểu dữ liệu có sẵn tương tự như (với ngoặc vuông và kiểu dữ liệu bên trong):
+//// tab | Python 3.9+
- * `list`
- * `tuple`
- * `set`
- * `dict`
+Bạn có thể sử dụng các kiểu dữ liệu có sẵn tương tự như (với ngoặc vuông và kiểu dữ liệu bên trong):
- Và tương tự với Python 3.6, từ mô đun `typing`:
+* `list`
+* `tuple`
+* `set`
+* `dict`
- * `Union`
- * `Optional`
- * ...and others.
+Và tương tự với Python 3.6, từ mô đun `typing`:
-=== "Python 3.8+"
+* `Union`
+* `Optional`
+* ...and others.
- * `List`
- * `Tuple`
- * `Set`
- * `Dict`
- * `Union`
- * `Optional`
- * ...và các kiểu khác.
+////
+
+//// tab | Python 3.8+
+
+* `List`
+* `Tuple`
+* `Set`
+* `Dict`
+* `Union`
+* `Optional`
+* ...và các kiểu khác.
+
+////
### Lớp như kiểu dữ liệu
@@ -421,13 +458,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!}
```
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!}
```
Và lại một lần nữa, bạn có được tất cả sự hỗ trợ từ trình soạn thảo:
@@ -452,56 +489,71 @@ Và bạn nhận được tất cả sự hỗ trợ của trình soạn thảo
Một ví dụ từ tài liệu chính thức của Pydantic:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python
- {!> ../../../docs_src/python_types/tutorial011_py310.py!}
- ```
+```Python
+{!> ../../docs_src/python_types/tutorial011_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python
- {!> ../../../docs_src/python_types/tutorial011_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python
+{!> ../../docs_src/python_types/tutorial011_py39.py!}
+```
- ```Python
- {!> ../../../docs_src/python_types/tutorial011.py!}
- ```
+////
-!!! info
- Để học nhiều hơn về Pydantic, tham khảo tài liệu của nó.
+//// tab | Python 3.8+
+
+```Python
+{!> ../../docs_src/python_types/tutorial011.py!}
+```
+
+////
+
+/// info
+
+Để học nhiều hơn về Pydantic, tham khảo tài liệu của nó.
+
+///
**FastAPI** được dựa hoàn toàn trên Pydantic.
Bạn sẽ thấy nhiều ví dụ thực tế hơn trong [Hướng dẫn sử dụng](tutorial/index.md){.internal-link target=_blank}.
-!!! tip
- Pydantic có một hành vi đặc biệt khi bạn sử dụng `Optional` hoặc `Union[Something, None]` mà không có giá trị mặc dịnh, bạn có thể đọc nhiều hơn về nó trong tài liệu của Pydantic về Required Optional fields.
+/// tip
+Pydantic có một hành vi đặc biệt khi bạn sử dụng `Optional` hoặc `Union[Something, None]` mà không có giá trị mặc dịnh, bạn có thể đọc nhiều hơn về nó trong tài liệu của Pydantic về Required Optional fields.
+
+///
## Type Hints với Metadata Annotations
Python cũng có một tính năng cho phép đặt **metadata bổ sung** trong những gợi ý kiểu dữ liệu này bằng cách sử dụng `Annotated`.
-=== "Python 3.9+"
+//// tab | Python 3.9+
- Trong Python 3.9, `Annotated` là một phần của thư viện chuẩn, do đó bạn có thể import nó từ `typing`.
+Trong Python 3.9, `Annotated` là một phần của thư viện chuẩn, do đó bạn có thể import nó từ `typing`.
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial013_py39.py!}
- ```
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial013_py39.py!}
+```
-=== "Python 3.8+"
+////
- Ở phiên bản dưới Python 3.9, bạn import `Annotated` từ `typing_extensions`.
+//// tab | Python 3.8+
- Nó đã được cài đặt sẵng cùng với **FastAPI**.
+Ở phiên bản dưới Python 3.9, bạn import `Annotated` từ `typing_extensions`.
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial013.py!}
- ```
+Nó đã được cài đặt sẵng cùng với **FastAPI**.
+
+```Python hl_lines="1 4"
+{!> ../../docs_src/python_types/tutorial013.py!}
+```
+
+////
Python bản thân nó không làm bất kì điều gì với `Annotated`. Với các trình soạn thảo và các công cụ khác, kiểu dữ liệu vẫn là `str`.
@@ -514,10 +566,13 @@ Bây giờ, bạn chỉ cần biết rằng `Annotated` tồn tại, và nó là
Sau đó, bạn sẽ thấy sự **mạnh mẽ** mà nó có thể làm.
-!!! tip
- Thực tế, cái này là **tiêu chuẩn của Python**, nghĩa là bạn vẫn sẽ có được **trải nghiệm phát triển tốt nhất có thể** với trình soạn thảo của bạn, với các công cụ bạn sử dụng để phân tích và tái cấu trúc code của bạn, etc. ✨
+/// tip
- Và code của bạn sẽ tương thích với nhiều công cụ và thư viện khác của Python. 🚀
+Thực tế, cái này là **tiêu chuẩn của Python**, nghĩa là bạn vẫn sẽ có được **trải nghiệm phát triển tốt nhất có thể** với trình soạn thảo của bạn, với các công cụ bạn sử dụng để phân tích và tái cấu trúc code của bạn, etc. ✨
+
+Và code của bạn sẽ tương thích với nhiều công cụ và thư viện khác của Python. 🚀
+
+///
## Các gợi ý kiểu dữ liệu trong **FastAPI**
@@ -541,5 +596,8 @@ Với **FastAPI**, bạn khai báo các tham số với gợi ý kiểu và bạ
Điều quan trọng là bằng việc sử dụng các kiểu dữ liệu chuẩn của Python (thay vì thêm các lớp, decorators,...), **FastAPI** sẽ thực hiện nhiều công việc cho bạn.
-!!! info
- Nếu bạn đã đi qua toàn bộ các hướng dẫn và quay trở lại để tìm hiểu nhiều hơn về các kiểu dữ liệu, một tài nguyên tốt như "cheat sheet" từ `mypy`.
+/// info
+
+Nếu bạn đã đi qua toàn bộ các hướng dẫn và quay trở lại để tìm hiểu nhiều hơn về các kiểu dữ liệu, một tài nguyên tốt như "cheat sheet" từ `mypy`.
+
+///
diff --git a/docs/vi/docs/tutorial/first-steps.md b/docs/vi/docs/tutorial/first-steps.md
index 712f00852..d80d78506 100644
--- a/docs/vi/docs/tutorial/first-steps.md
+++ b/docs/vi/docs/tutorial/first-steps.md
@@ -3,7 +3,7 @@
Tệp tin FastAPI đơn giản nhất có thể trông như này:
```Python
-{!../../../docs_src/first_steps/tutorial001.py!}
+{!../../docs_src/first_steps/tutorial001.py!}
```
Sao chép sang một tệp tin `main.py`.
@@ -24,12 +24,15 @@ $ uvicorn main:app --reload
-!!! note
- Câu lệnh `uvicorn main:app` được giải thích như sau:
+/// note
- * `main`: tệp tin `main.py` (một Python "mô đun").
- * `app`: một object được tạo ra bên trong `main.py` với dòng `app = FastAPI()`.
- * `--reload`: làm server khởi động lại sau mỗi lần thay đổi. Chỉ sử dụng trong môi trường phát triển.
+Câu lệnh `uvicorn main:app` được giải thích như sau:
+
+* `main`: tệp tin `main.py` (một Python "mô đun").
+* `app`: một object được tạo ra bên trong `main.py` với dòng `app = FastAPI()`.
+* `--reload`: làm server khởi động lại sau mỗi lần thay đổi. Chỉ sử dụng trong môi trường phát triển.
+
+///
Trong output, có một dòng giống như:
@@ -131,20 +134,23 @@ 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!}
```
`FastAPI` là một Python class cung cấp tất cả chức năng cho API của bạn.
-!!! note "Chi tiết kĩ thuật"
- `FastAPI` là một class kế thừa trực tiếp `Starlette`.
+/// note | "Chi tiết kĩ thuật"
- Bạn cũng có thể sử dụng tất cả Starlette chức năng với `FastAPI`.
+`FastAPI` là một class kế thừa trực tiếp `Starlette`.
+
+Bạn cũng có thể sử dụng tất cả Starlette chức năng với `FastAPI`.
+
+///
### Bước 2: Tạo một `FastAPI` "instance"
```Python hl_lines="3"
-{!../../../docs_src/first_steps/tutorial001.py!}
+{!../../docs_src/first_steps/tutorial001.py!}
```
Biến `app` này là một "instance" của class `FastAPI`.
@@ -166,7 +172,7 @@ $ uvicorn main:app --reload
Nếu bạn tạo ứng dụng của bạn giống như:
```Python hl_lines="3"
-{!../../../docs_src/first_steps/tutorial002.py!}
+{!../../docs_src/first_steps/tutorial002.py!}
```
Và đặt nó trong một tệp tin `main.py`, sau đó bạn sẽ gọi `uvicorn` giống như:
@@ -199,8 +205,11 @@ https://example.com/items/foo
/items/foo
```
-!!! info
- Một đường dẫn cũng là một cách gọi chung cho một "endpoint" hoặc một "route".
+/// info
+
+Một đường dẫn cũng là một cách gọi chung cho một "endpoint" hoặc một "route".
+
+///
Trong khi xây dựng một API, "đường dẫn" là các chính để phân tách "mối quan hệ" và "tài nguyên".
@@ -242,7 +251,7 @@ Chúng ta cũng sẽ gọi chúng là "**các toán tử**".
#### Định nghĩa moojt *decorator cho đường dẫn toán tử*
```Python hl_lines="6"
-{!../../../docs_src/first_steps/tutorial001.py!}
+{!../../docs_src/first_steps/tutorial001.py!}
```
`@app.get("/")` nói **FastAPI** rằng hàm bên dưới có trách nhiệm xử lí request tới:
@@ -250,16 +259,19 @@ Chúng ta cũng sẽ gọi chúng là "**các toán tử**".
* đường dẫn `/`
* sử dụng một toán tửget
-!!! info Thông tin về "`@decorator`"
- Cú pháp `@something` trong Python được gọi là một "decorator".
+/// info | Thông tin về "`@decorator`"
- Bạn đặt nó trên một hàm. Giống như một chiếc mũ xinh xắn (Tôi ddonas đó là lí do mà thuật ngữ này ra đời).
+Cú pháp `@something` trong Python được gọi là một "decorator".
- Một "decorator" lấy một hàm bên dưới và thực hiện một vài thứ với nó.
+Bạn đặt nó trên một hàm. Giống như một chiếc mũ xinh xắn (Tôi ddonas đó là lí do mà thuật ngữ này ra đời).
- Trong trường hợp của chúng ta, decorator này nói **FastAPI** rằng hàm bên dưới ứng với **đường dẫn** `/` và một **toán tử** `get`.
+Một "decorator" lấy một hàm bên dưới và thực hiện một vài thứ với nó.
- Nó là một "**decorator đường dẫn toán tử**".
+Trong trường hợp của chúng ta, decorator này nói **FastAPI** rằng hàm bên dưới ứng với **đường dẫn** `/` và một **toán tử** `get`.
+
+Nó là một "**decorator đường dẫn toán tử**".
+
+///
Bạn cũng có thể sử dụng với các toán tử khác:
@@ -274,14 +286,17 @@ Và nhiều hơn với các toán tử còn lại:
* `@app.patch()`
* `@app.trace()`
-!!! tip
- Bạn thoải mái sử dụng mỗi toán tử (phương thức HTTP) như bạn mơ ước.
+/// tip
- **FastAPI** không bắt buộc bất kì ý nghĩa cụ thể nào.
+Bạn thoải mái sử dụng mỗi toán tử (phương thức HTTP) như bạn mơ ước.
- Thông tin ở đây được biểu thị như là một chỉ dẫn, không phải là một yêu cầu bắt buộc.
+**FastAPI** không bắt buộc bất kì ý nghĩa cụ thể nào.
- Ví dụ, khi sử dụng GraphQL bạn thông thường thực hiện tất cả các hành động chỉ bằng việc sử dụng các toán tử `POST`.
+Thông tin ở đây được biểu thị như là một chỉ dẫn, không phải là một yêu cầu bắt buộc.
+
+Ví dụ, khi sử dụng GraphQL bạn thông thường thực hiện tất cả các hành động chỉ bằng việc sử dụng các toán tử `POST`.
+
+///
### Step 4: Định nghĩa **hàm cho đường dẫn toán tử**
@@ -292,7 +307,7 @@ Và nhiều hơn với các toán tử còn lại:
* **hàm**: là hàm bên dưới "decorator" (bên dưới `@app.get("/")`).
```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial001.py!}
+{!../../docs_src/first_steps/tutorial001.py!}
```
Đây là một hàm Python.
@@ -306,16 +321,19 @@ Trong trường hợp này, nó là một hàm `async`.
Bạn cũng có thể định nghĩa nó như là một hàm thông thường thay cho `async def`:
```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial003.py!}
+{!../../docs_src/first_steps/tutorial003.py!}
```
-!!! note
- Nếu bạn không biết sự khác nhau, kiểm tra [Async: *"Trong khi vội vàng?"*](../async.md#in-a-hurry){.internal-link target=_blank}.
+/// note
+
+Nếu bạn không biết sự khác nhau, kiểm tra [Async: *"Trong khi vội vàng?"*](../async.md#in-a-hurry){.internal-link target=_blank}.
+
+///
### Bước 5: Nội dung trả về
```Python hl_lines="8"
-{!../../../docs_src/first_steps/tutorial001.py!}
+{!../../docs_src/first_steps/tutorial001.py!}
```
Bạn có thể trả về một `dict`, `list`, một trong những giá trị đơn như `str`, `int`,...
diff --git a/docs/vi/docs/tutorial/index.md b/docs/vi/docs/tutorial/index.md
index e8a93fe40..dfeeed8c5 100644
--- a/docs/vi/docs/tutorial/index.md
+++ b/docs/vi/docs/tutorial/index.md
@@ -52,22 +52,25 @@ $ pip install "fastapi[all]"
...dó cũng bao gồm `uvicorn`, bạn có thể sử dụng như một server để chạy code của bạn.
-!!! note
- Bạn cũng có thể cài đặt nó từng phần.
+/// note
- Đây là những gì bạn có thể sẽ làm một lần duy nhất bạn muốn triển khai ứng dụng của bạn lên production:
+Bạn cũng có thể cài đặt nó từng phần.
- ```
- pip install fastapi
- ```
+Đây là những gì bạn có thể sẽ làm một lần duy nhất bạn muốn triển khai ứng dụng của bạn lên production:
- Cũng cài đặt `uvicorn` để làm việc như một server:
+```
+pip install fastapi
+```
- ```
- pip install "uvicorn[standard]"
- ```
+Cũng cài đặt `uvicorn` để làm việc như một server:
- Và tương tự với từng phụ thuộc tùy chọn mà bạn muốn sử dụng.
+```
+pip install "uvicorn[standard]"
+```
+
+Và tương tự với từng phụ thuộc tùy chọn mà bạn muốn sử dụng.
+
+///
## Hướng dẫn nâng cao
diff --git a/docs/yo/docs/index.md b/docs/yo/docs/index.md
index eb20adbb5..ee7f56220 100644
--- a/docs/yo/docs/index.md
+++ b/docs/yo/docs/index.md
@@ -449,7 +449,7 @@ Láti ní òye síi nípa rẹ̀, wo abala àwọn email_validator - fún ifọwọsi ímeèlì.
+* email-validator - fún ifọwọsi ímeèlì.
* pydantic-settings - fún ètò ìsàkóso.
* pydantic-extra-types - fún àfikún oríṣi láti lọ pẹ̀lú Pydantic.
diff --git a/docs/zh-hant/docs/benchmarks.md b/docs/zh-hant/docs/benchmarks.md
index cbd5a6cde..c59e8e71c 100644
--- a/docs/zh-hant/docs/benchmarks.md
+++ b/docs/zh-hant/docs/benchmarks.md
@@ -1,34 +1,34 @@
-# 基準測試
-
-由第三方機構 TechEmpower 的基準測試表明在 Uvicorn 下運行的 **FastAPI** 應用程式是 最快的 Python 可用框架之一,僅次於 Starlette 和 Uvicorn 本身(於 FastAPI 內部使用)。
-
-但是在查看基準得分和對比時,請注意以下幾點。
-
-## 基準測試和速度
-
-當你查看基準測試時,時常會見到幾個不同類型的工具被同時進行測試。
-
-具體來說,是將 Uvicorn、Starlette 和 FastAPI 同時進行比較(以及許多其他工具)。
-
-該工具解決的問題越簡單,其效能就越好。而且大多數基準測試不會測試該工具提供的附加功能。
-
-層次結構如下:
-
-* **Uvicorn**:ASGI 伺服器
- * **Starlette**:(使用 Uvicorn)一個網頁微框架
- * **FastAPI**:(使用 Starlette)一個 API 微框架,具有用於建立 API 的多個附加功能、資料驗證等。
-
-* **Uvicorn**:
- * 具有最佳效能,因為除了伺服器本身之外,它沒有太多額外的程式碼。
- * 你不會直接在 Uvicorn 中編寫應用程式。這意味著你的程式碼必須或多或少地包含 Starlette(或 **FastAPI**)提供的所有程式碼。如果你這樣做,你的最終應用程式將具有與使用框架相同的開銷並最大限度地減少應用程式程式碼和錯誤。
- * 如果你要比較 Uvicorn,請將其與 Daphne、Hypercorn、uWSGI 等應用程式伺服器進行比較。
-* **Starlette**:
- * 繼 Uvicorn 之後的次佳表現。事實上,Starlette 使用 Uvicorn 來運行。因此它將可能只透過執行更多程式碼而變得比 Uvicorn「慢」。
- * 但它為你提供了建立簡單網頁應用程式的工具,以及基於路徑的路由等。
- * 如果你要比較 Starlette,請將其與 Sanic、Flask、Django 等網頁框架(或微框架)進行比較。
-* **FastAPI**:
- * 就像 Starlette 使用 Uvicorn 並不能比它更快一樣, **FastAPI** 使用 Starlette,所以它不能比它更快。
- * FastAPI 在 Starlette 基礎之上提供了更多功能。包含建構 API 時所需要的功能,例如資料驗證和序列化。FastAPI 可以幫助你自動產生 API 文件,(應用程式啟動時將會自動生成文件,所以不會增加應用程式運行時的開銷)。
- * 如果你沒有使用 FastAPI 而是直接使用 Starlette(或其他工具,如 Sanic、Flask、Responder 等),你將必須自行實現所有資料驗證和序列化。因此,你的最終應用程式仍然具有與使用 FastAPI 建置相同的開銷。在許多情況下,這種資料驗證和序列化是應用程式中編寫最大量的程式碼。
- * 因此透過使用 FastAPI,你可以節省開發時間、錯誤與程式碼數量,並且相比不使用 FastAPI 你很大可能會獲得相同或更好的效能(因為那樣你必須在程式碼中實現所有相同的功能)。
- * 如果你要與 FastAPI 比較,請將其與能夠提供資料驗證、序列化和文件的網頁應用程式框架(或工具集)進行比較,例如 Flask-apispec、NestJS、Molten 等框架。
+# 基準測試
+
+由第三方機構 TechEmpower 的基準測試表明在 Uvicorn 下運行的 **FastAPI** 應用程式是 最快的 Python 可用框架之一,僅次於 Starlette 和 Uvicorn 本身(於 FastAPI 內部使用)。
+
+但是在查看基準得分和對比時,請注意以下幾點。
+
+## 基準測試和速度
+
+當你查看基準測試時,時常會見到幾個不同類型的工具被同時進行測試。
+
+具體來說,是將 Uvicorn、Starlette 和 FastAPI 同時進行比較(以及許多其他工具)。
+
+該工具解決的問題越簡單,其效能就越好。而且大多數基準測試不會測試該工具提供的附加功能。
+
+層次結構如下:
+
+* **Uvicorn**:ASGI 伺服器
+ * **Starlette**:(使用 Uvicorn)一個網頁微框架
+ * **FastAPI**:(使用 Starlette)一個 API 微框架,具有用於建立 API 的多個附加功能、資料驗證等。
+
+* **Uvicorn**:
+ * 具有最佳效能,因為除了伺服器本身之外,它沒有太多額外的程式碼。
+ * 你不會直接在 Uvicorn 中編寫應用程式。這意味著你的程式碼必須或多或少地包含 Starlette(或 **FastAPI**)提供的所有程式碼。如果你這樣做,你的最終應用程式將具有與使用框架相同的開銷並最大限度地減少應用程式程式碼和錯誤。
+ * 如果你要比較 Uvicorn,請將其與 Daphne、Hypercorn、uWSGI 等應用程式伺服器進行比較。
+* **Starlette**:
+ * 繼 Uvicorn 之後的次佳表現。事實上,Starlette 使用 Uvicorn 來運行。因此它將可能只透過執行更多程式碼而變得比 Uvicorn「慢」。
+ * 但它為你提供了建立簡單網頁應用程式的工具,以及基於路徑的路由等。
+ * 如果你要比較 Starlette,請將其與 Sanic、Flask、Django 等網頁框架(或微框架)進行比較。
+* **FastAPI**:
+ * 就像 Starlette 使用 Uvicorn 並不能比它更快一樣, **FastAPI** 使用 Starlette,所以它不能比它更快。
+ * FastAPI 在 Starlette 基礎之上提供了更多功能。包含建構 API 時所需要的功能,例如資料驗證和序列化。FastAPI 可以幫助你自動產生 API 文件,(應用程式啟動時將會自動生成文件,所以不會增加應用程式運行時的開銷)。
+ * 如果你沒有使用 FastAPI 而是直接使用 Starlette(或其他工具,如 Sanic、Flask、Responder 等),你將必須自行實現所有資料驗證和序列化。因此,你的最終應用程式仍然具有與使用 FastAPI 建置相同的開銷。在許多情況下,這種資料驗證和序列化是應用程式中編寫最大量的程式碼。
+ * 因此透過使用 FastAPI,你可以節省開發時間、錯誤與程式碼數量,並且相比不使用 FastAPI 你很大可能會獲得相同或更好的效能(因為那樣你必須在程式碼中實現所有相同的功能)。
+ * 如果你要與 FastAPI 比較,請將其與能夠提供資料驗證、序列化和文件的網頁應用程式框架(或工具集)進行比較,例如 Flask-apispec、NestJS、Molten 等框架。
diff --git a/docs/zh-hant/docs/fastapi-people.md b/docs/zh-hant/docs/fastapi-people.md
deleted file mode 100644
index cc671cacf..000000000
--- a/docs/zh-hant/docs/fastapi-people.md
+++ /dev/null
@@ -1,236 +0,0 @@
----
-hide:
- - navigation
----
-
-# FastAPI 社群
-
-FastAPI 有一個非常棒的社群,歡迎來自不同背景的朋友參與。
-
-## 作者
-
-嘿! 👋
-
-關於我:
-
-{% if people %}
-email_validator - 用於電子郵件驗證。
+- email-validator - 用於電子郵件驗證。
- pydantic-settings - 用於設定管理。
- pydantic-extra-types - 用於與 Pydantic 一起使用的額外型別。
diff --git a/docs/zh/docs/advanced/additional-responses.md b/docs/zh/docs/advanced/additional-responses.md
index 2a1e1ed89..f051b12a4 100644
--- a/docs/zh/docs/advanced/additional-responses.md
+++ b/docs/zh/docs/advanced/additional-responses.md
@@ -17,22 +17,26 @@
例如,要声明另一个具有状态码 `404` 和`Pydantic`模型 `Message` 的响应,可以写:
```Python hl_lines="18 22"
-{!../../../docs_src/additional_responses/tutorial001.py!}
+{!../../docs_src/additional_responses/tutorial001.py!}
```
+/// note
-!!! Note
- 请记住,您必须直接返回 `JSONResponse` 。
+请记住,您必须直接返回 `JSONResponse` 。
-!!! Info
- `model` 密钥不是OpenAPI的一部分。
- **FastAPI**将从那里获取`Pydantic`模型,生成` JSON Schema` ,并将其放在正确的位置。
- - 正确的位置是:
- - 在键 `content` 中,其具有另一个`JSON`对象( `dict` )作为值,该`JSON`对象包含:
- - 媒体类型的密钥,例如 `application/json` ,它包含另一个`JSON`对象作为值,该对象包含:
- - 一个键` schema` ,它的值是来自模型的`JSON Schema`,正确的位置在这里。
- - **FastAPI**在这里添加了对OpenAPI中另一个地方的全局JSON模式的引用,而不是直接包含它。这样,其他应用程序和客户端可以直接使用这些JSON模式,提供更好的代码生成工具等。
+///
+/// info
+
+`model` 密钥不是OpenAPI的一部分。
+**FastAPI**将从那里获取`Pydantic`模型,生成` JSON Schema` ,并将其放在正确的位置。
+- 正确的位置是:
+ - 在键 `content` 中,其具有另一个`JSON`对象( `dict` )作为值,该`JSON`对象包含:
+ - 媒体类型的密钥,例如 `application/json` ,它包含另一个`JSON`对象作为值,该对象包含:
+ - 一个键` schema` ,它的值是来自模型的`JSON Schema`,正确的位置在这里。
+ - **FastAPI**在这里添加了对OpenAPI中另一个地方的全局JSON模式的引用,而不是直接包含它。这样,其他应用程序和客户端可以直接使用这些JSON模式,提供更好的代码生成工具等。
+
+///
**在OpenAPI中为该路径操作生成的响应将是:**
@@ -160,15 +164,21 @@
例如,您可以添加一个额外的媒体类型` image/png` ,声明您的路径操作可以返回JSON对象(媒体类型 `application/json` )或PNG图像:
```Python hl_lines="19-24 28"
-{!../../../docs_src/additional_responses/tutorial002.py!}
+{!../../docs_src/additional_responses/tutorial002.py!}
```
-!!! Note
- - 请注意,您必须直接使用 `FileResponse` 返回图像。
+/// note
-!!! Info
- - 除非在 `responses` 参数中明确指定不同的媒体类型,否则**FastAPI**将假定响应与主响应类具有相同的媒体类型(默认为` application/json` )。
- - 但是如果您指定了一个自定义响应类,并将 `None `作为其媒体类型,**FastAPI**将使用 `application/json` 作为具有关联模型的任何其他响应。
+- 请注意,您必须直接使用 `FileResponse` 返回图像。
+
+///
+
+/// info
+
+- 除非在 `responses` 参数中明确指定不同的媒体类型,否则**FastAPI**将假定响应与主响应类具有相同的媒体类型(默认为` application/json` )。
+- 但是如果您指定了一个自定义响应类,并将 `None `作为其媒体类型,**FastAPI**将使用 `application/json` 作为具有关联模型的任何其他响应。
+
+///
## 组合信息
您还可以联合接收来自多个位置的响应信息,包括 `response_model `、 `status_code` 和 `responses `参数。
@@ -182,7 +192,7 @@
以及一个状态码为 `200` 的响应,它使用您的 `response_model` ,但包含自定义的 `example` :
```Python hl_lines="20-31"
-{!../../../docs_src/additional_responses/tutorial003.py!}
+{!../../docs_src/additional_responses/tutorial003.py!}
```
所有这些都将被合并并包含在您的OpenAPI中,并在API文档中显示:
@@ -210,7 +220,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!}
```
## 有关OpenAPI响应的更多信息
diff --git a/docs/zh/docs/advanced/additional-status-codes.md b/docs/zh/docs/advanced/additional-status-codes.md
index 54ec9775b..f79b853ef 100644
--- a/docs/zh/docs/advanced/additional-status-codes.md
+++ b/docs/zh/docs/advanced/additional-status-codes.md
@@ -15,20 +15,26 @@
要实现它,导入 `JSONResponse`,然后在其中直接返回你的内容,并将 `status_code` 设置为为你要的值。
```Python hl_lines="4 25"
-{!../../../docs_src/additional_status_codes/tutorial001.py!}
+{!../../docs_src/additional_status_codes/tutorial001.py!}
```
-!!! warning "警告"
- 当你直接返回一个像上面例子中的 `Response` 对象时,它会直接返回。
+/// warning | "警告"
- FastAPI 不会用模型等对该响应进行序列化。
+当你直接返回一个像上面例子中的 `Response` 对象时,它会直接返回。
- 确保其中有你想要的数据,且返回的值为合法的 JSON(如果你使用 `JSONResponse` 的话)。
+FastAPI 不会用模型等对该响应进行序列化。
-!!! note "技术细节"
- 你也可以使用 `from starlette.responses import JSONResponse`。
+确保其中有你想要的数据,且返回的值为合法的 JSON(如果你使用 `JSONResponse` 的话)。
- 出于方便,**FastAPI** 为开发者提供同 `starlette.responses` 一样的 `fastapi.responses`。但是大多数可用的响应都是直接来自 Starlette。`status` 也是一样。
+///
+
+/// note | "技术细节"
+
+你也可以使用 `from starlette.responses import JSONResponse`。
+
+出于方便,**FastAPI** 为开发者提供同 `starlette.responses` 一样的 `fastapi.responses`。但是大多数可用的响应都是直接来自 Starlette。`status` 也是一样。
+
+///
## OpenAPI 和 API 文档
diff --git a/docs/zh/docs/advanced/advanced-dependencies.md b/docs/zh/docs/advanced/advanced-dependencies.md
index b2f6e3559..f3fe1e395 100644
--- a/docs/zh/docs/advanced/advanced-dependencies.md
+++ b/docs/zh/docs/advanced/advanced-dependencies.md
@@ -19,7 +19,7 @@ Python 可以把类实例变为**可调用项**。
为此,需要声明 `__call__` 方法:
```Python hl_lines="10"
-{!../../../docs_src/dependencies/tutorial011.py!}
+{!../../docs_src/dependencies/tutorial011.py!}
```
本例中,**FastAPI** 使用 `__call__` 检查附加参数及子依赖项,稍后,还要调用它向*路径操作函数*传递值。
@@ -29,7 +29,7 @@ Python 可以把类实例变为**可调用项**。
接下来,使用 `__init__` 声明用于**参数化**依赖项的实例参数:
```Python hl_lines="7"
-{!../../../docs_src/dependencies/tutorial011.py!}
+{!../../docs_src/dependencies/tutorial011.py!}
```
本例中,**FastAPI** 不使用 `__init__`,我们要直接在代码中使用。
@@ -39,7 +39,7 @@ Python 可以把类实例变为**可调用项**。
使用以下代码创建类实例:
```Python hl_lines="16"
-{!../../../docs_src/dependencies/tutorial011.py!}
+{!../../docs_src/dependencies/tutorial011.py!}
```
这样就可以**参数化**依赖项,它包含 `checker.fixed_content` 的属性 - `"bar"`。
@@ -57,15 +57,17 @@ checker(q="somequery")
……并用*路径操作函数*的参数 `fixed_content_included` 返回依赖项的值:
```Python hl_lines="20"
-{!../../../docs_src/dependencies/tutorial011.py!}
+{!../../docs_src/dependencies/tutorial011.py!}
```
-!!! tip "提示"
+/// tip | "提示"
- 本章示例有些刻意,也看不出有什么用处。
+本章示例有些刻意,也看不出有什么用处。
- 这个简例只是为了说明高级依赖项的运作机制。
+这个简例只是为了说明高级依赖项的运作机制。
- 在有关安全的章节中,工具函数将以这种方式实现。
+在有关安全的章节中,工具函数将以这种方式实现。
- 只要能理解本章内容,就能理解安全工具背后的运行机制。
+只要能理解本章内容,就能理解安全工具背后的运行机制。
+
+///
diff --git a/docs/zh/docs/advanced/behind-a-proxy.md b/docs/zh/docs/advanced/behind-a-proxy.md
index 17fc2830a..8c4b6bb04 100644
--- a/docs/zh/docs/advanced/behind-a-proxy.md
+++ b/docs/zh/docs/advanced/behind-a-proxy.md
@@ -37,9 +37,11 @@ browser --> proxy
proxy --> server
```
-!!! tip "提示"
+/// tip | "提示"
- IP `0.0.0.0` 常用于指程序监听本机或服务器上的所有有效 IP。
+IP `0.0.0.0` 常用于指程序监听本机或服务器上的所有有效 IP。
+
+///
API 文档还需要 OpenAPI 概图声明 API `server` 位于 `/api/v1`(使用代理时的 URL)。例如:
@@ -76,11 +78,13 @@ $ uvicorn main:app --root-path /api/v1
Hypercorn 也支持 `--root-path `选项。
-!!! note "技术细节"
+/// note | "技术细节"
- ASGI 规范定义的 `root_path` 就是为了这种用例。
+ASGI 规范定义的 `root_path` 就是为了这种用例。
- 并且 `--root-path` 命令行选项支持 `root_path`。
+并且 `--root-path` 命令行选项支持 `root_path`。
+
+///
### 查看当前的 `root_path`
@@ -89,7 +93,7 @@ Hypercorn 也支持 `--root-path `选项。
我们在这里的信息里包含 `roo_path` 只是为了演示。
```Python hl_lines="8"
-{!../../../docs_src/behind_a_proxy/tutorial001.py!}
+{!../../docs_src/behind_a_proxy/tutorial001.py!}
```
然后,用以下命令启动 Uvicorn:
@@ -118,7 +122,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!}
```
传递 `root_path` 给 `FastAPI` 与传递 `--root-path` 命令行选项给 Uvicorn 或 Hypercorn 一样。
@@ -168,9 +172,11 @@ Uvicorn 预期代理在 `http://127.0.0.1:8000/app` 访问 Uvicorn,而在顶
这个文件把 Traefik 监听端口设置为 `9999`,并设置要使用另一个文件 `routes.toml`。
-!!! tip "提示"
+/// tip | "提示"
- 使用端口 9999 代替标准的 HTTP 端口 80,这样就不必使用管理员权限运行(`sudo`)。
+使用端口 9999 代替标准的 HTTP 端口 80,这样就不必使用管理员权限运行(`sudo`)。
+
+///
接下来,创建 `routes.toml`:
@@ -236,9 +242,11 @@ $ uvicorn main:app --root-path /api/v1
}
```
-!!! tip "提示"
+/// tip | "提示"
- 注意,就算访问 `http://127.0.0.1:8000/app`,也显示从选项 `--root-path` 中提取的 `/api/v1`,这是 `root_path` 的值。
+注意,就算访问 `http://127.0.0.1:8000/app`,也显示从选项 `--root-path` 中提取的 `/api/v1`,这是 `root_path` 的值。
+
+///
打开含 Traefik 端口的 URL,包含路径前缀:http://127.0.0.1:9999/api/v1/app。
@@ -281,9 +289,11 @@ $ uvicorn main:app --root-path /api/v1
## 附加的服务器
-!!! warning "警告"
+/// warning | "警告"
- 此用例较难,可以跳过。
+此用例较难,可以跳过。
+
+///
默认情况下,**FastAPI** 使用 `root_path` 的链接在 OpenAPI 概图中创建 `server`。
@@ -294,7 +304,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!}
```
这段代码生产如下 OpenAPI 概图:
@@ -322,24 +332,28 @@ $ uvicorn main:app --root-path /api/v1
}
```
-!!! tip "提示"
+/// tip | "提示"
- 注意,自动生成服务器时,`url` 的值 `/api/v1` 提取自 `roog_path`。
+注意,自动生成服务器时,`url` 的值 `/api/v1` 提取自 `roog_path`。
+
+///
http://127.0.0.1:9999/api/v1/docs 的 API 文档所示如下:
-!!! tip "提示"
+/// tip | "提示"
- API 文档与所选的服务器进行交互。
+API 文档与所选的服务器进行交互。
+
+///
### 从 `root_path` 禁用自动服务器
如果不想让 **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!}
```
这样,就不会在 OpenAPI 概图中包含服务器了。
diff --git a/docs/zh/docs/advanced/custom-response.md b/docs/zh/docs/advanced/custom-response.md
index 155ce2882..27c026904 100644
--- a/docs/zh/docs/advanced/custom-response.md
+++ b/docs/zh/docs/advanced/custom-response.md
@@ -12,8 +12,11 @@
并且如果该 `Response` 有一个 JSON 媒体类型(`application/json`),比如使用 `JSONResponse` 或者 `UJSONResponse` 的时候,返回的数据将使用你在路径操作装饰器中声明的任何 Pydantic 的 `response_model` 自动转换(和过滤)。
-!!! note "说明"
- 如果你使用不带有任何媒体类型的响应类,FastAPI 认为你的响应没有任何内容,所以不会在生成的OpenAPI文档中记录响应格式。
+/// note | "说明"
+
+如果你使用不带有任何媒体类型的响应类,FastAPI 认为你的响应没有任何内容,所以不会在生成的OpenAPI文档中记录响应格式。
+
+///
## 使用 `ORJSONResponse`
@@ -22,20 +25,24 @@
导入你想要使用的 `Response` 类(子类)然后在 *路径操作装饰器* 中声明它。
```Python hl_lines="2 7"
-{!../../../docs_src/custom_response/tutorial001b.py!}
+{!../../docs_src/custom_response/tutorial001b.py!}
```
-!!! info "提示"
- 参数 `response_class` 也会用来定义响应的「媒体类型」。
+/// info | "提示"
- 在这个例子中,HTTP 头的 `Content-Type` 会被设置成 `application/json`。
+参数 `response_class` 也会用来定义响应的「媒体类型」。
- 并且在 OpenAPI 文档中也会这样记录。
+在这个例子中,HTTP 头的 `Content-Type` 会被设置成 `application/json`。
-!!! tip "小贴士"
- `ORJSONResponse` 目前只在 FastAPI 中可用,而在 Starlette 中不可用。
+并且在 OpenAPI 文档中也会这样记录。
+///
+/// tip | "小贴士"
+
+`ORJSONResponse` 目前只在 FastAPI 中可用,而在 Starlette 中不可用。
+
+///
## HTML 响应
@@ -45,15 +52,18 @@
* 将 `HTMLResponse` 作为你的 *路径操作* 的 `response_class` 参数传入。
```Python hl_lines="2 7"
-{!../../../docs_src/custom_response/tutorial002.py!}
+{!../../docs_src/custom_response/tutorial002.py!}
```
-!!! info "提示"
- 参数 `response_class` 也会用来定义响应的「媒体类型」。
+/// info | "提示"
- 在这个例子中,HTTP 头的 `Content-Type` 会被设置成 `text/html`。
+参数 `response_class` 也会用来定义响应的「媒体类型」。
- 并且在 OpenAPI 文档中也会这样记录。
+在这个例子中,HTTP 头的 `Content-Type` 会被设置成 `text/html`。
+
+并且在 OpenAPI 文档中也会这样记录。
+
+///
### 返回一个 `Response`
@@ -62,14 +72,20 @@
和上面一样的例子,返回一个 `HTMLResponse` 看起来可能是这样:
```Python hl_lines="2 7 19"
-{!../../../docs_src/custom_response/tutorial003.py!}
+{!../../docs_src/custom_response/tutorial003.py!}
```
-!!! warning "警告"
- *路径操作函数* 直接返回的 `Response` 不会被 OpenAPI 的文档记录(比如,`Content-Type` 不会被文档记录),并且在自动化交互文档中也是不可见的。
+/// warning | "警告"
-!!! info "提示"
- 当然,实际的 `Content-Type` 头,状态码等等,将来自于你返回的 `Response` 对象。
+*路径操作函数* 直接返回的 `Response` 不会被 OpenAPI 的文档记录(比如,`Content-Type` 不会被文档记录),并且在自动化交互文档中也是不可见的。
+
+///
+
+/// info | "提示"
+
+当然,实际的 `Content-Type` 头,状态码等等,将来自于你返回的 `Response` 对象。
+
+///
### OpenAPI 中的文档和重载 `Response`
@@ -82,7 +98,7 @@
比如像这样:
```Python hl_lines="7 23 21"
-{!../../../docs_src/custom_response/tutorial004.py!}
+{!../../docs_src/custom_response/tutorial004.py!}
```
在这个例子中,函数 `generate_html_response()` 已经生成并返回 `Response` 对象而不是在 `str` 中返回 HTML。
@@ -99,10 +115,13 @@
要记得你可以使用 `Response` 来返回任何其他东西,甚至创建一个自定义的子类。
-!!! note "技术细节"
- 你也可以使用 `from starlette.responses import HTMLResponse`。
+/// note | "技术细节"
- **FastAPI** 提供了同 `fastapi.responses` 相同的 `starlette.responses` 只是为了方便开发者。但大多数可用的响应都直接来自 Starlette。
+你也可以使用 `from starlette.responses import HTMLResponse`。
+
+**FastAPI** 提供了同 `fastapi.responses` 相同的 `starlette.responses` 只是为了方便开发者。但大多数可用的响应都直接来自 Starlette。
+
+///
### `Response`
@@ -121,7 +140,7 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它
```Python hl_lines="1 18"
-{!../../../docs_src/response_directly/tutorial002.py!}
+{!../../docs_src/response_directly/tutorial002.py!}
```
### `HTMLResponse`
@@ -133,7 +152,7 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它
接受文本或字节并返回纯文本响应。
```Python hl_lines="2 7 9"
-{!../../../docs_src/custom_response/tutorial005.py!}
+{!../../docs_src/custom_response/tutorial005.py!}
```
### `JSONResponse`
@@ -151,22 +170,28 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它
`UJSONResponse` 是一个使用 `ujson` 的可选 JSON 响应。
-!!! warning "警告"
- 在处理某些边缘情况时,`ujson` 不如 Python 的内置实现那么谨慎。
+/// warning | "警告"
+
+在处理某些边缘情况时,`ujson` 不如 Python 的内置实现那么谨慎。
+
+///
```Python hl_lines="2 7"
-{!../../../docs_src/custom_response/tutorial001.py!}
+{!../../docs_src/custom_response/tutorial001.py!}
```
-!!! tip "小贴士"
- `ORJSONResponse` 可能是一个更快的选择。
+/// tip | "小贴士"
+
+`ORJSONResponse` 可能是一个更快的选择。
+
+///
### `RedirectResponse`
返回 HTTP 重定向。默认情况下使用 307 状态代码(临时重定向)。
```Python hl_lines="2 9"
-{!../../../docs_src/custom_response/tutorial006.py!}
+{!../../docs_src/custom_response/tutorial006.py!}
```
### `StreamingResponse`
@@ -174,7 +199,7 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它
采用异步生成器或普通生成器/迭代器,然后流式传输响应主体。
```Python hl_lines="2 14"
-{!../../../docs_src/custom_response/tutorial007.py!}
+{!../../docs_src/custom_response/tutorial007.py!}
```
#### 对类似文件的对象使用 `StreamingResponse`
@@ -184,11 +209,14 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它
包括许多与云存储,视频处理等交互的库。
```Python hl_lines="2 10-12 14"
-{!../../../docs_src/custom_response/tutorial008.py!}
+{!../../docs_src/custom_response/tutorial008.py!}
```
-!!! tip "小贴士"
- 注意在这里,因为我们使用的是不支持 `async` 和 `await` 的标准 `open()`,我们使用普通的 `def` 声明了路径操作。
+/// tip | "小贴士"
+
+注意在这里,因为我们使用的是不支持 `async` 和 `await` 的标准 `open()`,我们使用普通的 `def` 声明了路径操作。
+
+///
### `FileResponse`
@@ -204,7 +232,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!}
```
## 额外文档
diff --git a/docs/zh/docs/advanced/dataclasses.md b/docs/zh/docs/advanced/dataclasses.md
index 5a93877cc..f33c05ff4 100644
--- a/docs/zh/docs/advanced/dataclasses.md
+++ b/docs/zh/docs/advanced/dataclasses.md
@@ -5,7 +5,7 @@ FastAPI 基于 **Pydantic** 构建,前文已经介绍过如何使用 Pydantic
但 FastAPI 还可以使用数据类(`dataclasses`):
```Python hl_lines="1 7-12 19-20"
-{!../../../docs_src/dataclasses/tutorial001.py!}
+{!../../docs_src/dataclasses/tutorial001.py!}
```
这还是借助于 **Pydantic** 及其内置的 `dataclasses`。
@@ -20,20 +20,22 @@ FastAPI 基于 **Pydantic** 构建,前文已经介绍过如何使用 Pydantic
数据类的和运作方式与 Pydantic 模型相同。实际上,它的底层使用的也是 Pydantic。
-!!! info "说明"
+/// info | "说明"
- 注意,数据类不支持 Pydantic 模型的所有功能。
+注意,数据类不支持 Pydantic 模型的所有功能。
- 因此,开发时仍需要使用 Pydantic 模型。
+因此,开发时仍需要使用 Pydantic 模型。
- 但如果数据类很多,这一技巧能给 FastAPI 开发 Web API 增添不少助力。🤓
+但如果数据类很多,这一技巧能给 FastAPI 开发 Web API 增添不少助力。🤓
+
+///
## `response_model` 使用数据类
在 `response_model` 参数中使用 `dataclasses`:
```Python hl_lines="1 7-13 19"
-{!../../../docs_src/dataclasses/tutorial002.py!}
+{!../../docs_src/dataclasses/tutorial002.py!}
```
本例把数据类自动转换为 Pydantic 数据类。
@@ -51,7 +53,7 @@ API 文档中也会显示相关概图:
本例把标准的 `dataclasses` 直接替换为 `pydantic.dataclasses`:
```{ .python .annotate hl_lines="1 5 8-11 14-17 23-25 28" }
-{!../../../docs_src/dataclasses/tutorial003.py!}
+{!../../docs_src/dataclasses/tutorial003.py!}
```
1. 本例依然要从标准的 `dataclasses` 中导入 `field`;
diff --git a/docs/zh/docs/advanced/events.md b/docs/zh/docs/advanced/events.md
index 8e5fa7d12..e5b44f321 100644
--- a/docs/zh/docs/advanced/events.md
+++ b/docs/zh/docs/advanced/events.md
@@ -4,16 +4,18 @@
事件函数既可以声明为异步函数(`async def`),也可以声明为普通函数(`def`)。
-!!! warning "警告"
+/// warning | "警告"
- **FastAPI** 只执行主应用中的事件处理器,不执行[子应用 - 挂载](sub-applications.md){.internal-link target=_blank}中的事件处理器。
+**FastAPI** 只执行主应用中的事件处理器,不执行[子应用 - 挂载](sub-applications.md){.internal-link target=_blank}中的事件处理器。
+
+///
## `startup` 事件
使用 `startup` 事件声明 `app` 启动前运行的函数:
```Python hl_lines="8"
-{!../../../docs_src/events/tutorial001.py!}
+{!../../docs_src/events/tutorial001.py!}
```
本例中,`startup` 事件处理器函数为项目数据库(只是**字典**)提供了一些初始值。
@@ -27,25 +29,31 @@
使用 `shutdown` 事件声明 `app` 关闭时运行的函数:
```Python hl_lines="6"
-{!../../../docs_src/events/tutorial002.py!}
+{!../../docs_src/events/tutorial002.py!}
```
此处,`shutdown` 事件处理器函数在 `log.txt` 中写入一行文本 `Application shutdown`。
-!!! info "说明"
+/// info | "说明"
- `open()` 函数中,`mode="a"` 指的是**追加**。因此这行文本会添加在文件已有内容之后,不会覆盖之前的内容。
+`open()` 函数中,`mode="a"` 指的是**追加**。因此这行文本会添加在文件已有内容之后,不会覆盖之前的内容。
-!!! tip "提示"
+///
- 注意,本例使用 Python `open()` 标准函数与文件交互。
+/// tip | "提示"
- 这个函数执行 I/O(输入/输出)操作,需要等待内容写进磁盘。
+注意,本例使用 Python `open()` 标准函数与文件交互。
- 但 `open()` 函数不支持使用 `async` 与 `await`。
+这个函数执行 I/O(输入/输出)操作,需要等待内容写进磁盘。
- 因此,声明事件处理函数要使用 `def`,不能使用 `asnyc def`。
+但 `open()` 函数不支持使用 `async` 与 `await`。
-!!! info "说明"
+因此,声明事件处理函数要使用 `def`,不能使用 `asnyc def`。
- 有关事件处理器的详情,请参阅 Starlette 官档 - 事件。
+///
+
+/// info | "说明"
+
+有关事件处理器的详情,请参阅 Starlette 官档 - 事件。
+
+///
diff --git a/docs/zh/docs/advanced/generate-clients.md b/docs/zh/docs/advanced/generate-clients.md
index c4ffcb46c..baf131361 100644
--- a/docs/zh/docs/advanced/generate-clients.md
+++ b/docs/zh/docs/advanced/generate-clients.md
@@ -16,17 +16,21 @@
让我们从一个简单的 FastAPI 应用开始:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="7-9 12-13 16-17 21"
- {!> ../../../docs_src/generate_clients/tutorial001_py39.py!}
- ```
+```Python hl_lines="7-9 12-13 16-17 21"
+{!> ../../docs_src/generate_clients/tutorial001_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9-11 14-15 18 19 23"
- {!> ../../../docs_src/generate_clients/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="9-11 14-15 18 19 23"
+{!> ../../docs_src/generate_clients/tutorial001.py!}
+```
+
+////
请注意,*路径操作* 定义了他们所用于请求数据和回应数据的模型,所使用的模型是`Item` 和 `ResponseMessage`。
@@ -111,8 +115,11 @@ frontend-app@1.0.0 generate-client /home/user/code/frontend-app
-!!! tip
- 请注意, `name` 和 `price` 的自动补全,是通过其在`Item`模型(FastAPI)中的定义实现的。
+/// tip
+
+请注意, `name` 和 `price` 的自动补全,是通过其在`Item`模型(FastAPI)中的定义实现的。
+
+///
如果发送的数据字段不符,你也会看到编辑器的错误提示:
@@ -128,17 +135,21 @@ frontend-app@1.0.0 generate-client /home/user/code/frontend-app
例如,您可以有一个用 `items` 的部分和另一个用于 `users` 的部分,它们可以用标签来分隔:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="21 26 34"
- {!> ../../../docs_src/generate_clients/tutorial002_py39.py!}
- ```
+```Python hl_lines="21 26 34"
+{!> ../../docs_src/generate_clients/tutorial002_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="23 28 36"
- {!> ../../../docs_src/generate_clients/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="23 28 36"
+{!> ../../docs_src/generate_clients/tutorial002.py!}
+```
+
+////
### 生成带有标签的 TypeScript 客户端
@@ -185,17 +196,21 @@ FastAPI为每个*路径操作*使用一个**唯一ID**,它用于**操作ID**
然后,你可以将这个自定义函数作为 `generate_unique_id_function` 参数传递给 **FastAPI**:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="6-7 10"
- {!> ../../../docs_src/generate_clients/tutorial003_py39.py!}
- ```
+```Python hl_lines="6-7 10"
+{!> ../../docs_src/generate_clients/tutorial003_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="8-9 12"
- {!> ../../../docs_src/generate_clients/tutorial003.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="8-9 12"
+{!> ../../docs_src/generate_clients/tutorial003.py!}
+```
+
+////
### 使用自定义操作ID生成TypeScript客户端
@@ -218,7 +233,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/index.md b/docs/zh/docs/advanced/index.md
index e39eed805..6525802fc 100644
--- a/docs/zh/docs/advanced/index.md
+++ b/docs/zh/docs/advanced/index.md
@@ -6,10 +6,13 @@
你会在接下来的章节中了解到其他的选项、配置以及额外的特性。
-!!! tip
- 接下来的章节**并不一定是**「高级的」。
+/// tip
- 而且对于你的使用场景来说,解决方案很可能就在其中。
+接下来的章节**并不一定是**「高级的」。
+
+而且对于你的使用场景来说,解决方案很可能就在其中。
+
+///
## 先阅读教程
diff --git a/docs/zh/docs/advanced/middleware.md b/docs/zh/docs/advanced/middleware.md
index 06232fe17..525dc89ac 100644
--- a/docs/zh/docs/advanced/middleware.md
+++ b/docs/zh/docs/advanced/middleware.md
@@ -43,11 +43,13 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow")
**FastAPI** 为常见用例提供了一些中间件,下面介绍怎么使用这些中间件。
-!!! note "技术细节"
+/// note | "技术细节"
- 以下几个示例中也可以使用 `from starlette.middleware.something import SomethingMiddleware`。
+以下几个示例中也可以使用 `from starlette.middleware.something import SomethingMiddleware`。
- **FastAPI** 在 `fastapi.middleware` 中提供的中间件只是为了方便开发者使用,但绝大多数可用的中间件都直接继承自 Starlette。
+**FastAPI** 在 `fastapi.middleware` 中提供的中间件只是为了方便开发者使用,但绝大多数可用的中间件都直接继承自 Starlette。
+
+///
## `HTTPSRedirectMiddleware`
@@ -56,7 +58,7 @@ 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!}
```
## `TrustedHostMiddleware`
@@ -64,7 +66,7 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow")
强制所有传入请求都必须正确设置 `Host` 请求头,以防 HTTP 主机头攻击。
```Python hl_lines="2 6-8"
-{!../../../docs_src/advanced_middleware/tutorial002.py!}
+{!../../docs_src/advanced_middleware/tutorial002.py!}
```
支持以下参数:
@@ -80,7 +82,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!}
```
支持以下参数:
@@ -93,7 +95,6 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow")
例如:
-* Sentry
* Uvicorn 的 `ProxyHeadersMiddleware`
* MessagePack
diff --git a/docs/zh/docs/advanced/openapi-callbacks.md b/docs/zh/docs/advanced/openapi-callbacks.md
index e2dadbfb0..dc1c2539b 100644
--- a/docs/zh/docs/advanced/openapi-callbacks.md
+++ b/docs/zh/docs/advanced/openapi-callbacks.md
@@ -32,12 +32,14 @@ API 的用户 (外部开发者)要在您的 API 内使用 POST 请求创建
这部分代码很常规,您对绝大多数代码应该都比较熟悉了:
```Python hl_lines="10-14 37-54"
-{!../../../docs_src/openapi_callbacks/tutorial001.py!}
+{!../../docs_src/openapi_callbacks/tutorial001.py!}
```
-!!! tip "提示"
+/// tip | "提示"
- `callback_url` 查询参数使用 Pydantic 的 URL 类型。
+`callback_url` 查询参数使用 Pydantic 的 URL 类型。
+
+///
此处唯一比较新的内容是*路径操作装饰器*中的 `callbacks=invoices_callback_router.routes` 参数,下文介绍。
@@ -62,11 +64,13 @@ requests.post(callback_url, json={"description": "Invoice paid", "paid": True})
本例没有实现回调本身(只是一行代码),只有文档部分。
-!!! tip "提示"
+/// tip | "提示"
- 实际的回调只是 HTTP 请求。
+实际的回调只是 HTTP 请求。
- 实现回调时,要使用 HTTPX 或 Requests。
+实现回调时,要使用 HTTPX 或 Requests。
+
+///
## 编写回调文档代码
@@ -76,18 +80,20 @@ requests.post(callback_url, json={"description": "Invoice paid", "paid": True})
我们要使用与存档*外部 API* 相同的知识……通过创建外部 API 要实现的*路径操作*(您的 API 要调用的)。
-!!! tip "提示"
+/// tip | "提示"
- 编写存档回调的代码时,假设您是*外部开发者*可能会用的上。并且您当前正在实现的是*外部 API*,不是*您自己的 API*。
+编写存档回调的代码时,假设您是*外部开发者*可能会用的上。并且您当前正在实现的是*外部 API*,不是*您自己的 API*。
- 临时改变(为外部开发者的)视角能让您更清楚该如何放置*外部 API* 响应和请求体的参数与 Pydantic 模型等。
+临时改变(为外部开发者的)视角能让您更清楚该如何放置*外部 API* 响应和请求体的参数与 Pydantic 模型等。
+
+///
### 创建回调的 `APIRouter`
首先,新建包含一些用于回调的 `APIRouter`。
```Python hl_lines="5 26"
-{!../../../docs_src/openapi_callbacks/tutorial001.py!}
+{!../../docs_src/openapi_callbacks/tutorial001.py!}
```
### 创建回调*路径操作*
@@ -100,7 +106,7 @@ requests.post(callback_url, json={"description": "Invoice paid", "paid": True})
* 还要声明要返回的响应,例如,`response_model=InvoiceEventReceived`
```Python hl_lines="17-19 22-23 29-33"
-{!../../../docs_src/openapi_callbacks/tutorial001.py!}
+{!../../docs_src/openapi_callbacks/tutorial001.py!}
```
回调*路径操作*与常规*路径操作*有两点主要区别:
@@ -157,9 +163,11 @@ JSON 请求体包含如下内容:
}
```
-!!! tip "提示"
+/// tip | "提示"
- 注意,回调 URL包含 `callback_url` (`https://www.external.org/events`)中的查询参数,还有 JSON 请求体内部的发票 ID(`2expen51ve`)。
+注意,回调 URL包含 `callback_url` (`https://www.external.org/events`)中的查询参数,还有 JSON 请求体内部的发票 ID(`2expen51ve`)。
+
+///
### 添加回调路由
@@ -168,12 +176,14 @@ JSON 请求体包含如下内容:
现在使用 API *路径操作装饰器*的参数 `callbacks`,从回调路由传递属性 `.routes`(实际上只是路由/路径操作的**列表**):
```Python hl_lines="36"
-{!../../../docs_src/openapi_callbacks/tutorial001.py!}
+{!../../docs_src/openapi_callbacks/tutorial001.py!}
```
-!!! tip "提示"
+/// tip | "提示"
- 注意,不能把路由本身(`invoices_callback_router`)传递给 `callback=`,要传递 `invoices_callback_router.routes` 中的 `.routes` 属性。
+注意,不能把路由本身(`invoices_callback_router`)传递给 `callback=`,要传递 `invoices_callback_router.routes` 中的 `.routes` 属性。
+
+///
### 查看文档
diff --git a/docs/zh/docs/advanced/path-operation-advanced-configuration.md b/docs/zh/docs/advanced/path-operation-advanced-configuration.md
index 7da9f251e..0d77dd69e 100644
--- a/docs/zh/docs/advanced/path-operation-advanced-configuration.md
+++ b/docs/zh/docs/advanced/path-operation-advanced-configuration.md
@@ -2,15 +2,18 @@
## OpenAPI 的 operationId
-!!! warning
- 如果你并非 OpenAPI 的「专家」,你可能不需要这部分内容。
+/// warning
+
+如果你并非 OpenAPI 的「专家」,你可能不需要这部分内容。
+
+///
你可以在路径操作中通过参数 `operation_id` 设置要使用的 OpenAPI `operationId`。
务必确保每个操作路径的 `operation_id` 都是唯一的。
```Python hl_lines="6"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial001.py!}
+{!../../docs_src/path_operation_advanced_configuration/tutorial001.py!}
```
### 使用 *路径操作函数* 的函数名作为 operationId
@@ -20,23 +23,29 @@
你应该在添加了所有 *路径操作* 之后执行此操作。
```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!}
```
-!!! tip
- 如果你手动调用 `app.openapi()`,你应该在此之前更新 `operationId`。
+/// tip
-!!! warning
- 如果你这样做,务必确保你的每个 *路径操作函数* 的名字唯一。
+如果你手动调用 `app.openapi()`,你应该在此之前更新 `operationId`。
- 即使它们在不同的模块中(Python 文件)。
+///
+
+/// warning
+
+如果你这样做,务必确保你的每个 *路径操作函数* 的名字唯一。
+
+即使它们在不同的模块中(Python 文件)。
+
+///
## 从 OpenAPI 中排除
使用参数 `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!}
```
## docstring 的高级描述
@@ -49,5 +58,5 @@
```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!}
```
diff --git a/docs/zh/docs/advanced/response-change-status-code.md b/docs/zh/docs/advanced/response-change-status-code.md
index a289cf201..c38f80f1f 100644
--- a/docs/zh/docs/advanced/response-change-status-code.md
+++ b/docs/zh/docs/advanced/response-change-status-code.md
@@ -21,7 +21,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!}
```
然后你可以像平常一样返回任何你需要的对象(例如一个`dict`或者一个数据库模型)。如果你声明了一个`response_model`,它仍然会被用来过滤和转换你返回的对象。
diff --git a/docs/zh/docs/advanced/response-cookies.md b/docs/zh/docs/advanced/response-cookies.md
index 3e53c5319..5772664b0 100644
--- a/docs/zh/docs/advanced/response-cookies.md
+++ b/docs/zh/docs/advanced/response-cookies.md
@@ -5,7 +5,7 @@
你可以在 *路径函数* 中定义一个类型为 `Response`的参数,这样你就可以在这个临时响应对象中设置cookie了。
```Python hl_lines="1 8-9"
-{!../../../docs_src/response_cookies/tutorial002.py!}
+{!../../docs_src/response_cookies/tutorial002.py!}
```
而且你还可以根据你的需要响应不同的对象,比如常用的 `dict`,数据库model等。
@@ -25,23 +25,29 @@
然后设置Cookies,并返回:
```Python hl_lines="10-12"
-{!../../../docs_src/response_cookies/tutorial001.py!}
+{!../../docs_src/response_cookies/tutorial001.py!}
```
-!!! tip
- 需要注意,如果你直接反馈一个response对象,而不是使用`Response`入参,FastAPI则会直接反馈你封装的response对象。
+/// tip
- 所以你需要确保你响应数据类型的正确性,如:你可以使用`JSONResponse`来兼容JSON的场景。
+需要注意,如果你直接反馈一个response对象,而不是使用`Response`入参,FastAPI则会直接反馈你封装的response对象。
- 同时,你也应当仅反馈通过`response_model`过滤过的数据。
+所以你需要确保你响应数据类型的正确性,如:你可以使用`JSONResponse`来兼容JSON的场景。
+
+同时,你也应当仅反馈通过`response_model`过滤过的数据。
+
+///
### 更多信息
-!!! note "技术细节"
- 你也可以使用`from starlette.responses import Response` 或者 `from starlette.responses import JSONResponse`。
+/// note | "技术细节"
- 为了方便开发者,**FastAPI** 封装了相同数据类型,如`starlette.responses` 和 `fastapi.responses`。不过大部分response对象都是直接引用自Starlette。
+你也可以使用`from starlette.responses import Response` 或者 `from starlette.responses import JSONResponse`。
- 因为`Response`对象可以非常便捷的设置headers和cookies,所以 **FastAPI** 同时也封装了`fastapi.Response`。
+为了方便开发者,**FastAPI** 封装了相同数据类型,如`starlette.responses` 和 `fastapi.responses`。不过大部分response对象都是直接引用自Starlette。
+
+因为`Response`对象可以非常便捷的设置headers和cookies,所以 **FastAPI** 同时也封装了`fastapi.Response`。
+
+///
如果你想查看所有可用的参数和选项,可以参考 Starlette帮助文档
diff --git a/docs/zh/docs/advanced/response-directly.md b/docs/zh/docs/advanced/response-directly.md
index 797a878eb..9d191c622 100644
--- a/docs/zh/docs/advanced/response-directly.md
+++ b/docs/zh/docs/advanced/response-directly.md
@@ -14,8 +14,11 @@
事实上,你可以返回任意 `Response` 或者任意 `Response` 的子类。
-!!! tip "小贴士"
- `JSONResponse` 本身是一个 `Response` 的子类。
+/// tip | "小贴士"
+
+`JSONResponse` 本身是一个 `Response` 的子类。
+
+///
当你返回一个 `Response` 时,**FastAPI** 会直接传递它。
@@ -33,13 +36,16 @@
```Python hl_lines="4 6 20 21"
-{!../../../docs_src/response_directly/tutorial001.py!}
+{!../../docs_src/response_directly/tutorial001.py!}
```
-!!! note "技术细节"
- 你也可以使用 `from starlette.responses import JSONResponse`。
+/// note | "技术细节"
- 出于方便,**FastAPI** 会提供与 `starlette.responses` 相同的 `fastapi.responses` 给开发者。但是大多数可用的响应都直接来自 Starlette。
+你也可以使用 `from starlette.responses import JSONResponse`。
+
+出于方便,**FastAPI** 会提供与 `starlette.responses` 相同的 `fastapi.responses` 给开发者。但是大多数可用的响应都直接来自 Starlette。
+
+///
## 返回自定义 `Response`
@@ -52,7 +58,7 @@
你可以把你的 XML 内容放到一个字符串中,放到一个 `Response` 中,然后返回。
```Python hl_lines="1 18"
-{!../../../docs_src/response_directly/tutorial002.py!}
+{!../../docs_src/response_directly/tutorial002.py!}
```
## 说明
diff --git a/docs/zh/docs/advanced/response-headers.md b/docs/zh/docs/advanced/response-headers.md
index 229efffcb..d593fdccc 100644
--- a/docs/zh/docs/advanced/response-headers.md
+++ b/docs/zh/docs/advanced/response-headers.md
@@ -6,7 +6,7 @@
然后你可以在这个*临时*响应对象中设置头部。
```Python hl_lines="1 7-8"
-{!../../../docs_src/response_headers/tutorial002.py!}
+{!../../docs_src/response_headers/tutorial002.py!}
```
然后你可以像平常一样返回任何你需要的对象(例如一个`dict`或者一个数据库模型)。如果你声明了一个`response_model`,它仍然会被用来过滤和转换你返回的对象。
@@ -21,16 +21,19 @@
按照[直接返回响应](response-directly.md){.internal-link target=_blank}中所述创建响应,并将头部作为附加参数传递:
```Python hl_lines="10-12"
-{!../../../docs_src/response_headers/tutorial001.py!}
+{!../../docs_src/response_headers/tutorial001.py!}
```
-!!! note "技术细节"
- 你也可以使用`from starlette.responses import Response`或`from starlette.responses import JSONResponse`。
+/// note | "技术细节"
- **FastAPI**提供了与`fastapi.responses`相同的`starlette.responses`,只是为了方便开发者。但是,大多数可用的响应都直接来自Starlette。
+你也可以使用`from starlette.responses import Response`或`from starlette.responses import JSONResponse`。
- 由于`Response`经常用于设置头部和cookies,因此**FastAPI**还在`fastapi.Response`中提供了它。
+**FastAPI**提供了与`fastapi.responses`相同的`starlette.responses`,只是为了方便开发者。但是,大多数可用的响应都直接来自Starlette。
+
+由于`Response`经常用于设置头部和cookies,因此**FastAPI**还在`fastapi.Response`中提供了它。
+
+///
## 自定义头部
diff --git a/docs/zh/docs/advanced/security/http-basic-auth.md b/docs/zh/docs/advanced/security/http-basic-auth.md
index ab8961e7c..06c6dbbab 100644
--- a/docs/zh/docs/advanced/security/http-basic-auth.md
+++ b/docs/zh/docs/advanced/security/http-basic-auth.md
@@ -20,26 +20,35 @@ HTTP 基础授权让浏览器显示内置的用户名与密码提示。
* 返回类型为 `HTTPBasicCredentials` 的对象:
* 包含发送的 `username` 与 `password`
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="4 8 12"
- {!> ../../../docs_src/security/tutorial006_an_py39.py!}
- ```
+```Python hl_lines="4 8 12"
+{!> ../../docs_src/security/tutorial006_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="2 7 11"
- {!> ../../../docs_src/security/tutorial006_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="2 7 11"
+{!> ../../docs_src/security/tutorial006_an.py!}
+```
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+////
- ```Python hl_lines="2 6 10"
- {!> ../../../docs_src/security/tutorial006.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="2 6 10"
+{!> ../../docs_src/security/tutorial006.py!}
+```
+
+////
第一次打开 URL(或在 API 文档中点击 **Execute** 按钮)时,浏览器要求输入用户名与密码:
@@ -59,26 +68,36 @@ HTTP 基础授权让浏览器显示内置的用户名与密码提示。
然后我们可以使用 `secrets.compare_digest()` 来确保 `credentials.username` 是 `"stanleyjobson"`,且 `credentials.password` 是`"swordfish"`。
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="1 12-24"
- {!> ../../../docs_src/security/tutorial007_an_py39.py!}
- ```
+```Python hl_lines="1 12-24"
+{!> ../../docs_src/security/tutorial007_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1 12-24"
- {!> ../../../docs_src/security/tutorial007_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="1 12-24"
+{!> ../../docs_src/security/tutorial007_an.py!}
+```
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="1 11-21"
+{!> ../../docs_src/security/tutorial007.py!}
+```
+
+////
- ```Python hl_lines="1 11-21"
- {!> ../../../docs_src/security/tutorial007.py!}
- ```
这类似于:
```Python
@@ -141,23 +160,32 @@ if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish":
检测到凭证不正确后,返回 `HTTPException` 及状态码 401(与无凭证时返回的内容一样),并添加请求头 `WWW-Authenticate`,让浏览器再次显示登录提示:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="26-30"
- {!> ../../../docs_src/security/tutorial007_an_py39.py!}
- ```
+```Python hl_lines="26-30"
+{!> ../../docs_src/security/tutorial007_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="26-30"
- {!> ../../../docs_src/security/tutorial007_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="26-30"
+{!> ../../docs_src/security/tutorial007_an.py!}
+```
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+////
- ```Python hl_lines="23-27"
- {!> ../../../docs_src/security/tutorial007.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="23-27"
+{!> ../../docs_src/security/tutorial007.py!}
+```
+
+////
diff --git a/docs/zh/docs/advanced/security/index.md b/docs/zh/docs/advanced/security/index.md
index e2bef4765..836086ae2 100644
--- a/docs/zh/docs/advanced/security/index.md
+++ b/docs/zh/docs/advanced/security/index.md
@@ -4,10 +4,13 @@
除 [教程 - 用户指南: 安全性](../../tutorial/security/index.md){.internal-link target=_blank} 中涵盖的功能之外,还有一些额外的功能来处理安全性.
-!!! tip "小贴士"
- 接下来的章节 **并不一定是 "高级的"**.
+/// tip | "小贴士"
- 而且对于你的使用场景来说,解决方案很可能就在其中。
+接下来的章节 **并不一定是 "高级的"**.
+
+而且对于你的使用场景来说,解决方案很可能就在其中。
+
+///
## 先阅读教程
diff --git a/docs/zh/docs/advanced/security/oauth2-scopes.md b/docs/zh/docs/advanced/security/oauth2-scopes.md
index e5eeffb0a..d6354230e 100644
--- a/docs/zh/docs/advanced/security/oauth2-scopes.md
+++ b/docs/zh/docs/advanced/security/oauth2-scopes.md
@@ -10,19 +10,21 @@ OAuth2 也是脸书、谷歌、GitHub、微软、推特等第三方身份验证
本章介绍如何在 **FastAPI** 应用中使用 OAuth2 作用域管理验证与授权。
-!!! warning "警告"
+/// warning | "警告"
- 本章内容较难,刚接触 FastAPI 的新手可以跳过。
+本章内容较难,刚接触 FastAPI 的新手可以跳过。
- OAuth2 作用域不是必需的,没有它,您也可以处理身份验证与授权。
+OAuth2 作用域不是必需的,没有它,您也可以处理身份验证与授权。
- 但 OAuth2 作用域与 API(通过 OpenAPI)及 API 文档集成地更好。
+但 OAuth2 作用域与 API(通过 OpenAPI)及 API 文档集成地更好。
- 不管怎么说,**FastAPI** 支持在代码中使用作用域或其它安全/授权需求项。
+不管怎么说,**FastAPI** 支持在代码中使用作用域或其它安全/授权需求项。
- 很多情况下,OAuth2 作用域就像一把牛刀。
+很多情况下,OAuth2 作用域就像一把牛刀。
- 但如果您确定要使用作用域,或对它有兴趣,请继续阅读。
+但如果您确定要使用作用域,或对它有兴趣,请继续阅读。
+
+///
## OAuth2 作用域与 OpenAPI
@@ -44,22 +46,24 @@ OpenAPI 中(例如 API 文档)可以定义**安全方案**。
* 脸书和 Instagram 使用 `instagram_basic`
* 谷歌使用 `https://www.googleapis.com/auth/drive`
-!!! info "说明"
+/// info | "说明"
- OAuth2 中,**作用域**只是声明特定权限的字符串。
+OAuth2 中,**作用域**只是声明特定权限的字符串。
- 是否使用冒号 `:` 等符号,或是不是 URL 并不重要。
+是否使用冒号 `:` 等符号,或是不是 URL 并不重要。
- 这些细节只是特定的实现方式。
+这些细节只是特定的实现方式。
- 对 OAuth2 来说,它们都只是字符串而已。
+对 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!}
```
下面,我们逐步说明修改的代码内容。
@@ -71,7 +75,7 @@ OpenAPI 中(例如 API 文档)可以定义**安全方案**。
`scopes` 参数接收**字典**,键是作用域、值是作用域的描述:
```Python hl_lines="62-65"
-{!../../../docs_src/security/tutorial005.py!}
+{!../../docs_src/security/tutorial005.py!}
```
因为声明了作用域,所以登录或授权时会在 API 文档中显示。
@@ -90,14 +94,16 @@ OpenAPI 中(例如 API 文档)可以定义**安全方案**。
这样,返回的 JWT 令牌中就包含了作用域。
-!!! danger "危险"
+/// danger | "危险"
- 为了简明起见,本例把接收的作用域直接添加到了令牌里。
+为了简明起见,本例把接收的作用域直接添加到了令牌里。
- 但在您的应用中,为了安全,应该只把作用域添加到确实需要作用域的用户,或预定义的用户。
+但在您的应用中,为了安全,应该只把作用域添加到确实需要作用域的用户,或预定义的用户。
+
+///
```Python hl_lines="153"
-{!../../../docs_src/security/tutorial005.py!}
+{!../../docs_src/security/tutorial005.py!}
```
## 在*路径操作*与依赖项中声明作用域
@@ -116,23 +122,27 @@ OpenAPI 中(例如 API 文档)可以定义**安全方案**。
本例要求使用作用域 `me`(还可以使用更多作用域)。
-!!! note "笔记"
+/// note | "笔记"
- 不必在不同位置添加不同的作用域。
+不必在不同位置添加不同的作用域。
- 本例使用的这种方式只是为了展示 **FastAPI** 如何处理在不同层级声明的作用域。
+本例使用的这种方式只是为了展示 **FastAPI** 如何处理在不同层级声明的作用域。
+
+///
```Python hl_lines="4 139 166"
-{!../../../docs_src/security/tutorial005.py!}
+{!../../docs_src/security/tutorial005.py!}
```
-!!! info "技术细节"
+/// info | "技术细节"
- `Security` 实际上是 `Depends` 的子类,而且只比 `Depends` 多一个参数。
+`Security` 实际上是 `Depends` 的子类,而且只比 `Depends` 多一个参数。
- 但使用 `Security` 代替 `Depends`,**FastAPI** 可以声明安全作用域,并在内部使用这些作用域,同时,使用 OpenAPI 存档 API。
+但使用 `Security` 代替 `Depends`,**FastAPI** 可以声明安全作用域,并在内部使用这些作用域,同时,使用 OpenAPI 存档 API。
- 但实际上,从 `fastapi` 导入的 `Query`、`Path`、`Depends`、`Security` 等对象,只是返回特殊类的函数。
+但实际上,从 `fastapi` 导入的 `Query`、`Path`、`Depends`、`Security` 等对象,只是返回特殊类的函数。
+
+///
## 使用 `SecurityScopes`
@@ -149,7 +159,7 @@ OpenAPI 中(例如 API 文档)可以定义**安全方案**。
`SecuriScopes` 类与 `Request` 类似(`Request` 用于直接提取请求对象)。
```Python hl_lines="8 105"
-{!../../../docs_src/security/tutorial005.py!}
+{!../../docs_src/security/tutorial005.py!}
```
## 使用 `scopes`
@@ -165,7 +175,7 @@ OpenAPI 中(例如 API 文档)可以定义**安全方案**。
该异常包含了作用域所需的(如有),以空格分割的字符串(使用 `scope_str`)。该字符串要放到包含作用域的 `WWW-Authenticate` 请求头中(这也是规范的要求)。
```Python hl_lines="105 107-115"
-{!../../../docs_src/security/tutorial005.py!}
+{!../../docs_src/security/tutorial005.py!}
```
## 校验 `username` 与数据形状
@@ -183,7 +193,7 @@ OpenAPI 中(例如 API 文档)可以定义**安全方案**。
还可以使用用户名验证用户,如果没有用户,也会触发之前创建的异常。
```Python hl_lines="46 116-127"
-{!../../../docs_src/security/tutorial005.py!}
+{!../../docs_src/security/tutorial005.py!}
```
## 校验 `scopes`
@@ -193,7 +203,7 @@ OpenAPI 中(例如 API 文档)可以定义**安全方案**。
为此,要使用包含所有作用域**字符串列表**的 `security_scopes.scopes`, 。
```Python hl_lines="128-134"
-{!../../../docs_src/security/tutorial005.py!}
+{!../../docs_src/security/tutorial005.py!}
```
## 依赖项树与作用域
@@ -221,11 +231,13 @@ OpenAPI 中(例如 API 文档)可以定义**安全方案**。
* `security_scopes.scopes` 包含*路径操作* `read_users_me` 的 `["me"]`,因为它在依赖项里被声明
* `security_scopes.scopes` 包含用于*路径操作* `read_system_status` 的 `[]`(空列表),并且它的依赖项 `get_current_user` 也没有声明任何 `scope`
-!!! tip "提示"
+/// tip | "提示"
- 此处重要且**神奇**的事情是,`get_current_user` 检查每个*路径操作*时可以使用不同的 `scopes` 列表。
+此处重要且**神奇**的事情是,`get_current_user` 检查每个*路径操作*时可以使用不同的 `scopes` 列表。
- 所有这些都依赖于在每个*路径操作*和指定*路径操作*的依赖树中的每个依赖项。
+所有这些都依赖于在每个*路径操作*和指定*路径操作*的依赖树中的每个依赖项。
+
+///
## `SecurityScopes` 的更多细节
@@ -263,11 +275,13 @@ OpenAPI 中(例如 API 文档)可以定义**安全方案**。
最安全的是代码流,但实现起来更复杂,而且需要更多步骤。因为它更复杂,很多第三方身份验证应用最终建议使用隐式流。
-!!! note "笔记"
+/// note | "笔记"
- 每个身份验证应用都会采用不同方式会命名流,以便融合入自己的品牌。
+每个身份验证应用都会采用不同方式会命名流,以便融合入自己的品牌。
- 但归根结底,它们使用的都是 OAuth2 标准。
+但归根结底,它们使用的都是 OAuth2 标准。
+
+///
**FastAPI** 的 `fastapi.security.oauth2` 里包含了所有 OAuth2 身份验证流工具。
diff --git a/docs/zh/docs/advanced/settings.md b/docs/zh/docs/advanced/settings.md
index d793b9c7f..4d35731cb 100644
--- a/docs/zh/docs/advanced/settings.md
+++ b/docs/zh/docs/advanced/settings.md
@@ -8,44 +8,51 @@
## 环境变量
-!!! tip
- 如果您已经知道什么是"环境变量"以及如何使用它们,请随意跳到下面的下一节。
+/// tip
+
+如果您已经知道什么是"环境变量"以及如何使用它们,请随意跳到下面的下一节。
+
+///
环境变量(也称为"env var")是一种存在于 Python 代码之外、存在于操作系统中的变量,可以被您的 Python 代码(或其他程序)读取。
您可以在 shell 中创建和使用环境变量,而无需使用 Python:
-=== "Linux、macOS、Windows Bash"
+//// tab | Linux、macOS、Windows Bash
-
-!!! info
- 漂亮的插画来自 Ketrina Thompson. 🎨
+/// info
+
+漂亮的插画来自 Ketrina Thompson. 🎨
+
+///
---
@@ -199,8 +205,11 @@ Python 的现代版本支持通过一种叫**"协程"**——使用 `async` 和
没有太多的交谈或调情,因为大部分时间 🕙 都在柜台前等待😞。
-!!! info
- 漂亮的插画来自 Ketrina Thompson. 🎨
+/// info
+
+漂亮的插画来自 Ketrina Thompson. 🎨
+
+///
---
@@ -392,12 +401,15 @@ Starlette (和 **FastAPI**) 是基于
+email_validator - 用于 email 校验。
+* email-validator - 用于 email 校验。
用于 Starlette:
diff --git a/docs/zh/docs/project-generation.md b/docs/zh/docs/project-generation.md
index 0655cb0a9..48eb990df 100644
--- a/docs/zh/docs/project-generation.md
+++ b/docs/zh/docs/project-generation.md
@@ -1,84 +1,28 @@
-# 项目生成 - 模板
+# FastAPI全栈模板
-项目生成器一般都会提供很多初始设置、安全措施、数据库,甚至还准备好了第一个 API 端点,能帮助您快速上手。
+模板通常带有特定的设置,而且被设计为灵活和可定制的。这允许您根据项目的需求修改和调整它们,使它们成为一个很好的起点。🏁
-项目生成器的设置通常都很主观,您可以按需更新或修改,但对于您的项目来说,它是非常好的起点。
+您可以使用此模板开始,因为它包含了许多已经为您完成的初始设置、安全性、数据库和一些API端点。
-## 全栈 FastAPI + PostgreSQL
+代码仓: Full Stack FastAPI Template
-GitHub:https://github.com/tiangolo/full-stack-fastapi-postgresql
+## FastAPI全栈模板 - 技术栈和特性
-### 全栈 FastAPI + PostgreSQL - 功能
-
-* 完整的 **Docker** 集成(基于 Docker)
-* Docker Swarm 开发模式
-* **Docker Compose** 本地开发集成与优化
-* **生产可用**的 Python 网络服务器,使用 Uvicorn 或 Gunicorn
-* Python **FastAPI** 后端:
-* * **速度快**:可与 **NodeJS** 和 **Go** 比肩的极高性能(归功于 Starlette 和 Pydantic)
- * **直观**:强大的编辑器支持,处处皆可自动补全,减少调试时间
- * **简单**:易学、易用,阅读文档所需时间更短
- * **简短**:代码重复最小化,每次参数声明都可以实现多个功能
- * **健壮**: 生产级别的代码,还有自动交互文档
- * **基于标准**:完全兼容并基于 API 开放标准:OpenAPI 和 JSON Schema
- * **更多功能**包括自动验证、序列化、交互文档、OAuth2 JWT 令牌身份验证等
-* **安全密码**,默认使用密码哈希
-* **JWT 令牌**身份验证
-* **SQLAlchemy** 模型(独立于 Flask 扩展,可直接用于 Celery Worker)
-* 基础的用户模型(可按需修改或删除)
-* **Alembic** 迁移
-* **CORS**(跨域资源共享)
-* **Celery** Worker 可从后端其它部分有选择地导入并使用模型和代码
-* REST 后端测试基于 Pytest,并与 Docker 集成,可独立于数据库实现完整的 API 交互测试。因为是在 Docker 中运行,每次都可从头构建新的数据存储(使用 ElasticSearch、MongoDB、CouchDB 等数据库,仅测试 API 运行)
-* Python 与 **Jupyter Kernels** 集成,用于远程或 Docker 容器内部开发,使用 Atom Hydrogen 或 Visual Studio Code 的 Jupyter 插件
-* **Vue** 前端:
- * 由 Vue CLI 生成
- * **JWT 身份验证**处理
- * 登录视图
- * 登录后显示主仪表盘视图
- * 主仪表盘支持用户创建与编辑
- * 用户信息编辑
- * **Vuex**
- * **Vue-router**
- * **Vuetify** 美化组件
- * **TypeScript**
- * 基于 **Nginx** 的 Docker 服务器(优化了 Vue-router 配置)
- * Docker 多阶段构建,无需保存或提交编译的代码
- * 在构建时运行前端测试(可禁用)
- * 尽量模块化,开箱即用,但仍可使用 Vue CLI 重新生成或创建所需项目,或复用所需内容
-* 使用 **PGAdmin** 管理 PostgreSQL 数据库,可轻松替换为 PHPMyAdmin 或 MySQL
-* 使用 **Flower** 监控 Celery 任务
-* 使用 **Traefik** 处理前后端负载平衡,可把前后端放在同一个域下,按路径分隔,但在不同容器中提供服务
-* Traefik 集成,包括自动生成 Let's Encrypt **HTTPS** 凭证
-* GitLab **CI**(持续集成),包括前后端测试
-
-## 全栈 FastAPI + Couchbase
-
-GitHub:https://github.com/tiangolo/full-stack-fastapi-couchbase
-
-⚠️ **警告** ⚠️
-
-如果您想从头开始创建新项目,建议使用以下备选方案。
-
-例如,项目生成器全栈 FastAPI + PostgreSQL 会更适用,这个项目的维护积极,用的人也多,还包括了所有新功能和改进内容。
-
-当然,您也可以放心使用这个基于 Couchbase 的生成器,它也能正常使用。就算用它生成项目也没有任何问题(为了更好地满足需求,您可以自行更新这个项目)。
-
-详见资源仓库中的文档。
-
-## 全栈 FastAPI + MongoDB
-
-……敬请期待,得看我有没有时间做这个项目。😅 🎉
-
-## FastAPI + spaCy 机器学习模型
-
-GitHub:https://github.com/microsoft/cookiecutter-spacy-fastapi
-
-### FastAPI + spaCy 机器学习模型 - 功能
-
-* 集成 **spaCy** NER 模型
-* 内置 **Azure 认知搜索**请求格式
-* **生产可用**的 Python 网络服务器,使用 Uvicorn 与 Gunicorn
-* 内置 **Azure DevOps** Kubernetes (AKS) CI/CD 开发
-* **多语**支持,可在项目设置时选择 spaCy 内置的语言
-* 不仅局限于 spaCy,可**轻松扩展**至其它模型框架(Pytorch、TensorFlow)
+- ⚡ [**FastAPI**](https://fastapi.tiangolo.com) 用于Python后端API.
+ - 🧰 [SQLModel](https://sqlmodel.tiangolo.com) 用于Python和SQL数据库的集成(ORM)。
+ - 🔍 [Pydantic](https://docs.pydantic.dev) FastAPI的依赖项之一,用于数据验证和配置管理。
+ - 💾 [PostgreSQL](https://www.postgresql.org) 作为SQL数据库。
+- 🚀 [React](https://react.dev) 用于前端。
+ - 💃 使用了TypeScript、hooks、[Vite](https://vitejs.dev)和其他一些现代化的前端技术栈。
+ - 🎨 [Chakra UI](https://chakra-ui.com) 用于前端组件。
+ - 🤖 一个自动化生成的前端客户端。
+ - 🧪 [Playwright](https://playwright.dev)用于端到端测试。
+ - 🦇 支持暗黑主题(Dark mode)。
+- 🐋 [Docker Compose](https://www.docker.com) 用于开发环境和生产环境。
+- 🔒 默认使用密码哈希来保证安全。
+- 🔑 JWT令牌用于权限验证。
+- 📫 使用邮箱来进行密码恢复。
+- ✅ 单元测试用了[Pytest](https://pytest.org).
+- 📞 [Traefik](https://traefik.io) 用于反向代理和负载均衡。
+- 🚢 部署指南(Docker Compose)包含了如何起一个Traefik前端代理来自动化HTTPS认证。
+- 🏭 CI(持续集成)和 CD(持续部署)基于GitHub Actions。
diff --git a/docs/zh/docs/python-types.md b/docs/zh/docs/python-types.md
index 214b47611..dab6bd4c0 100644
--- a/docs/zh/docs/python-types.md
+++ b/docs/zh/docs/python-types.md
@@ -12,15 +12,18 @@
但即使你不会用到 **FastAPI**,了解一下类型提示也会让你从中受益。
-!!! note
- 如果你已经精通 Python,并且了解关于类型提示的一切知识,直接跳到下一章节吧。
+/// note
+
+如果你已经精通 Python,并且了解关于类型提示的一切知识,直接跳到下一章节吧。
+
+///
## 动机
让我们从一个简单的例子开始:
```Python
-{!../../../docs_src/python_types/tutorial001.py!}
+{!../../docs_src/python_types/tutorial001.py!}
```
运行这段程序将输出:
@@ -36,7 +39,7 @@ John Doe
* 中间用一个空格来拼接它们。
```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial001.py!}
+{!../../docs_src/python_types/tutorial001.py!}
```
### 修改示例
@@ -80,7 +83,7 @@ John Doe
这些就是"类型提示":
```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial002.py!}
+{!../../docs_src/python_types/tutorial002.py!}
```
这和声明默认值是不同的,例如:
@@ -110,7 +113,7 @@ John Doe
下面是一个已经有类型提示的函数:
```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial003.py!}
+{!../../docs_src/python_types/tutorial003.py!}
```
因为编辑器已经知道了这些变量的类型,所以不仅能对代码进行补全,还能检查其中的错误:
@@ -120,7 +123,7 @@ John Doe
现在你知道了必须先修复这个问题,通过 `str(age)` 把 `age` 转换成字符串:
```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial004.py!}
+{!../../docs_src/python_types/tutorial004.py!}
```
## 声明类型
@@ -141,7 +144,7 @@ John Doe
* `bytes`
```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial005.py!}
+{!../../docs_src/python_types/tutorial005.py!}
```
### 嵌套类型
@@ -159,7 +162,7 @@ John Doe
从 `typing` 模块导入 `List`(注意是大写的 `L`):
```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial006.py!}
+{!../../docs_src/python_types/tutorial006.py!}
```
同样以冒号(`:`)来声明这个变量。
@@ -169,7 +172,7 @@ John Doe
由于列表是带有"子类型"的类型,所以我们把子类型放在方括号中:
```Python hl_lines="4"
-{!../../../docs_src/python_types/tutorial006.py!}
+{!../../docs_src/python_types/tutorial006.py!}
```
这表示:"变量 `items` 是一个 `list`,并且这个列表里的每一个元素都是 `str`"。
@@ -189,7 +192,7 @@ John Doe
声明 `tuple` 和 `set` 的方法也是一样的:
```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial007.py!}
+{!../../docs_src/python_types/tutorial007.py!}
```
这表示:
@@ -206,7 +209,7 @@ John Doe
第二个子类型声明 `dict` 的所有值:
```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial008.py!}
+{!../../docs_src/python_types/tutorial008.py!}
```
这表示:
@@ -222,13 +225,13 @@ John Doe
假设你有一个名为 `Person` 的类,拥有 name 属性:
```Python hl_lines="1-3"
-{!../../../docs_src/python_types/tutorial010.py!}
+{!../../docs_src/python_types/tutorial010.py!}
```
接下来,你可以将一个变量声明为 `Person` 类型:
```Python hl_lines="6"
-{!../../../docs_src/python_types/tutorial010.py!}
+{!../../docs_src/python_types/tutorial010.py!}
```
然后,你将再次获得所有的编辑器支持:
@@ -250,11 +253,14 @@ John Doe
下面的例子来自 Pydantic 官方文档:
```Python
-{!../../../docs_src/python_types/tutorial010.py!}
+{!../../docs_src/python_types/tutorial010.py!}
```
-!!! info
- 想进一步了解 Pydantic,请阅读其文档.
+/// info
+
+想进一步了解 Pydantic,请阅读其文档.
+
+///
整个 **FastAPI** 建立在 Pydantic 的基础之上。
@@ -282,5 +288,8 @@ John Doe
最重要的是,通过使用标准的 Python 类型,只需要在一个地方声明(而不是添加更多的类、装饰器等),**FastAPI** 会为你完成很多的工作。
-!!! info
- 如果你已经阅读了所有教程,回过头来想了解有关类型的更多信息,来自 `mypy` 的"速查表"是不错的资源。
+/// info
+
+如果你已经阅读了所有教程,回过头来想了解有关类型的更多信息,来自 `mypy` 的"速查表"是不错的资源。
+
+///
diff --git a/docs/zh/docs/tutorial/background-tasks.md b/docs/zh/docs/tutorial/background-tasks.md
index 94b75d4fd..fc9312bc5 100644
--- a/docs/zh/docs/tutorial/background-tasks.md
+++ b/docs/zh/docs/tutorial/background-tasks.md
@@ -16,7 +16,7 @@
首先导入 `BackgroundTasks` 并在 *路径操作函数* 中使用类型声明 `BackgroundTasks` 定义一个参数:
```Python hl_lines="1 13"
-{!../../../docs_src/background_tasks/tutorial001.py!}
+{!../../docs_src/background_tasks/tutorial001.py!}
```
**FastAPI** 会创建一个 `BackgroundTasks` 类型的对象并作为该参数传入。
@@ -34,7 +34,7 @@
由于写操作不使用 `async` 和 `await`,我们用普通的 `def` 定义函数:
```Python hl_lines="6-9"
-{!../../../docs_src/background_tasks/tutorial001.py!}
+{!../../docs_src/background_tasks/tutorial001.py!}
```
## 添加后台任务
@@ -42,7 +42,7 @@
在你的 *路径操作函数* 里,用 `.add_task()` 方法将任务函数传到 *后台任务* 对象中:
```Python hl_lines="14"
-{!../../../docs_src/background_tasks/tutorial001.py!}
+{!../../docs_src/background_tasks/tutorial001.py!}
```
`.add_task()` 接收以下参数:
@@ -57,41 +57,57 @@
**FastAPI** 知道在每种情况下该做什么以及如何复用同一对象,因此所有后台任务被合并在一起并且随后在后台运行:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="13 15 22 25"
- {!> ../../../docs_src/background_tasks/tutorial002_an_py310.py!}
- ```
+```Python hl_lines="13 15 22 25"
+{!> ../../docs_src/background_tasks/tutorial002_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="13 15 22 25"
- {!> ../../../docs_src/background_tasks/tutorial002_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="13 15 22 25"
+{!> ../../docs_src/background_tasks/tutorial002_an_py39.py!}
+```
- ```Python hl_lines="14 16 23 26"
- {!> ../../../docs_src/background_tasks/tutorial002_an.py!}
- ```
+////
-=== "Python 3.10+ 没Annotated"
+//// tab | Python 3.8+
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+```Python hl_lines="14 16 23 26"
+{!> ../../docs_src/background_tasks/tutorial002_an.py!}
+```
- ```Python hl_lines="11 13 20 23"
- {!> ../../../docs_src/background_tasks/tutorial002_py310.py!}
- ```
+////
-=== "Python 3.8+ 没Annotated"
+//// tab | Python 3.10+ 没Annotated
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+/// tip
- ```Python hl_lines="13 15 22 25"
- {!> ../../../docs_src/background_tasks/tutorial002.py!}
- ```
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="11 13 20 23"
+{!> ../../docs_src/background_tasks/tutorial002_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ 没Annotated
+
+/// tip
+
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="13 15 22 25"
+{!> ../../docs_src/background_tasks/tutorial002.py!}
+```
+
+////
该示例中,信息会在响应发出 *之后* 被写到 `log.txt` 文件。
diff --git a/docs/zh/docs/tutorial/bigger-applications.md b/docs/zh/docs/tutorial/bigger-applications.md
index 422cd7c16..64afd99af 100644
--- a/docs/zh/docs/tutorial/bigger-applications.md
+++ b/docs/zh/docs/tutorial/bigger-applications.md
@@ -4,8 +4,11 @@
**FastAPI** 提供了一个方便的工具,可以在保持所有灵活性的同时构建你的应用程序。
-!!! info
- 如果你来自 Flask,那这将相当于 Flask 的 Blueprints。
+/// info
+
+如果你来自 Flask,那这将相当于 Flask 的 Blueprints。
+
+///
## 一个文件结构示例
@@ -26,16 +29,19 @@
│ └── admin.py
```
-!!! tip
- 上面有几个 `__init__.py` 文件:每个目录或子目录中都有一个。
+/// tip
- 这就是能将代码从一个文件导入到另一个文件的原因。
+上面有几个 `__init__.py` 文件:每个目录或子目录中都有一个。
- 例如,在 `app/main.py` 中,你可以有如下一行:
+这就是能将代码从一个文件导入到另一个文件的原因。
- ```
- from app.routers import items
- ```
+例如,在 `app/main.py` 中,你可以有如下一行:
+
+```
+from app.routers import items
+```
+
+///
* `app` 目录包含了所有内容。并且它有一个空文件 `app/__init__.py`,因此它是一个「Python 包」(「Python 模块」的集合):`app`。
* 它包含一个 `app/main.py` 文件。由于它位于一个 Python 包(一个包含 `__init__.py` 文件的目录)中,因此它是该包的一个「模块」:`app.main`。
@@ -80,7 +86,7 @@
你可以导入它并通过与 `FastAPI` 类相同的方式创建一个「实例」:
```Python hl_lines="1 3" title="app/routers/users.py"
-{!../../../docs_src/bigger_applications/app/routers/users.py!}
+{!../../docs_src/bigger_applications/app/routers/users.py!}
```
### 使用 `APIRouter` 的*路径操作*
@@ -90,7 +96,7 @@
使用方式与 `FastAPI` 类相同:
```Python hl_lines="6 11 16" title="app/routers/users.py"
-{!../../../docs_src/bigger_applications/app/routers/users.py!}
+{!../../docs_src/bigger_applications/app/routers/users.py!}
```
你可以将 `APIRouter` 视为一个「迷你 `FastAPI`」类。
@@ -99,8 +105,11 @@
所有相同的 `parameters`、`responses`、`dependencies`、`tags` 等等。
-!!! tip
- 在此示例中,该变量被命名为 `router`,但你可以根据你的想法自由命名。
+/// tip
+
+在此示例中,该变量被命名为 `router`,但你可以根据你的想法自由命名。
+
+///
我们将在主 `FastAPI` 应用中包含该 `APIRouter`,但首先,让我们来看看依赖项和另一个 `APIRouter`。
@@ -113,13 +122,16 @@
现在我们将使用一个简单的依赖项来读取一个自定义的 `X-Token` 请求首部:
```Python hl_lines="1 4-6" title="app/dependencies.py"
-{!../../../docs_src/bigger_applications/app/dependencies.py!}
+{!../../docs_src/bigger_applications/app/dependencies.py!}
```
-!!! tip
- 我们正在使用虚构的请求首部来简化此示例。
+/// tip
- 但在实际情况下,使用集成的[安全性实用工具](security/index.md){.internal-link target=_blank}会得到更好的效果。
+我们正在使用虚构的请求首部来简化此示例。
+
+但在实际情况下,使用集成的[安全性实用工具](security/index.md){.internal-link target=_blank}会得到更好的效果。
+
+///
## 其他使用 `APIRouter` 的模块
@@ -144,7 +156,7 @@
因此,我们可以将其添加到 `APIRouter` 中,而不是将其添加到每个路径操作中。
```Python hl_lines="5-10 16 21" title="app/routers/items.py"
-{!../../../docs_src/bigger_applications/app/routers/items.py!}
+{!../../docs_src/bigger_applications/app/routers/items.py!}
```
由于每个*路径操作*的路径都必须以 `/` 开头,例如:
@@ -163,8 +175,11 @@ async def read_item(item_id: str):
我们可以添加一个 `dependencies` 列表,这些依赖项将被添加到路由器中的所有*路径操作*中,并将针对向它们发起的每个请求执行/解决。
-!!! tip
- 请注意,和[*路径操作装饰器*中的依赖项](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}很类似,没有值会被传递给你的*路径操作函数*。
+/// tip
+
+请注意,和[*路径操作装饰器*中的依赖项](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}很类似,没有值会被传递给你的*路径操作函数*。
+
+///
最终结果是项目相关的路径现在为:
@@ -181,11 +196,17 @@ async def read_item(item_id: str):
* 路由器的依赖项最先执行,然后是[装饰器中的 `dependencies`](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank},再然后是普通的参数依赖项。
* 你还可以添加[具有 `scopes` 的 `Security` 依赖项](../advanced/security/oauth2-scopes.md){.internal-link target=_blank}。
-!!! tip
- 在 `APIRouter`中具有 `dependencies` 可以用来,例如,对一整组的*路径操作*要求身份认证。即使这些依赖项并没有分别添加到每个路径操作中。
+/// tip
-!!! check
- `prefix`、`tags`、`responses` 以及 `dependencies` 参数只是(和其他很多情况一样)**FastAPI** 的一个用于帮助你避免代码重复的功能。
+在 `APIRouter`中具有 `dependencies` 可以用来,例如,对一整组的*路径操作*要求身份认证。即使这些依赖项并没有分别添加到每个路径操作中。
+
+///
+
+/// check
+
+`prefix`、`tags`、`responses` 以及 `dependencies` 参数只是(和其他很多情况一样)**FastAPI** 的一个用于帮助你避免代码重复的功能。
+
+///
### 导入依赖项
@@ -196,13 +217,16 @@ async def read_item(item_id: str):
因此,我们通过 `..` 对依赖项使用了相对导入:
```Python hl_lines="3" title="app/routers/items.py"
-{!../../../docs_src/bigger_applications/app/routers/items.py!}
+{!../../docs_src/bigger_applications/app/routers/items.py!}
```
#### 相对导入如何工作
-!!! tip
- 如果你完全了解导入的工作原理,请从下面的下一部分继续。
+/// tip
+
+如果你完全了解导入的工作原理,请从下面的下一部分继续。
+
+///
一个单点 `.`,例如:
@@ -266,13 +290,16 @@ from ...dependencies import get_token_header
但是我们仍然可以添加*更多*将会应用于特定的*路径操作*的 `tags`,以及一些特定于该*路径操作*的额外 `responses`:
```Python hl_lines="30-31" title="app/routers/items.py"
-{!../../../docs_src/bigger_applications/app/routers/items.py!}
+{!../../docs_src/bigger_applications/app/routers/items.py!}
```
-!!! tip
- 最后的这个路径操作将包含标签的组合:`["items","custom"]`。
+/// tip
- 并且在文档中也会有两个响应,一个用于 `404`,一个用于 `403`。
+最后的这个路径操作将包含标签的组合:`["items","custom"]`。
+
+并且在文档中也会有两个响应,一个用于 `404`,一个用于 `403`。
+
+///
## `FastAPI` 主体
@@ -291,7 +318,7 @@ from ...dependencies import get_token_header
我们甚至可以声明[全局依赖项](dependencies/global-dependencies.md){.internal-link target=_blank},它会和每个 `APIRouter` 的依赖项组合在一起:
```Python hl_lines="1 3 7" title="app/main.py"
-{!../../../docs_src/bigger_applications/app/main.py!}
+{!../../docs_src/bigger_applications/app/main.py!}
```
### 导入 `APIRouter`
@@ -299,7 +326,7 @@ from ...dependencies import get_token_header
现在,我们导入具有 `APIRouter` 的其他子模块:
```Python hl_lines="5" title="app/main.py"
-{!../../../docs_src/bigger_applications/app/main.py!}
+{!../../docs_src/bigger_applications/app/main.py!}
```
由于文件 `app/routers/users.py` 和 `app/routers/items.py` 是同一 Python 包 `app` 一个部分的子模块,因此我们可以使用单个点 ` .` 通过「相对导入」来导入它们。
@@ -328,20 +355,23 @@ from .routers import items, users
from app.routers import items, users
```
-!!! info
- 第一个版本是「相对导入」:
+/// info
- ```Python
- from .routers import items, users
- ```
+第一个版本是「相对导入」:
- 第二个版本是「绝对导入」:
+```Python
+from .routers import items, users
+```
- ```Python
- from app.routers import items, users
- ```
+第二个版本是「绝对导入」:
- 要了解有关 Python 包和模块的更多信息,请查阅关于 Modules 的 Python 官方文档。
+```Python
+from app.routers import items, users
+```
+
+要了解有关 Python 包和模块的更多信息,请查阅关于 Modules 的 Python 官方文档。
+
+///
### 避免名称冲突
@@ -361,7 +391,7 @@ from .routers.users import router
因此,为了能够在同一个文件中使用它们,我们直接导入子模块:
```Python hl_lines="5" title="app/main.py"
-{!../../../docs_src/bigger_applications/app/main.py!}
+{!../../docs_src/bigger_applications/app/main.py!}
```
### 包含 `users` 和 `items` 的 `APIRouter`
@@ -369,29 +399,38 @@ from .routers.users import router
现在,让我们来包含来自 `users` 和 `items` 子模块的 `router`。
```Python hl_lines="10-11" title="app/main.py"
-{!../../../docs_src/bigger_applications/app/main.py!}
+{!../../docs_src/bigger_applications/app/main.py!}
```
-!!! info
- `users.router` 包含了 `app/routers/users.py` 文件中的 `APIRouter`。
+/// info
- `items.router` 包含了 `app/routers/items.py` 文件中的 `APIRouter`。
+`users.router` 包含了 `app/routers/users.py` 文件中的 `APIRouter`。
+
+`items.router` 包含了 `app/routers/items.py` 文件中的 `APIRouter`。
+
+///
使用 `app.include_router()`,我们可以将每个 `APIRouter` 添加到主 `FastAPI` 应用程序中。
它将包含来自该路由器的所有路由作为其一部分。
-!!! note "技术细节"
- 实际上,它将在内部为声明在 `APIRouter` 中的每个*路径操作*创建一个*路径操作*。
+/// note | "技术细节"
- 所以,在幕后,它实际上会像所有的东西都是同一个应用程序一样工作。
+实际上,它将在内部为声明在 `APIRouter` 中的每个*路径操作*创建一个*路径操作*。
-!!! check
- 包含路由器时,你不必担心性能问题。
+所以,在幕后,它实际上会像所有的东西都是同一个应用程序一样工作。
- 这将花费几微秒时间,并且只会在启动时发生。
+///
- 因此,它不会影响性能。⚡
+/// check
+
+包含路由器时,你不必担心性能问题。
+
+这将花费几微秒时间,并且只会在启动时发生。
+
+因此,它不会影响性能。⚡
+
+///
### 包含一个有自定义 `prefix`、`tags`、`responses` 和 `dependencies` 的 `APIRouter`
@@ -402,7 +441,7 @@ from .routers.users import router
对于此示例,它将非常简单。但是假设由于它是与组织中的其他项目所共享的,因此我们无法对其进行修改,以及直接在 `APIRouter` 中添加 `prefix`、`dependencies`、`tags` 等:
```Python hl_lines="3" title="app/internal/admin.py"
-{!../../../docs_src/bigger_applications/app/internal/admin.py!}
+{!../../docs_src/bigger_applications/app/internal/admin.py!}
```
但是我们仍然希望在包含 `APIRouter` 时设置一个自定义的 `prefix`,以便其所有*路径操作*以 `/admin` 开头,我们希望使用本项目已经有的 `dependencies` 保护它,并且我们希望它包含自定义的 `tags` 和 `responses`。
@@ -410,7 +449,7 @@ from .routers.users import router
我们可以通过将这些参数传递给 `app.include_router()` 来完成所有的声明,而不必修改原始的 `APIRouter`:
```Python hl_lines="14-17" title="app/main.py"
-{!../../../docs_src/bigger_applications/app/main.py!}
+{!../../docs_src/bigger_applications/app/main.py!}
```
这样,原始的 `APIRouter` 将保持不变,因此我们仍然可以与组织中的其他项目共享相同的 `app/internal/admin.py` 文件。
@@ -433,21 +472,24 @@ from .routers.users import router
这里我们这样做了...只是为了表明我们可以做到🤷:
```Python hl_lines="21-23" title="app/main.py"
-{!../../../docs_src/bigger_applications/app/main.py!}
+{!../../docs_src/bigger_applications/app/main.py!}
```
它将与通过 `app.include_router()` 添加的所有其他*路径操作*一起正常运行。
-!!! info "特别的技术细节"
- **注意**:这是一个非常技术性的细节,你也许可以**直接跳过**。
+/// info | "特别的技术细节"
- ---
+**注意**:这是一个非常技术性的细节,你也许可以**直接跳过**。
- `APIRouter` 没有被「挂载」,它们与应用程序的其余部分没有隔离。
+---
- 这是因为我们想要在 OpenAPI 模式和用户界面中包含它们的*路径操作*。
+`APIRouter` 没有被「挂载」,它们与应用程序的其余部分没有隔离。
- 由于我们不能仅仅隔离它们并独立于其余部分来「挂载」它们,因此*路径操作*是被「克隆的」(重新创建),而不是直接包含。
+这是因为我们想要在 OpenAPI 模式和用户界面中包含它们的*路径操作*。
+
+由于我们不能仅仅隔离它们并独立于其余部分来「挂载」它们,因此*路径操作*是被「克隆的」(重新创建),而不是直接包含。
+
+///
## 查看自动化的 API 文档
diff --git a/docs/zh/docs/tutorial/body-fields.md b/docs/zh/docs/tutorial/body-fields.md
index 6c68f1008..ac59d7e6a 100644
--- a/docs/zh/docs/tutorial/body-fields.md
+++ b/docs/zh/docs/tutorial/body-fields.md
@@ -6,101 +6,139 @@
首先,从 Pydantic 中导入 `Field`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="4"
+{!> ../../docs_src/body_fields/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="4"
+{!> ../../docs_src/body_fields/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+```Python hl_lines="4"
+{!> ../../docs_src/body_fields/tutorial001_an.py!}
+```
- ```Python hl_lines="2"
- {!> ../../../docs_src/body_fields/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+/// tip
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001.py!}
- ```
+尽可能选择使用 `Annotated` 的版本。
-!!! warning "警告"
+///
- 注意,与从 `fastapi` 导入 `Query`,`Path`、`Body` 不同,要直接从 `pydantic` 导入 `Field` 。
+```Python hl_lines="2"
+{!> ../../docs_src/body_fields/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="4"
+{!> ../../docs_src/body_fields/tutorial001.py!}
+```
+
+////
+
+/// warning | "警告"
+
+注意,与从 `fastapi` 导入 `Query`,`Path`、`Body` 不同,要直接从 `pydantic` 导入 `Field` 。
+
+///
## 声明模型属性
然后,使用 `Field` 定义模型的属性:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="11-14"
+{!> ../../docs_src/body_fields/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="11-14"
+{!> ../../docs_src/body_fields/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="12-15"
- {!> ../../../docs_src/body_fields/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="12-15"
+{!> ../../docs_src/body_fields/tutorial001_an.py!}
+```
- ```Python hl_lines="9-12"
- {!> ../../../docs_src/body_fields/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001.py!}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="9-12"
+{!> ../../docs_src/body_fields/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python hl_lines="11-14"
+{!> ../../docs_src/body_fields/tutorial001.py!}
+```
+
+////
`Field` 的工作方式和 `Query`、`Path`、`Body` 相同,参数也相同。
-!!! note "技术细节"
+/// note | "技术细节"
- 实际上,`Query`、`Path` 都是 `Params` 的子类,而 `Params` 类又是 Pydantic 中 `FieldInfo` 的子类。
+实际上,`Query`、`Path` 都是 `Params` 的子类,而 `Params` 类又是 Pydantic 中 `FieldInfo` 的子类。
- Pydantic 的 `Field` 返回也是 `FieldInfo` 的类实例。
+Pydantic 的 `Field` 返回也是 `FieldInfo` 的类实例。
- `Body` 直接返回的也是 `FieldInfo` 的子类的对象。后文还会介绍一些 `Body` 的子类。
+`Body` 直接返回的也是 `FieldInfo` 的子类的对象。后文还会介绍一些 `Body` 的子类。
- 注意,从 `fastapi` 导入的 `Query`、`Path` 等对象实际上都是返回特殊类的函数。
+注意,从 `fastapi` 导入的 `Query`、`Path` 等对象实际上都是返回特殊类的函数。
-!!! tip "提示"
+///
- 注意,模型属性的类型、默认值及 `Field` 的代码结构与*路径操作函数*的参数相同,只不过是用 `Field` 替换了`Path`、`Query`、`Body`。
+/// 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 c93ef2f5c..c3bc0db9e 100644
--- a/docs/zh/docs/tutorial/body-multiple-params.md
+++ b/docs/zh/docs/tutorial/body-multiple-params.md
@@ -8,44 +8,63 @@
你还可以通过将默认值设置为 `None` 来将请求体参数声明为可选参数:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="18-20"
- {!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="18-20"
+{!> ../../docs_src/body_multiple_params/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="18-20"
- {!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="18-20"
+{!> ../../docs_src/body_multiple_params/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="19-21"
- {!> ../../../docs_src/body_multiple_params/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+```Python hl_lines="19-21"
+{!> ../../docs_src/body_multiple_params/tutorial001_an.py!}
+```
- ```Python hl_lines="17-19"
- {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+/// tip
- ```Python hl_lines="19-21"
- {!> ../../../docs_src/body_multiple_params/tutorial001.py!}
- ```
+尽可能选择使用 `Annotated` 的版本。
-!!! note
- 请注意,在这种情况下,将从请求体获取的 `item` 是可选的。因为它的默认值为 `None`。
+///
+
+```Python hl_lines="17-19"
+{!> ../../docs_src/body_multiple_params/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="19-21"
+{!> ../../docs_src/body_multiple_params/tutorial001.py!}
+```
+
+////
+
+/// note
+
+请注意,在这种情况下,将从请求体获取的 `item` 是可选的。因为它的默认值为 `None`。
+
+///
## 多个请求体参数
@@ -62,17 +81,21 @@
但是你也可以声明多个请求体参数,例如 `item` 和 `user`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!}
- ```
+```Python hl_lines="20"
+{!> ../../docs_src/body_multiple_params/tutorial002_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="22"
- {!> ../../../docs_src/body_multiple_params/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="22"
+{!> ../../docs_src/body_multiple_params/tutorial002.py!}
+```
+
+////
在这种情况下,**FastAPI** 将注意到该函数中有多个请求体参数(两个 Pydantic 模型参数)。
@@ -93,9 +116,11 @@
}
```
-!!! note
- 请注意,即使 `item` 的声明方式与之前相同,但现在它被期望通过 `item` 键内嵌在请求体中。
+/// note
+请注意,即使 `item` 的声明方式与之前相同,但现在它被期望通过 `item` 键内嵌在请求体中。
+
+///
**FastAPI** 将自动对请求中的数据进行转换,因此 `item` 参数将接收指定的内容,`user` 参数也是如此。
@@ -112,41 +137,57 @@
但是你可以使用 `Body` 指示 **FastAPI** 将其作为请求体的另一个键进行处理。
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="23"
- {!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!}
- ```
+```Python hl_lines="23"
+{!> ../../docs_src/body_multiple_params/tutorial003_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="23"
- {!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="23"
+{!> ../../docs_src/body_multiple_params/tutorial003_an_py39.py!}
+```
- ```Python hl_lines="24"
- {!> ../../../docs_src/body_multiple_params/tutorial003_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+```Python hl_lines="24"
+{!> ../../docs_src/body_multiple_params/tutorial003_an.py!}
+```
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+/// tip
- ```Python hl_lines="22"
- {!> ../../../docs_src/body_multiple_params/tutorial003.py!}
- ```
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="20"
+{!> ../../docs_src/body_multiple_params/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="22"
+{!> ../../docs_src/body_multiple_params/tutorial003.py!}
+```
+
+////
在这种情况下,**FastAPI** 将期望像这样的请求体:
@@ -181,45 +222,63 @@ q: str = None
比如:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!}
- ```
+```Python hl_lines="27"
+{!> ../../docs_src/body_multiple_params/tutorial004_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="27"
+{!> ../../docs_src/body_multiple_params/tutorial004_an_py39.py!}
+```
- ```Python hl_lines="28"
- {!> ../../../docs_src/body_multiple_params/tutorial004_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+```Python hl_lines="28"
+{!> ../../docs_src/body_multiple_params/tutorial004_an.py!}
+```
- ```Python hl_lines="25"
- {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+/// tip
- ```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004.py!}
- ```
+尽可能选择使用 `Annotated` 的版本。
-!!! info
- `Body` 同样具有与 `Query`、`Path` 以及其他后面将看到的类完全相同的额外校验和元数据参数。
+///
+```Python hl_lines="25"
+{!> ../../docs_src/body_multiple_params/tutorial004_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="27"
+{!> ../../docs_src/body_multiple_params/tutorial004.py!}
+```
+
+////
+
+/// info
+
+`Body` 同样具有与 `Query`、`Path` 以及其他后面将看到的类完全相同的额外校验和元数据参数。
+
+///
## 嵌入单个请求体参数
@@ -235,41 +294,57 @@ item: Item = Body(embed=True)
比如:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="17"
- {!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!}
- ```
+```Python hl_lines="17"
+{!> ../../docs_src/body_multiple_params/tutorial005_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="17"
- {!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="17"
+{!> ../../docs_src/body_multiple_params/tutorial005_an_py39.py!}
+```
- ```Python hl_lines="18"
- {!> ../../../docs_src/body_multiple_params/tutorial005_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+```Python hl_lines="18"
+{!> ../../docs_src/body_multiple_params/tutorial005_an.py!}
+```
- ```Python hl_lines="15"
- {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+/// tip
- ```Python hl_lines="17"
- {!> ../../../docs_src/body_multiple_params/tutorial005.py!}
- ```
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="15"
+{!> ../../docs_src/body_multiple_params/tutorial005_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="17"
+{!> ../../docs_src/body_multiple_params/tutorial005.py!}
+```
+
+////
在这种情况下,**FastAPI** 将期望像这样的请求体:
diff --git a/docs/zh/docs/tutorial/body-nested-models.md b/docs/zh/docs/tutorial/body-nested-models.md
index 3f519ae33..316ba9878 100644
--- a/docs/zh/docs/tutorial/body-nested-models.md
+++ b/docs/zh/docs/tutorial/body-nested-models.md
@@ -6,17 +6,21 @@
你可以将一个属性定义为拥有子元素的类型。例如 Python `list`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="12"
- {!> ../../../docs_src/body_nested_models/tutorial001_py310.py!}
- ```
+```Python hl_lines="12"
+{!> ../../docs_src/body_nested_models/tutorial001_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="14"
+{!> ../../docs_src/body_nested_models/tutorial001.py!}
+```
+
+////
这将使 `tags` 成为一个由元素组成的列表。不过它没有声明每个元素的类型。
@@ -29,7 +33,7 @@
首先,从 Python 的标准库 `typing` 模块中导入 `List`:
```Python hl_lines="1"
-{!> ../../../docs_src/body_nested_models/tutorial002.py!}
+{!> ../../docs_src/body_nested_models/tutorial002.py!}
```
### 声明具有子类型的 List
@@ -51,23 +55,29 @@ my_list: List[str]
因此,在我们的示例中,我们可以将 `tags` 明确地指定为一个「字符串列表」:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="12"
- {!> ../../../docs_src/body_nested_models/tutorial002_py310.py!}
- ```
+```Python hl_lines="12"
+{!> ../../docs_src/body_nested_models/tutorial002_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial002_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="14"
+{!> ../../docs_src/body_nested_models/tutorial002_py39.py!}
+```
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial002.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="14"
+{!> ../../docs_src/body_nested_models/tutorial002.py!}
+```
+
+////
## Set 类型
@@ -77,23 +87,29 @@ Python 具有一种特殊的数据类型来保存一组唯一的元素,即 `se
然后我们可以导入 `Set` 并将 `tag` 声明为一个由 `str` 组成的 `set`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="12"
- {!> ../../../docs_src/body_nested_models/tutorial003_py310.py!}
- ```
+```Python hl_lines="12"
+{!> ../../docs_src/body_nested_models/tutorial003_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial003_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="14"
+{!> ../../docs_src/body_nested_models/tutorial003_py39.py!}
+```
- ```Python hl_lines="1 14"
- {!> ../../../docs_src/body_nested_models/tutorial003.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="1 14"
+{!> ../../docs_src/body_nested_models/tutorial003.py!}
+```
+
+////
这样,即使你收到带有重复数据的请求,这些数据也会被转换为一组唯一项。
@@ -115,45 +131,57 @@ Pydantic 模型的每个属性都具有类型。
例如,我们可以定义一个 `Image` 模型:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7-9"
- {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!}
- ```
+```Python hl_lines="7-9"
+{!> ../../docs_src/body_nested_models/tutorial004_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="9-11"
- {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="9-11"
+{!> ../../docs_src/body_nested_models/tutorial004_py39.py!}
+```
- ```Python hl_lines="9-11"
- {!> ../../../docs_src/body_nested_models/tutorial004.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="9-11"
+{!> ../../docs_src/body_nested_models/tutorial004.py!}
+```
+
+////
### 将子模型用作类型
然后我们可以将其用作一个属性的类型:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="18"
- {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!}
- ```
+```Python hl_lines="18"
+{!> ../../docs_src/body_nested_models/tutorial004_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="20"
+{!> ../../docs_src/body_nested_models/tutorial004_py39.py!}
+```
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial004.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="20"
+{!> ../../docs_src/body_nested_models/tutorial004.py!}
+```
+
+////
这意味着 **FastAPI** 将期望类似于以下内容的请求体:
@@ -186,23 +214,29 @@ Pydantic 模型的每个属性都具有类型。
例如,在 `Image` 模型中我们有一个 `url` 字段,我们可以把它声明为 Pydantic 的 `HttpUrl`,而不是 `str`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="2 8"
- {!> ../../../docs_src/body_nested_models/tutorial005_py310.py!}
- ```
+```Python hl_lines="2 8"
+{!> ../../docs_src/body_nested_models/tutorial005_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="4 10"
- {!> ../../../docs_src/body_nested_models/tutorial005_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="4 10"
+{!> ../../docs_src/body_nested_models/tutorial005_py39.py!}
+```
- ```Python hl_lines="4 10"
- {!> ../../../docs_src/body_nested_models/tutorial005.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="4 10"
+{!> ../../docs_src/body_nested_models/tutorial005.py!}
+```
+
+////
该字符串将被检查是否为有效的 URL,并在 JSON Schema / OpenAPI 文档中进行记录。
@@ -210,23 +244,29 @@ Pydantic 模型的每个属性都具有类型。
你还可以将 Pydantic 模型用作 `list`、`set` 等的子类型:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="18"
- {!> ../../../docs_src/body_nested_models/tutorial006_py310.py!}
- ```
+```Python hl_lines="18"
+{!> ../../docs_src/body_nested_models/tutorial006_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial006_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="20"
+{!> ../../docs_src/body_nested_models/tutorial006_py39.py!}
+```
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial006.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="20"
+{!> ../../docs_src/body_nested_models/tutorial006.py!}
+```
+
+////
这将期望(转换,校验,记录文档等)下面这样的 JSON 请求体:
@@ -254,33 +294,45 @@ Pydantic 模型的每个属性都具有类型。
}
```
-!!! info
- 请注意 `images` 键现在具有一组 image 对象是如何发生的。
+/// info
+
+请注意 `images` 键现在具有一组 image 对象是如何发生的。
+
+///
## 深度嵌套模型
你可以定义任意深度的嵌套模型:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7 12 18 21 25"
- {!> ../../../docs_src/body_nested_models/tutorial007_py310.py!}
- ```
+```Python hl_lines="7 12 18 21 25"
+{!> ../../docs_src/body_nested_models/tutorial007_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="9 14 20 23 27"
- {!> ../../../docs_src/body_nested_models/tutorial007_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="9 14 20 23 27"
+{!> ../../docs_src/body_nested_models/tutorial007_py39.py!}
+```
- ```Python hl_lines="9 14 20 23 27"
- {!> ../../../docs_src/body_nested_models/tutorial007.py!}
- ```
+////
-!!! info
- 请注意 `Offer` 拥有一组 `Item` 而反过来 `Item` 又是一个可选的 `Image` 列表是如何发生的。
+//// tab | Python 3.8+
+
+```Python hl_lines="9 14 20 23 27"
+{!> ../../docs_src/body_nested_models/tutorial007.py!}
+```
+
+////
+
+/// info
+
+请注意 `Offer` 拥有一组 `Item` 而反过来 `Item` 又是一个可选的 `Image` 列表是如何发生的。
+
+///
## 纯列表请求体
@@ -292,17 +344,21 @@ images: List[Image]
例如:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="13"
- {!> ../../../docs_src/body_nested_models/tutorial008_py39.py!}
- ```
+```Python hl_lines="13"
+{!> ../../docs_src/body_nested_models/tutorial008_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="15"
- {!> ../../../docs_src/body_nested_models/tutorial008.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="15"
+{!> ../../docs_src/body_nested_models/tutorial008.py!}
+```
+
+////
## 无处不在的编辑器支持
@@ -332,26 +388,33 @@ images: List[Image]
在下面的例子中,你将接受任意键为 `int` 类型并且值为 `float` 类型的 `dict`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="7"
- {!> ../../../docs_src/body_nested_models/tutorial009_py39.py!}
- ```
+```Python hl_lines="7"
+{!> ../../docs_src/body_nested_models/tutorial009_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/body_nested_models/tutorial009.py!}
- ```
+//// tab | Python 3.8+
-!!! tip
- 请记住 JSON 仅支持将 `str` 作为键。
+```Python hl_lines="9"
+{!> ../../docs_src/body_nested_models/tutorial009.py!}
+```
- 但是 Pydantic 具有自动转换数据的功能。
+////
- 这意味着,即使你的 API 客户端只能将字符串作为键发送,只要这些字符串内容仅包含整数,Pydantic 就会对其进行转换并校验。
+/// tip
- 然后你接收的名为 `weights` 的 `dict` 实际上将具有 `int` 类型的键和 `float` 类型的值。
+请记住 JSON 仅支持将 `str` 作为键。
+
+但是 Pydantic 具有自动转换数据的功能。
+
+这意味着,即使你的 API 客户端只能将字符串作为键发送,只要这些字符串内容仅包含整数,Pydantic 就会对其进行转换并校验。
+
+然后你接收的名为 `weights` 的 `dict` 实际上将具有 `int` 类型的键和 `float` 类型的值。
+
+///
## 总结
diff --git a/docs/zh/docs/tutorial/body-updates.md b/docs/zh/docs/tutorial/body-updates.md
index e529fc914..5e9008d6a 100644
--- a/docs/zh/docs/tutorial/body-updates.md
+++ b/docs/zh/docs/tutorial/body-updates.md
@@ -7,7 +7,7 @@
把输入数据转换为以 JSON 格式存储的数据(比如,使用 NoSQL 数据库时),可以使用 `jsonable_encoder`。例如,把 `datetime` 转换为 `str`。
```Python hl_lines="30-35"
-{!../../../docs_src/body_updates/tutorial001.py!}
+{!../../docs_src/body_updates/tutorial001.py!}
```
`PUT` 用于接收替换现有数据的数据。
@@ -34,15 +34,17 @@
即,只发送要更新的数据,其余数据保持不变。
-!!! note "笔记"
+/// note | "笔记"
- `PATCH` 没有 `PUT` 知名,也怎么不常用。
+`PATCH` 没有 `PUT` 知名,也怎么不常用。
- 很多人甚至只用 `PUT` 实现部分更新。
+很多人甚至只用 `PUT` 实现部分更新。
- **FastAPI** 对此没有任何限制,可以**随意**互换使用这两种操作。
+**FastAPI** 对此没有任何限制,可以**随意**互换使用这两种操作。
- 但本指南也会分别介绍这两种操作各自的用途。
+但本指南也会分别介绍这两种操作各自的用途。
+
+///
### 使用 Pydantic 的 `exclude_unset` 参数
@@ -55,7 +57,7 @@
然后再用它生成一个只含已设置(在请求中所发送)数据,且省略了默认值的 `dict`:
```Python hl_lines="34"
-{!../../../docs_src/body_updates/tutorial002.py!}
+{!../../docs_src/body_updates/tutorial002.py!}
```
### 使用 Pydantic 的 `update` 参数
@@ -65,7 +67,7 @@
例如,`stored_item_model.copy(update=update_data)`:
```Python hl_lines="35"
-{!../../../docs_src/body_updates/tutorial002.py!}
+{!../../docs_src/body_updates/tutorial002.py!}
```
### 更新部分数据小结
@@ -84,18 +86,22 @@
* 返回更新后的模型。
```Python hl_lines="30-37"
-{!../../../docs_src/body_updates/tutorial002.py!}
+{!../../docs_src/body_updates/tutorial002.py!}
```
-!!! tip "提示"
+/// tip | "提示"
- 实际上,HTTP `PUT` 也可以完成相同的操作。
- 但本节以 `PATCH` 为例的原因是,该操作就是为了这种用例创建的。
+实际上,HTTP `PUT` 也可以完成相同的操作。
+但本节以 `PATCH` 为例的原因是,该操作就是为了这种用例创建的。
-!!! note "笔记"
+///
- 注意,输入模型仍需验证。
+/// note | "笔记"
- 因此,如果希望接收的部分更新数据可以省略其他所有属性,则要把模型中所有的属性标记为可选(使用默认值或 `None`)。
+注意,输入模型仍需验证。
- 为了区分用于**更新**所有可选值的模型与用于**创建**包含必选值的模型,请参照[更多模型](extra-models.md){.internal-link target=_blank} 一节中的思路。
+因此,如果希望接收的部分更新数据可以省略其他所有属性,则要把模型中所有的属性标记为可选(使用默认值或 `None`)。
+
+为了区分用于**更新**所有可选值的模型与用于**创建**包含必选值的模型,请参照[更多模型](extra-models.md){.internal-link target=_blank} 一节中的思路。
+
+///
diff --git a/docs/zh/docs/tutorial/body.md b/docs/zh/docs/tutorial/body.md
index 65d459cd1..67a7f28e0 100644
--- a/docs/zh/docs/tutorial/body.md
+++ b/docs/zh/docs/tutorial/body.md
@@ -8,29 +8,35 @@ API 基本上肯定要发送**响应体**,但是客户端不一定发送**请
使用 Pydantic 模型声明**请求体**,能充分利用它的功能和优点。
-!!! info "说明"
+/// info | "说明"
- 发送数据使用 `POST`(最常用)、`PUT`、`DELETE`、`PATCH` 等操作。
+发送数据使用 `POST`(最常用)、`PUT`、`DELETE`、`PATCH` 等操作。
- 规范中没有定义使用 `GET` 发送请求体的操作,但不管怎样,FastAPI 也支持这种方式,只不过仅用于非常复杂或极端的用例。
+规范中没有定义使用 `GET` 发送请求体的操作,但不管怎样,FastAPI 也支持这种方式,只不过仅用于非常复杂或极端的用例。
- 我们不建议使用 `GET`,因此,在 Swagger UI 交互文档中不会显示有关 `GET` 的内容,而且代理协议也不一定支持 `GET`。
+我们不建议使用 `GET`,因此,在 Swagger UI 交互文档中不会显示有关 `GET` 的内容,而且代理协议也不一定支持 `GET`。
+
+///
## 导入 Pydantic 的 `BaseModel`
从 `pydantic` 中导入 `BaseModel`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="2"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
+```Python hl_lines="2"
+{!> ../../docs_src/body/tutorial001_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="4"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="4"
+{!> ../../docs_src/body/tutorial001.py!}
+```
+
+////
## 创建数据模型
@@ -38,17 +44,21 @@ API 基本上肯定要发送**响应体**,但是客户端不一定发送**请
使用 Python 标准类型声明所有属性:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="5-9"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
+```Python hl_lines="5-9"
+{!> ../../docs_src/body/tutorial001_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="7-11"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="7-11"
+{!> ../../docs_src/body/tutorial001.py!}
+```
+
+////
与声明查询参数一样,包含默认值的模型属性是可选的,否则就是必选的。默认值为 `None` 的模型属性也是可选的。
@@ -76,17 +86,21 @@ API 基本上肯定要发送**响应体**,但是客户端不一定发送**请
使用与声明路径和查询参数相同的方式声明请求体,把请求体添加至*路径操作*:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="16"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
+```Python hl_lines="16"
+{!> ../../docs_src/body/tutorial001_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="18"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="18"
+{!> ../../docs_src/body/tutorial001.py!}
+```
+
+////
……此处,请求体参数的类型为 `Item` 模型。
@@ -135,33 +149,39 @@ Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文
-!!! tip "提示"
+/// tip | "提示"
- 使用 PyCharm 编辑器时,推荐安装 Pydantic PyCharm 插件。
+使用 PyCharm 编辑器时,推荐安装 Pydantic PyCharm 插件。
- 该插件用于完善 PyCharm 对 Pydantic 模型的支持,优化的功能如下:
+该插件用于完善 PyCharm 对 Pydantic 模型的支持,优化的功能如下:
- * 自动补全
- * 类型检查
- * 代码重构
- * 查找
- * 代码审查
+* 自动补全
+* 类型检查
+* 代码重构
+* 查找
+* 代码审查
+
+///
## 使用模型
在*路径操作*函数内部直接访问模型对象的属性:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="19"
- {!> ../../../docs_src/body/tutorial002_py310.py!}
- ```
+```Python hl_lines="19"
+{!> ../../docs_src/body/tutorial002_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="21"
- {!> ../../../docs_src/body/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="21"
+{!> ../../docs_src/body/tutorial002.py!}
+```
+
+////
## 请求体 + 路径参数
@@ -169,17 +189,21 @@ Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文
**FastAPI** 能识别与**路径参数**匹配的函数参数,还能识别从**请求体**中获取的类型为 Pydantic 模型的函数参数。
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="15-16"
- {!> ../../../docs_src/body/tutorial003_py310.py!}
- ```
+```Python hl_lines="15-16"
+{!> ../../docs_src/body/tutorial003_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="17-18"
- {!> ../../../docs_src/body/tutorial003.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="17-18"
+{!> ../../docs_src/body/tutorial003.py!}
+```
+
+////
## 请求体 + 路径参数 + 查询参数
@@ -187,17 +211,21 @@ Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文
**FastAPI** 能够正确识别这三种参数,并从正确的位置获取数据。
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="16"
- {!> ../../../docs_src/body/tutorial004_py310.py!}
- ```
+```Python hl_lines="16"
+{!> ../../docs_src/body/tutorial004_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="18"
- {!> ../../../docs_src/body/tutorial004.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="18"
+{!> ../../docs_src/body/tutorial004.py!}
+```
+
+////
函数参数按如下规则进行识别:
@@ -205,11 +233,13 @@ Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文
- 类型是(`int`、`float`、`str`、`bool` 等)**单类型**的参数,是**查询**参数
- 类型是 **Pydantic 模型**的参数,是**请求体**
-!!! note "笔记"
+/// note | "笔记"
- 因为默认值是 `None`, FastAPI 会把 `q` 当作可选参数。
+因为默认值是 `None`, FastAPI 会把 `q` 当作可选参数。
- FastAPI 不使用 `Optional[str]` 中的 `Optional`, 但 `Optional` 可以让编辑器提供更好的支持,并检测错误。
+FastAPI 不使用 `Optional[str]` 中的 `Optional`, 但 `Optional` 可以让编辑器提供更好的支持,并检测错误。
+
+///
## 不使用 Pydantic
diff --git a/docs/zh/docs/tutorial/cookie-params.md b/docs/zh/docs/tutorial/cookie-params.md
index 8571422dd..b01c28238 100644
--- a/docs/zh/docs/tutorial/cookie-params.md
+++ b/docs/zh/docs/tutorial/cookie-params.md
@@ -6,41 +6,57 @@
首先,导入 `Cookie`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="3"
+{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="3"
+{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+```Python hl_lines="3"
+{!> ../../docs_src/cookie_params/tutorial001_an.py!}
+```
- ```Python hl_lines="1"
- {!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+/// tip
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001.py!}
- ```
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="1"
+{!> ../../docs_src/cookie_params/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="3"
+{!> ../../docs_src/cookie_params/tutorial001.py!}
+```
+
+////
## 声明 `Cookie` 参数
@@ -49,51 +65,71 @@
第一个值是默认值,还可以传递所有验证参数或注释参数:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="9"
+{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/cookie_params/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+```Python hl_lines="10"
+{!> ../../docs_src/cookie_params/tutorial001_an.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+/// tip
- ```Python hl_lines="9"
- {!> ../../../docs_src/cookie_params/tutorial001.py!}
- ```
+尽可能选择使用 `Annotated` 的版本。
-!!! note "技术细节"
+///
- `Cookie` 、`Path` 、`Query` 是**兄弟类**,都继承自共用的 `Param` 类。
+```Python hl_lines="7"
+{!> ../../docs_src/cookie_params/tutorial001_py310.py!}
+```
- 注意,从 `fastapi` 导入的 `Query`、`Path`、`Cookie` 等对象,实际上是返回特殊类的函数。
+////
-!!! info "说明"
+//// tab | Python 3.8+ non-Annotated
- 必须使用 `Cookie` 声明 cookie 参数,否则该参数会被解释为查询参数。
+/// tip
+
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="9"
+{!> ../../docs_src/cookie_params/tutorial001.py!}
+```
+
+////
+
+/// note | "技术细节"
+
+`Cookie` 、`Path` 、`Query` 是**兄弟类**,都继承自共用的 `Param` 类。
+
+注意,从 `fastapi` 导入的 `Query`、`Path`、`Cookie` 等对象,实际上是返回特殊类的函数。
+
+///
+
+/// info | "说明"
+
+必须使用 `Cookie` 声明 cookie 参数,否则该参数会被解释为查询参数。
+
+///
## 小结
diff --git a/docs/zh/docs/tutorial/cors.md b/docs/zh/docs/tutorial/cors.md
index ddd4e7682..1166d5c97 100644
--- a/docs/zh/docs/tutorial/cors.md
+++ b/docs/zh/docs/tutorial/cors.md
@@ -47,7 +47,7 @@
* 特定的 HTTP headers 或者使用通配符 `"*"` 允许所有 headers。
```Python hl_lines="2 6-11 13-19"
-{!../../../docs_src/cors/tutorial001.py!}
+{!../../docs_src/cors/tutorial001.py!}
```
默认情况下,这个 `CORSMiddleware` 实现所使用的默认参数较为保守,所以你需要显式地启用特定的源、方法或者 headers,以便浏览器能够在跨域上下文中使用它们。
@@ -78,7 +78,10 @@
更多关于 CORS 的信息,请查看 Mozilla CORS 文档。
-!!! note "技术细节"
- 你也可以使用 `from starlette.middleware.cors import CORSMiddleware`。
+/// note | "技术细节"
- 出于方便,**FastAPI** 在 `fastapi.middleware` 中为开发者提供了几个中间件。但是大多数可用的中间件都是直接来自 Starlette。
+你也可以使用 `from starlette.middleware.cors import CORSMiddleware`。
+
+出于方便,**FastAPI** 在 `fastapi.middleware` 中为开发者提供了几个中间件。但是大多数可用的中间件都是直接来自 Starlette。
+
+///
diff --git a/docs/zh/docs/tutorial/debugging.md b/docs/zh/docs/tutorial/debugging.md
index 51801d498..a5afa1aaa 100644
--- a/docs/zh/docs/tutorial/debugging.md
+++ b/docs/zh/docs/tutorial/debugging.md
@@ -7,7 +7,7 @@
在你的 FastAPI 应用中直接导入 `uvicorn` 并运行:
```Python hl_lines="1 15"
-{!../../../docs_src/debugging/tutorial001.py!}
+{!../../docs_src/debugging/tutorial001.py!}
```
### 关于 `__name__ == "__main__"`
@@ -70,8 +70,11 @@ from myapp import app
uvicorn.run(app, host="0.0.0.0", port=8000)
```
-!!! info
- 更多信息请检查 Python 官方文档.
+/// info
+
+更多信息请检查 Python 官方文档.
+
+///
## 使用你的调试器运行代码
diff --git a/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md
index 1866da298..917459d1d 100644
--- a/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md
+++ b/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md
@@ -6,17 +6,21 @@
在前面的例子中, 我们从依赖项 ("可依赖对象") 中返回了一个 `dict`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+```Python hl_lines="7"
+{!> ../../docs_src/dependencies/tutorial001_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../docs_src/dependencies/tutorial001.py!}
+```
+
+////
但是后面我们在路径操作函数的参数 `commons` 中得到了一个 `dict`。
@@ -79,45 +83,57 @@ fluffy = Cat(name="Mr Fluffy")
所以,我们可以将上面的依赖项 "可依赖对象" `common_parameters` 更改为类 `CommonQueryParams`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9-13"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
+```Python hl_lines="9-13"
+{!> ../../docs_src/dependencies/tutorial002_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="11-15"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="11-15"
+{!> ../../docs_src/dependencies/tutorial002.py!}
+```
+
+////
注意用于创建类实例的 `__init__` 方法:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="10"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
+```Python hl_lines="10"
+{!> ../../docs_src/dependencies/tutorial002_py310.py!}
+```
-=== "Python 3.6+"
+////
- ```Python hl_lines="12"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
- ```
+//// tab | Python 3.6+
+
+```Python hl_lines="12"
+{!> ../../docs_src/dependencies/tutorial002.py!}
+```
+
+////
...它与我们以前的 `common_parameters` 具有相同的参数:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="6"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+```Python hl_lines="6"
+{!> ../../docs_src/dependencies/tutorial001_py310.py!}
+```
-=== "Python 3.6+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+//// tab | Python 3.6+
+
+```Python hl_lines="9"
+{!> ../../docs_src/dependencies/tutorial001.py!}
+```
+
+////
这些参数就是 **FastAPI** 用来 "处理" 依赖项的。
@@ -133,17 +149,21 @@ fluffy = Cat(name="Mr Fluffy")
现在,您可以使用这个类来声明你的依赖项了。
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
+```Python hl_lines="17"
+{!> ../../docs_src/dependencies/tutorial002_py310.py!}
+```
-=== "Python 3.6+"
+////
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
- ```
+//// tab | Python 3.6+
+
+```Python hl_lines="19"
+{!> ../../docs_src/dependencies/tutorial002.py!}
+```
+
+////
**FastAPI** 调用 `CommonQueryParams` 类。这将创建该类的一个 "实例",该实例将作为参数 `commons` 被传递给你的函数。
@@ -183,17 +203,21 @@ commons = Depends(CommonQueryParams)
..就像:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial003_py310.py!}
- ```
+```Python hl_lines="17"
+{!> ../../docs_src/dependencies/tutorial003_py310.py!}
+```
-=== "Python 3.6+"
+////
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial003.py!}
- ```
+//// tab | Python 3.6+
+
+```Python hl_lines="19"
+{!> ../../docs_src/dependencies/tutorial003.py!}
+```
+
+////
但是声明类型是被鼓励的,因为那样你的编辑器就会知道将传递什么作为参数 `commons` ,然后它可以帮助你完成代码,类型检查,等等:
@@ -227,21 +251,28 @@ commons: CommonQueryParams = Depends()
同样的例子看起来像这样:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial004_py310.py!}
- ```
+```Python hl_lines="17"
+{!> ../../docs_src/dependencies/tutorial004_py310.py!}
+```
-=== "Python 3.6+"
+////
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial004.py!}
- ```
+//// tab | Python 3.6+
+
+```Python hl_lines="19"
+{!> ../../docs_src/dependencies/tutorial004.py!}
+```
+
+////
... **FastAPI** 会知道怎么处理。
-!!! tip
- 如果这看起来更加混乱而不是更加有帮助,那么请忽略它,你不*需要*它。
+/// tip
- 这只是一个快捷方式。因为 **FastAPI** 关心的是帮助您减少代码重复。
+如果这看起来更加混乱而不是更加有帮助,那么请忽略它,你不*需要*它。
+
+这只是一个快捷方式。因为 **FastAPI** 关心的是帮助您减少代码重复。
+
+///
diff --git a/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
index 61ea371e5..c7cfe0531 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
@@ -15,24 +15,28 @@
该参数的值是由 `Depends()` 组成的 `list`:
```Python hl_lines="17"
-{!../../../docs_src/dependencies/tutorial006.py!}
+{!../../docs_src/dependencies/tutorial006.py!}
```
路径操作装饰器依赖项(以下简称为**“路径装饰器依赖项”**)的执行或解析方式和普通依赖项一样,但就算这些依赖项会返回值,它们的值也不会传递给*路径操作函数*。
-!!! tip "提示"
+/// tip | "提示"
- 有些编辑器会检查代码中没使用过的函数参数,并显示错误提示。
+有些编辑器会检查代码中没使用过的函数参数,并显示错误提示。
- 在*路径操作装饰器*中使用 `dependencies` 参数,可以确保在执行依赖项的同时,避免编辑器显示错误提示。
+在*路径操作装饰器*中使用 `dependencies` 参数,可以确保在执行依赖项的同时,避免编辑器显示错误提示。
- 使用路径装饰器依赖项还可以避免开发新人误会代码中包含无用的未使用参数。
+使用路径装饰器依赖项还可以避免开发新人误会代码中包含无用的未使用参数。
-!!! info "说明"
+///
- 本例中,使用的是自定义响应头 `X-Key` 和 `X-Token`。
+/// info | "说明"
- 但实际开发中,尤其是在实现安全措施时,最好使用 FastAPI 内置的[安全工具](../security/index.md){.internal-link target=_blank}(详见下一章)。
+本例中,使用的是自定义响应头 `X-Key` 和 `X-Token`。
+
+但实际开发中,尤其是在实现安全措施时,最好使用 FastAPI 内置的[安全工具](../security/index.md){.internal-link target=_blank}(详见下一章)。
+
+///
## 依赖项错误和返回值
@@ -43,7 +47,7 @@
路径装饰器依赖项可以声明请求的需求项(比如响应头)或其他子依赖项:
```Python hl_lines="6 11"
-{!../../../docs_src/dependencies/tutorial006.py!}
+{!../../docs_src/dependencies/tutorial006.py!}
```
### 触发异常
@@ -51,7 +55,7 @@
路径装饰器依赖项与正常的依赖项一样,可以 `raise` 异常:
```Python hl_lines="8 13"
-{!../../../docs_src/dependencies/tutorial006.py!}
+{!../../docs_src/dependencies/tutorial006.py!}
```
### 返回值
@@ -61,7 +65,7 @@
因此,可以复用在其他位置使用过的、(能返回值的)普通依赖项,即使没有使用这个值,也会执行该依赖项:
```Python hl_lines="9 14"
-{!../../../docs_src/dependencies/tutorial006.py!}
+{!../../docs_src/dependencies/tutorial006.py!}
```
## 为一组路径操作定义依赖项
diff --git a/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md
index 4159d626e..a30313719 100644
--- a/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md
+++ b/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md
@@ -1,161 +1,284 @@
# 使用yield的依赖项
-FastAPI支持在完成后执行一些额外步骤的依赖项.
+FastAPI支持在完成后执行一些额外步骤的依赖项.
-为此,请使用 `yield` 而不是 `return`,然后再编写额外的步骤(代码)。
+为此,你需要使用 `yield` 而不是 `return`,然后再编写这些额外的步骤(代码)。
-!!! tip "提示"
- 确保只使用一次 `yield` 。
+/// tip | 提示
-!!! note "技术细节"
+确保在每个依赖中只使用一次 `yield`。
- 任何一个可以与以下内容一起使用的函数:
+///
- * `@contextlib.contextmanager` 或者
- * `@contextlib.asynccontextmanager`
+/// note | "技术细节"
- 都可以作为 **FastAPI** 的依赖项。
+任何一个可以与以下内容一起使用的函数:
- 实际上,FastAPI内部就使用了这两个装饰器。
+* `@contextlib.contextmanager` 或者
+* `@contextlib.asynccontextmanager`
+都可以作为 **FastAPI** 的依赖项。
+
+实际上,FastAPI内部就使用了这两个装饰器。
+
+///
## 使用 `yield` 的数据库依赖项
-例如,您可以使用这种方式创建一个数据库会话,并在完成后关闭它。
+例如,你可以使用这种方式创建一个数据库会话,并在完成后关闭它。
在发送响应之前,只会执行 `yield` 语句及之前的代码:
```Python hl_lines="2-4"
-{!../../../docs_src/dependencies/tutorial007.py!}
+{!../../docs_src/dependencies/tutorial007.py!}
```
-生成的值会注入到*路径操作*和其他依赖项中:
+生成的值会注入到 *路由函数* 和其他依赖项中:
```Python hl_lines="4"
-{!../../../docs_src/dependencies/tutorial007.py!}
+{!../../docs_src/dependencies/tutorial007.py!}
```
-"yield"语句后面的代码会在发送响应后执行::
+`yield` 语句后面的代码会在创建响应后,发送响应前执行:
```Python hl_lines="5-6"
-{!../../../docs_src/dependencies/tutorial007.py!}
+{!../../docs_src/dependencies/tutorial007.py!}
```
-!!! tip "提示"
+/// tip | 提示
- 您可以使用 `async` 或普通函数。
+你可以使用 `async` 或普通函数。
- **FastAPI** 会像处理普通依赖关系一样,对每个依赖关系做正确的处理。
+**FastAPI** 会像处理普通依赖一样,对每个依赖做正确的处理。
-## 同时包含了 `yield` 和 `try` 的依赖项
+///
-如果在带有 `yield` 的依赖关系中使用 `try` 代码块,就会收到使用依赖关系时抛出的任何异常。
+## 包含 `yield` 和 `try` 的依赖项
-例如,如果中间某个代码在另一个依赖中或在*路径操作*中使数据库事务 "回滚 "或产生任何其他错误,您就会在依赖中收到异常。
+如果在包含 `yield` 的依赖中使用 `try` 代码块,你会捕获到使用依赖时抛出的任何异常。
-因此,你可以使用 `except SomeException` 在依赖关系中查找特定的异常。
+例如,如果某段代码在另一个依赖中或在 *路由函数* 中使数据库事务"回滚"或产生任何其他错误,你将会在依赖中捕获到异常。
-同样,您也可以使用 `finally` 来确保退出步骤得到执行,无论是否存在异常。
+因此,你可以使用 `except SomeException` 在依赖中捕获特定的异常。
+
+同样,你也可以使用 `finally` 来确保退出步骤得到执行,无论是否存在异常。
```Python hl_lines="3 5"
-{!../../../docs_src/dependencies/tutorial007.py!}
+{!../../docs_src/dependencies/tutorial007.py!}
```
-## 使用`yield`的子依赖项
+## 使用 `yield` 的子依赖项
-你可以拥有任意大小和形状的子依赖和子依赖的“树”,而且它们中的任何一个或所有的都可以使用`yield`。
+你可以声明任意数量和层级的树状依赖,而且它们中的任何一个或所有的都可以使用 `yield`。
-**FastAPI** 会确保每个带有`yield`的依赖中的“退出代码”按正确顺序运行。
+**FastAPI** 会确保每个带有 `yield` 的依赖中的"退出代码"按正确顺序运行。
例如,`dependency_c` 可以依赖于 `dependency_b`,而 `dependency_b` 则依赖于 `dependency_a`。
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="6 14 22"
- {!> ../../../docs_src/dependencies/tutorial008_an_py39.py!}
- ```
+```Python hl_lines="6 14 22"
+{!> ../../docs_src/dependencies/tutorial008_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="5 13 21"
- {!> ../../../docs_src/dependencies/tutorial008_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python hl_lines="5 13 21"
+{!> ../../docs_src/dependencies/tutorial008_an.py!}
+```
- !!! tip
- 如果可能,请尽量使用“ Annotated”版本。
+////
- ```Python hl_lines="4 12 20"
- {!> ../../../docs_src/dependencies/tutorial008.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
-所有这些依赖都可以使用`yield`。
+/// tip | 提示
-在这种情况下,`dependency_c` 在执行其退出代码时需要`dependency_b`(此处称为 `dep_b`)的值仍然可用。
+如果可以,请尽量使用 `Annotated` 版本。
-而`dependency_b` 反过来则需要`dependency_a`(此处称为 `dep_a`)的值在其退出代码中可用。
+///
-=== "Python 3.9+"
+```Python hl_lines="4 12 20"
+{!> ../../docs_src/dependencies/tutorial008.py!}
+```
- ```Python hl_lines="18-19 26-27"
- {!> ../../../docs_src/dependencies/tutorial008_an_py39.py!}
- ```
+////
-=== "Python 3.8+"
+所有这些依赖都可以使用 `yield`。
- ```Python hl_lines="17-18 25-26"
- {!> ../../../docs_src/dependencies/tutorial008_an.py!}
- ```
+在这种情况下,`dependency_c` 在执行其退出代码时需要 `dependency_b`(此处称为 `dep_b`)的值仍然可用。
-=== "Python 3.8+ non-Annotated"
+而 `dependency_b` 反过来则需要 `dependency_a`(此处称为 `dep_a` )的值在其退出代码中可用。
- !!! tip
- 如果可能,请尽量使用“ Annotated”版本。
+//// tab | Python 3.9+
- ```Python hl_lines="16-17 24-25"
- {!> ../../../docs_src/dependencies/tutorial008.py!}
- ```
+```Python hl_lines="18-19 26-27"
+{!> ../../docs_src/dependencies/tutorial008_an_py39.py!}
+```
-同样,你可以有混合了`yield`和`return`的依赖。
+////
-你也可以有一个单一的依赖需要多个其他带有`yield`的依赖,等等。
+//// tab | Python 3.8+
+
+```Python hl_lines="17-18 25-26"
+{!> ../../docs_src/dependencies/tutorial008_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | 提示
+
+如果可以,请尽量使用 `Annotated` 版本。
+
+///
+
+```Python hl_lines="16-17 24-25"
+{!> ../../docs_src/dependencies/tutorial008.py!}
+```
+
+////
+
+同样,你可以混合使用带有 `yield` 或 `return` 的依赖。
+
+你也可以声明一个依赖于多个带有 `yield` 的依赖,等等。
你可以拥有任何你想要的依赖组合。
**FastAPI** 将确保按正确的顺序运行所有内容。
-!!! note "技术细节"
+/// note | "技术细节"
- 这是由 Python 的上下文管理器完成的。
+这是由 Python 的上下文管理器完成的。
- **FastAPI** 在内部使用它们来实现这一点。
+**FastAPI** 在内部使用它们来实现这一点。
+///
-## 使用 `yield` 和 `HTTPException` 的依赖项
+## 包含 `yield` 和 `HTTPException` 的依赖项
-您看到可以使用带有 `yield` 的依赖项,并且具有捕获异常的 `try` 块。
+你可以使用带有 `yield` 的依赖项,并且可以包含 `try` 代码块用于捕获异常。
-在 `yield` 后抛出 `HTTPException` 或类似的异常是很诱人的,但是**这不起作用**。
+同样,你可以在 `yield` 之后的退出代码中抛出一个 `HTTPException` 或类似的异常。
-带有`yield`的依赖中的退出代码在响应发送之后执行,因此[异常处理程序](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}已经运行过。没有任何东西可以捕获退出代码(在`yield`之后)中的依赖抛出的异常。
+/// tip | 提示
-所以,如果在`yield`之后抛出`HTTPException`,默认(或任何自定义)异常处理程序捕获`HTTPException`并返回HTTP 400响应的机制将不再能够捕获该异常。
+这是一种相对高级的技巧,在大多数情况下你并不需要使用它,因为你可以在其他代码中抛出异常(包括 `HTTPException` ),例如在 *路由函数* 中。
-这就是允许在依赖中设置的任何东西(例如数据库会话(DB session))可以被后台任务使用的原因。
+但是如果你需要,你也可以在依赖项中做到这一点。🤓
-后台任务在响应发送之后运行。因此,无法触发`HTTPException`,因为甚至没有办法更改*已发送*的响应。
+///
-但如果后台任务产生了数据库错误,至少你可以在带有`yield`的依赖中回滚或清理关闭会话,并且可能记录错误或将其报告给远程跟踪系统。
+//// tab | Python 3.9+
-如果你知道某些代码可能会引发异常,那就做最“Pythonic”的事情,就是在代码的那部分添加一个`try`块。
+```Python hl_lines="18-22 31"
+{!> ../../docs_src/dependencies/tutorial008b_an_py39.py!}
+```
-如果你有自定义异常,希望在返回响应之前处理,并且可能修改响应甚至触发`HTTPException`,可以创建[自定义异常处理程序](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}。
+////
-!!! tip
+//// tab | Python 3.8+
- 在`yield`之前仍然可以引发包括`HTTPException`在内的异常,但在`yield`之后则不行。
+```Python hl_lines="17-21 30"
+{!> ../../docs_src/dependencies/tutorial008b_an.py!}
+```
-执行的顺序大致如下图所示。时间从上到下流动。每列都是相互交互或执行代码的其中一部分。
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | 提示
+
+如果可以,请尽量使用 `Annotated` 版本。
+
+///
+
+```Python hl_lines="16-20 29"
+{!> ../../docs_src/dependencies/tutorial008b.py!}
+```
+
+////
+
+你还可以创建一个 [自定义异常处理器](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank} 用于捕获异常(同时也可以抛出另一个 `HTTPException`)。
+
+## 包含 `yield` 和 `except` 的依赖项
+
+如果你在包含 `yield` 的依赖项中使用 `except` 捕获了一个异常,然后你没有重新抛出该异常(或抛出一个新异常),与在普通的Python代码中相同,FastAPI不会注意到发生了异常。
+
+//// 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 | 提示
+
+如果可以,请尽量使用 `Annotated` 版本。
+
+///
+
+```Python hl_lines="13-14"
+{!> ../../docs_src/dependencies/tutorial008c.py!}
+```
+
+////
+
+在示例代码的情况下,客户端将会收到 *HTTP 500 Internal Server Error* 的响应,因为我们没有抛出 `HTTPException` 或者类似的异常,并且服务器也 **不会有任何日志** 或者其他提示来告诉我们错误是什么。😱
+
+### 在包含 `yield` 和 `except` 的依赖项中一定要 `raise`
+
+如果你在使用 `yield` 的依赖项中捕获到了一个异常,你应该再次抛出捕获到的异常,除非你抛出 `HTTPException` 或类似的其他异常,
+
+你可以使用 `raise` 再次抛出捕获到的异常。
+
+//// tab | Python 3.9+
+
+```Python hl_lines="17"
+{!> ../../docs_src/dependencies/tutorial008d_an_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="16"
+{!> ../../docs_src/dependencies/tutorial008d_an.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | 提示
+
+如果可以,请尽量使用 `Annotated` 版本。
+
+///
+
+```Python hl_lines="15"
+{!> ../../docs_src/dependencies/tutorial008d.py!}
+```
+
+////
+
+现在客户端同样会得到 *HTTP 500 Internal Server Error* 响应,但是服务器日志会记录下我们自定义的 `InternalError`。
+
+## 使用 `yield` 的依赖项的执行
+
+执行顺序大致如下时序图所示。时间轴从上到下,每一列都代表交互或者代码执行的一部分。
```mermaid
sequenceDiagram
@@ -166,54 +289,89 @@ participant dep as Dep with yield
participant operation as Path Operation
participant tasks as Background tasks
- Note over client,tasks: Can raise exception for dependency, handled after response is sent
- Note over client,operation: Can raise HTTPException and can change the response
+ Note over client,operation: Can raise exceptions, including HTTPException
client ->> dep: Start request
Note over dep: Run code up to yield
- opt raise
- dep -->> handler: Raise HTTPException
+ opt raise Exception
+ dep -->> handler: Raise Exception
handler -->> client: HTTP error response
- dep -->> dep: Raise other exception
end
dep ->> operation: Run dependency, e.g. DB session
opt raise
- operation -->> dep: Raise HTTPException
- dep -->> handler: Auto forward exception
+ operation -->> dep: Raise Exception (e.g. HTTPException)
+ opt handle
+ dep -->> dep: Can catch exception, raise a new HTTPException, raise other exception
+ end
handler -->> client: HTTP error response
- operation -->> dep: Raise other exception
- dep -->> handler: Auto forward exception
end
+
operation ->> client: Return response to client
Note over client,operation: Response is already sent, can't change it anymore
opt Tasks
operation -->> tasks: Send background tasks
end
opt Raise other exception
- tasks -->> dep: Raise other exception
- end
- Note over dep: After yield
- opt Handle other exception
- dep -->> dep: Handle exception, can't change response. E.g. close DB session.
+ tasks -->> tasks: Handle exceptions in the background task code
end
```
-!!! info
- 只会向客户端发送**一次响应**,可能是一个错误响应之一,也可能是来自*路径操作*的响应。
+/// info | 说明
- 在发送了其中一个响应之后,就无法再发送其他响应了。
+只会向客户端发送 **一次响应** ,可能是一个错误响应,也可能是来自 *路由函数* 的响应。
-!!! tip
- 这个图表展示了`HTTPException`,但你也可以引发任何其他你创建了[自定义异常处理程序](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}的异常。
+在发送了其中一个响应之后,就无法再发送其他响应了。
- 如果你引发任何异常,它将传递给带有`yield`的依赖,包括`HTTPException`,然后**再次**传递给异常处理程序。如果没有针对该异常的异常处理程序,那么它将被默认的内部`ServerErrorMiddleware`处理,返回500 HTTP状态码,告知客户端服务器发生了错误。
+///
+
+/// tip | 提示
+
+这个时序图展示了 `HTTPException`,除此之外你也可以抛出任何你在使用 `yield` 的依赖项中或者[自定义异常处理器](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}中捕获的异常。
+
+如果你引发任何异常,它将传递给使用 `yield` 的依赖项,包括 `HTTPException`。在大多数情况下你应当从使用 `yield` 的依赖项中重新抛出捕获的异常或者一个新的异常来确保它会被正确的处理。
+
+///
+
+## 包含 `yield`, `HTTPException`, `except` 的依赖项和后台任务
+
+/// warning | 注意
+
+你大概率不需要了解这些技术细节,可以跳过这一章节继续阅读后续的内容。
+
+如果你使用的FastAPI的版本早于0.106.0,并且在使用后台任务中使用了包含 `yield` 的依赖项中的资源,那么这些细节会对你有一些用处。
+
+///
+
+### 包含 `yield` 和 `except` 的依赖项的技术细节
+
+在FastAPI 0.110.0版本之前,如果使用了一个包含 `yield` 的依赖项,你在依赖项中使用 `except` 捕获了一个异常,但是你没有再次抛出该异常,这个异常会被自动抛出/转发到异常处理器或者内部服务错误处理器。
+
+### 后台任务和使用 `yield` 的依赖项的技术细节
+
+在FastAPI 0.106.0版本之前,在 `yield` 后面抛出异常是不可行的,因为 `yield` 之后的退出代码是在响应被发送之后再执行,这个时候异常处理器已经执行过了。
+
+这样设计的目的主要是为了允许在后台任务中使用被依赖项`yield`的对象,因为退出代码会在后台任务结束后再执行。
+
+然而这也意味着在等待响应通过网络传输的同时,非必要的持有一个 `yield` 依赖项中的资源(例如数据库连接),这一行为在FastAPI 0.106.0被改变了。
+
+/// tip | 提示
+
+除此之外,后台任务通常是一组独立的逻辑,应该被单独处理,并且使用它自己的资源(例如它自己的数据库连接)。
+
+这样也会让你的代码更加简洁。
+
+///
+
+如果你之前依赖于这一行为,那么现在你应该在后台任务中创建并使用它自己的资源,不要在内部使用属于 `yield` 依赖项的资源。
+
+例如,你应该在后台任务中创建一个新的数据库会话用于查询数据,而不是使用相同的会话。你应该将对象的ID作为参数传递给后台任务函数,然后在该函数中重新获取该对象,而不是直接将数据库对象作为参数。
## 上下文管理器
-### 什么是“上下文管理器”
+### 什么是"上下文管理器"
-“上下文管理器”是您可以在`with`语句中使用的任何Python对象。
+"上下文管理器"是你可以在 `with` 语句中使用的任何Python对象。
-例如,您可以使用`with`读取文件:
+例如,你可以使用`with`读取文件:
```Python
with open("./somefile.txt") as f:
@@ -221,33 +379,39 @@ with open("./somefile.txt") as f:
print(contents)
```
-在底层,`open("./somefile.txt")`创建了一个被称为“上下文管理器”的对象。
+在底层,`open("./somefile.txt")`创建了一个被称为"上下文管理器"的对象。
-当`with`块结束时,它会确保关闭文件,即使发生了异常也是如此。
+当 `with` 代码块结束时,它会确保关闭文件,即使发生了异常也是如此。
-当你使用`yield`创建一个依赖项时,**FastAPI**会在内部将其转换为上下文管理器,并与其他相关工具结合使用。
+当你使用 `yield` 创建一个依赖项时,**FastAPI** 会在内部将其转换为上下文管理器,并与其他相关工具结合使用。
-### 在依赖项中使用带有`yield`的上下文管理器
+### 在使用 `yield` 的依赖项中使用上下文管理器
-!!! warning
- 这是一个更为“高级”的想法。
+/// warning | 注意
- 如果您刚开始使用**FastAPI**,您可能暂时可以跳过它。
+这是一个更为"高级"的想法。
+
+如果你刚开始使用 **FastAPI** ,你可以暂时可以跳过它。
+
+///
在Python中,你可以通过创建一个带有`__enter__()`和`__exit__()`方法的类来创建上下文管理器。
-你也可以在**FastAPI**的依赖项中使用带有`yield`的`with`或`async with`语句,通过在依赖函数内部使用它们。
+你也可以在 **FastAPI** 的 `yield` 依赖项中通过 `with` 或者 `async with` 语句来使用它们:
```Python hl_lines="1-9 13"
-{!../../../docs_src/dependencies/tutorial010.py!}
+{!../../docs_src/dependencies/tutorial010.py!}
```
-!!! tip
- 另一种创建上下文管理器的方法是:
+/// tip | 提示
- * `@contextlib.contextmanager`或者
- * `@contextlib.asynccontextmanager`
+另一种创建上下文管理器的方法是:
- 使用上下文管理器装饰一个只有单个`yield`的函数。这就是**FastAPI**在内部用于带有`yield`的依赖项的方式。
+* `@contextlib.contextmanager`或者
+* `@contextlib.asynccontextmanager`
- 但是你不需要为FastAPI的依赖项使用这些装饰器(而且也不应该)。FastAPI会在内部为你处理这些。
+使用它们装饰一个只有单个 `yield` 的函数。这就是 **FastAPI** 内部对于 `yield` 依赖项的处理方式。
+
+但是你不需要为FastAPI的依赖项使用这些装饰器(而且也不应该)。FastAPI会在内部为你处理这些。
+
+///
diff --git a/docs/zh/docs/tutorial/dependencies/global-dependencies.md b/docs/zh/docs/tutorial/dependencies/global-dependencies.md
index 3f7afa32c..66f153f6b 100644
--- a/docs/zh/docs/tutorial/dependencies/global-dependencies.md
+++ b/docs/zh/docs/tutorial/dependencies/global-dependencies.md
@@ -7,7 +7,7 @@
这样一来,就可以为所有*路径操作*应用该依赖项:
```Python hl_lines="15"
-{!../../../docs_src/dependencies/tutorial012.py!}
+{!../../docs_src/dependencies/tutorial012.py!}
```
[*路径装饰器依赖项*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} 一章的思路均适用于全局依赖项, 在本例中,这些依赖项可以用于应用中的所有*路径操作*。
diff --git a/docs/zh/docs/tutorial/dependencies/index.md b/docs/zh/docs/tutorial/dependencies/index.md
index 7a133061d..b039e1654 100644
--- a/docs/zh/docs/tutorial/dependencies/index.md
+++ b/docs/zh/docs/tutorial/dependencies/index.md
@@ -32,7 +32,7 @@ FastAPI 提供了简单易用,但功能强大的** read_users
这样,只编写一次代码,**FastAPI** 就可以为多个*路径操作*共享这段代码 。
-!!! check "检查"
+/// check | "检查"
- 注意,无需创建专门的类,并将之传递给 **FastAPI** 以进行「注册」或执行类似的操作。
+注意,无需创建专门的类,并将之传递给 **FastAPI** 以进行「注册」或执行类似的操作。
- 只要把它传递给 `Depends`,**FastAPI** 就知道该如何执行后续操作。
+只要把它传递给 `Depends`,**FastAPI** 就知道该如何执行后续操作。
+
+///
## 要不要使用 `async`?
@@ -114,9 +118,11 @@ common_parameters --> read_users
上述这些操作都是可行的,**FastAPI** 知道该怎么处理。
-!!! note "笔记"
+/// note | "笔记"
- 如里不了解异步,请参阅[异步:*“着急了?”*](../../async.md){.internal-link target=_blank} 一章中 `async` 和 `await` 的内容。
+如里不了解异步,请参阅[异步:*“着急了?”*](../../async.md){.internal-link target=_blank} 一章中 `async` 和 `await` 的内容。
+
+///
## 与 OpenAPI 集成
diff --git a/docs/zh/docs/tutorial/dependencies/sub-dependencies.md b/docs/zh/docs/tutorial/dependencies/sub-dependencies.md
index 58377bbfe..dd4c60857 100644
--- a/docs/zh/docs/tutorial/dependencies/sub-dependencies.md
+++ b/docs/zh/docs/tutorial/dependencies/sub-dependencies.md
@@ -11,7 +11,7 @@ FastAPI 支持创建含**子依赖项**的依赖项。
下列代码创建了第一层依赖项:
```Python hl_lines="8-9"
-{!../../../docs_src/dependencies/tutorial005.py!}
+{!../../docs_src/dependencies/tutorial005.py!}
```
这段代码声明了类型为 `str` 的可选查询参数 `q`,然后返回这个查询参数。
@@ -23,7 +23,7 @@ FastAPI 支持创建含**子依赖项**的依赖项。
接下来,创建另一个依赖项函数,并同时用该依赖项自身再声明一个依赖项(所以这也是一个「依赖项」):
```Python hl_lines="13"
-{!../../../docs_src/dependencies/tutorial005.py!}
+{!../../docs_src/dependencies/tutorial005.py!}
```
这里重点说明一下声明的参数:
@@ -38,14 +38,16 @@ FastAPI 支持创建含**子依赖项**的依赖项。
接下来,就可以使用依赖项:
```Python hl_lines="22"
-{!../../../docs_src/dependencies/tutorial005.py!}
+{!../../docs_src/dependencies/tutorial005.py!}
```
-!!! info "信息"
+/// info | "信息"
- 注意,这里在*路径操作函数*中只声明了一个依赖项,即 `query_or_cookie_extractor` 。
+注意,这里在*路径操作函数*中只声明了一个依赖项,即 `query_or_cookie_extractor` 。
- 但 **FastAPI** 必须先处理 `query_extractor`,以便在调用 `query_or_cookie_extractor` 时使用 `query_extractor` 返回的结果。
+但 **FastAPI** 必须先处理 `query_extractor`,以便在调用 `query_or_cookie_extractor` 时使用 `query_extractor` 返回的结果。
+
+///
```mermaid
graph TB
@@ -79,10 +81,12 @@ async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False
但它依然非常强大,能够声明任意嵌套深度的「图」或树状的依赖结构。
-!!! tip "提示"
+/// tip | "提示"
- 这些简单的例子现在看上去虽然没有什么实用价值,
+这些简单的例子现在看上去虽然没有什么实用价值,
- 但在**安全**一章中,您会了解到这些例子的用途,
+但在**安全**一章中,您会了解到这些例子的用途,
- 以及这些例子所能节省的代码量。
+以及这些例子所能节省的代码量。
+
+///
diff --git a/docs/zh/docs/tutorial/encoder.md b/docs/zh/docs/tutorial/encoder.md
index 859ebc2e8..41f37cd8d 100644
--- a/docs/zh/docs/tutorial/encoder.md
+++ b/docs/zh/docs/tutorial/encoder.md
@@ -20,17 +20,21 @@
它接收一个对象,比如Pydantic模型,并会返回一个JSON兼容的版本:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="4 21"
- {!> ../../../docs_src/encoder/tutorial001_py310.py!}
- ```
+```Python hl_lines="4 21"
+{!> ../../docs_src/encoder/tutorial001_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="5 22"
- {!> ../../../docs_src/encoder/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="5 22"
+{!> ../../docs_src/encoder/tutorial001.py!}
+```
+
+////
在这个例子中,它将Pydantic模型转换为`dict`,并将`datetime`转换为`str`。
@@ -38,5 +42,8 @@
这个操作不会返回一个包含JSON格式(作为字符串)数据的庞大的`str`。它将返回一个Python标准数据结构(例如`dict`),其值和子值都与JSON兼容。
-!!! note
- `jsonable_encoder`实际上是FastAPI内部用来转换数据的。但是它在许多其他场景中也很有用。
+/// note
+
+`jsonable_encoder`实际上是FastAPI内部用来转换数据的。但是它在许多其他场景中也很有用。
+
+///
diff --git a/docs/zh/docs/tutorial/extra-data-types.md b/docs/zh/docs/tutorial/extra-data-types.md
index cf39de0dd..ea5798b67 100644
--- a/docs/zh/docs/tutorial/extra-data-types.md
+++ b/docs/zh/docs/tutorial/extra-data-types.md
@@ -55,76 +55,108 @@
下面是一个*路径操作*的示例,其中的参数使用了上面的一些类型。
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="1 3 12-16"
- {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="1 3 12-16"
+{!> ../../docs_src/extra_data_types/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="1 3 12-16"
- {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="1 3 12-16"
+{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="1 3 13-17"
- {!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+```Python hl_lines="1 3 13-17"
+{!> ../../docs_src/extra_data_types/tutorial001_an.py!}
+```
- ```Python hl_lines="1 2 11-15"
- {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+/// tip
- ```Python hl_lines="1 2 12-16"
- {!> ../../../docs_src/extra_data_types/tutorial001.py!}
- ```
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="1 2 11-15"
+{!> ../../docs_src/extra_data_types/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="1 2 12-16"
+{!> ../../docs_src/extra_data_types/tutorial001.py!}
+```
+
+////
注意,函数内的参数有原生的数据类型,你可以,例如,执行正常的日期操作,如:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="18-19"
+{!> ../../docs_src/extra_data_types/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="18-19"
+{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="19-20"
- {!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+```Python hl_lines="19-20"
+{!> ../../docs_src/extra_data_types/tutorial001_an.py!}
+```
- ```Python hl_lines="17-18"
- {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+/// tip
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/extra_data_types/tutorial001.py!}
- ```
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="17-18"
+{!> ../../docs_src/extra_data_types/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="18-19"
+{!> ../../docs_src/extra_data_types/tutorial001.py!}
+```
+
+////
diff --git a/docs/zh/docs/tutorial/extra-models.md b/docs/zh/docs/tutorial/extra-models.md
index 94d82c524..6649b06c7 100644
--- a/docs/zh/docs/tutorial/extra-models.md
+++ b/docs/zh/docs/tutorial/extra-models.md
@@ -8,27 +8,33 @@
* **输出模型**不应含密码
* **数据库模型**需要加密的密码
-!!! danger "危险"
+/// danger | "危险"
- 千万不要存储用户的明文密码。始终存储可以进行验证的**安全哈希值**。
+千万不要存储用户的明文密码。始终存储可以进行验证的**安全哈希值**。
- 如果不了解这方面的知识,请参阅[安全性中的章节](security/simple-oauth2.md#password-hashing){.internal-link target=_blank},了解什么是**密码哈希**。
+如果不了解这方面的知识,请参阅[安全性中的章节](security/simple-oauth2.md#password-hashing){.internal-link target=_blank},了解什么是**密码哈希**。
+
+///
## 多个模型
下面的代码展示了不同模型处理密码字段的方式,及使用位置的大致思路:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39"
- {!> ../../../docs_src/extra_models/tutorial001_py310.py!}
- ```
+```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39"
+{!> ../../docs_src/extra_models/tutorial001_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41"
- {!> ../../../docs_src/extra_models/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41"
+{!> ../../docs_src/extra_models/tutorial001.py!}
+```
+
+////
### `**user_in.dict()` 简介
@@ -140,9 +146,11 @@ UserInDB(
)
```
-!!! warning "警告"
+/// warning | "警告"
- 辅助的附加函数只是为了演示可能的数据流,但它们显然不能提供任何真正的安全机制。
+辅助的附加函数只是为了演示可能的数据流,但它们显然不能提供任何真正的安全机制。
+
+///
## 减少重复
@@ -162,17 +170,21 @@ FastAPI 可以做得更好。
通过这种方式,可以只声明模型之间的区别(分别包含明文密码、哈希密码,以及无密码的模型)。
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7 13-14 17-18 21-22"
- {!> ../../../docs_src/extra_models/tutorial002_py310.py!}
- ```
+```Python hl_lines="7 13-14 17-18 21-22"
+{!> ../../docs_src/extra_models/tutorial002_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9 15-16 19-20 23-24"
- {!> ../../../docs_src/extra_models/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="9 15-16 19-20 23-24"
+{!> ../../docs_src/extra_models/tutorial002.py!}
+```
+
+////
## `Union` 或者 `anyOf`
@@ -182,21 +194,27 @@ FastAPI 可以做得更好。
为此,请使用 Python 标准类型提示 `typing.Union`:
-!!! note "笔记"
+/// note | "笔记"
- 定义 `Union` 类型时,要把详细的类型写在前面,然后是不太详细的类型。下例中,更详细的 `PlaneItem` 位于 `Union[PlaneItem,CarItem]` 中的 `CarItem` 之前。
+定义 `Union` 类型时,要把详细的类型写在前面,然后是不太详细的类型。下例中,更详细的 `PlaneItem` 位于 `Union[PlaneItem,CarItem]` 中的 `CarItem` 之前。
-=== "Python 3.10+"
+///
- ```Python hl_lines="1 14-15 18-20 33"
- {!> ../../../docs_src/extra_models/tutorial003_py310.py!}
- ```
+//// tab | Python 3.10+
-=== "Python 3.8+"
+```Python hl_lines="1 14-15 18-20 33"
+{!> ../../docs_src/extra_models/tutorial003_py310.py!}
+```
- ```Python hl_lines="1 14-15 18-20 33"
- {!> ../../../docs_src/extra_models/tutorial003.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="1 14-15 18-20 33"
+{!> ../../docs_src/extra_models/tutorial003.py!}
+```
+
+////
## 模型列表
@@ -204,17 +222,21 @@ FastAPI 可以做得更好。
为此,请使用标准的 Python `typing.List`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="18"
- {!> ../../../docs_src/extra_models/tutorial004_py39.py!}
- ```
+```Python hl_lines="18"
+{!> ../../docs_src/extra_models/tutorial004_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1 20"
- {!> ../../../docs_src/extra_models/tutorial004.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="1 20"
+{!> ../../docs_src/extra_models/tutorial004.py!}
+```
+
+////
## 任意 `dict` 构成的响应
@@ -224,17 +246,21 @@ FastAPI 可以做得更好。
此时,可以使用 `typing.Dict`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="6"
- {!> ../../../docs_src/extra_models/tutorial005_py39.py!}
- ```
+```Python hl_lines="6"
+{!> ../../docs_src/extra_models/tutorial005_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="1 8"
- {!> ../../../docs_src/extra_models/tutorial005.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="1 8"
+{!> ../../docs_src/extra_models/tutorial005.py!}
+```
+
+////
## 小结
diff --git a/docs/zh/docs/tutorial/first-steps.md b/docs/zh/docs/tutorial/first-steps.md
index 30fae99cf..b9bbca193 100644
--- a/docs/zh/docs/tutorial/first-steps.md
+++ b/docs/zh/docs/tutorial/first-steps.md
@@ -3,7 +3,7 @@
最简单的 FastAPI 文件可能像下面这样:
```Python
-{!../../../docs_src/first_steps/tutorial001.py!}
+{!../../docs_src/first_steps/tutorial001.py!}
```
将其复制到 `main.py` 文件中。
@@ -24,13 +24,15 @@ $ uvicorn main:app --reload
-!!! note
- `uvicorn main:app` 命令含义如下:
+/// note
- * `main`:`main.py` 文件(一个 Python「模块」)。
- * `app`:在 `main.py` 文件中通过 `app = FastAPI()` 创建的对象。
- * `--reload`:让服务器在更新代码后重新启动。仅在开发时使用该选项。
+`uvicorn main:app` 命令含义如下:
+* `main`:`main.py` 文件(一个 Python「模块」)。
+* `app`:在 `main.py` 文件中通过 `app = FastAPI()` 创建的对象。
+* `--reload`:让服务器在更新代码后重新启动。仅在开发时使用该选项。
+
+///
在输出中,会有一行信息像下面这样:
@@ -133,20 +135,23 @@ OpenAPI 为你的 API 定义 API 模式。该模式中包含了你的 API 发送
### 步骤 1:导入 `FastAPI`
```Python hl_lines="1"
-{!../../../docs_src/first_steps/tutorial001.py!}
+{!../../docs_src/first_steps/tutorial001.py!}
```
`FastAPI` 是一个为你的 API 提供了所有功能的 Python 类。
-!!! note "技术细节"
- `FastAPI` 是直接从 `Starlette` 继承的类。
+/// note | "技术细节"
- 你可以通过 `FastAPI` 使用所有的 Starlette 的功能。
+`FastAPI` 是直接从 `Starlette` 继承的类。
+
+你可以通过 `FastAPI` 使用所有的 Starlette 的功能。
+
+///
### 步骤 2:创建一个 `FastAPI`「实例」
```Python hl_lines="3"
-{!../../../docs_src/first_steps/tutorial001.py!}
+{!../../docs_src/first_steps/tutorial001.py!}
```
这里的变量 `app` 会是 `FastAPI` 类的一个「实例」。
@@ -168,7 +173,7 @@ $ uvicorn main:app --reload
如果你像下面这样创建应用:
```Python hl_lines="3"
-{!../../../docs_src/first_steps/tutorial002.py!}
+{!../../docs_src/first_steps/tutorial002.py!}
```
将代码放入 `main.py` 文件中,然后你可以像下面这样运行 `uvicorn`:
@@ -201,8 +206,11 @@ https://example.com/items/foo
/items/foo
```
-!!! info
- 「路径」也通常被称为「端点」或「路由」。
+/// info
+
+「路径」也通常被称为「端点」或「路由」。
+
+///
开发 API 时,「路径」是用来分离「关注点」和「资源」的主要手段。
@@ -244,7 +252,7 @@ https://example.com/items/foo
#### 定义一个*路径操作装饰器*
```Python hl_lines="6"
-{!../../../docs_src/first_steps/tutorial001.py!}
+{!../../docs_src/first_steps/tutorial001.py!}
```
`@app.get("/")` 告诉 **FastAPI** 在它下方的函数负责处理如下访问请求:
@@ -252,16 +260,19 @@ https://example.com/items/foo
* 请求路径为 `/`
* 使用 get 操作
-!!! info "`@decorator` Info"
- `@something` 语法在 Python 中被称为「装饰器」。
+/// info | "`@decorator` Info"
- 像一顶漂亮的装饰帽一样,将它放在一个函数的上方(我猜测这个术语的命名就是这么来的)。
+`@something` 语法在 Python 中被称为「装饰器」。
- 装饰器接收位于其下方的函数并且用它完成一些工作。
+像一顶漂亮的装饰帽一样,将它放在一个函数的上方(我猜测这个术语的命名就是这么来的)。
- 在我们的例子中,这个装饰器告诉 **FastAPI** 位于其下方的函数对应着**路径** `/` 加上 `get` **操作**。
+装饰器接收位于其下方的函数并且用它完成一些工作。
- 它是一个「**路径操作装饰器**」。
+在我们的例子中,这个装饰器告诉 **FastAPI** 位于其下方的函数对应着**路径** `/` 加上 `get` **操作**。
+
+它是一个「**路径操作装饰器**」。
+
+///
你也可以使用其他的操作:
@@ -276,14 +287,17 @@ https://example.com/items/foo
* `@app.patch()`
* `@app.trace()`
-!!! tip
- 您可以随意使用任何一个操作(HTTP方法)。
+/// tip
- **FastAPI** 没有强制要求操作有任何特定的含义。
+您可以随意使用任何一个操作(HTTP方法)。
- 此处提供的信息仅作为指导,而不是要求。
+**FastAPI** 没有强制要求操作有任何特定的含义。
- 比如,当使用 GraphQL 时通常你所有的动作都通过 `post` 一种方法执行。
+此处提供的信息仅作为指导,而不是要求。
+
+比如,当使用 GraphQL 时通常你所有的动作都通过 `post` 一种方法执行。
+
+///
### 步骤 4:定义**路径操作函数**
@@ -294,7 +308,7 @@ https://example.com/items/foo
* **函数**:是位于「装饰器」下方的函数(位于 `@app.get("/")` 下方)。
```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial001.py!}
+{!../../docs_src/first_steps/tutorial001.py!}
```
这是一个 Python 函数。
@@ -308,16 +322,19 @@ https://example.com/items/foo
你也可以将其定义为常规函数而不使用 `async def`:
```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial003.py!}
+{!../../docs_src/first_steps/tutorial003.py!}
```
-!!! note
- 如果你不知道两者的区别,请查阅 [Async: *"In a hurry?"*](https://fastapi.tiangolo.com/async/#in-a-hurry){.internal-link target=_blank}。
+/// note
+
+如果你不知道两者的区别,请查阅 [Async: *"In a hurry?"*](https://fastapi.tiangolo.com/async/#in-a-hurry){.internal-link target=_blank}。
+
+///
### 步骤 5:返回内容
```Python hl_lines="8"
-{!../../../docs_src/first_steps/tutorial001.py!}
+{!../../docs_src/first_steps/tutorial001.py!}
```
你可以返回一个 `dict`、`list`,像 `str`、`int` 一样的单个值,等等。
diff --git a/docs/zh/docs/tutorial/handling-errors.md b/docs/zh/docs/tutorial/handling-errors.md
index 701cd241e..0820c363c 100644
--- a/docs/zh/docs/tutorial/handling-errors.md
+++ b/docs/zh/docs/tutorial/handling-errors.md
@@ -26,7 +26,7 @@
### 导入 `HTTPException`
```Python hl_lines="1"
-{!../../../docs_src/handling_errors/tutorial001.py!}
+{!../../docs_src/handling_errors/tutorial001.py!}
```
@@ -43,7 +43,7 @@
本例中,客户端用 `ID` 请求的 `item` 不存在时,触发状态码为 `404` 的异常:
```Python hl_lines="11"
-{!../../../docs_src/handling_errors/tutorial001.py!}
+{!../../docs_src/handling_errors/tutorial001.py!}
```
@@ -67,14 +67,15 @@
```
-!!! tip "提示"
+/// tip | "提示"
- 触发 `HTTPException` 时,可以用参数 `detail` 传递任何能转换为 JSON 的值,不仅限于 `str`。
+触发 `HTTPException` 时,可以用参数 `detail` 传递任何能转换为 JSON 的值,不仅限于 `str`。
- 还支持传递 `dict`、`list` 等数据结构。
+还支持传递 `dict`、`list` 等数据结构。
- **FastAPI** 能自动处理这些数据,并将之转换为 JSON。
+**FastAPI** 能自动处理这些数据,并将之转换为 JSON。
+///
## 添加自定义响应头
@@ -85,7 +86,7 @@
但对于某些高级应用场景,还是需要添加自定义响应头:
```Python hl_lines="14"
-{!../../../docs_src/handling_errors/tutorial002.py!}
+{!../../docs_src/handling_errors/tutorial002.py!}
```
@@ -100,7 +101,7 @@
此时,可以用 `@app.exception_handler()` 添加自定义异常控制器:
```Python hl_lines="5-7 13-18 24"
-{!../../../docs_src/handling_errors/tutorial003.py!}
+{!../../docs_src/handling_errors/tutorial003.py!}
```
@@ -115,12 +116,13 @@
```
-!!! note "技术细节"
+/// note | "技术细节"
- `from starlette.requests import Request` 和 `from starlette.responses import JSONResponse` 也可以用于导入 `Request` 和 `JSONResponse`。
+`from starlette.requests import Request` 和 `from starlette.responses import JSONResponse` 也可以用于导入 `Request` 和 `JSONResponse`。
- **FastAPI** 提供了与 `starlette.responses` 相同的 `fastapi.responses` 作为快捷方式,但大部分响应操作都可以直接从 Starlette 导入。同理,`Request` 也是如此。
+**FastAPI** 提供了与 `starlette.responses` 相同的 `fastapi.responses` 作为快捷方式,但大部分响应操作都可以直接从 Starlette 导入。同理,`Request` 也是如此。
+///
## 覆盖默认异常处理器
@@ -141,7 +143,7 @@
这样,异常处理器就可以接收 `Request` 与异常。
```Python hl_lines="2 14-16"
-{!../../../docs_src/handling_errors/tutorial004.py!}
+{!../../docs_src/handling_errors/tutorial004.py!}
```
@@ -174,10 +176,11 @@ path -> item_id
### `RequestValidationError` vs `ValidationError`
-!!! warning "警告"
+/// warning | "警告"
- 如果您觉得现在还用不到以下技术细节,可以先跳过下面的内容。
+如果您觉得现在还用不到以下技术细节,可以先跳过下面的内容。
+///
`RequestValidationError` 是 Pydantic 的 `ValidationError` 的子类。
@@ -196,16 +199,17 @@ path -> item_id
例如,只为错误返回纯文本响应,而不是返回 JSON 格式的内容:
```Python hl_lines="3-4 9-11 22"
-{!../../../docs_src/handling_errors/tutorial004.py!}
+{!../../docs_src/handling_errors/tutorial004.py!}
```
-!!! note "技术细节"
+/// note | "技术细节"
- 还可以使用 `from starlette.responses import PlainTextResponse`。
+还可以使用 `from starlette.responses import PlainTextResponse`。
- **FastAPI** 提供了与 `starlette.responses` 相同的 `fastapi.responses` 作为快捷方式,但大部分响应都可以直接从 Starlette 导入。
+**FastAPI** 提供了与 `starlette.responses` 相同的 `fastapi.responses` 作为快捷方式,但大部分响应都可以直接从 Starlette 导入。
+///
### 使用 `RequestValidationError` 的请求体
@@ -214,7 +218,7 @@ path -> item_id
开发时,可以用这个请求体生成日志、调试错误,并返回给用户。
```Python hl_lines="14"
-{!../../../docs_src/handling_errors/tutorial005.py!}
+{!../../docs_src/handling_errors/tutorial005.py!}
```
@@ -280,7 +284,7 @@ FastAPI 支持先对异常进行某些处理,然后再使用 **FastAPI** 中
从 `fastapi.exception_handlers` 中导入要复用的默认异常处理器:
```Python hl_lines="2-5 15 21"
-{!../../../docs_src/handling_errors/tutorial006.py!}
+{!../../docs_src/handling_errors/tutorial006.py!}
```
diff --git a/docs/zh/docs/tutorial/header-params.md b/docs/zh/docs/tutorial/header-params.md
index 25dfeba87..4de8bf4df 100644
--- a/docs/zh/docs/tutorial/header-params.md
+++ b/docs/zh/docs/tutorial/header-params.md
@@ -6,41 +6,57 @@
首先,导入 `Header`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="3"
- {!> ../../../docs_src/header_params/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="3"
+{!> ../../docs_src/header_params/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="3"
- {!> ../../../docs_src/header_params/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="3"
+{!> ../../docs_src/header_params/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="3"
- {!> ../../../docs_src/header_params/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+```Python hl_lines="3"
+{!> ../../docs_src/header_params/tutorial001_an.py!}
+```
- ```Python hl_lines="1"
- {!> ../../../docs_src/header_params/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+/// tip
- ```Python hl_lines="3"
- {!> ../../../docs_src/header_params/tutorial001.py!}
- ```
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="1"
+{!> ../../docs_src/header_params/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="3"
+{!> ../../docs_src/header_params/tutorial001.py!}
+```
+
+////
## 声明 `Header` 参数
@@ -48,51 +64,71 @@
第一个值是默认值,还可以传递所有验证参数或注释参数:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/header_params/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="9"
+{!> ../../docs_src/header_params/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/header_params/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+```Python hl_lines="10"
+{!> ../../docs_src/header_params/tutorial001_an.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/header_params/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+/// tip
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial001.py!}
- ```
+尽可能选择使用 `Annotated` 的版本。
-!!! note "技术细节"
+///
- `Header` 是 `Path`、`Query`、`Cookie` 的**兄弟类**,都继承自共用的 `Param` 类。
+```Python hl_lines="7"
+{!> ../../docs_src/header_params/tutorial001_py310.py!}
+```
- 注意,从 `fastapi` 导入的 `Query`、`Path`、`Header` 等对象,实际上是返回特殊类的函数。
+////
-!!! info "说明"
+//// tab | Python 3.8+ non-Annotated
- 必须使用 `Header` 声明 header 参数,否则该参数会被解释为查询参数。
+/// tip
+
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="9"
+{!> ../../docs_src/header_params/tutorial001.py!}
+```
+
+////
+
+/// note | "技术细节"
+
+`Header` 是 `Path`、`Query`、`Cookie` 的**兄弟类**,都继承自共用的 `Param` 类。
+
+注意,从 `fastapi` 导入的 `Query`、`Path`、`Header` 等对象,实际上是返回特殊类的函数。
+
+///
+
+/// info | "说明"
+
+必须使用 `Header` 声明 header 参数,否则该参数会被解释为查询参数。
+
+///
## 自动转换
@@ -110,46 +146,63 @@
如需禁用下划线自动转换为连字符,可以把 `Header` 的 `convert_underscores` 参数设置为 `False`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="10"
- {!> ../../../docs_src/header_params/tutorial002_an_py310.py!}
- ```
+```Python hl_lines="10"
+{!> ../../docs_src/header_params/tutorial002_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="11"
- {!> ../../../docs_src/header_params/tutorial002_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="11"
+{!> ../../docs_src/header_params/tutorial002_an_py39.py!}
+```
- ```Python hl_lines="12"
- {!> ../../../docs_src/header_params/tutorial002_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+```Python hl_lines="12"
+{!> ../../docs_src/header_params/tutorial002_an.py!}
+```
- ```Python hl_lines="8"
- {!> ../../../docs_src/header_params/tutorial002_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+/// tip
- ```Python hl_lines="10"
- {!> ../../../docs_src/header_params/tutorial002.py!}
- ```
+尽可能选择使用 `Annotated` 的版本。
-!!! warning "警告"
+///
- 注意,使用 `convert_underscores = False` 要慎重,有些 HTTP 代理和服务器不支持使用带有下划线的请求头。
+```Python hl_lines="8"
+{!> ../../docs_src/header_params/tutorial002_py310.py!}
+```
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="10"
+{!> ../../docs_src/header_params/tutorial002.py!}
+```
+
+////
+
+/// warning | "警告"
+
+注意,使用 `convert_underscores = False` 要慎重,有些 HTTP 代理和服务器不支持使用带有下划线的请求头。
+
+///
## 重复的请求头
@@ -161,50 +214,71 @@
例如,声明 `X-Token` 多次出现的请求头,可以写成这样:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial003_an_py310.py!}
- ```
+```Python hl_lines="9"
+{!> ../../docs_src/header_params/tutorial003_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial003_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="9"
+{!> ../../docs_src/header_params/tutorial003_an_py39.py!}
+```
- ```Python hl_lines="10"
- {!> ../../../docs_src/header_params/tutorial003_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="10"
+{!> ../../docs_src/header_params/tutorial003_an.py!}
+```
- ```Python hl_lines="7"
- {!> ../../../docs_src/header_params/tutorial003_py310.py!}
- ```
+////
-=== "Python 3.9+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+/// tip
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial003_py39.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.8+ non-Annotated"
+///
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+```Python hl_lines="7"
+{!> ../../docs_src/header_params/tutorial003_py310.py!}
+```
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial003.py!}
- ```
+////
+
+//// tab | Python 3.9+ non-Annotated
+
+/// tip
+
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="9"
+{!> ../../docs_src/header_params/tutorial003_py39.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="9"
+{!> ../../docs_src/header_params/tutorial003.py!}
+```
+
+////
与*路径操作*通信时,以下面的方式发送两个 HTTP 请求头:
diff --git a/docs/zh/docs/tutorial/index.md b/docs/zh/docs/tutorial/index.md
index 6180d3de3..ab19f02c5 100644
--- a/docs/zh/docs/tutorial/index.md
+++ b/docs/zh/docs/tutorial/index.md
@@ -52,22 +52,25 @@ $ pip install "fastapi[all]"
......以上安装还包括了 `uvicorn`,你可以将其用作运行代码的服务器。
-!!! note
- 你也可以分开来安装。
+/// note
- 假如你想将应用程序部署到生产环境,你可能要执行以下操作:
+你也可以分开来安装。
- ```
- pip install fastapi
- ```
+假如你想将应用程序部署到生产环境,你可能要执行以下操作:
- 并且安装`uvicorn`来作为服务器:
+```
+pip install fastapi
+```
- ```
- pip install "uvicorn[standard]"
- ```
+并且安装`uvicorn`来作为服务器:
- 然后对你想使用的每个可选依赖项也执行相同的操作。
+```
+pip install "uvicorn[standard]"
+```
+
+然后对你想使用的每个可选依赖项也执行相同的操作。
+
+///
## 进阶用户指南
diff --git a/docs/zh/docs/tutorial/metadata.md b/docs/zh/docs/tutorial/metadata.md
index 59a4af86e..7252db9f6 100644
--- a/docs/zh/docs/tutorial/metadata.md
+++ b/docs/zh/docs/tutorial/metadata.md
@@ -1,101 +1,110 @@
-# 元数据和文档 URL
-
-你可以在 FastAPI 应用程序中自定义多个元数据配置。
-
-## API 元数据
-
-你可以在设置 OpenAPI 规范和自动 API 文档 UI 中使用的以下字段:
-
-| 参数 | 类型 | 描述 |
-|------------|------|-------------|
-| `title` | `str` | API 的标题。 |
-| `summary` | `str` | API 的简短摘要。 自 OpenAPI 3.1.0、FastAPI 0.99.0 起可用。. |
-| `description` | `str` | API 的简短描述。可以使用Markdown。 |
-| `version` | `string` | API 的版本。这是您自己的应用程序的版本,而不是 OpenAPI 的版本。例如 `2.5.0` 。 |
-| `terms_of_service` | `str` | API 服务条款的 URL。如果提供,则必须是 URL。 |
-| `contact` | `dict` | 公开的 API 的联系信息。它可以包含多个字段。contact 字段| 参数 | Type | 描述 |
|---|---|---|
name | str | 联系人/组织的识别名称。 |
url | str | 指向联系信息的 URL。必须采用 URL 格式。 |
email | str | 联系人/组织的电子邮件地址。必须采用电子邮件地址的格式。 |
license_info 字段| 参数 | 类型 | 描述 |
|---|---|---|
name | str | 必须的 (如果设置了license_info). 用于 API 的许可证名称。 |
identifier | str | 一个API的SPDX许可证表达。 The identifier field is mutually exclusive of the url field. 自 OpenAPI 3.1.0、FastAPI 0.99.0 起可用。 |
url | str | 用于 API 的许可证的 URL。必须采用 URL 格式。 |
-
-## 标签元数据
-
-### 创建标签元数据
-
-让我们在带有标签的示例中为 `users` 和 `items` 试一下。
-
-创建标签元数据并把它传递给 `openapi_tags` 参数:
-
-```Python hl_lines="3-16 18"
-{!../../../docs_src/metadata/tutorial004.py!}
-```
-
-注意你可以在描述内使用 Markdown,例如「login」会显示为粗体(**login**)以及「fancy」会显示为斜体(_fancy_)。
-
-!!! tip "提示"
- 不必为你使用的所有标签都添加元数据。
-
-### 使用你的标签
-
-将 `tags` 参数和*路径操作*(以及 `APIRouter`)一起使用,将其分配给不同的标签:
-
-```Python hl_lines="21 26"
-{!../../../docs_src/metadata/tutorial004.py!}
-```
-
-!!! info "信息"
- 阅读更多关于标签的信息[路径操作配置](path-operation-configuration.md#tags){.internal-link target=_blank}。
-
-### 查看文档
-
-如果你现在查看文档,它们会显示所有附加的元数据:
-
-
-
-### 标签顺序
-
-每个标签元数据字典的顺序也定义了在文档用户界面显示的顺序。
-
-例如按照字母顺序,即使 `users` 排在 `items` 之后,它也会显示在前面,因为我们将它的元数据添加为列表内的第一个字典。
-
-## OpenAPI URL
-
-默认情况下,OpenAPI 模式服务于 `/openapi.json`。
-
-但是你可以通过参数 `openapi_url` 对其进行配置。
-
-例如,将其设置为服务于 `/api/v1/openapi.json`:
-
-```Python hl_lines="3"
-{!../../../docs_src/metadata/tutorial002.py!}
-```
-
-如果你想完全禁用 OpenAPI 模式,可以将其设置为 `openapi_url=None`,这样也会禁用使用它的文档用户界面。
-
-## 文档 URLs
-
-你可以配置两个文档用户界面,包括:
-
-* **Swagger UI**:服务于 `/docs`。
- * 可以使用参数 `docs_url` 设置它的 URL。
- * 可以通过设置 `docs_url=None` 禁用它。
-* ReDoc:服务于 `/redoc`。
- * 可以使用参数 `redoc_url` 设置它的 URL。
- * 可以通过设置 `redoc_url=None` 禁用它。
-
-例如,设置 Swagger UI 服务于 `/documentation` 并禁用 ReDoc:
-
-```Python hl_lines="3"
-{!../../../docs_src/metadata/tutorial003.py!}
-```
+# 元数据和文档 URL
+
+你可以在 FastAPI 应用程序中自定义多个元数据配置。
+
+## API 元数据
+
+你可以在设置 OpenAPI 规范和自动 API 文档 UI 中使用的以下字段:
+
+| 参数 | 类型 | 描述 |
+|------------|------|-------------|
+| `title` | `str` | API 的标题。 |
+| `summary` | `str` | API 的简短摘要。 自 OpenAPI 3.1.0、FastAPI 0.99.0 起可用。. |
+| `description` | `str` | API 的简短描述。可以使用Markdown。 |
+| `version` | `string` | API 的版本。这是您自己的应用程序的版本,而不是 OpenAPI 的版本。例如 `2.5.0` 。 |
+| `terms_of_service` | `str` | API 服务条款的 URL。如果提供,则必须是 URL。 |
+| `contact` | `dict` | 公开的 API 的联系信息。它可以包含多个字段。contact 字段| 参数 | Type | 描述 |
|---|---|---|
name | str | 联系人/组织的识别名称。 |
url | str | 指向联系信息的 URL。必须采用 URL 格式。 |
email | str | 联系人/组织的电子邮件地址。必须采用电子邮件地址的格式。 |
license_info 字段| 参数 | 类型 | 描述 |
|---|---|---|
name | str | 必须的 (如果设置了license_info). 用于 API 的许可证名称。 |
identifier | str | 一个API的SPDX许可证表达。 The identifier field is mutually exclusive of the url field. 自 OpenAPI 3.1.0、FastAPI 0.99.0 起可用。 |
url | str | 用于 API 的许可证的 URL。必须采用 URL 格式。 |
+
+## 标签元数据
+
+### 创建标签元数据
+
+让我们在带有标签的示例中为 `users` 和 `items` 试一下。
+
+创建标签元数据并把它传递给 `openapi_tags` 参数:
+
+```Python hl_lines="3-16 18"
+{!../../docs_src/metadata/tutorial004.py!}
+```
+
+注意你可以在描述内使用 Markdown,例如「login」会显示为粗体(**login**)以及「fancy」会显示为斜体(_fancy_)。
+
+/// tip | "提示"
+
+不必为你使用的所有标签都添加元数据。
+
+///
+
+### 使用你的标签
+
+将 `tags` 参数和*路径操作*(以及 `APIRouter`)一起使用,将其分配给不同的标签:
+
+```Python hl_lines="21 26"
+{!../../docs_src/metadata/tutorial004.py!}
+```
+
+/// info | "信息"
+
+阅读更多关于标签的信息[路径操作配置](path-operation-configuration.md#tags){.internal-link target=_blank}。
+
+///
+
+### 查看文档
+
+如果你现在查看文档,它们会显示所有附加的元数据:
+
+
+
+### 标签顺序
+
+每个标签元数据字典的顺序也定义了在文档用户界面显示的顺序。
+
+例如按照字母顺序,即使 `users` 排在 `items` 之后,它也会显示在前面,因为我们将它的元数据添加为列表内的第一个字典。
+
+## OpenAPI URL
+
+默认情况下,OpenAPI 模式服务于 `/openapi.json`。
+
+但是你可以通过参数 `openapi_url` 对其进行配置。
+
+例如,将其设置为服务于 `/api/v1/openapi.json`:
+
+```Python hl_lines="3"
+{!../../docs_src/metadata/tutorial002.py!}
+```
+
+如果你想完全禁用 OpenAPI 模式,可以将其设置为 `openapi_url=None`,这样也会禁用使用它的文档用户界面。
+
+## 文档 URLs
+
+你可以配置两个文档用户界面,包括:
+
+* **Swagger UI**:服务于 `/docs`。
+ * 可以使用参数 `docs_url` 设置它的 URL。
+ * 可以通过设置 `docs_url=None` 禁用它。
+* ReDoc:服务于 `/redoc`。
+ * 可以使用参数 `redoc_url` 设置它的 URL。
+ * 可以通过设置 `redoc_url=None` 禁用它。
+
+例如,设置 Swagger UI 服务于 `/documentation` 并禁用 ReDoc:
+
+```Python hl_lines="3"
+{!../../docs_src/metadata/tutorial003.py!}
+```
diff --git a/docs/zh/docs/tutorial/middleware.md b/docs/zh/docs/tutorial/middleware.md
index c9a7e7725..fb2874ba3 100644
--- a/docs/zh/docs/tutorial/middleware.md
+++ b/docs/zh/docs/tutorial/middleware.md
@@ -11,10 +11,13 @@
* 它可以对该**响应**做些什么或者执行任何需要的代码.
* 然后它返回这个 **响应**.
-!!! note "技术细节"
- 如果你使用了 `yield` 关键字依赖, 依赖中的退出代码将在执行中间件*后*执行.
+/// note | "技术细节"
- 如果有任何后台任务(稍后记录), 它们将在执行中间件*后*运行.
+如果你使用了 `yield` 关键字依赖, 依赖中的退出代码将在执行中间件*后*执行.
+
+如果有任何后台任务(稍后记录), 它们将在执行中间件*后*运行.
+
+///
## 创建中间件
@@ -29,18 +32,24 @@
* 然后你可以在返回 `response` 前进一步修改它.
```Python hl_lines="8-9 11 14"
-{!../../../docs_src/middleware/tutorial001.py!}
+{!../../docs_src/middleware/tutorial001.py!}
```
-!!! tip
- 请记住可以 用'X-' 前缀添加专有自定义请求头.
+/// tip
- 但是如果你想让浏览器中的客户端看到你的自定义请求头, 你需要把它们加到 CORS 配置 ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) 的 `expose_headers` 参数中,在 Starlette's CORS docs文档中.
+请记住可以 用'X-' 前缀添加专有自定义请求头.
-!!! note "技术细节"
- 你也可以使用 `from starlette.requests import Request`.
+但是如果你想让浏览器中的客户端看到你的自定义请求头, 你需要把它们加到 CORS 配置 ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) 的 `expose_headers` 参数中,在 Starlette's CORS docs文档中.
- **FastAPI** 为了开发者方便提供了该对象. 但其实它直接来自于 Starlette.
+///
+
+/// note | "技术细节"
+
+你也可以使用 `from starlette.requests import Request`.
+
+**FastAPI** 为了开发者方便提供了该对象. 但其实它直接来自于 Starlette.
+
+///
### 在 `response` 的前和后
@@ -51,7 +60,7 @@
例如你可以添加自定义请求头 `X-Process-Time` 包含以秒为单位的接收请求和生成响应的时间:
```Python hl_lines="10 12-13"
-{!../../../docs_src/middleware/tutorial001.py!}
+{!../../docs_src/middleware/tutorial001.py!}
```
## 其他中间件
diff --git a/docs/zh/docs/tutorial/path-operation-configuration.md b/docs/zh/docs/tutorial/path-operation-configuration.md
index f79b0e692..12e1f24ba 100644
--- a/docs/zh/docs/tutorial/path-operation-configuration.md
+++ b/docs/zh/docs/tutorial/path-operation-configuration.md
@@ -2,9 +2,11 @@
*路径操作装饰器*支持多种配置参数。
-!!! warning "警告"
+/// warning | "警告"
- 注意:以下参数应直接传递给**路径操作装饰器**,不能传递给*路径操作函数*。
+注意:以下参数应直接传递给**路径操作装饰器**,不能传递给*路径操作函数*。
+
+///
## `status_code` 状态码
@@ -15,23 +17,25 @@
如果记不住数字码的涵义,也可以用 `status` 的快捷常量:
```Python hl_lines="3 17"
-{!../../../docs_src/path_operation_configuration/tutorial001.py!}
+{!../../docs_src/path_operation_configuration/tutorial001.py!}
```
状态码在响应中使用,并会被添加到 OpenAPI 概图。
-!!! note "技术细节"
+/// note | "技术细节"
- 也可以使用 `from starlette import status` 导入状态码。
+也可以使用 `from starlette import status` 导入状态码。
- **FastAPI** 的`fastapi.status` 和 `starlette.status` 一样,只是快捷方式。实际上,`fastapi.status` 直接继承自 Starlette。
+**FastAPI** 的`fastapi.status` 和 `starlette.status` 一样,只是快捷方式。实际上,`fastapi.status` 直接继承自 Starlette。
+
+///
## `tags` 参数
`tags` 参数的值是由 `str` 组成的 `list` (一般只有一个 `str` ),`tags` 用于为*路径操作*添加标签:
```Python hl_lines="17 22 27"
-{!../../../docs_src/path_operation_configuration/tutorial002.py!}
+{!../../docs_src/path_operation_configuration/tutorial002.py!}
```
OpenAPI 概图会自动添加标签,供 API 文档接口使用:
@@ -43,7 +47,7 @@ OpenAPI 概图会自动添加标签,供 API 文档接口使用:
路径装饰器还支持 `summary` 和 `description` 这两个参数:
```Python hl_lines="20-21"
-{!../../../docs_src/path_operation_configuration/tutorial003.py!}
+{!../../docs_src/path_operation_configuration/tutorial003.py!}
```
## 文档字符串(`docstring`)
@@ -53,7 +57,7 @@ OpenAPI 概图会自动添加标签,供 API 文档接口使用:
文档字符串支持 Markdown,能正确解析和显示 Markdown 的内容,但要注意文档字符串的缩进。
```Python hl_lines="19-27"
-{!../../../docs_src/path_operation_configuration/tutorial004.py!}
+{!../../docs_src/path_operation_configuration/tutorial004.py!}
```
下图为 Markdown 文本在 API 文档中的显示效果:
@@ -65,18 +69,22 @@ OpenAPI 概图会自动添加标签,供 API 文档接口使用:
`response_description` 参数用于定义响应的描述说明:
```Python hl_lines="21"
-{!../../../docs_src/path_operation_configuration/tutorial005.py!}
+{!../../docs_src/path_operation_configuration/tutorial005.py!}
```
-!!! info "说明"
+/// info | "说明"
- 注意,`response_description` 只用于描述响应,`description` 一般则用于描述*路径操作*。
+注意,`response_description` 只用于描述响应,`description` 一般则用于描述*路径操作*。
-!!! check "检查"
+///
- OpenAPI 规定每个*路径操作*都要有响应描述。
+/// check | "检查"
- 如果没有定义响应描述,**FastAPI** 则自动生成内容为 "Successful response" 的响应描述。
+OpenAPI 规定每个*路径操作*都要有响应描述。
+
+如果没有定义响应描述,**FastAPI** 则自动生成内容为 "Successful response" 的响应描述。
+
+///
@@ -85,7 +93,7 @@ OpenAPI 概图会自动添加标签,供 API 文档接口使用:
`deprecated` 参数可以把*路径操作*标记为弃用,无需直接删除:
```Python hl_lines="16"
-{!../../../docs_src/path_operation_configuration/tutorial006.py!}
+{!../../docs_src/path_operation_configuration/tutorial006.py!}
```
API 文档会把该路径操作标记为弃用:
diff --git a/docs/zh/docs/tutorial/path-params-numeric-validations.md b/docs/zh/docs/tutorial/path-params-numeric-validations.md
index 9b41ad7cf..29197ac53 100644
--- a/docs/zh/docs/tutorial/path-params-numeric-validations.md
+++ b/docs/zh/docs/tutorial/path-params-numeric-validations.md
@@ -6,41 +6,57 @@
首先,从 `fastapi` 导入 `Path`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="1 3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="1 3"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="1 3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="1 3"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="3-4"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+```Python hl_lines="3-4"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
+```
- ```Python hl_lines="1"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+/// tip
- ```Python hl_lines="3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
- ```
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="1"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="3"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!}
+```
+
+////
## 声明元数据
@@ -48,48 +64,67 @@
例如,要声明路径参数 `item_id`的 `title` 元数据值,你可以输入:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
- ```
+```Python hl_lines="10"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="10"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
+```
- ```Python hl_lines="11"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+```Python hl_lines="11"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
+```
- ```Python hl_lines="8"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+/// tip
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
- ```
+尽可能选择使用 `Annotated` 的版本。
-!!! note
- 路径参数总是必需的,因为它必须是路径的一部分。
+///
- 所以,你应该在声明时使用 `...` 将其标记为必需参数。
+```Python hl_lines="8"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
+```
- 然而,即使你使用 `None` 声明路径参数或设置一个其他默认值也不会有任何影响,它依然会是必需参数。
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="10"
+{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!}
+```
+
+////
+
+/// note
+
+路径参数总是必需的,因为它必须是路径的一部分。
+
+所以,你应该在声明时使用 `...` 将其标记为必需参数。
+
+然而,即使你使用 `None` 声明路径参数或设置一个其他默认值也不会有任何影响,它依然会是必需参数。
+
+///
## 按需对参数排序
@@ -107,14 +142,19 @@
因此,你可以将函数声明为:
-=== "Python 3.8 non-Annotated"
+//// tab | Python 3.8 non-Annotated
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+/// tip
- ```Python hl_lines="7"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!}
- ```
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="7"
+{!> ../../docs_src/path_params_numeric_validations/tutorial002.py!}
+```
+
+////
## 按需对参数排序的技巧
@@ -125,7 +165,7 @@
Python 不会对该 `*` 做任何事情,但是它将知道之后的所有参数都应作为关键字参数(键值对),也被称为 kwargs,来调用。即使它们没有默认值。
```Python hl_lines="7"
-{!../../../docs_src/path_params_numeric_validations/tutorial003.py!}
+{!../../docs_src/path_params_numeric_validations/tutorial003.py!}
```
## 数值校验:大于等于
@@ -135,7 +175,7 @@ Python 不会对该 `*` 做任何事情,但是它将知道之后的所有参
像下面这样,添加 `ge=1` 后,`item_id` 将必须是一个大于(`g`reater than)或等于(`e`qual)`1` 的整数。
```Python hl_lines="8"
-{!../../../docs_src/path_params_numeric_validations/tutorial004.py!}
+{!../../docs_src/path_params_numeric_validations/tutorial004.py!}
```
## 数值校验:大于和小于等于
@@ -146,7 +186,7 @@ Python 不会对该 `*` 做任何事情,但是它将知道之后的所有参
* `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!}
```
## 数值校验:浮点数、大于和小于
@@ -160,7 +200,7 @@ Python 不会对该 `*` 做任何事情,但是它将知道之后的所有参
对于 lt 也是一样的。
```Python hl_lines="11"
-{!../../../docs_src/path_params_numeric_validations/tutorial006.py!}
+{!../../docs_src/path_params_numeric_validations/tutorial006.py!}
```
## 总结
@@ -174,18 +214,24 @@ Python 不会对该 `*` 做任何事情,但是它将知道之后的所有参
* `lt`:小于(`l`ess `t`han)
* `le`:小于等于(`l`ess than or `e`qual)
-!!! info
- `Query`、`Path` 以及你后面会看到的其他类继承自一个共同的 `Param` 类(不需要直接使用它)。
+/// info
- 而且它们都共享相同的所有你已看到并用于添加额外校验和元数据的参数。
+`Query`、`Path` 以及你后面会看到的其他类继承自一个共同的 `Param` 类(不需要直接使用它)。
-!!! note "技术细节"
- 当你从 `fastapi` 导入 `Query`、`Path` 和其他同类对象时,它们实际上是函数。
+而且它们都共享相同的所有你已看到并用于添加额外校验和元数据的参数。
- 当被调用时,它们返回同名类的实例。
+///
- 如此,你导入 `Query` 这个函数。当你调用它时,它将返回一个同样命名为 `Query` 的类的实例。
+/// note | "技术细节"
- 因为使用了这些函数(而不是直接使用类),所以你的编辑器不会标记有关其类型的错误。
+当你从 `fastapi` 导入 `Query`、`Path` 和其他同类对象时,它们实际上是函数。
- 这样,你可以使用常规的编辑器和编码工具,而不必添加自定义配置来忽略这些错误。
+当被调用时,它们返回同名类的实例。
+
+如此,你导入 `Query` 这个函数。当你调用它时,它将返回一个同样命名为 `Query` 的类的实例。
+
+因为使用了这些函数(而不是直接使用类),所以你的编辑器不会标记有关其类型的错误。
+
+这样,你可以使用常规的编辑器和编码工具,而不必添加自定义配置来忽略这些错误。
+
+///
diff --git a/docs/zh/docs/tutorial/path-params.md b/docs/zh/docs/tutorial/path-params.md
index 12a08b4a3..a29ee0e2b 100644
--- a/docs/zh/docs/tutorial/path-params.md
+++ b/docs/zh/docs/tutorial/path-params.md
@@ -3,7 +3,7 @@
FastAPI 支持使用 Python 字符串格式化语法声明**路径参数**(**变量**):
```Python hl_lines="6-7"
-{!../../../docs_src/path_params/tutorial001.py!}
+{!../../docs_src/path_params/tutorial001.py!}
```
这段代码把路径参数 `item_id` 的值传递给路径函数的参数 `item_id`。
@@ -19,14 +19,16 @@ FastAPI 支持使用 Python 字符串格式化语法声明**路径参数**(**
使用 Python 标准类型注解,声明路径操作函数中路径参数的类型。
```Python hl_lines="7"
-{!../../../docs_src/path_params/tutorial002.py!}
+{!../../docs_src/path_params/tutorial002.py!}
```
本例把 `item_id` 的类型声明为 `int`。
-!!! check "检查"
+/// check | "检查"
- 类型声明将为函数提供错误检查、代码补全等编辑器支持。
+类型声明将为函数提供错误检查、代码补全等编辑器支持。
+
+///
## 数据转换
@@ -36,11 +38,13 @@ FastAPI 支持使用 Python 字符串格式化语法声明**路径参数**(**
{"item_id":3}
```
-!!! check "检查"
+/// check | "检查"
- 注意,函数接收并返回的值是 `3`( `int`),不是 `"3"`(`str`)。
+注意,函数接收并返回的值是 `3`( `int`),不是 `"3"`(`str`)。
- **FastAPI** 通过类型声明自动**解析**请求中的数据。
+**FastAPI** 通过类型声明自动**解析**请求中的数据。
+
+///
## 数据校验
@@ -65,13 +69,15 @@ FastAPI 支持使用 Python 字符串格式化语法声明**路径参数**(**
值的类型不是 `int ` 而是浮点数(`float`)时也会显示同样的错误,比如: http://127.0.0.1:8000/items/4.2。
-!!! check "检查"
+/// check | "检查"
- **FastAPI** 使用 Python 类型声明实现了数据校验。
+**FastAPI** 使用 Python 类型声明实现了数据校验。
- 注意,上面的错误清晰地指出了未通过校验的具体原因。
+注意,上面的错误清晰地指出了未通过校验的具体原因。
- 这在开发调试与 API 交互的代码时非常有用。
+这在开发调试与 API 交互的代码时非常有用。
+
+///
## 查看文档
@@ -79,11 +85,13 @@ FastAPI 支持使用 Python 字符串格式化语法声明**路径参数**(**
-!!! check "检查"
+/// check | "检查"
- 还是使用 Python 类型声明,**FastAPI** 提供了(集成 Swagger UI 的)API 文档。
+还是使用 Python 类型声明,**FastAPI** 提供了(集成 Swagger UI 的)API 文档。
- 注意,路径参数的类型是整数。
+注意,路径参数的类型是整数。
+
+///
## 基于标准的好处,备选文档
@@ -114,7 +122,7 @@ FastAPI 充分地利用了 枚举(即 enums)。
+Python 3.4 及之后版本支持枚举(即 enums)。
-!!! tip "提示"
+///
- **AlexNet**、**ResNet**、**LeNet** 是机器学习模型。
+/// tip | "提示"
+
+**AlexNet**、**ResNet**、**LeNet** 是机器学习模型。
+
+///
### 声明*路径参数*
使用 Enum 类(`ModelName`)创建使用类型注解的*路径参数*:
```Python hl_lines="16"
-{!../../../docs_src/path_params/tutorial005.py!}
+{!../../docs_src/path_params/tutorial005.py!}
```
### 查看文档
@@ -166,7 +178,7 @@ FastAPI 充分地利用了 ../../../docs_src/query_params_str_validations/tutorial001_py310.py!}
- ```
+```Python hl_lines="7"
+{!> ../../docs_src/query_params_str_validations/tutorial001_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../docs_src/query_params_str_validations/tutorial001.py!}
+```
+
+////
查询参数 `q` 的类型为 `str`,默认值为 `None`,因此它是可选的。
@@ -27,7 +31,7 @@
为此,首先从 `fastapi` 导入 `Query`:
```Python hl_lines="1"
-{!../../../docs_src/query_params_str_validations/tutorial002.py!}
+{!../../docs_src/query_params_str_validations/tutorial002.py!}
```
## 使用 `Query` 作为默认值
@@ -35,7 +39,7 @@
现在,将 `Query` 用作查询参数的默认值,并将它的 `max_length` 参数设置为 50:
```Python hl_lines="9"
-{!../../../docs_src/query_params_str_validations/tutorial002.py!}
+{!../../docs_src/query_params_str_validations/tutorial002.py!}
```
由于我们必须用 `Query(default=None)` 替换默认值 `None`,`Query` 的第一个参数同样也是用于定义默认值。
@@ -67,7 +71,7 @@ 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!}
```
## 添加正则表达式
@@ -75,7 +79,7 @@ q: Union[str, None] = Query(default=None, max_length=50)
你可以定义一个参数值必须匹配的正则表达式:
```Python hl_lines="11"
-{!../../../docs_src/query_params_str_validations/tutorial004.py!}
+{!../../docs_src/query_params_str_validations/tutorial004.py!}
```
这个指定的正则表达式通过以下规则检查接收到的参数值:
@@ -95,11 +99,14 @@ 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!}
```
-!!! note
- 具有默认值还会使该参数成为可选参数。
+/// note
+
+具有默认值还会使该参数成为可选参数。
+
+///
## 声明为必需参数
@@ -124,7 +131,7 @@ q: Union[str, None] = Query(default=None, min_length=3)
因此,当你在使用 `Query` 且需要声明一个值是必需的时,只需不声明默认参数:
```Python hl_lines="7"
-{!../../../docs_src/query_params_str_validations/tutorial006.py!}
+{!../../docs_src/query_params_str_validations/tutorial006.py!}
```
### 使用省略号(`...`)声明必需参数
@@ -132,12 +139,15 @@ q: Union[str, None] = Query(default=None, min_length=3)
有另一种方法可以显式的声明一个值是必需的,即将默认参数的默认值设为 `...` :
```Python hl_lines="7"
-{!../../../docs_src/query_params_str_validations/tutorial006b.py!}
+{!../../docs_src/query_params_str_validations/tutorial006b.py!}
```
-!!! info
- 如果你之前没见过 `...` 这种用法:它是一个特殊的单独值,它是 Python 的一部分并且被称为「省略号」。
- Pydantic 和 FastAPI 使用它来显式的声明需要一个值。
+/// info
+
+如果你之前没见过 `...` 这种用法:它是一个特殊的单独值,它是 Python 的一部分并且被称为「省略号」。
+Pydantic 和 FastAPI 使用它来显式的声明需要一个值。
+
+///
这将使 **FastAPI** 知道此查询参数是必需的。
@@ -148,23 +158,28 @@ q: Union[str, None] = Query(default=None, min_length=3)
为此,你可以声明`None`是一个有效的类型,并仍然使用`default=...`:
```Python hl_lines="9"
-{!../../../docs_src/query_params_str_validations/tutorial006c.py!}
+{!../../docs_src/query_params_str_validations/tutorial006c.py!}
```
-!!! tip
- Pydantic 是 FastAPI 中所有数据验证和序列化的核心,当你在没有设默认值的情况下使用 `Optional` 或 `Union[Something, None]` 时,它具有特殊行为,你可以在 Pydantic 文档中阅读有关必需可选字段的更多信息。
+/// tip
+
+Pydantic 是 FastAPI 中所有数据验证和序列化的核心,当你在没有设默认值的情况下使用 `Optional` 或 `Union[Something, None]` 时,它具有特殊行为,你可以在 Pydantic 文档中阅读有关必需可选字段的更多信息。
+
+///
### 使用Pydantic中的`Required`代替省略号(`...`)
如果你觉得使用 `...` 不舒服,你也可以从 Pydantic 导入并使用 `Required`:
```Python hl_lines="2 8"
-{!../../../docs_src/query_params_str_validations/tutorial006d.py!}
+{!../../docs_src/query_params_str_validations/tutorial006d.py!}
```
-!!! tip
- 请记住,在大多数情况下,当你需要某些东西时,可以简单地省略 `default` 参数,因此你通常不必使用 `...` 或 `Required`
+/// tip
+请记住,在大多数情况下,当你需要某些东西时,可以简单地省略 `default` 参数,因此你通常不必使用 `...` 或 `Required`
+
+///
## 查询参数列表 / 多个值
@@ -173,7 +188,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!}
```
然后,输入如下网址:
@@ -195,8 +210,11 @@ http://localhost:8000/items/?q=foo&q=bar
}
```
-!!! tip
- 要声明类型为 `list` 的查询参数,如上例所示,你需要显式地使用 `Query`,否则该参数将被解释为请求体。
+/// tip
+
+要声明类型为 `list` 的查询参数,如上例所示,你需要显式地使用 `Query`,否则该参数将被解释为请求体。
+
+///
交互式 API 文档将会相应地进行更新,以允许使用多个值:
@@ -207,7 +225,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!}
```
如果你访问:
@@ -232,13 +250,16 @@ http://localhost:8000/items/
你也可以直接使用 `list` 代替 `List [str]`:
```Python hl_lines="7"
-{!../../../docs_src/query_params_str_validations/tutorial013.py!}
+{!../../docs_src/query_params_str_validations/tutorial013.py!}
```
-!!! note
- 请记住,在这种情况下 FastAPI 将不会检查列表的内容。
+/// note
- 例如,`List[int]` 将检查(并记录到文档)列表的内容必须是整数。但是单独的 `list` 不会。
+请记住,在这种情况下 FastAPI 将不会检查列表的内容。
+
+例如,`List[int]` 将检查(并记录到文档)列表的内容必须是整数。但是单独的 `list` 不会。
+
+///
## 声明更多元数据
@@ -246,21 +267,24 @@ http://localhost:8000/items/
这些信息将包含在生成的 OpenAPI 模式中,并由文档用户界面和外部工具所使用。
-!!! note
- 请记住,不同的工具对 OpenAPI 的支持程度可能不同。
+/// note
- 其中一些可能不会展示所有已声明的额外信息,尽管在大多数情况下,缺少的这部分功能已经计划进行开发。
+请记住,不同的工具对 OpenAPI 的支持程度可能不同。
+
+其中一些可能不会展示所有已声明的额外信息,尽管在大多数情况下,缺少的这部分功能已经计划进行开发。
+
+///
你可以添加 `title`:
```Python hl_lines="10"
-{!../../../docs_src/query_params_str_validations/tutorial007.py!}
+{!../../docs_src/query_params_str_validations/tutorial007.py!}
```
以及 `description`:
```Python hl_lines="13"
-{!../../../docs_src/query_params_str_validations/tutorial008.py!}
+{!../../docs_src/query_params_str_validations/tutorial008.py!}
```
## 别名参数
@@ -282,7 +306,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems
这时你可以用 `alias` 参数声明一个别名,该别名将用于在 URL 中查找查询参数值:
```Python hl_lines="9"
-{!../../../docs_src/query_params_str_validations/tutorial009.py!}
+{!../../docs_src/query_params_str_validations/tutorial009.py!}
```
## 弃用参数
@@ -294,7 +318,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!}
```
文档将会像下面这样展示它:
diff --git a/docs/zh/docs/tutorial/query-params.md b/docs/zh/docs/tutorial/query-params.md
index 77138de51..f17d43d3a 100644
--- a/docs/zh/docs/tutorial/query-params.md
+++ b/docs/zh/docs/tutorial/query-params.md
@@ -3,7 +3,7 @@
声明的参数不是路径参数时,路径操作函数会把该参数自动解释为**查询**参数。
```Python hl_lines="9"
-{!../../../docs_src/query_params/tutorial001.py!}
+{!../../docs_src/query_params/tutorial001.py!}
```
查询字符串是键值对的集合,这些键值对位于 URL 的 `?` 之后,以 `&` 分隔。
@@ -63,39 +63,59 @@ http://127.0.0.1:8000/items/?skip=20
同理,把默认值设为 `None` 即可声明**可选的**查询参数:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params/tutorial002_py310.py!}
- ```
+```Python hl_lines="7"
+{!> ../../docs_src/query_params/tutorial002_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+```Python hl_lines="9"
+{!> ../../docs_src/query_params/tutorial002.py!}
+```
+
+////
本例中,查询参数 `q` 是可选的,默认值为 `None`。
-!!! check "检查"
+/// check | "检查"
- 注意,**FastAPI** 可以识别出 `item_id` 是路径参数,`q` 不是路径参数,而是查询参数。
+注意,**FastAPI** 可以识别出 `item_id` 是路径参数,`q` 不是路径参数,而是查询参数。
-!!! note "笔记"
+///
- 因为默认值为 `= None`,FastAPI 把 `q` 识别为可选参数。
+/// note | "笔记"
- FastAPI 不使用 `Optional[str]` 中的 `Optional`(只使用 `str`),但 `Optional[str]` 可以帮助编辑器发现代码中的错误。
+因为默认值为 `= None`,FastAPI 把 `q` 识别为可选参数。
+
+FastAPI 不使用 `Optional[str]` 中的 `Optional`(只使用 `str`),但 `Optional[str]` 可以帮助编辑器发现代码中的错误。
+
+///
## 查询参数类型转换
参数还可以声明为 `bool` 类型,FastAPI 会自动转换参数类型:
-```Python hl_lines="9"
-{!../../../docs_src/query_params/tutorial003.py!}
+
+//// 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!}
+```
+
+////
+
本例中,访问:
```
@@ -137,10 +157,22 @@ http://127.0.0.1:8000/items/foo?short=yes
FastAPI 通过参数名进行检测:
-```Python hl_lines="8 10"
-{!../../../docs_src/query_params/tutorial004.py!}
+//// tab | Python 3.10+
+
+```Python hl_lines="6 8"
+{!> ../../docs_src/query_params/tutorial004_py310.py!}
```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="8 10"
+{!> ../../docs_src/query_params/tutorial004.py!}
+```
+
+////
+
## 必选查询参数
为不是路径参数的参数声明默认值(至此,仅有查询参数),该参数就**不是必选**的了。
@@ -150,7 +182,7 @@ FastAPI 通过参数名进行检测:
如果要把查询参数设置为**必选**,就不要声明默认值:
```Python hl_lines="6-7"
-{!../../../docs_src/query_params/tutorial005.py!}
+{!../../docs_src/query_params/tutorial005.py!}
```
这里的查询参数 `needy` 是类型为 `str` 的必选查询参数。
@@ -195,15 +227,30 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
当然,把一些参数定义为必选,为另一些参数设置默认值,再把其它参数定义为可选,这些操作都是可以的:
-```Python hl_lines="10"
-{!../../../docs_src/query_params/tutorial006.py!}
+//// 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!}
+```
+
+////
+
本例中有 3 个查询参数:
* `needy`,必选的 `str` 类型参数
* `skip`,默认值为 `0` 的 `int` 类型参数
* `limit`,可选的 `int` 类型参数
-!!! tip "提示"
- 还可以像在[路径参数](path-params.md#_8){.internal-link target=_blank} 中那样使用 `Enum`。
+/// tip | "提示"
+
+还可以像在[路径参数](path-params.md#_8){.internal-link target=_blank} 中那样使用 `Enum`。
+
+///
diff --git a/docs/zh/docs/tutorial/request-files.md b/docs/zh/docs/tutorial/request-files.md
index 1cd3518cf..026771495 100644
--- a/docs/zh/docs/tutorial/request-files.md
+++ b/docs/zh/docs/tutorial/request-files.md
@@ -2,20 +2,22 @@
`File` 用于定义客户端的上传文件。
-!!! info "说明"
+/// info | "说明"
- 因为上传文件以「表单数据」形式发送。
+因为上传文件以「表单数据」形式发送。
- 所以接收上传文件,要预先安装 `python-multipart`。
+所以接收上传文件,要预先安装 `python-multipart`。
- 例如: `pip install python-multipart`。
+例如: `pip install python-multipart`。
+
+///
## 导入 `File`
从 `fastapi` 导入 `File` 和 `UploadFile`:
```Python hl_lines="1"
-{!../../../docs_src/request_files/tutorial001.py!}
+{!../../docs_src/request_files/tutorial001.py!}
```
## 定义 `File` 参数
@@ -23,18 +25,22 @@
创建文件(`File`)参数的方式与 `Body` 和 `Form` 一样:
```Python hl_lines="7"
-{!../../../docs_src/request_files/tutorial001.py!}
+{!../../docs_src/request_files/tutorial001.py!}
```
-!!! info "说明"
+/// info | "说明"
- `File` 是直接继承自 `Form` 的类。
+`File` 是直接继承自 `Form` 的类。
- 注意,从 `fastapi` 导入的 `Query`、`Path`、`File` 等项,实际上是返回特定类的函数。
+注意,从 `fastapi` 导入的 `Query`、`Path`、`File` 等项,实际上是返回特定类的函数。
-!!! tip "提示"
+///
- 声明文件体必须使用 `File`,否则,FastAPI 会把该参数当作查询参数或请求体(JSON)参数。
+/// tip | "提示"
+
+声明文件体必须使用 `File`,否则,FastAPI 会把该参数当作查询参数或请求体(JSON)参数。
+
+///
文件作为「表单数据」上传。
@@ -49,7 +55,7 @@
定义文件参数时使用 `UploadFile`:
```Python hl_lines="12"
-{!../../../docs_src/request_files/tutorial001.py!}
+{!../../docs_src/request_files/tutorial001.py!}
```
`UploadFile` 与 `bytes` 相比有更多优势:
@@ -92,13 +98,17 @@ contents = await myfile.read()
contents = myfile.file.read()
```
-!!! note "`async` 技术细节"
+/// note | "`async` 技术细节"
- 使用 `async` 方法时,**FastAPI** 在线程池中执行文件方法,并 `await` 操作完成。
+使用 `async` 方法时,**FastAPI** 在线程池中执行文件方法,并 `await` 操作完成。
-!!! note "Starlette 技术细节"
+///
- **FastAPI** 的 `UploadFile` 直接继承自 **Starlette** 的 `UploadFile`,但添加了一些必要功能,使之与 **Pydantic** 及 FastAPI 的其它部件兼容。
+/// note | "Starlette 技术细节"
+
+**FastAPI** 的 `UploadFile` 直接继承自 **Starlette** 的 `UploadFile`,但添加了一些必要功能,使之与 **Pydantic** 及 FastAPI 的其它部件兼容。
+
+///
## 什么是 「表单数据」
@@ -106,42 +116,50 @@ contents = myfile.file.read()
**FastAPI** 要确保从正确的位置读取数据,而不是读取 JSON。
-!!! note "技术细节"
+/// note | "技术细节"
- 不包含文件时,表单数据一般用 `application/x-www-form-urlencoded`「媒体类型」编码。
+不包含文件时,表单数据一般用 `application/x-www-form-urlencoded`「媒体类型」编码。
- 但表单包含文件时,编码为 `multipart/form-data`。使用了 `File`,**FastAPI** 就知道要从请求体的正确位置获取文件。
+但表单包含文件时,编码为 `multipart/form-data`。使用了 `File`,**FastAPI** 就知道要从请求体的正确位置获取文件。
- 编码和表单字段详见 MDN Web 文档的 POST 小节。
+编码和表单字段详见 MDN Web 文档的 POST 小节。
-!!! warning "警告"
+///
- 可在一个*路径操作*中声明多个 `File` 和 `Form` 参数,但不能同时声明要接收 JSON 的 `Body` 字段。因为此时请求体的编码是 `multipart/form-data`,不是 `application/json`。
+/// warning | "警告"
- 这不是 **FastAPI** 的问题,而是 HTTP 协议的规定。
+可在一个*路径操作*中声明多个 `File` 和 `Form` 参数,但不能同时声明要接收 JSON 的 `Body` 字段。因为此时请求体的编码是 `multipart/form-data`,不是 `application/json`。
+
+这不是 **FastAPI** 的问题,而是 HTTP 协议的规定。
+
+///
## 可选文件上传
您可以通过使用标准类型注解并将 None 作为默认值的方式将一个文件参数设为可选:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="7 14"
- {!> ../../../docs_src/request_files/tutorial001_02_py310.py!}
- ```
+```Python hl_lines="7 14"
+{!> ../../docs_src/request_files/tutorial001_02_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9 17"
- {!> ../../../docs_src/request_files/tutorial001_02.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="9 17"
+{!> ../../docs_src/request_files/tutorial001_02.py!}
+```
+
+////
## 带有额外元数据的 `UploadFile`
您也可以将 `File()` 与 `UploadFile` 一起使用,例如,设置额外的元数据:
```Python hl_lines="13"
-{!../../../docs_src/request_files/tutorial001_03.py!}
+{!../../docs_src/request_files/tutorial001_03.py!}
```
## 多文件上传
@@ -152,42 +170,52 @@ FastAPI 支持同时上传多个文件。
上传多个文件时,要声明含 `bytes` 或 `UploadFile` 的列表(`List`):
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="8 13"
- {!> ../../../docs_src/request_files/tutorial002_py39.py!}
- ```
+```Python hl_lines="8 13"
+{!> ../../docs_src/request_files/tutorial002_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="10 15"
- {!> ../../../docs_src/request_files/tutorial002.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="10 15"
+{!> ../../docs_src/request_files/tutorial002.py!}
+```
+
+////
接收的也是含 `bytes` 或 `UploadFile` 的列表(`list`)。
-!!! note "技术细节"
+/// note | "技术细节"
- 也可以使用 `from starlette.responses import HTMLResponse`。
+也可以使用 `from starlette.responses import HTMLResponse`。
- `fastapi.responses` 其实与 `starlette.responses` 相同,只是为了方便开发者调用。实际上,大多数 **FastAPI** 的响应都直接从 Starlette 调用。
+`fastapi.responses` 其实与 `starlette.responses` 相同,只是为了方便开发者调用。实际上,大多数 **FastAPI** 的响应都直接从 Starlette 调用。
+
+///
### 带有额外元数据的多文件上传
和之前的方式一样, 您可以为 `File()` 设置额外参数, 即使是 `UploadFile`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="16"
- {!> ../../../docs_src/request_files/tutorial003_py39.py!}
- ```
+```Python hl_lines="16"
+{!> ../../docs_src/request_files/tutorial003_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="18"
- {!> ../../../docs_src/request_files/tutorial003.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="18"
+{!> ../../docs_src/request_files/tutorial003.py!}
+```
+
+////
## 小结
diff --git a/docs/zh/docs/tutorial/request-forms-and-files.md b/docs/zh/docs/tutorial/request-forms-and-files.md
index f58593669..ae0fd82ca 100644
--- a/docs/zh/docs/tutorial/request-forms-and-files.md
+++ b/docs/zh/docs/tutorial/request-forms-and-files.md
@@ -2,16 +2,18 @@
FastAPI 支持同时使用 `File` 和 `Form` 定义文件和表单字段。
-!!! info "说明"
+/// info | "说明"
- 接收上传文件或表单数据,要预先安装 `python-multipart`。
+接收上传文件或表单数据,要预先安装 `python-multipart`。
- 例如,`pip install python-multipart`。
+例如,`pip install python-multipart`。
+
+///
## 导入 `File` 与 `Form`
```Python hl_lines="1"
-{!../../../docs_src/request_forms_and_files/tutorial001.py!}
+{!../../docs_src/request_forms_and_files/tutorial001.py!}
```
## 定义 `File` 与 `Form` 参数
@@ -19,18 +21,20 @@ FastAPI 支持同时使用 `File` 和 `Form` 定义文件和表单字段。
创建文件和表单参数的方式与 `Body` 和 `Query` 一样:
```Python hl_lines="8"
-{!../../../docs_src/request_forms_and_files/tutorial001.py!}
+{!../../docs_src/request_forms_and_files/tutorial001.py!}
```
文件和表单字段作为表单数据上传与接收。
声明文件可以使用 `bytes` 或 `UploadFile` 。
-!!! warning "警告"
+/// warning | "警告"
- 可在一个*路径操作*中声明多个 `File` 与 `Form` 参数,但不能同时声明要接收 JSON 的 `Body` 字段。因为此时请求体的编码为 `multipart/form-data`,不是 `application/json`。
+可在一个*路径操作*中声明多个 `File` 与 `Form` 参数,但不能同时声明要接收 JSON 的 `Body` 字段。因为此时请求体的编码为 `multipart/form-data`,不是 `application/json`。
- 这不是 **FastAPI** 的问题,而是 HTTP 协议的规定。
+这不是 **FastAPI** 的问题,而是 HTTP 协议的规定。
+
+///
## 小结
diff --git a/docs/zh/docs/tutorial/request-forms.md b/docs/zh/docs/tutorial/request-forms.md
index e4fcd88ff..94c8839b3 100644
--- a/docs/zh/docs/tutorial/request-forms.md
+++ b/docs/zh/docs/tutorial/request-forms.md
@@ -2,18 +2,20 @@
接收的不是 JSON,而是表单字段时,要使用 `Form`。
-!!! info "说明"
+/// info | "说明"
- 要使用表单,需预先安装 `python-multipart`。
+要使用表单,需预先安装 `python-multipart`。
- 例如,`pip install python-multipart`。
+例如,`pip install python-multipart`。
+
+///
## 导入 `Form`
从 `fastapi` 导入 `Form`:
```Python hl_lines="1"
-{!../../../docs_src/request_forms/tutorial001.py!}
+{!../../docs_src/request_forms/tutorial001.py!}
```
## 定义 `Form` 参数
@@ -21,7 +23,7 @@
创建表单(`Form`)参数的方式与 `Body` 和 `Query` 一样:
```Python hl_lines="7"
-{!../../../docs_src/request_forms/tutorial001.py!}
+{!../../docs_src/request_forms/tutorial001.py!}
```
例如,OAuth2 规范的 "密码流" 模式规定要通过表单字段发送 `username` 和 `password`。
@@ -30,13 +32,17 @@
使用 `Form` 可以声明与 `Body` (及 `Query`、`Path`、`Cookie`)相同的元数据和验证。
-!!! info "说明"
+/// info | "说明"
- `Form` 是直接继承自 `Body` 的类。
+`Form` 是直接继承自 `Body` 的类。
-!!! tip "提示"
+///
- 声明表单体要显式使用 `Form` ,否则,FastAPI 会把该参数当作查询参数或请求体(JSON)参数。
+/// tip | "提示"
+
+声明表单体要显式使用 `Form` ,否则,FastAPI 会把该参数当作查询参数或请求体(JSON)参数。
+
+///
## 关于 "表单字段"
@@ -44,19 +50,23 @@
**FastAPI** 要确保从正确的位置读取数据,而不是读取 JSON。
-!!! note "技术细节"
+/// note | "技术细节"
- 表单数据的「媒体类型」编码一般为 `application/x-www-form-urlencoded`。
+表单数据的「媒体类型」编码一般为 `application/x-www-form-urlencoded`。
- 但包含文件的表单编码为 `multipart/form-data`。文件处理详见下节。
+但包含文件的表单编码为 `multipart/form-data`。文件处理详见下节。
- 编码和表单字段详见 MDN Web 文档的 POST小节。
+编码和表单字段详见 MDN Web 文档的 POST小节。
-!!! warning "警告"
+///
- 可在一个*路径操作*中声明多个 `Form` 参数,但不能同时声明要接收 JSON 的 `Body` 字段。因为此时请求体的编码是 `application/x-www-form-urlencoded`,不是 `application/json`。
+/// warning | "警告"
- 这不是 **FastAPI** 的问题,而是 HTTP 协议的规定。
+可在一个*路径操作*中声明多个 `Form` 参数,但不能同时声明要接收 JSON 的 `Body` 字段。因为此时请求体的编码是 `application/x-www-form-urlencoded`,不是 `application/json`。
+
+这不是 **FastAPI** 的问题,而是 HTTP 协议的规定。
+
+///
## 小结
diff --git a/docs/zh/docs/tutorial/response-model.md b/docs/zh/docs/tutorial/response-model.md
index 0f1b3b4b9..40fb40720 100644
--- a/docs/zh/docs/tutorial/response-model.md
+++ b/docs/zh/docs/tutorial/response-model.md
@@ -8,26 +8,35 @@
* `@app.delete()`
* 等等。
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001_py310.py!}
- ```
+```Python hl_lines="17 22 24-27"
+{!> ../../docs_src/response_model/tutorial001_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="17 22 24-27"
+{!> ../../docs_src/response_model/tutorial001_py39.py!}
+```
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001.py!}
- ```
+////
-!!! note
- 注意,`response_model`是「装饰器」方法(`get`,`post` 等)的一个参数。不像之前的所有参数和请求体,它不属于*路径操作函数*。
+//// tab | Python 3.8+
+
+```Python hl_lines="17 22 24-27"
+{!> ../../docs_src/response_model/tutorial001.py!}
+```
+
+////
+
+/// note
+
+注意,`response_model`是「装饰器」方法(`get`,`post` 等)的一个参数。不像之前的所有参数和请求体,它不属于*路径操作函数*。
+
+///
它接收的类型与你将为 Pydantic 模型属性所声明的类型相同,因此它可以是一个 Pydantic 模型,但也可以是一个由 Pydantic 模型组成的 `list`,例如 `List[Item]`。
@@ -42,21 +51,24 @@ FastAPI 将使用此 `response_model` 来:
* 会将输出数据限制在该模型定义内。下面我们会看到这一点有多重要。
-!!! note "技术细节"
- 响应模型在参数中被声明,而不是作为函数返回类型的注解,这是因为路径函数可能不会真正返回该响应模型,而是返回一个 `dict`、数据库对象或其他模型,然后再使用 `response_model` 来执行字段约束和序列化。
+/// note | "技术细节"
+
+响应模型在参数中被声明,而不是作为函数返回类型的注解,这是因为路径函数可能不会真正返回该响应模型,而是返回一个 `dict`、数据库对象或其他模型,然后再使用 `response_model` 来执行字段约束和序列化。
+
+///
## 返回与输入相同的数据
现在我们声明一个 `UserIn` 模型,它将包含一个明文密码属性。
```Python hl_lines="9 11"
-{!../../../docs_src/response_model/tutorial002.py!}
+{!../../docs_src/response_model/tutorial002.py!}
```
我们正在使用此模型声明输入数据,并使用同一模型声明输出数据:
```Python hl_lines="17-18"
-{!../../../docs_src/response_model/tutorial002.py!}
+{!../../docs_src/response_model/tutorial002.py!}
```
现在,每当浏览器使用一个密码创建用户时,API 都会在响应中返回相同的密码。
@@ -65,52 +77,67 @@ FastAPI 将使用此 `response_model` 来:
但是,如果我们在其他的*路径操作*中使用相同的模型,则可能会将用户的密码发送给每个客户端。
-!!! danger
- 永远不要存储用户的明文密码,也不要在响应中发送密码。
+/// danger
+
+永远不要存储用户的明文密码,也不要在响应中发送密码。
+
+///
## 添加输出模型
相反,我们可以创建一个有明文密码的输入模型和一个没有明文密码的输出模型:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="9 11 16"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
+```Python hl_lines="9 11 16"
+{!> ../../docs_src/response_model/tutorial003_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9 11 16"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="9 11 16"
+{!> ../../docs_src/response_model/tutorial003.py!}
+```
+
+////
这样,即便我们的*路径操作函数*将会返回包含密码的相同输入用户:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
+```Python hl_lines="24"
+{!> ../../docs_src/response_model/tutorial003_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="24"
+{!> ../../docs_src/response_model/tutorial003.py!}
+```
+
+////
...我们已经将 `response_model` 声明为了不包含密码的 `UserOut` 模型:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
+```Python hl_lines="22"
+{!> ../../docs_src/response_model/tutorial003_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="22"
+{!> ../../docs_src/response_model/tutorial003.py!}
+```
+
+////
因此,**FastAPI** 将会负责过滤掉未在输出模型中声明的所有数据(使用 Pydantic)。
@@ -129,7 +156,7 @@ FastAPI 将使用此 `response_model` 来:
你的响应模型可以具有默认值,例如:
```Python hl_lines="11 13-14"
-{!../../../docs_src/response_model/tutorial004.py!}
+{!../../docs_src/response_model/tutorial004.py!}
```
* `description: Union[str, None] = None` 具有默认值 `None`。
@@ -145,7 +172,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!}
```
然后响应中将不会包含那些默认值,而是仅有实际设置的值。
@@ -159,16 +186,22 @@ FastAPI 将使用此 `response_model` 来:
}
```
-!!! info
- FastAPI 通过 Pydantic 模型的 `.dict()` 配合 该方法的 `exclude_unset` 参数 来实现此功能。
+/// info
-!!! info
- 你还可以使用:
+FastAPI 通过 Pydantic 模型的 `.dict()` 配合 该方法的 `exclude_unset` 参数 来实现此功能。
- * `response_model_exclude_defaults=True`
- * `response_model_exclude_none=True`
+///
- 参考 Pydantic 文档 中对 `exclude_defaults` 和 `exclude_none` 的描述。
+/// info
+
+你还可以使用:
+
+* `response_model_exclude_defaults=True`
+* `response_model_exclude_none=True`
+
+参考 Pydantic 文档 中对 `exclude_defaults` 和 `exclude_none` 的描述。
+
+///
#### 默认值字段有实际值的数据
@@ -203,10 +236,13 @@ FastAPI 将使用此 `response_model` 来:
因此,它们将包含在 JSON 响应中。
-!!! tip
- 请注意默认值可以是任何值,而不仅是`None`。
+/// tip
- 它们可以是一个列表(`[]`),一个值为 `10.5`的 `float`,等等。
+请注意默认值可以是任何值,而不仅是`None`。
+
+它们可以是一个列表(`[]`),一个值为 `10.5`的 `float`,等等。
+
+///
### `response_model_include` 和 `response_model_exclude`
@@ -216,28 +252,34 @@ FastAPI 将使用此 `response_model` 来:
如果你只有一个 Pydantic 模型,并且想要从输出中移除一些数据,则可以使用这种快捷方法。
-!!! tip
- 但是依然建议你使用上面提到的主意,使用多个类而不是这些参数。
+/// tip
- 这是因为即使使用 `response_model_include` 或 `response_model_exclude` 来省略某些属性,在应用程序的 OpenAPI 定义(和文档)中生成的 JSON Schema 仍将是完整的模型。
+但是依然建议你使用上面提到的主意,使用多个类而不是这些参数。
- 这也适用于作用类似的 `response_model_by_alias`。
+这是因为即使使用 `response_model_include` 或 `response_model_exclude` 来省略某些属性,在应用程序的 OpenAPI 定义(和文档)中生成的 JSON Schema 仍将是完整的模型。
+
+这也适用于作用类似的 `response_model_by_alias`。
+
+///
```Python hl_lines="31 37"
-{!../../../docs_src/response_model/tutorial005.py!}
+{!../../docs_src/response_model/tutorial005.py!}
```
-!!! tip
- `{"name", "description"}` 语法创建一个具有这两个值的 `set`。
+/// tip
- 等同于 `set(["name", "description"])`。
+`{"name", "description"}` 语法创建一个具有这两个值的 `set`。
+
+等同于 `set(["name", "description"])`。
+
+///
#### 使用 `list` 而不是 `set`
如果你忘记使用 `set` 而是使用 `list` 或 `tuple`,FastAPI 仍会将其转换为 `set` 并且正常工作:
```Python hl_lines="31 37"
-{!../../../docs_src/response_model/tutorial006.py!}
+{!../../docs_src/response_model/tutorial006.py!}
```
## 总结
diff --git a/docs/zh/docs/tutorial/response-status-code.md b/docs/zh/docs/tutorial/response-status-code.md
index cc23231b4..55bf502ae 100644
--- a/docs/zh/docs/tutorial/response-status-code.md
+++ b/docs/zh/docs/tutorial/response-status-code.md
@@ -9,18 +9,22 @@
* 等……
```Python hl_lines="6"
-{!../../../docs_src/response_status_code/tutorial001.py!}
+{!../../docs_src/response_status_code/tutorial001.py!}
```
-!!! note "笔记"
+/// note | "笔记"
- 注意,`status_code` 是(`get`、`post` 等)**装饰器**方法中的参数。与之前的参数和请求体不同,不是*路径操作函数*的参数。
+注意,`status_code` 是(`get`、`post` 等)**装饰器**方法中的参数。与之前的参数和请求体不同,不是*路径操作函数*的参数。
+
+///
`status_code` 参数接收表示 HTTP 状态码的数字。
-!!! info "说明"
+/// info | "说明"
- `status_code` 还能接收 `IntEnum` 类型,比如 Python 的 `http.HTTPStatus`。
+`status_code` 还能接收 `IntEnum` 类型,比如 Python 的 `http.HTTPStatus`。
+
+///
它可以:
@@ -29,17 +33,21 @@
-!!! note "笔记"
+/// note | "笔记"
- 某些响应状态码表示响应没有响应体(参阅下一章)。
+某些响应状态码表示响应没有响应体(参阅下一章)。
- FastAPI 可以进行识别,并生成表明无响应体的 OpenAPI 文档。
+FastAPI 可以进行识别,并生成表明无响应体的 OpenAPI 文档。
+
+///
## 关于 HTTP 状态码
-!!! note "笔记"
+/// note | "笔记"
- 如果已经了解 HTTP 状态码,请跳到下一章。
+如果已经了解 HTTP 状态码,请跳到下一章。
+
+///
在 HTTP 协议中,发送 3 位数的数字状态码是响应的一部分。
@@ -58,16 +66,18 @@
* 对于来自客户端的一般错误,可以只使用 `400`
* `500` 及以上的状态码用于表示服务器端错误。几乎永远不会直接使用这些状态码。应用代码或服务器出现问题时,会自动返回这些状态代码
-!!! tip "提示"
+/// tip | "提示"
- 状态码及适用场景的详情,请参阅 MDN 的 HTTP 状态码文档。
+状态码及适用场景的详情,请参阅 MDN 的 HTTP 状态码文档。
+
+///
## 状态码名称快捷方式
再看下之前的例子:
```Python hl_lines="6"
-{!../../../docs_src/response_status_code/tutorial001.py!}
+{!../../docs_src/response_status_code/tutorial001.py!}
```
`201` 表示**已创建**的状态码。
@@ -77,18 +87,20 @@
可以使用 `fastapi.status` 中的快捷变量。
```Python hl_lines="1 6"
-{!../../../docs_src/response_status_code/tutorial002.py!}
+{!../../docs_src/response_status_code/tutorial002.py!}
```
这只是一种快捷方式,具有相同的数字代码,但它可以使用编辑器的自动补全功能:
-!!! note "技术细节"
+/// note | "技术细节"
- 也可以使用 `from starlette import status`。
+也可以使用 `from starlette import status`。
- 为了让开发者更方便,**FastAPI** 提供了与 `starlette.status` 完全相同的 `fastapi.status`。但它直接来自于 Starlette。
+为了让开发者更方便,**FastAPI** 提供了与 `starlette.status` 完全相同的 `fastapi.status`。但它直接来自于 Starlette。
+
+///
## 更改默认状态码
diff --git a/docs/zh/docs/tutorial/schema-extra-example.md b/docs/zh/docs/tutorial/schema-extra-example.md
index ae204dc61..b3883e4d3 100644
--- a/docs/zh/docs/tutorial/schema-extra-example.md
+++ b/docs/zh/docs/tutorial/schema-extra-example.md
@@ -10,17 +10,21 @@
您可以使用 `Config` 和 `schema_extra` 为Pydantic模型声明一个示例,如Pydantic 文档:定制 Schema 中所述:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="13-21"
- {!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!}
- ```
+```Python hl_lines="13-21"
+{!> ../../docs_src/schema_extra_example/tutorial001_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="15-23"
- {!> ../../../docs_src/schema_extra_example/tutorial001.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="15-23"
+{!> ../../docs_src/schema_extra_example/tutorial001.py!}
+```
+
+////
这些额外的信息将按原样添加到输出的JSON模式中。
@@ -28,20 +32,27 @@
在 `Field`, `Path`, `Query`, `Body` 和其他你之后将会看到的工厂函数,你可以为JSON 模式声明额外信息,你也可以通过给工厂函数传递其他的任意参数来给JSON 模式声明额外信息,比如增加 `example`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="2 8-11"
- {!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!}
- ```
+```Python hl_lines="2 8-11"
+{!> ../../docs_src/schema_extra_example/tutorial002_py310.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="4 10-13"
- {!> ../../../docs_src/schema_extra_example/tutorial002.py!}
- ```
+//// tab | Python 3.8+
-!!! warning
- 请记住,传递的那些额外参数不会添加任何验证,只会添加注释,用于文档的目的。
+```Python hl_lines="4 10-13"
+{!> ../../docs_src/schema_extra_example/tutorial002.py!}
+```
+
+////
+
+/// warning
+
+请记住,传递的那些额外参数不会添加任何验证,只会添加注释,用于文档的目的。
+
+///
## `Body` 额外参数
@@ -49,41 +60,57 @@
比如,你可以将请求体的一个 `example` 传递给 `Body`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="22-27"
- {!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!}
- ```
+```Python hl_lines="22-27"
+{!> ../../docs_src/schema_extra_example/tutorial003_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="22-27"
- {!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="22-27"
+{!> ../../docs_src/schema_extra_example/tutorial003_an_py39.py!}
+```
- ```Python hl_lines="23-28"
- {!> ../../../docs_src/schema_extra_example/tutorial003_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+```Python hl_lines="23-28"
+{!> ../../docs_src/schema_extra_example/tutorial003_an.py!}
+```
- ```Python hl_lines="18-23"
- {!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+/// tip
- ```Python hl_lines="20-25"
- {!> ../../../docs_src/schema_extra_example/tutorial003.py!}
- ```
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="18-23"
+{!> ../../docs_src/schema_extra_example/tutorial003_py310.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="20-25"
+{!> ../../docs_src/schema_extra_example/tutorial003.py!}
+```
+
+////
## 文档 UI 中的例子
diff --git a/docs/zh/docs/tutorial/security/first-steps.md b/docs/zh/docs/tutorial/security/first-steps.md
index f28cc24f8..8294b6444 100644
--- a/docs/zh/docs/tutorial/security/first-steps.md
+++ b/docs/zh/docs/tutorial/security/first-steps.md
@@ -20,36 +20,47 @@
把下面的示例代码复制到 `main.py`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python
- {!> ../../../docs_src/security/tutorial001_an_py39.py!}
- ```
+```Python
+{!> ../../docs_src/security/tutorial001_an_py39.py!}
+```
-=== "Python 3.8+"
+////
- ```Python
- {!> ../../../docs_src/security/tutorial001_an.py!}
- ```
+//// tab | Python 3.8+
-=== "Python 3.8+ non-Annotated"
+```Python
+{!> ../../docs_src/security/tutorial001_an.py!}
+```
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+////
- ```Python
- {!> ../../../docs_src/security/tutorial001.py!}
- ```
+//// tab | Python 3.8+ non-Annotated
+
+/// tip
+
+尽可能选择使用 `Annotated` 的版本。
+
+///
+
+```Python
+{!> ../../docs_src/security/tutorial001.py!}
+```
+
+////
## 运行
-!!! info "说明"
+/// info | "说明"
- 先安装 `python-multipart`。
+先安装 `python-multipart`。
- 安装命令: `pip install python-multipart`。
+安装命令: `pip install python-multipart`。
- 这是因为 **OAuth2** 使用**表单数据**发送 `username` 与 `password`。
+这是因为 **OAuth2** 使用**表单数据**发送 `username` 与 `password`。
+
+///
用下面的命令运行该示例:
@@ -71,19 +82,23 @@ $ uvicorn main:app --reload
-!!! check "Authorize 按钮!"
+/// check | "Authorize 按钮!"
- 页面右上角出现了一个「**Authorize**」按钮。
+页面右上角出现了一个「**Authorize**」按钮。
- *路径操作*的右上角也出现了一个可以点击的小锁图标。
+*路径操作*的右上角也出现了一个可以点击的小锁图标。
+
+///
点击 **Authorize** 按钮,弹出授权表单,输入 `username` 与 `password` 及其它可选字段:
-!!! note "笔记"
+/// note | "笔记"
- 目前,在表单中输入内容不会有任何反应,后文会介绍相关内容。
+目前,在表单中输入内容不会有任何反应,后文会介绍相关内容。
+
+///
虽然此文档不是给前端最终用户使用的,但这个自动工具非常实用,可在文档中与所有 API 交互。
@@ -125,39 +140,45 @@ OAuth2 的设计目标是为了让后端或 API 独立于服务器验证用户
本例使用 **OAuth2** 的 **Password** 流以及 **Bearer** 令牌(`Token`)。为此要使用 `OAuth2PasswordBearer` 类。
-!!! info "说明"
+/// info | "说明"
- `Bearer` 令牌不是唯一的选择。
+`Bearer` 令牌不是唯一的选择。
- 但它是最适合这个用例的方案。
+但它是最适合这个用例的方案。
- 甚至可以说,它是适用于绝大多数用例的最佳方案,除非您是 OAuth2 的专家,知道为什么其它方案更合适。
+甚至可以说,它是适用于绝大多数用例的最佳方案,除非您是 OAuth2 的专家,知道为什么其它方案更合适。
- 本例中,**FastAPI** 还提供了构建工具。
+本例中,**FastAPI** 还提供了构建工具。
+
+///
创建 `OAuth2PasswordBearer` 的类实例时,要传递 `tokenUrl` 参数。该参数包含客户端(用户浏览器中运行的前端) 的 URL,用于发送 `username` 与 `password`,并获取令牌。
```Python hl_lines="6"
-{!../../../docs_src/security/tutorial001.py!}
+{!../../docs_src/security/tutorial001.py!}
```
-!!! tip "提示"
+/// tip | "提示"
- 在此,`tokenUrl="token"` 指向的是暂未创建的相对 URL `token`。这个相对 URL 相当于 `./token`。
+在此,`tokenUrl="token"` 指向的是暂未创建的相对 URL `token`。这个相对 URL 相当于 `./token`。
- 因为使用的是相对 URL,如果 API 位于 `https://example.com/`,则指向 `https://example.com/token`。但如果 API 位于 `https://example.com/api/v1/`,它指向的就是`https://example.com/api/v1/token`。
+因为使用的是相对 URL,如果 API 位于 `https://example.com/`,则指向 `https://example.com/token`。但如果 API 位于 `https://example.com/api/v1/`,它指向的就是`https://example.com/api/v1/token`。
- 使用相对 URL 非常重要,可以确保应用在遇到[使用代理](../../advanced/behind-a-proxy.md){.internal-link target=_blank}这样的高级用例时,也能正常运行。
+使用相对 URL 非常重要,可以确保应用在遇到[使用代理](../../advanced/behind-a-proxy.md){.internal-link target=_blank}这样的高级用例时,也能正常运行。
+
+///
该参数不会创建端点或*路径操作*,但会声明客户端用来获取令牌的 URL `/token` 。此信息用于 OpenAPI 及 API 文档。
接下来,学习如何创建实际的路径操作。
-!!! info "说明"
+/// info | "说明"
- 严苛的 **Pythonista** 可能不喜欢用 `tokenUrl` 这种命名风格代替 `token_url`。
+严苛的 **Pythonista** 可能不喜欢用 `tokenUrl` 这种命名风格代替 `token_url`。
- 这种命名方式是因为要使用与 OpenAPI 规范中相同的名字。以便在深入校验安全方案时,能通过复制粘贴查找更多相关信息。
+这种命名方式是因为要使用与 OpenAPI 规范中相同的名字。以便在深入校验安全方案时,能通过复制粘贴查找更多相关信息。
+
+///
`oauth2_scheme` 变量是 `OAuth2PasswordBearer` 的实例,也是**可调用项**。
@@ -174,18 +195,20 @@ oauth2_scheme(some, parameters)
接下来,使用 `Depends` 把 `oauth2_scheme` 传入依赖项。
```Python hl_lines="10"
-{!../../../docs_src/security/tutorial001.py!}
+{!../../docs_src/security/tutorial001.py!}
```
该依赖项使用字符串(`str`)接收*路径操作函数*的参数 `token` 。
**FastAPI** 使用依赖项在 OpenAPI 概图(及 API 文档)中定义**安全方案**。
-!!! info "技术细节"
+/// info | "技术细节"
- **FastAPI** 使用(在依赖项中声明的)类 `OAuth2PasswordBearer` 在 OpenAPI 中定义安全方案,这是因为它继承自 `fastapi.security.oauth2.OAuth2`,而该类又是继承自`fastapi.security.base.SecurityBase`。
+**FastAPI** 使用(在依赖项中声明的)类 `OAuth2PasswordBearer` 在 OpenAPI 中定义安全方案,这是因为它继承自 `fastapi.security.oauth2.OAuth2`,而该类又是继承自`fastapi.security.base.SecurityBase`。
- 所有与 OpenAPI(及 API 文档)集成的安全工具都继承自 `SecurityBase`, 这就是为什么 **FastAPI** 能把它们集成至 OpenAPI 的原因。
+所有与 OpenAPI(及 API 文档)集成的安全工具都继承自 `SecurityBase`, 这就是为什么 **FastAPI** 能把它们集成至 OpenAPI 的原因。
+
+///
## 实现的操作
diff --git a/docs/zh/docs/tutorial/security/get-current-user.md b/docs/zh/docs/tutorial/security/get-current-user.md
index 1f17f5bd9..97461817a 100644
--- a/docs/zh/docs/tutorial/security/get-current-user.md
+++ b/docs/zh/docs/tutorial/security/get-current-user.md
@@ -3,7 +3,7 @@
上一章中,(基于依赖注入系统的)安全系统向*路径操作函数*传递了 `str` 类型的 `token`:
```Python hl_lines="10"
-{!../../../docs_src/security/tutorial001.py!}
+{!../../docs_src/security/tutorial001.py!}
```
但这并不实用。
@@ -18,7 +18,7 @@
与使用 Pydantic 声明请求体相同,并且可在任何位置使用:
```Python hl_lines="5 12-16"
-{!../../../docs_src/security/tutorial002.py!}
+{!../../docs_src/security/tutorial002.py!}
```
## 创建 `get_current_user` 依赖项
@@ -32,7 +32,7 @@
与之前直接在路径操作中的做法相同,新的 `get_current_user` 依赖项从子依赖项 `oauth2_scheme` 中接收 `str` 类型的 `token`:
```Python hl_lines="25"
-{!../../../docs_src/security/tutorial002.py!}
+{!../../docs_src/security/tutorial002.py!}
```
## 获取用户
@@ -40,7 +40,7 @@
`get_current_user` 使用创建的(伪)工具函数,该函数接收 `str` 类型的令牌,并返回 Pydantic 的 `User` 模型:
```Python hl_lines="19-22 26-27"
-{!../../../docs_src/security/tutorial002.py!}
+{!../../docs_src/security/tutorial002.py!}
```
## 注入当前用户
@@ -48,25 +48,28 @@
在*路径操作* 的 `Depends` 中使用 `get_current_user`:
```Python hl_lines="31"
-{!../../../docs_src/security/tutorial002.py!}
+{!../../docs_src/security/tutorial002.py!}
```
注意,此处把 `current_user` 的类型声明为 Pydantic 的 `User` 模型。
这有助于在函数内部使用代码补全和类型检查。
-!!! tip "提示"
+/// tip | "提示"
- 还记得请求体也是使用 Pydantic 模型声明的吧。
+还记得请求体也是使用 Pydantic 模型声明的吧。
- 放心,因为使用了 `Depends`,**FastAPI** 不会搞混。
+放心,因为使用了 `Depends`,**FastAPI** 不会搞混。
-!!! check "检查"
+///
- 依赖系统的这种设计方式可以支持不同的依赖项返回同一个 `User` 模型。
+/// check | "检查"
- 而不是局限于只能有一个返回该类型数据的依赖项。
+依赖系统的这种设计方式可以支持不同的依赖项返回同一个 `User` 模型。
+而不是局限于只能有一个返回该类型数据的依赖项。
+
+///
## 其它模型
@@ -102,7 +105,7 @@
所有*路径操作*只需 3 行代码就可以了:
```Python hl_lines="30-32"
-{!../../../docs_src/security/tutorial002.py!}
+{!../../docs_src/security/tutorial002.py!}
```
## 小结
diff --git a/docs/zh/docs/tutorial/security/index.md b/docs/zh/docs/tutorial/security/index.md
index 0595f5f63..e888a4fe9 100644
--- a/docs/zh/docs/tutorial/security/index.md
+++ b/docs/zh/docs/tutorial/security/index.md
@@ -32,9 +32,11 @@ OAuth2是一个规范,它定义了几种处理身份认证和授权的方法
OAuth2 没有指定如何加密通信,它期望你为应用程序使用 HTTPS 进行通信。
-!!! tip
- 在有关**部署**的章节中,你将了解如何使用 Traefik 和 Let's Encrypt 免费设置 HTTPS。
+/// tip
+在有关**部署**的章节中,你将了解如何使用 Traefik 和 Let's Encrypt 免费设置 HTTPS。
+
+///
## OpenID Connect
@@ -87,10 +89,13 @@ OpenAPI 定义了以下安全方案:
* 此自动发现机制是 OpenID Connect 规范中定义的内容。
-!!! tip
- 集成其他身份认证/授权提供者(例如Google,Facebook,Twitter,GitHub等)也是可能的,而且较为容易。
+/// tip
- 最复杂的问题是创建一个像这样的身份认证/授权提供程序,但是 **FastAPI** 为你提供了轻松完成任务的工具,同时为你解决了重活。
+集成其他身份认证/授权提供者(例如Google,Facebook,Twitter,GitHub等)也是可能的,而且较为容易。
+
+最复杂的问题是创建一个像这样的身份认证/授权提供程序,但是 **FastAPI** 为你提供了轻松完成任务的工具,同时为你解决了重活。
+
+///
## **FastAPI** 实用工具
diff --git a/docs/zh/docs/tutorial/security/oauth2-jwt.md b/docs/zh/docs/tutorial/security/oauth2-jwt.md
index 117f74d3e..8e497b844 100644
--- a/docs/zh/docs/tutorial/security/oauth2-jwt.md
+++ b/docs/zh/docs/tutorial/security/oauth2-jwt.md
@@ -40,11 +40,13 @@ $ pip install pyjwt
-!!! info "说明"
+/// info | "说明"
- 如果您打算使用类似 RSA 或 ECDSA 的数字签名算法,您应该安装加密库依赖项 `pyjwt[crypto]`。
+如果您打算使用类似 RSA 或 ECDSA 的数字签名算法,您应该安装加密库依赖项 `pyjwt[crypto]`。
- 您可以在 PyJWT Installation docs 获得更多信息。
+您可以在 PyJWT Installation docs 获得更多信息。
+
+///
## 密码哈希
@@ -80,13 +82,15 @@ $ pip install passlib[bcrypt]
-!!! tip "提示"
+/// tip | "提示"
- `passlib` 甚至可以读取 Django、Flask 的安全插件等工具创建的密码。
+`passlib` 甚至可以读取 Django、Flask 的安全插件等工具创建的密码。
- 例如,把 Django 应用的数据共享给 FastAPI 应用的数据库。或利用同一个数据库,可以逐步把应用从 Django 迁移到 FastAPI。
+例如,把 Django 应用的数据共享给 FastAPI 应用的数据库。或利用同一个数据库,可以逐步把应用从 Django 迁移到 FastAPI。
- 并且,用户可以同时从 Django 应用或 FastAPI 应用登录。
+并且,用户可以同时从 Django 应用或 FastAPI 应用登录。
+
+///
## 密码哈希与校验
@@ -94,13 +98,15 @@ $ pip install passlib[bcrypt]
创建用于密码哈希和身份校验的 PassLib **上下文**。
-!!! tip "提示"
+/// tip | "提示"
- PassLib 上下文还支持使用不同哈希算法的功能,包括只能校验的已弃用旧算法等。
+PassLib 上下文还支持使用不同哈希算法的功能,包括只能校验的已弃用旧算法等。
- 例如,用它读取和校验其它系统(如 Django)生成的密码,但要使用其它算法,如 Bcrypt,生成新的哈希密码。
+例如,用它读取和校验其它系统(如 Django)生成的密码,但要使用其它算法,如 Bcrypt,生成新的哈希密码。
- 同时,这些功能都是兼容的。
+同时,这些功能都是兼容的。
+
+///
接下来,创建三个工具函数,其中一个函数用于哈希用户的密码。
@@ -108,45 +114,63 @@ $ pip install passlib[bcrypt]
第三个函数用于身份验证,并返回用户。
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="8 49 56-57 60-61 70-76"
- {!> ../../../docs_src/security/tutorial004_an_py310.py!}
- ```
+```Python hl_lines="8 49 56-57 60-61 70-76"
+{!> ../../docs_src/security/tutorial004_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="8 49 56-57 60-61 70-76"
- {!> ../../../docs_src/security/tutorial004_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="8 49 56-57 60-61 70-76"
+{!> ../../docs_src/security/tutorial004_an_py39.py!}
+```
- ```Python hl_lines="8 50 57-58 61-62 71-77"
- {!> ../../../docs_src/security/tutorial004_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="8 50 57-58 61-62 71-77"
+{!> ../../docs_src/security/tutorial004_an.py!}
+```
- ```Python hl_lines="7 48 55-56 59-60 69-75"
- {!> ../../../docs_src/security/tutorial004_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="8 49 56-57 60-61 70-76"
- {!> ../../../docs_src/security/tutorial004.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-!!! note "笔记"
+///
- 查看新的(伪)数据库 `fake_users_db`,就能看到哈希后的密码:`"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`。
+```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!}
+```
+
+////
+
+/// note | "笔记"
+
+查看新的(伪)数据库 `fake_users_db`,就能看到哈希后的密码:`"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`。
+
+///
## 处理 JWT 令牌
@@ -177,7 +201,7 @@ $ openssl rand -hex 32
创建生成新的访问令牌的工具函数。
```Python hl_lines="6 12-14 28-30 78-86"
-{!../../../docs_src/security/tutorial004.py!}
+{!../../docs_src/security/tutorial004.py!}
```
## 更新依赖项
@@ -188,41 +212,57 @@ $ openssl rand -hex 32
如果令牌无效,则直接返回 HTTP 错误。
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="4 7 13-15 29-31 79-87"
- {!> ../../../docs_src/security/tutorial004_an_py310.py!}
- ```
+```Python hl_lines="4 7 13-15 29-31 79-87"
+{!> ../../docs_src/security/tutorial004_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="4 7 13-15 29-31 79-87"
- {!> ../../../docs_src/security/tutorial004_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="4 7 13-15 29-31 79-87"
+{!> ../../docs_src/security/tutorial004_an_py39.py!}
+```
- ```Python hl_lines="4 7 14-16 30-32 80-88"
- {!> ../../../docs_src/security/tutorial004_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="4 7 14-16 30-32 80-88"
+{!> ../../docs_src/security/tutorial004_an.py!}
+```
- ```Python hl_lines="3 6 12-14 28-30 78-86"
- {!> ../../../docs_src/security/tutorial004_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="4 7 13-15 29-31 79-87"
- {!> ../../../docs_src/security/tutorial004.py!}
- ```
+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!}
+```
+
+////
## 更新 `/token` *路径操作*
@@ -230,41 +270,57 @@ $ openssl rand -hex 32
创建并返回真正的 JWT 访问令牌。
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="118-133"
- {!> ../../../docs_src/security/tutorial004_an_py310.py!}
- ```
+```Python hl_lines="118-133"
+{!> ../../docs_src/security/tutorial004_an_py310.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="118-133"
- {!> ../../../docs_src/security/tutorial004_an_py39.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="118-133"
+{!> ../../docs_src/security/tutorial004_an_py39.py!}
+```
- ```Python hl_lines="119-134"
- {!> ../../../docs_src/security/tutorial004_an.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python hl_lines="119-134"
+{!> ../../docs_src/security/tutorial004_an.py!}
+```
- ```Python hl_lines="115-130"
- {!> ../../../docs_src/security/tutorial004_py310.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="116-131"
- {!> ../../../docs_src/security/tutorial004.py!}
- ```
+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!}
+```
+
+////
### JWT `sub` 的技术细节
@@ -302,9 +358,11 @@ JWT 规范还包括 `sub` 键,值是令牌的主题。
用户名: `johndoe` 密码: `secret`
-!!! check "检查"
+/// check | "检查"
- 注意,代码中没有明文密码**`secret`**,只保存了它的哈希值。
+注意,代码中没有明文密码**`secret`**,只保存了它的哈希值。
+
+///
@@ -325,9 +383,11 @@ JWT 规范还包括 `sub` 键,值是令牌的主题。
-!!! note "笔记"
+/// note | "笔记"
- 注意,请求中 `Authorization` 响应头的值以 `Bearer` 开头。
+注意,请求中 `Authorization` 响应头的值以 `Bearer` 开头。
+
+///
## `scopes` 高级用法
diff --git a/docs/zh/docs/tutorial/security/simple-oauth2.md b/docs/zh/docs/tutorial/security/simple-oauth2.md
index 751767ea2..1f031a6b2 100644
--- a/docs/zh/docs/tutorial/security/simple-oauth2.md
+++ b/docs/zh/docs/tutorial/security/simple-oauth2.md
@@ -32,15 +32,17 @@ OAuth2 还支持客户端发送**`scope`**表单字段。
* 脸书和 Instagram 使用 `instagram_basic`
* 谷歌使用 `https://www.googleapis.com/auth/drive`
-!!! info "说明"
+/// info | "说明"
- OAuth2 中,**作用域**只是声明指定权限的字符串。
+OAuth2 中,**作用域**只是声明指定权限的字符串。
- 是否使用冒号 `:` 等符号,或是不是 URL 并不重要。
+是否使用冒号 `:` 等符号,或是不是 URL 并不重要。
- 这些细节只是特定的实现方式。
+这些细节只是特定的实现方式。
- 对 OAuth2 来说,都只是字符串而已。
+对 OAuth2 来说,都只是字符串而已。
+
+///
## 获取 `username` 和 `password` 的代码
@@ -51,7 +53,7 @@ OAuth2 还支持客户端发送**`scope`**表单字段。
首先,导入 `OAuth2PasswordRequestForm`,然后,在 `/token` *路径操作* 中,用 `Depends` 把该类作为依赖项。
```Python hl_lines="4 76"
-{!../../../docs_src/security/tutorial003.py!}
+{!../../docs_src/security/tutorial003.py!}
```
`OAuth2PasswordRequestForm` 是用以下几项内容声明表单请求体的类依赖项:
@@ -61,32 +63,38 @@ OAuth2 还支持客户端发送**`scope`**表单字段。
* 可选的 `scope` 字段,由多个空格分隔的字符串组成的长字符串
* 可选的 `grant_type`
-!!! tip "提示"
+/// tip | "提示"
- 实际上,OAuth2 规范*要求* `grant_type` 字段使用固定值 `password`,但 `OAuth2PasswordRequestForm` 没有作强制约束。
+实际上,OAuth2 规范*要求* `grant_type` 字段使用固定值 `password`,但 `OAuth2PasswordRequestForm` 没有作强制约束。
- 如需强制使用固定值 `password`,则不要用 `OAuth2PasswordRequestForm`,而是用 `OAuth2PasswordRequestFormStrict`。
+如需强制使用固定值 `password`,则不要用 `OAuth2PasswordRequestForm`,而是用 `OAuth2PasswordRequestFormStrict`。
+
+///
* 可选的 `client_id`(本例未使用)
* 可选的 `client_secret`(本例未使用)
-!!! info "说明"
+/// info | "说明"
- `OAuth2PasswordRequestForm` 与 `OAuth2PasswordBearer` 一样,都不是 FastAPI 的特殊类。
+`OAuth2PasswordRequestForm` 与 `OAuth2PasswordBearer` 一样,都不是 FastAPI 的特殊类。
- **FastAPI** 把 `OAuth2PasswordBearer` 识别为安全方案。因此,可以通过这种方式把它添加至 OpenAPI。
+**FastAPI** 把 `OAuth2PasswordBearer` 识别为安全方案。因此,可以通过这种方式把它添加至 OpenAPI。
- 但 `OAuth2PasswordRequestForm` 只是可以自行编写的类依赖项,也可以直接声明 `Form` 参数。
+但 `OAuth2PasswordRequestForm` 只是可以自行编写的类依赖项,也可以直接声明 `Form` 参数。
- 但由于这种用例很常见,FastAPI 为了简便,就直接提供了对它的支持。
+但由于这种用例很常见,FastAPI 为了简便,就直接提供了对它的支持。
+
+///
### 使用表单数据
-!!! tip "提示"
+/// tip | "提示"
- `OAuth2PasswordRequestForm` 类依赖项的实例没有以空格分隔的长字符串属性 `scope`,但它支持 `scopes` 属性,由已发送的 scope 字符串列表组成。
+`OAuth2PasswordRequestForm` 类依赖项的实例没有以空格分隔的长字符串属性 `scope`,但它支持 `scopes` 属性,由已发送的 scope 字符串列表组成。
- 本例没有使用 `scopes`,但开发者也可以根据需要使用该属性。
+本例没有使用 `scopes`,但开发者也可以根据需要使用该属性。
+
+///
现在,即可使用表单字段 `username`,从(伪)数据库中获取用户数据。
@@ -95,7 +103,7 @@ OAuth2 还支持客户端发送**`scope`**表单字段。
本例使用 `HTTPException` 异常显示此错误:
```Python hl_lines="3 77-79"
-{!../../../docs_src/security/tutorial003.py!}
+{!../../docs_src/security/tutorial003.py!}
```
### 校验密码
@@ -123,7 +131,7 @@ OAuth2 还支持客户端发送**`scope`**表单字段。
这样一来,窃贼就无法在其它应用中使用窃取的密码,要知道,很多用户在所有系统中都使用相同的密码,风险超大。
```Python hl_lines="80-83"
-{!../../../docs_src/security/tutorial003.py!}
+{!../../docs_src/security/tutorial003.py!}
```
#### 关于 `**user_dict`
@@ -142,9 +150,11 @@ UserInDB(
)
```
-!!! info "说明"
+/// info | "说明"
- `user_dict` 的说明,详见[**更多模型**一章](../extra-models.md#user_indict){.internal-link target=_blank}。
+`user_dict` 的说明,详见[**更多模型**一章](../extra-models.md#user_indict){.internal-link target=_blank}。
+
+///
## 返回 Token
@@ -156,25 +166,29 @@ UserInDB(
本例只是简单的演示,返回的 Token 就是 `username`,但这种方式极不安全。
-!!! tip "提示"
+/// tip | "提示"
- 下一章介绍使用哈希密码和 JWT Token 的真正安全机制。
+下一章介绍使用哈希密码和 JWT Token 的真正安全机制。
- 但现在,仅关注所需的特定细节。
+但现在,仅关注所需的特定细节。
+
+///
```Python hl_lines="85"
-{!../../../docs_src/security/tutorial003.py!}
+{!../../docs_src/security/tutorial003.py!}
```
-!!! tip "提示"
+/// tip | "提示"
- 按规范的要求,应像本示例一样,返回带有 `access_token` 和 `token_type` 的 JSON 对象。
+按规范的要求,应像本示例一样,返回带有 `access_token` 和 `token_type` 的 JSON 对象。
- 这是开发者必须在代码中自行完成的工作,并且要确保使用这些 JSON 的键。
+这是开发者必须在代码中自行完成的工作,并且要确保使用这些 JSON 的键。
- 这几乎是唯一需要开发者牢记在心,并按规范要求正确执行的事。
+这几乎是唯一需要开发者牢记在心,并按规范要求正确执行的事。
- **FastAPI** 则负责处理其它的工作。
+**FastAPI** 则负责处理其它的工作。
+
+///
## 更新依赖项
@@ -189,24 +203,26 @@ UserInDB(
因此,在端点中,只有当用户存在、通过身份验证、且状态为激活时,才能获得该用户:
```Python hl_lines="58-67 69-72 90"
-{!../../../docs_src/security/tutorial003.py!}
+{!../../docs_src/security/tutorial003.py!}
```
-!!! info "说明"
+/// info | "说明"
- 此处返回值为 `Bearer` 的响应头 `WWW-Authenticate` 也是规范的一部分。
+此处返回值为 `Bearer` 的响应头 `WWW-Authenticate` 也是规范的一部分。
- 任何 401**UNAUTHORIZED**HTTP(错误)状态码都应返回 `WWW-Authenticate` 响应头。
+任何 401**UNAUTHORIZED**HTTP(错误)状态码都应返回 `WWW-Authenticate` 响应头。
- 本例中,因为使用的是 Bearer Token,该响应头的值应为 `Bearer`。
+本例中,因为使用的是 Bearer Token,该响应头的值应为 `Bearer`。
- 实际上,忽略这个附加响应头,也不会有什么问题。
+实际上,忽略这个附加响应头,也不会有什么问题。
- 之所以在此提供这个附加响应头,是为了符合规范的要求。
+之所以在此提供这个附加响应头,是为了符合规范的要求。
- 说不定什么时候,就有工具用得上它,而且,开发者或用户也可能用得上。
+说不定什么时候,就有工具用得上它,而且,开发者或用户也可能用得上。
- 这就是遵循标准的好处……
+这就是遵循标准的好处……
+
+///
## 实际效果
diff --git a/docs/zh/docs/tutorial/sql-databases.md b/docs/zh/docs/tutorial/sql-databases.md
index 8629b23fa..379c44143 100644
--- a/docs/zh/docs/tutorial/sql-databases.md
+++ b/docs/zh/docs/tutorial/sql-databases.md
@@ -1,11 +1,14 @@
# SQL (关系型) 数据库
-!!! info
- 这些文档即将被更新。🎉
+/// info
- 当前版本假设Pydantic v1和SQLAlchemy版本小于2。
+这些文档即将被更新。🎉
- 新的文档将包括Pydantic v2以及 SQLModel(也是基于SQLAlchemy),一旦SQLModel更新为为使用Pydantic v2。
+当前版本假设Pydantic v1和SQLAlchemy版本小于2。
+
+新的文档将包括Pydantic v2以及 SQLModel(也是基于SQLAlchemy),一旦SQLModel更新为为使用Pydantic v2。
+
+///
**FastAPI**不需要你使用SQL(关系型)数据库。
@@ -25,11 +28,17 @@
稍后,对于您的产品级别的应用程序,您可能会要使用像**PostgreSQL**这样的数据库服务器。
-!!! tip
- 这儿有一个**FastAPI**和**PostgreSQL**的官方项目生成器,全部基于**Docker**,包括前端和更多工具:https://github.com/tiangolo/full-stack-fastapi-postgresql
+/// tip
-!!! note
- 请注意,大部分代码是`SQLAlchemy`的标准代码,您可以用于任何框架。FastAPI特定的代码和往常一样少。
+这儿有一个**FastAPI**和**PostgreSQL**的官方项目生成器,全部基于**Docker**,包括前端和更多工具:https://github.com/tiangolo/full-stack-fastapi-postgresql
+
+///
+
+/// note
+
+请注意,大部分代码是`SQLAlchemy`的标准代码,您可以用于任何框架。FastAPI特定的代码和往常一样少。
+
+///
## ORMs(对象关系映射)
@@ -63,8 +72,11 @@ ORM 具有在代码和数据库表(“*关系型”)中的**对象**之间
以类似的方式,您也可以使用任何其他 ORM。
-!!! tip
- 在文档中也有一篇使用 Peewee 的等效的文章。
+/// tip
+
+在文档中也有一篇使用 Peewee 的等效的文章。
+
+///
## 文件结构
@@ -106,13 +118,13 @@ $ pip install sqlalchemy
### 导入 SQLAlchemy 部件
```Python hl_lines="1-3"
-{!../../../docs_src/sql_databases/sql_app/database.py!}
+{!../../docs_src/sql_databases/sql_app/database.py!}
```
### 为 SQLAlchemy 定义数据库 URL地址
```Python hl_lines="5-6"
-{!../../../docs_src/sql_databases/sql_app/database.py!}
+{!../../docs_src/sql_databases/sql_app/database.py!}
```
在这个例子中,我们正在“连接”到一个 SQLite 数据库(用 SQLite 数据库打开一个文件)。
@@ -129,9 +141,11 @@ SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db"
...并根据您的数据库数据和相关凭据(也适用于 MySQL、MariaDB 或任何其他)对其进行调整。
-!!! tip
+/// tip
- 如果您想使用不同的数据库,这是就是您必须修改的地方。
+如果您想使用不同的数据库,这是就是您必须修改的地方。
+
+///
### 创建 SQLAlchemy 引擎
@@ -140,7 +154,7 @@ SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db"
我们稍后会将这个`engine`在其他地方使用。
```Python hl_lines="8-10"
-{!../../../docs_src/sql_databases/sql_app/database.py!}
+{!../../docs_src/sql_databases/sql_app/database.py!}
```
#### 注意
@@ -153,15 +167,17 @@ connect_args={"check_same_thread": False}
...仅用于`SQLite`,在其他数据库不需要它。
-!!! info "技术细节"
+/// info | "技术细节"
- 默认情况下,SQLite 只允许一个线程与其通信,假设有多个线程的话,也只将处理一个独立的请求。
+默认情况下,SQLite 只允许一个线程与其通信,假设有多个线程的话,也只将处理一个独立的请求。
- 这是为了防止意外地为不同的事物(不同的请求)共享相同的连接。
+这是为了防止意外地为不同的事物(不同的请求)共享相同的连接。
- 但是在 FastAPI 中,使用普通函数(def)时,多个线程可以为同一个请求与数据库交互,所以我们需要使用`connect_args={"check_same_thread": False}`来让SQLite允许这样。
+但是在 FastAPI 中,使用普通函数(def)时,多个线程可以为同一个请求与数据库交互,所以我们需要使用`connect_args={"check_same_thread": False}`来让SQLite允许这样。
- 此外,我们将确保每个请求都在依赖项中获得自己的数据库连接会话,因此不需要该默认机制。
+此外,我们将确保每个请求都在依赖项中获得自己的数据库连接会话,因此不需要该默认机制。
+
+///
### 创建一个`SessionLocal`类
@@ -176,7 +192,7 @@ connect_args={"check_same_thread": False}
要创建`SessionLocal`类,请使用函数`sessionmaker`:
```Python hl_lines="11"
-{!../../../docs_src/sql_databases/sql_app/database.py!}
+{!../../docs_src/sql_databases/sql_app/database.py!}
```
### 创建一个`Base`类
@@ -186,7 +202,7 @@ connect_args={"check_same_thread": False}
稍后我们将继承这个类,来创建每个数据库模型或类(ORM 模型):
```Python hl_lines="13"
-{!../../../docs_src/sql_databases/sql_app/database.py!}
+{!../../docs_src/sql_databases/sql_app/database.py!}
```
## 创建数据库模型
@@ -197,10 +213,13 @@ connect_args={"check_same_thread": False}
我们将使用我们之前创建的`Base`类来创建 SQLAlchemy 模型。
-!!! tip
- SQLAlchemy 使用的“**模型**”这个术语 来指代与数据库交互的这些类和实例。
+/// tip
- 而 Pydantic 也使用“模型”这个术语 来指代不同的东西,即数据验证、转换以及文档类和实例。
+SQLAlchemy 使用的“**模型**”这个术语 来指代与数据库交互的这些类和实例。
+
+而 Pydantic 也使用“模型”这个术语 来指代不同的东西,即数据验证、转换以及文档类和实例。
+
+///
从`database`(来自上面的`database.py`文件)导入`Base`。
@@ -209,7 +228,7 @@ connect_args={"check_same_thread": False}
这些类就是 SQLAlchemy 模型。
```Python hl_lines="4 7-8 18-19"
-{!../../../docs_src/sql_databases/sql_app/models.py!}
+{!../../docs_src/sql_databases/sql_app/models.py!}
```
这个`__tablename__`属性是用来告诉 SQLAlchemy 要在数据库中为每个模型使用的数据库表的名称。
@@ -225,7 +244,7 @@ connect_args={"check_same_thread": False}
我们传递一个 SQLAlchemy “类型”,如`Integer`、`String`和`Boolean`,它定义了数据库中的类型,作为参数。
```Python hl_lines="1 10-13 21-24"
-{!../../../docs_src/sql_databases/sql_app/models.py!}
+{!../../docs_src/sql_databases/sql_app/models.py!}
```
### 创建关系
@@ -237,7 +256,7 @@ connect_args={"check_same_thread": False}
这将或多或少会成为一种“神奇”属性,其中表示该表与其他相关的表中的值。
```Python hl_lines="2 15 26"
-{!../../../docs_src/sql_databases/sql_app/models.py!}
+{!../../docs_src/sql_databases/sql_app/models.py!}
```
当访问 user 中的属性`items`时,如 中`my_user.items`,它将有一个`Item`SQLAlchemy 模型列表(来自`items`表),这些模型具有指向`users`表中此记录的外键。
@@ -250,12 +269,15 @@ connect_args={"check_same_thread": False}
现在让我们查看一下文件`sql_app/schemas.py`。
-!!! tip
- 为了避免 SQLAlchemy*模型*和 Pydantic*模型*之间的混淆,我们将有`models.py`(SQLAlchemy 模型的文件)和`schemas.py`( Pydantic 模型的文件)。
+/// tip
- 这些 Pydantic 模型或多或少地定义了一个“schema”(一个有效的数据形状)。
+为了避免 SQLAlchemy*模型*和 Pydantic*模型*之间的混淆,我们将有`models.py`(SQLAlchemy 模型的文件)和`schemas.py`( Pydantic 模型的文件)。
- 因此,这将帮助我们在使用两者时避免混淆。
+这些 Pydantic 模型或多或少地定义了一个“schema”(一个有效的数据形状)。
+
+因此,这将帮助我们在使用两者时避免混淆。
+
+///
### 创建初始 Pydantic*模型*/模式
@@ -267,23 +289,29 @@ connect_args={"check_same_thread": False}
但是为了安全起见,`password`不会出现在其他同类 Pydantic*模型*中,例如通过API读取一个用户数据时,它不应当包含在内。
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="1 4-6 9-10 21-22 25-26"
- {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
- ```
+```Python hl_lines="1 4-6 9-10 21-22 25-26"
+{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="3 6-8 11-12 23-24 27-28"
- {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="3 6-8 11-12 23-24 27-28"
+{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!}
+```
- ```Python hl_lines="3 6-8 11-12 23-24 27-28"
- {!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python hl_lines="3 6-8 11-12 23-24 27-28"
+{!> ../../docs_src/sql_databases/sql_app/schemas.py!}
+```
+
+////
#### SQLAlchemy 风格和 Pydantic 风格
@@ -311,26 +339,35 @@ name: str
不仅是这些项目的 ID,还有我们在 Pydantic*模型*中定义的用于读取项目的所有数据:`Item`.
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="13-15 29-32"
- {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
- ```
+```Python hl_lines="13-15 29-32"
+{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="15-17 31-34"
- {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="15-17 31-34"
+{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!}
+```
- ```Python hl_lines="15-17 31-34"
- {!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
- ```
+////
-!!! tip
- 请注意,读取用户(从 API 返回)时将使用不包括`password`的`User` Pydantic*模型*。
+//// tab | Python 3.8+
+
+```Python hl_lines="15-17 31-34"
+{!> ../../docs_src/sql_databases/sql_app/schemas.py!}
+```
+
+////
+
+/// tip
+
+请注意,读取用户(从 API 返回)时将使用不包括`password`的`User` Pydantic*模型*。
+
+///
### 使用 Pydantic 的`orm_mode`
@@ -340,32 +377,41 @@ name: str
在`Config`类中,设置属性`orm_mode = True`。
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python hl_lines="13 17-18 29 34-35"
- {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
- ```
+```Python hl_lines="13 17-18 29 34-35"
+{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!}
+```
-=== "Python 3.9+"
+////
- ```Python hl_lines="15 19-20 31 36-37"
- {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python hl_lines="15 19-20 31 36-37"
+{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!}
+```
- ```Python hl_lines="15 19-20 31 36-37"
- {!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
- ```
+////
-!!! tip
- 请注意,它使用`=`分配一个值,例如:
+//// tab | Python 3.8+
- `orm_mode = True`
+```Python hl_lines="15 19-20 31 36-37"
+{!> ../../docs_src/sql_databases/sql_app/schemas.py!}
+```
- 它不使用之前的`:`来类型声明。
+////
- 这是设置配置值,而不是声明类型。
+/// tip
+
+请注意,它使用`=`分配一个值,例如:
+
+`orm_mode = True`
+
+它不使用之前的`:`来类型声明。
+
+这是设置配置值,而不是声明类型。
+
+///
Pydantic`orm_mode`将告诉 Pydantic*模型*读取数据,即它不是一个`dict`,而是一个 ORM 模型(或任何其他具有属性的任意对象)。
@@ -428,11 +474,14 @@ current_user.items
* 查询多个项目。
```Python hl_lines="1 3 6-7 10-11 14-15 27-28"
-{!../../../docs_src/sql_databases/sql_app/crud.py!}
+{!../../docs_src/sql_databases/sql_app/crud.py!}
```
-!!! tip
- 通过创建仅专用于与数据库交互(获取用户或项目)的函数,独立于*路径操作函数*,您可以更轻松地在多个部分中重用它们,并为它们添加单元测试。
+/// tip
+
+通过创建仅专用于与数据库交互(获取用户或项目)的函数,独立于*路径操作函数*,您可以更轻松地在多个部分中重用它们,并为它们添加单元测试。
+
+///
### 创建数据
@@ -446,37 +495,46 @@ current_user.items
* 使用`refresh`来刷新您的实例对象(以便它包含来自数据库的任何新数据,例如生成的 ID)。
```Python hl_lines="18-24 31-36"
-{!../../../docs_src/sql_databases/sql_app/crud.py!}
+{!../../docs_src/sql_databases/sql_app/crud.py!}
```
-!!! tip
- SQLAlchemy 模型`User`包含一个`hashed_password`,它应该是一个包含散列的安全密码。
+/// tip
- 但由于 API 客户端提供的是原始密码,因此您需要将其提取并在应用程序中生成散列密码。
+SQLAlchemy 模型`User`包含一个`hashed_password`,它应该是一个包含散列的安全密码。
- 然后将hashed_password参数与要保存的值一起传递。
+但由于 API 客户端提供的是原始密码,因此您需要将其提取并在应用程序中生成散列密码。
-!!! warning
- 此示例不安全,密码未经过哈希处理。
+然后将hashed_password参数与要保存的值一起传递。
- 在现实生活中的应用程序中,您需要对密码进行哈希处理,并且永远不要以明文形式保存它们。
+///
- 有关更多详细信息,请返回教程中的安全部分。
+/// warning
- 在这里,我们只关注数据库的工具和机制。
+此示例不安全,密码未经过哈希处理。
-!!! tip
- 这里不是将每个关键字参数传递给Item并从Pydantic模型中读取每个参数,而是先生成一个字典,其中包含Pydantic模型的数据:
+在现实生活中的应用程序中,您需要对密码进行哈希处理,并且永远不要以明文形式保存它们。
- `item.dict()`
+有关更多详细信息,请返回教程中的安全部分。
- 然后我们将dict的键值对 作为关键字参数传递给 SQLAlchemy `Item`:
+在这里,我们只关注数据库的工具和机制。
- `Item(**item.dict())`
+///
- 然后我们传递 Pydantic模型未提供的额外关键字参数`owner_id`:
+/// tip
- `Item(**item.dict(), owner_id=user_id)`
+这里不是将每个关键字参数传递给Item并从Pydantic模型中读取每个参数,而是先生成一个字典,其中包含Pydantic模型的数据:
+
+`item.dict()`
+
+然后我们将dict的键值对 作为关键字参数传递给 SQLAlchemy `Item`:
+
+`Item(**item.dict())`
+
+然后我们传递 Pydantic模型未提供的额外关键字参数`owner_id`:
+
+`Item(**item.dict(), owner_id=user_id)`
+
+///
## 主**FastAPI**应用程序
@@ -486,17 +544,21 @@ current_user.items
以非常简单的方式创建数据库表:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="7"
- {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
- ```
+```Python hl_lines="7"
+{!> ../../docs_src/sql_databases/sql_app_py39/main.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="9"
- {!> ../../../docs_src/sql_databases/sql_app/main.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="9"
+{!> ../../docs_src/sql_databases/sql_app/main.py!}
+```
+
+////
#### Alembic 注意
@@ -520,63 +582,81 @@ current_user.items
我们的依赖项将创建一个新的 SQLAlchemy `SessionLocal`,它将在单个请求中使用,然后在请求完成后关闭它。
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="13-18"
- {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
- ```
+```Python hl_lines="13-18"
+{!> ../../docs_src/sql_databases/sql_app_py39/main.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="15-20"
- {!> ../../../docs_src/sql_databases/sql_app/main.py!}
- ```
+//// tab | Python 3.8+
-!!! info
- 我们将`SessionLocal()`请求的创建和处理放在一个`try`块中。
+```Python hl_lines="15-20"
+{!> ../../docs_src/sql_databases/sql_app/main.py!}
+```
- 然后我们在finally块中关闭它。
+////
- 通过这种方式,我们确保数据库会话在请求后始终关闭。即使在处理请求时出现异常。
+/// info
- 但是您不能从退出代码中引发另一个异常(在yield之后)。可以查阅 [Dependencies with yield and HTTPException](https://fastapi.tiangolo.com/zh/tutorial/dependencies/dependencies-with-yield/#dependencies-with-yield-and-httpexception)
+我们将`SessionLocal()`请求的创建和处理放在一个`try`块中。
+
+然后我们在finally块中关闭它。
+
+通过这种方式,我们确保数据库会话在请求后始终关闭。即使在处理请求时出现异常。
+
+但是您不能从退出代码中引发另一个异常(在yield之后)。可以查阅 [Dependencies with yield and HTTPException](https://fastapi.tiangolo.com/zh/tutorial/dependencies/dependencies-with-yield/#dependencies-with-yield-and-httpexception)
+
+///
*然后,当在路径操作函数*中使用依赖项时,我们使用`Session`,直接从 SQLAlchemy 导入的类型声明它。
*这将为我们在路径操作函数*中提供更好的编辑器支持,因为编辑器将知道`db`参数的类型`Session`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="22 30 36 45 51"
- {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
- ```
+```Python hl_lines="22 30 36 45 51"
+{!> ../../docs_src/sql_databases/sql_app_py39/main.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="24 32 38 47 53"
- {!> ../../../docs_src/sql_databases/sql_app/main.py!}
- ```
+//// tab | Python 3.8+
-!!! info "技术细节"
- 参数`db`实际上是 type `SessionLocal`,但是这个类(用 创建`sessionmaker()`)是 SQLAlchemy 的“代理” `Session`,所以,编辑器并不真正知道提供了哪些方法。
+```Python hl_lines="24 32 38 47 53"
+{!> ../../docs_src/sql_databases/sql_app/main.py!}
+```
- 但是通过将类型声明为Session,编辑器现在可以知道可用的方法(.add()、.query()、.commit()等)并且可以提供更好的支持(比如完成)。类型声明不影响实际对象。
+////
+
+/// info | "技术细节"
+
+参数`db`实际上是 type `SessionLocal`,但是这个类(用 创建`sessionmaker()`)是 SQLAlchemy 的“代理” `Session`,所以,编辑器并不真正知道提供了哪些方法。
+
+但是通过将类型声明为Session,编辑器现在可以知道可用的方法(.add()、.query()、.commit()等)并且可以提供更好的支持(比如完成)。类型声明不影响实际对象。
+
+///
### 创建您的**FastAPI** *路径操作*
现在,到了最后,编写标准的**FastAPI** *路径操作*代码。
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="21-26 29-32 35-40 43-47 50-53"
- {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
- ```
+```Python hl_lines="21-26 29-32 35-40 43-47 50-53"
+{!> ../../docs_src/sql_databases/sql_app_py39/main.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="23-28 31-34 37-42 45-49 52-55"
- {!> ../../../docs_src/sql_databases/sql_app/main.py!}
- ```
+//// tab | Python 3.8+
+
+```Python hl_lines="23-28 31-34 37-42 45-49 52-55"
+{!> ../../docs_src/sql_databases/sql_app/main.py!}
+```
+
+////
我们在依赖项中的每个请求之前利用`yield`创建数据库会话,然后关闭它。
@@ -584,15 +664,21 @@ current_user.items
这样,我们就可以直接从*路径操作函数*内部调用`crud.get_user`并使用该会话,来进行对数据库操作。
-!!! tip
- 请注意,您返回的值是 SQLAlchemy 模型或 SQLAlchemy 模型列表。
+/// tip
- 但是由于所有路径操作的response_model都使用 Pydantic模型/使用orm_mode模式,因此您的 Pydantic 模型中声明的数据将从它们中提取并返回给客户端,并进行所有正常的过滤和验证。
+请注意,您返回的值是 SQLAlchemy 模型或 SQLAlchemy 模型列表。
-!!! tip
- 另请注意,`response_models`应当是标准 Python 类型,例如`List[schemas.Item]`.
+但是由于所有路径操作的response_model都使用 Pydantic模型/使用orm_mode模式,因此您的 Pydantic 模型中声明的数据将从它们中提取并返回给客户端,并进行所有正常的过滤和验证。
- 但是由于它的内容/参数List是一个 使用orm_mode模式的Pydantic模型,所以数据将被正常检索并返回给客户端,所以没有问题。
+///
+
+/// tip
+
+另请注意,`response_models`应当是标准 Python 类型,例如`List[schemas.Item]`.
+
+但是由于它的内容/参数List是一个 使用orm_mode模式的Pydantic模型,所以数据将被正常检索并返回给客户端,所以没有问题。
+
+///
### 关于 `def` 对比 `async def`
@@ -621,11 +707,17 @@ def read_user(user_id: int, db: Session = Depends(get_db)):
...
```
-!!! info
- 如果您需要异步连接到关系数据库,请参阅[Async SQL (Relational) Databases](https://fastapi.tiangolo.com/zh/advanced/async-sql-databases/)
+/// info
-!!! note "Very Technical Details"
- 如果您很好奇并且拥有深厚的技术知识,您可以在[Async](https://fastapi.tiangolo.com/zh/async/#very-technical-details)文档中查看有关如何处理 `async def`于`def`差别的技术细节。
+如果您需要异步连接到关系数据库,请参阅[Async SQL (Relational) Databases](https://fastapi.tiangolo.com/zh/advanced/async-sql-databases/)
+
+///
+
+/// note | "Very Technical Details"
+
+如果您很好奇并且拥有深厚的技术知识,您可以在[Async](https://fastapi.tiangolo.com/zh/async/#very-technical-details)文档中查看有关如何处理 `async def`于`def`差别的技术细节。
+
+///
## 迁移
@@ -648,62 +740,74 @@ def read_user(user_id: int, db: Session = Depends(get_db)):
* `sql_app/database.py`:
```Python
-{!../../../docs_src/sql_databases/sql_app/database.py!}
+{!../../docs_src/sql_databases/sql_app/database.py!}
```
* `sql_app/models.py`:
```Python
-{!../../../docs_src/sql_databases/sql_app/models.py!}
+{!../../docs_src/sql_databases/sql_app/models.py!}
```
* `sql_app/schemas.py`:
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python
- {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
- ```
+```Python
+{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!}
+```
-=== "Python 3.9+"
+////
- ```Python
- {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python
+{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!}
+```
- ```Python
- {!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
- ```
+////
+
+//// tab | Python 3.8+
+
+```Python
+{!> ../../docs_src/sql_databases/sql_app/schemas.py!}
+```
+
+////
* `sql_app/crud.py`:
```Python
-{!../../../docs_src/sql_databases/sql_app/crud.py!}
+{!../../docs_src/sql_databases/sql_app/crud.py!}
```
* `sql_app/main.py`:
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python
- {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
- ```
+```Python
+{!> ../../docs_src/sql_databases/sql_app_py39/main.py!}
+```
-=== "Python 3.8+"
+////
- ```Python
- {!> ../../../docs_src/sql_databases/sql_app/main.py!}
- ```
+//// tab | Python 3.8+
+
+```Python
+{!> ../../docs_src/sql_databases/sql_app/main.py!}
+```
+
+////
## 执行项目
您可以复制这些代码并按原样使用它。
-!!! info
+/// info
- 事实上,这里的代码只是大多数测试代码的一部分。
+事实上,这里的代码只是大多数测试代码的一部分。
+
+///
你可以用 Uvicorn 运行它:
@@ -744,24 +848,31 @@ $ uvicorn sql_app.main:app --reload
我们要添加的中间件(只是一个函数)将为每个请求创建一个新的 SQLAlchemy`SessionLocal`,将其添加到请求中,然后在请求完成后关闭它。
-=== "Python 3.9+"
+//// tab | Python 3.9+
- ```Python hl_lines="12-20"
- {!> ../../../docs_src/sql_databases/sql_app_py39/alt_main.py!}
- ```
+```Python hl_lines="12-20"
+{!> ../../docs_src/sql_databases/sql_app_py39/alt_main.py!}
+```
-=== "Python 3.8+"
+////
- ```Python hl_lines="14-22"
- {!> ../../../docs_src/sql_databases/sql_app/alt_main.py!}
- ```
+//// tab | Python 3.8+
-!!! info
- 我们将`SessionLocal()`请求的创建和处理放在一个`try`块中。
+```Python hl_lines="14-22"
+{!> ../../docs_src/sql_databases/sql_app/alt_main.py!}
+```
- 然后我们在finally块中关闭它。
+////
- 通过这种方式,我们确保数据库会话在请求后始终关闭,即使在处理请求时出现异常也会关闭。
+/// info
+
+我们将`SessionLocal()`请求的创建和处理放在一个`try`块中。
+
+然后我们在finally块中关闭它。
+
+通过这种方式,我们确保数据库会话在请求后始终关闭,即使在处理请求时出现异常也会关闭。
+
+///
### 关于`request.state`
@@ -782,10 +893,16 @@ $ uvicorn sql_app.main:app --reload
* 将为每个请求创建一个连接。
* 即使处理该请求的*路径操作*不需要数据库。
-!!! tip
- 最好使用带有yield的依赖项,如果这足够满足用例需求
+/// tip
-!!! info
- 带有`yield`的依赖项是最近刚加入**FastAPI**中的。
+最好使用带有yield的依赖项,如果这足够满足用例需求
- 所以本教程的先前版本只有带有中间件的示例,并且可能有多个应用程序使用中间件进行数据库会话管理。
+///
+
+/// info
+
+带有`yield`的依赖项是最近刚加入**FastAPI**中的。
+
+所以本教程的先前版本只有带有中间件的示例,并且可能有多个应用程序使用中间件进行数据库会话管理。
+
+///
diff --git a/docs/zh/docs/tutorial/static-files.md b/docs/zh/docs/tutorial/static-files.md
index e7c5c3f0a..37e90ad43 100644
--- a/docs/zh/docs/tutorial/static-files.md
+++ b/docs/zh/docs/tutorial/static-files.md
@@ -8,13 +8,16 @@
* "挂载"(Mount) 一个 `StaticFiles()` 实例到一个指定路径。
```Python hl_lines="2 6"
-{!../../../docs_src/static_files/tutorial001.py!}
+{!../../docs_src/static_files/tutorial001.py!}
```
-!!! note "技术细节"
- 你也可以用 `from starlette.staticfiles import StaticFiles`。
+/// note | "技术细节"
- **FastAPI** 提供了和 `starlette.staticfiles` 相同的 `fastapi.staticfiles` ,只是为了方便你,开发者。但它确实来自Starlette。
+你也可以用 `from starlette.staticfiles import StaticFiles`。
+
+**FastAPI** 提供了和 `starlette.staticfiles` 相同的 `fastapi.staticfiles` ,只是为了方便你,开发者。但它确实来自Starlette。
+
+///
### 什么是"挂载"(Mounting)
diff --git a/docs/zh/docs/tutorial/testing.md b/docs/zh/docs/tutorial/testing.md
index 69841978c..173e6f8a6 100644
--- a/docs/zh/docs/tutorial/testing.md
+++ b/docs/zh/docs/tutorial/testing.md
@@ -8,10 +8,13 @@
## 使用 `TestClient`
-!!! info "信息"
- 要使用 `TestClient`,先要安装 `httpx`.
+/// info | "信息"
- 例:`pip install httpx`.
+要使用 `TestClient`,先要安装 `httpx`.
+
+例:`pip install httpx`.
+
+///
导入 `TestClient`.
@@ -24,23 +27,32 @@
为你需要检查的地方用标准的Python表达式写个简单的 `assert` 语句(重申,标准的`pytest`)。
```Python hl_lines="2 12 15-18"
-{!../../../docs_src/app_testing/tutorial001.py!}
+{!../../docs_src/app_testing/tutorial001.py!}
```
-!!! tip "提示"
- 注意测试函数是普通的 `def`,不是 `async def`。
+/// tip | "提示"
- 还有client的调用也是普通的调用,不是用 `await`。
+注意测试函数是普通的 `def`,不是 `async def`。
- 这让你可以直接使用 `pytest` 而不会遇到麻烦。
+还有client的调用也是普通的调用,不是用 `await`。
-!!! note "技术细节"
- 你也可以用 `from starlette.testclient import TestClient`。
+这让你可以直接使用 `pytest` 而不会遇到麻烦。
- **FastAPI** 提供了和 `starlette.testclient` 一样的 `fastapi.testclient`,只是为了方便开发者。但它直接来自Starlette。
+///
-!!! tip "提示"
- 除了发送请求之外,如果你还想测试时在FastAPI应用中调用 `async` 函数(例如异步数据库函数), 可以在高级教程中看下 [Async Tests](../advanced/async-tests.md){.internal-link target=_blank} 。
+/// note | "技术细节"
+
+你也可以用 `from starlette.testclient import TestClient`。
+
+**FastAPI** 提供了和 `starlette.testclient` 一样的 `fastapi.testclient`,只是为了方便开发者。但它直接来自Starlette。
+
+///
+
+/// tip | "提示"
+
+除了发送请求之外,如果你还想测试时在FastAPI应用中调用 `async` 函数(例如异步数据库函数), 可以在高级教程中看下 [Async Tests](../advanced/async-tests.md){.internal-link target=_blank} 。
+
+///
## 分离测试
@@ -63,7 +75,7 @@
```Python
-{!../../../docs_src/app_testing/main.py!}
+{!../../docs_src/app_testing/main.py!}
```
### 测试文件
@@ -81,7 +93,7 @@
因为这文件在同一个包中,所以你可以通过相对导入从 `main` 模块(`main.py`)导入`app`对象:
```Python hl_lines="3"
-{!../../../docs_src/app_testing/test_main.py!}
+{!../../docs_src/app_testing/test_main.py!}
```
...然后测试代码和之前一样的。
@@ -110,48 +122,64 @@
所有*路径操作* 都需要一个`X-Token` 头。
-=== "Python 3.10+"
+//// tab | Python 3.10+
- ```Python
- {!> ../../../docs_src/app_testing/app_b_an_py310/main.py!}
- ```
+```Python
+{!> ../../docs_src/app_testing/app_b_an_py310/main.py!}
+```
-=== "Python 3.9+"
+////
- ```Python
- {!> ../../../docs_src/app_testing/app_b_an_py39/main.py!}
- ```
+//// tab | Python 3.9+
-=== "Python 3.8+"
+```Python
+{!> ../../docs_src/app_testing/app_b_an_py39/main.py!}
+```
- ```Python
- {!> ../../../docs_src/app_testing/app_b_an/main.py!}
- ```
+////
-=== "Python 3.10+ non-Annotated"
+//// tab | Python 3.8+
- !!! tip "提示"
- Prefer to use the `Annotated` version if possible.
+```Python
+{!> ../../docs_src/app_testing/app_b_an/main.py!}
+```
- ```Python
- {!> ../../../docs_src/app_testing/app_b_py310/main.py!}
- ```
+////
-=== "Python 3.8+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip "提示"
- Prefer to use the `Annotated` version if possible.
+/// tip | "提示"
- ```Python
- {!> ../../../docs_src/app_testing/app_b/main.py!}
- ```
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python
+{!> ../../docs_src/app_testing/app_b_py310/main.py!}
+```
+
+////
+
+//// tab | Python 3.8+ non-Annotated
+
+/// tip | "提示"
+
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python
+{!> ../../docs_src/app_testing/app_b/main.py!}
+```
+
+////
### 扩展后的测试文件
然后您可以使用扩展后的测试更新`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的设计的。
@@ -168,10 +196,13 @@
关于如何传数据给后端的更多信息 (使用`httpx` 或 `TestClient`),请查阅 HTTPX 文档.
-!!! info "信息"
- 注意 `TestClient` 接收可以被转化为JSON的数据,而不是Pydantic模型。
+/// info | "信息"
- 如果你在测试中有一个Pydantic模型,并且你想在测试时发送它的数据给应用,你可以使用在[JSON Compatible Encoder](encoder.md){.internal-link target=_blank}介绍的`jsonable_encoder` 。
+注意 `TestClient` 接收可以被转化为JSON的数据,而不是Pydantic模型。
+
+如果你在测试中有一个Pydantic模型,并且你想在测试时发送它的数据给应用,你可以使用在[JSON Compatible Encoder](encoder.md){.internal-link target=_blank}介绍的`jsonable_encoder` 。
+
+///
## 运行起来
diff --git a/docs_src/advanced_middleware/tutorial003.py b/docs_src/advanced_middleware/tutorial003.py
index b99e3edd1..e2c87e67d 100644
--- a/docs_src/advanced_middleware/tutorial003.py
+++ b/docs_src/advanced_middleware/tutorial003.py
@@ -3,7 +3,7 @@ from fastapi.middleware.gzip import GZipMiddleware
app = FastAPI()
-app.add_middleware(GZipMiddleware, minimum_size=1000)
+app.add_middleware(GZipMiddleware, minimum_size=1000, compresslevel=5)
@app.get("/")
diff --git a/docs_src/app_testing/app_b_an/main.py b/docs_src/app_testing/app_b_an/main.py
index c63134fc9..c66278fdd 100644
--- a/docs_src/app_testing/app_b_an/main.py
+++ b/docs_src/app_testing/app_b_an/main.py
@@ -34,6 +34,6 @@ async def create_item(item: Item, x_token: Annotated[str, Header()]):
if x_token != fake_secret_token:
raise HTTPException(status_code=400, detail="Invalid X-Token header")
if item.id in fake_db:
- raise HTTPException(status_code=400, detail="Item already exists")
+ raise HTTPException(status_code=409, detail="Item already exists")
fake_db[item.id] = item
return item
diff --git a/docs_src/app_testing/app_b_an/test_main.py b/docs_src/app_testing/app_b_an/test_main.py
index e2eda449d..4e1c51ecc 100644
--- a/docs_src/app_testing/app_b_an/test_main.py
+++ b/docs_src/app_testing/app_b_an/test_main.py
@@ -61,5 +61,5 @@ def test_create_existing_item():
"description": "There goes my stealer",
},
)
- assert response.status_code == 400
+ assert response.status_code == 409
assert response.json() == {"detail": "Item already exists"}
diff --git a/docs_src/app_testing/app_b_an_py310/main.py b/docs_src/app_testing/app_b_an_py310/main.py
index 48c27a0b8..c5952be0b 100644
--- a/docs_src/app_testing/app_b_an_py310/main.py
+++ b/docs_src/app_testing/app_b_an_py310/main.py
@@ -33,6 +33,6 @@ async def create_item(item: Item, x_token: Annotated[str, Header()]):
if x_token != fake_secret_token:
raise HTTPException(status_code=400, detail="Invalid X-Token header")
if item.id in fake_db:
- raise HTTPException(status_code=400, detail="Item already exists")
+ raise HTTPException(status_code=409, detail="Item already exists")
fake_db[item.id] = item
return item
diff --git a/docs_src/app_testing/app_b_an_py310/test_main.py b/docs_src/app_testing/app_b_an_py310/test_main.py
index e2eda449d..4e1c51ecc 100644
--- a/docs_src/app_testing/app_b_an_py310/test_main.py
+++ b/docs_src/app_testing/app_b_an_py310/test_main.py
@@ -61,5 +61,5 @@ def test_create_existing_item():
"description": "There goes my stealer",
},
)
- assert response.status_code == 400
+ assert response.status_code == 409
assert response.json() == {"detail": "Item already exists"}
diff --git a/docs_src/app_testing/app_b_an_py39/main.py b/docs_src/app_testing/app_b_an_py39/main.py
index 935a510b7..142e23a26 100644
--- a/docs_src/app_testing/app_b_an_py39/main.py
+++ b/docs_src/app_testing/app_b_an_py39/main.py
@@ -33,6 +33,6 @@ async def create_item(item: Item, x_token: Annotated[str, Header()]):
if x_token != fake_secret_token:
raise HTTPException(status_code=400, detail="Invalid X-Token header")
if item.id in fake_db:
- raise HTTPException(status_code=400, detail="Item already exists")
+ raise HTTPException(status_code=409, detail="Item already exists")
fake_db[item.id] = item
return item
diff --git a/docs_src/app_testing/app_b_an_py39/test_main.py b/docs_src/app_testing/app_b_an_py39/test_main.py
index e2eda449d..4e1c51ecc 100644
--- a/docs_src/app_testing/app_b_an_py39/test_main.py
+++ b/docs_src/app_testing/app_b_an_py39/test_main.py
@@ -61,5 +61,5 @@ def test_create_existing_item():
"description": "There goes my stealer",
},
)
- assert response.status_code == 400
+ assert response.status_code == 409
assert response.json() == {"detail": "Item already exists"}
diff --git a/docs_src/async_sql_databases/tutorial001.py b/docs_src/async_sql_databases/tutorial001.py
deleted file mode 100644
index cbf43d790..000000000
--- a/docs_src/async_sql_databases/tutorial001.py
+++ /dev/null
@@ -1,65 +0,0 @@
-from typing import List
-
-import databases
-import sqlalchemy
-from fastapi import FastAPI
-from pydantic import BaseModel
-
-# SQLAlchemy specific code, as with any other app
-DATABASE_URL = "sqlite:///./test.db"
-# DATABASE_URL = "postgresql://user:password@postgresserver/db"
-
-database = databases.Database(DATABASE_URL)
-
-metadata = sqlalchemy.MetaData()
-
-notes = sqlalchemy.Table(
- "notes",
- metadata,
- sqlalchemy.Column("id", sqlalchemy.Integer, primary_key=True),
- sqlalchemy.Column("text", sqlalchemy.String),
- sqlalchemy.Column("completed", sqlalchemy.Boolean),
-)
-
-
-engine = sqlalchemy.create_engine(
- DATABASE_URL, connect_args={"check_same_thread": False}
-)
-metadata.create_all(engine)
-
-
-class NoteIn(BaseModel):
- text: str
- completed: bool
-
-
-class Note(BaseModel):
- id: int
- text: str
- completed: bool
-
-
-app = FastAPI()
-
-
-@app.on_event("startup")
-async def startup():
- await database.connect()
-
-
-@app.on_event("shutdown")
-async def shutdown():
- await database.disconnect()
-
-
-@app.get("/notes/", response_model=List[Note])
-async def read_notes():
- query = notes.select()
- return await database.fetch_all(query)
-
-
-@app.post("/notes/", response_model=Note)
-async def create_note(note: NoteIn):
- query = notes.insert().values(text=note.text, completed=note.completed)
- last_record_id = await database.execute(query)
- return {**note.dict(), "id": last_record_id}
diff --git a/docs_src/async_tests/test_main.py b/docs_src/async_tests/test_main.py
index 9f1527d5f..a57a31f7d 100644
--- a/docs_src/async_tests/test_main.py
+++ b/docs_src/async_tests/test_main.py
@@ -1,12 +1,14 @@
import pytest
-from httpx import AsyncClient
+from httpx import ASGITransport, AsyncClient
from .main import app
@pytest.mark.anyio
async def test_root():
- async with AsyncClient(app=app, base_url="http://test") as ac:
+ async with AsyncClient(
+ transport=ASGITransport(app=app), base_url="http://test"
+ ) as ac:
response = await ac.get("/")
assert response.status_code == 200
assert response.json() == {"message": "Tomato"}
diff --git a/docs_src/cookie_param_models/tutorial001.py b/docs_src/cookie_param_models/tutorial001.py
new file mode 100644
index 000000000..cc65c43e1
--- /dev/null
+++ b/docs_src/cookie_param_models/tutorial001.py
@@ -0,0 +1,17 @@
+from typing import Union
+
+from fastapi import Cookie, FastAPI
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class Cookies(BaseModel):
+ session_id: str
+ fatebook_tracker: Union[str, None] = None
+ googall_tracker: Union[str, None] = None
+
+
+@app.get("/items/")
+async def read_items(cookies: Cookies = Cookie()):
+ return cookies
diff --git a/docs_src/cookie_param_models/tutorial001_an.py b/docs_src/cookie_param_models/tutorial001_an.py
new file mode 100644
index 000000000..e5839ffd5
--- /dev/null
+++ b/docs_src/cookie_param_models/tutorial001_an.py
@@ -0,0 +1,18 @@
+from typing import Union
+
+from fastapi import Cookie, FastAPI
+from pydantic import BaseModel
+from typing_extensions import Annotated
+
+app = FastAPI()
+
+
+class Cookies(BaseModel):
+ session_id: str
+ fatebook_tracker: Union[str, None] = None
+ googall_tracker: Union[str, None] = None
+
+
+@app.get("/items/")
+async def read_items(cookies: Annotated[Cookies, Cookie()]):
+ return cookies
diff --git a/docs_src/cookie_param_models/tutorial001_an_py310.py b/docs_src/cookie_param_models/tutorial001_an_py310.py
new file mode 100644
index 000000000..24cc889a9
--- /dev/null
+++ b/docs_src/cookie_param_models/tutorial001_an_py310.py
@@ -0,0 +1,17 @@
+from typing import Annotated
+
+from fastapi import Cookie, FastAPI
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class Cookies(BaseModel):
+ session_id: str
+ fatebook_tracker: str | None = None
+ googall_tracker: str | None = None
+
+
+@app.get("/items/")
+async def read_items(cookies: Annotated[Cookies, Cookie()]):
+ return cookies
diff --git a/docs_src/cookie_param_models/tutorial001_an_py39.py b/docs_src/cookie_param_models/tutorial001_an_py39.py
new file mode 100644
index 000000000..3d90c2007
--- /dev/null
+++ b/docs_src/cookie_param_models/tutorial001_an_py39.py
@@ -0,0 +1,17 @@
+from typing import Annotated, Union
+
+from fastapi import Cookie, FastAPI
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class Cookies(BaseModel):
+ session_id: str
+ fatebook_tracker: Union[str, None] = None
+ googall_tracker: Union[str, None] = None
+
+
+@app.get("/items/")
+async def read_items(cookies: Annotated[Cookies, Cookie()]):
+ return cookies
diff --git a/docs_src/cookie_param_models/tutorial001_py310.py b/docs_src/cookie_param_models/tutorial001_py310.py
new file mode 100644
index 000000000..7cdee5a92
--- /dev/null
+++ b/docs_src/cookie_param_models/tutorial001_py310.py
@@ -0,0 +1,15 @@
+from fastapi import Cookie, FastAPI
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class Cookies(BaseModel):
+ session_id: str
+ fatebook_tracker: str | None = None
+ googall_tracker: str | None = None
+
+
+@app.get("/items/")
+async def read_items(cookies: Cookies = Cookie()):
+ return cookies
diff --git a/docs_src/cookie_param_models/tutorial002.py b/docs_src/cookie_param_models/tutorial002.py
new file mode 100644
index 000000000..9679e890f
--- /dev/null
+++ b/docs_src/cookie_param_models/tutorial002.py
@@ -0,0 +1,19 @@
+from typing import Union
+
+from fastapi import Cookie, FastAPI
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class Cookies(BaseModel):
+ model_config = {"extra": "forbid"}
+
+ session_id: str
+ fatebook_tracker: Union[str, None] = None
+ googall_tracker: Union[str, None] = None
+
+
+@app.get("/items/")
+async def read_items(cookies: Cookies = Cookie()):
+ return cookies
diff --git a/docs_src/cookie_param_models/tutorial002_an.py b/docs_src/cookie_param_models/tutorial002_an.py
new file mode 100644
index 000000000..ce5644b7b
--- /dev/null
+++ b/docs_src/cookie_param_models/tutorial002_an.py
@@ -0,0 +1,20 @@
+from typing import Union
+
+from fastapi import Cookie, FastAPI
+from pydantic import BaseModel
+from typing_extensions import Annotated
+
+app = FastAPI()
+
+
+class Cookies(BaseModel):
+ model_config = {"extra": "forbid"}
+
+ session_id: str
+ fatebook_tracker: Union[str, None] = None
+ googall_tracker: Union[str, None] = None
+
+
+@app.get("/items/")
+async def read_items(cookies: Annotated[Cookies, Cookie()]):
+ return cookies
diff --git a/docs_src/cookie_param_models/tutorial002_an_py310.py b/docs_src/cookie_param_models/tutorial002_an_py310.py
new file mode 100644
index 000000000..7fa70fe92
--- /dev/null
+++ b/docs_src/cookie_param_models/tutorial002_an_py310.py
@@ -0,0 +1,19 @@
+from typing import Annotated
+
+from fastapi import Cookie, FastAPI
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class Cookies(BaseModel):
+ model_config = {"extra": "forbid"}
+
+ session_id: str
+ fatebook_tracker: str | None = None
+ googall_tracker: str | None = None
+
+
+@app.get("/items/")
+async def read_items(cookies: Annotated[Cookies, Cookie()]):
+ return cookies
diff --git a/docs_src/cookie_param_models/tutorial002_an_py39.py b/docs_src/cookie_param_models/tutorial002_an_py39.py
new file mode 100644
index 000000000..a906ce6a1
--- /dev/null
+++ b/docs_src/cookie_param_models/tutorial002_an_py39.py
@@ -0,0 +1,19 @@
+from typing import Annotated, Union
+
+from fastapi import Cookie, FastAPI
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class Cookies(BaseModel):
+ model_config = {"extra": "forbid"}
+
+ session_id: str
+ fatebook_tracker: Union[str, None] = None
+ googall_tracker: Union[str, None] = None
+
+
+@app.get("/items/")
+async def read_items(cookies: Annotated[Cookies, Cookie()]):
+ return cookies
diff --git a/docs_src/cookie_param_models/tutorial002_pv1.py b/docs_src/cookie_param_models/tutorial002_pv1.py
new file mode 100644
index 000000000..13f78b850
--- /dev/null
+++ b/docs_src/cookie_param_models/tutorial002_pv1.py
@@ -0,0 +1,20 @@
+from typing import Union
+
+from fastapi import Cookie, FastAPI
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class Cookies(BaseModel):
+ class Config:
+ extra = "forbid"
+
+ session_id: str
+ fatebook_tracker: Union[str, None] = None
+ googall_tracker: Union[str, None] = None
+
+
+@app.get("/items/")
+async def read_items(cookies: Cookies = Cookie()):
+ return cookies
diff --git a/docs_src/cookie_param_models/tutorial002_pv1_an.py b/docs_src/cookie_param_models/tutorial002_pv1_an.py
new file mode 100644
index 000000000..ddfda9b6f
--- /dev/null
+++ b/docs_src/cookie_param_models/tutorial002_pv1_an.py
@@ -0,0 +1,21 @@
+from typing import Union
+
+from fastapi import Cookie, FastAPI
+from pydantic import BaseModel
+from typing_extensions import Annotated
+
+app = FastAPI()
+
+
+class Cookies(BaseModel):
+ class Config:
+ extra = "forbid"
+
+ session_id: str
+ fatebook_tracker: Union[str, None] = None
+ googall_tracker: Union[str, None] = None
+
+
+@app.get("/items/")
+async def read_items(cookies: Annotated[Cookies, Cookie()]):
+ return cookies
diff --git a/docs_src/cookie_param_models/tutorial002_pv1_an_py310.py b/docs_src/cookie_param_models/tutorial002_pv1_an_py310.py
new file mode 100644
index 000000000..ac00360b6
--- /dev/null
+++ b/docs_src/cookie_param_models/tutorial002_pv1_an_py310.py
@@ -0,0 +1,20 @@
+from typing import Annotated
+
+from fastapi import Cookie, FastAPI
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class Cookies(BaseModel):
+ class Config:
+ extra = "forbid"
+
+ session_id: str
+ fatebook_tracker: str | None = None
+ googall_tracker: str | None = None
+
+
+@app.get("/items/")
+async def read_items(cookies: Annotated[Cookies, Cookie()]):
+ return cookies
diff --git a/docs_src/cookie_param_models/tutorial002_pv1_an_py39.py b/docs_src/cookie_param_models/tutorial002_pv1_an_py39.py
new file mode 100644
index 000000000..573caea4b
--- /dev/null
+++ b/docs_src/cookie_param_models/tutorial002_pv1_an_py39.py
@@ -0,0 +1,20 @@
+from typing import Annotated, Union
+
+from fastapi import Cookie, FastAPI
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class Cookies(BaseModel):
+ class Config:
+ extra = "forbid"
+
+ session_id: str
+ fatebook_tracker: Union[str, None] = None
+ googall_tracker: Union[str, None] = None
+
+
+@app.get("/items/")
+async def read_items(cookies: Annotated[Cookies, Cookie()]):
+ return cookies
diff --git a/docs_src/cookie_param_models/tutorial002_pv1_py310.py b/docs_src/cookie_param_models/tutorial002_pv1_py310.py
new file mode 100644
index 000000000..2c59aad12
--- /dev/null
+++ b/docs_src/cookie_param_models/tutorial002_pv1_py310.py
@@ -0,0 +1,18 @@
+from fastapi import Cookie, FastAPI
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class Cookies(BaseModel):
+ class Config:
+ extra = "forbid"
+
+ session_id: str
+ fatebook_tracker: str | None = None
+ googall_tracker: str | None = None
+
+
+@app.get("/items/")
+async def read_items(cookies: Cookies = Cookie()):
+ return cookies
diff --git a/docs_src/cookie_param_models/tutorial002_py310.py b/docs_src/cookie_param_models/tutorial002_py310.py
new file mode 100644
index 000000000..f011aa1af
--- /dev/null
+++ b/docs_src/cookie_param_models/tutorial002_py310.py
@@ -0,0 +1,17 @@
+from fastapi import Cookie, FastAPI
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class Cookies(BaseModel):
+ model_config = {"extra": "forbid"}
+
+ session_id: str
+ fatebook_tracker: str | None = None
+ googall_tracker: str | None = None
+
+
+@app.get("/items/")
+async def read_items(cookies: Cookies = Cookie()):
+ return cookies
diff --git a/docs_src/header_param_models/tutorial001.py b/docs_src/header_param_models/tutorial001.py
new file mode 100644
index 000000000..4caaba87b
--- /dev/null
+++ b/docs_src/header_param_models/tutorial001.py
@@ -0,0 +1,19 @@
+from typing import List, Union
+
+from fastapi import FastAPI, Header
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class CommonHeaders(BaseModel):
+ host: str
+ save_data: bool
+ if_modified_since: Union[str, None] = None
+ traceparent: Union[str, None] = None
+ x_tag: List[str] = []
+
+
+@app.get("/items/")
+async def read_items(headers: CommonHeaders = Header()):
+ return headers
diff --git a/docs_src/header_param_models/tutorial001_an.py b/docs_src/header_param_models/tutorial001_an.py
new file mode 100644
index 000000000..b55c6b56b
--- /dev/null
+++ b/docs_src/header_param_models/tutorial001_an.py
@@ -0,0 +1,20 @@
+from typing import List, Union
+
+from fastapi import FastAPI, Header
+from pydantic import BaseModel
+from typing_extensions import Annotated
+
+app = FastAPI()
+
+
+class CommonHeaders(BaseModel):
+ host: str
+ save_data: bool
+ if_modified_since: Union[str, None] = None
+ traceparent: Union[str, None] = None
+ x_tag: List[str] = []
+
+
+@app.get("/items/")
+async def read_items(headers: Annotated[CommonHeaders, Header()]):
+ return headers
diff --git a/docs_src/header_param_models/tutorial001_an_py310.py b/docs_src/header_param_models/tutorial001_an_py310.py
new file mode 100644
index 000000000..acfb6b9bf
--- /dev/null
+++ b/docs_src/header_param_models/tutorial001_an_py310.py
@@ -0,0 +1,19 @@
+from typing import Annotated
+
+from fastapi import FastAPI, Header
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class CommonHeaders(BaseModel):
+ host: str
+ save_data: bool
+ if_modified_since: str | None = None
+ traceparent: str | None = None
+ x_tag: list[str] = []
+
+
+@app.get("/items/")
+async def read_items(headers: Annotated[CommonHeaders, Header()]):
+ return headers
diff --git a/docs_src/header_param_models/tutorial001_an_py39.py b/docs_src/header_param_models/tutorial001_an_py39.py
new file mode 100644
index 000000000..51a5f94fc
--- /dev/null
+++ b/docs_src/header_param_models/tutorial001_an_py39.py
@@ -0,0 +1,19 @@
+from typing import Annotated, Union
+
+from fastapi import FastAPI, Header
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class CommonHeaders(BaseModel):
+ host: str
+ save_data: bool
+ if_modified_since: Union[str, None] = None
+ traceparent: Union[str, None] = None
+ x_tag: list[str] = []
+
+
+@app.get("/items/")
+async def read_items(headers: Annotated[CommonHeaders, Header()]):
+ return headers
diff --git a/docs_src/header_param_models/tutorial001_py310.py b/docs_src/header_param_models/tutorial001_py310.py
new file mode 100644
index 000000000..7239c64ce
--- /dev/null
+++ b/docs_src/header_param_models/tutorial001_py310.py
@@ -0,0 +1,17 @@
+from fastapi import FastAPI, Header
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class CommonHeaders(BaseModel):
+ host: str
+ save_data: bool
+ if_modified_since: str | None = None
+ traceparent: str | None = None
+ x_tag: list[str] = []
+
+
+@app.get("/items/")
+async def read_items(headers: CommonHeaders = Header()):
+ return headers
diff --git a/docs_src/header_param_models/tutorial001_py39.py b/docs_src/header_param_models/tutorial001_py39.py
new file mode 100644
index 000000000..4c1137813
--- /dev/null
+++ b/docs_src/header_param_models/tutorial001_py39.py
@@ -0,0 +1,19 @@
+from typing import Union
+
+from fastapi import FastAPI, Header
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class CommonHeaders(BaseModel):
+ host: str
+ save_data: bool
+ if_modified_since: Union[str, None] = None
+ traceparent: Union[str, None] = None
+ x_tag: list[str] = []
+
+
+@app.get("/items/")
+async def read_items(headers: CommonHeaders = Header()):
+ return headers
diff --git a/docs_src/header_param_models/tutorial002.py b/docs_src/header_param_models/tutorial002.py
new file mode 100644
index 000000000..3f9aac58d
--- /dev/null
+++ b/docs_src/header_param_models/tutorial002.py
@@ -0,0 +1,21 @@
+from typing import List, Union
+
+from fastapi import FastAPI, Header
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class CommonHeaders(BaseModel):
+ model_config = {"extra": "forbid"}
+
+ host: str
+ save_data: bool
+ if_modified_since: Union[str, None] = None
+ traceparent: Union[str, None] = None
+ x_tag: List[str] = []
+
+
+@app.get("/items/")
+async def read_items(headers: CommonHeaders = Header()):
+ return headers
diff --git a/docs_src/header_param_models/tutorial002_an.py b/docs_src/header_param_models/tutorial002_an.py
new file mode 100644
index 000000000..771135d77
--- /dev/null
+++ b/docs_src/header_param_models/tutorial002_an.py
@@ -0,0 +1,22 @@
+from typing import List, Union
+
+from fastapi import FastAPI, Header
+from pydantic import BaseModel
+from typing_extensions import Annotated
+
+app = FastAPI()
+
+
+class CommonHeaders(BaseModel):
+ model_config = {"extra": "forbid"}
+
+ host: str
+ save_data: bool
+ if_modified_since: Union[str, None] = None
+ traceparent: Union[str, None] = None
+ x_tag: List[str] = []
+
+
+@app.get("/items/")
+async def read_items(headers: Annotated[CommonHeaders, Header()]):
+ return headers
diff --git a/docs_src/header_param_models/tutorial002_an_py310.py b/docs_src/header_param_models/tutorial002_an_py310.py
new file mode 100644
index 000000000..e9535f045
--- /dev/null
+++ b/docs_src/header_param_models/tutorial002_an_py310.py
@@ -0,0 +1,21 @@
+from typing import Annotated
+
+from fastapi import FastAPI, Header
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class CommonHeaders(BaseModel):
+ model_config = {"extra": "forbid"}
+
+ host: str
+ save_data: bool
+ if_modified_since: str | None = None
+ traceparent: str | None = None
+ x_tag: list[str] = []
+
+
+@app.get("/items/")
+async def read_items(headers: Annotated[CommonHeaders, Header()]):
+ return headers
diff --git a/docs_src/header_param_models/tutorial002_an_py39.py b/docs_src/header_param_models/tutorial002_an_py39.py
new file mode 100644
index 000000000..ca5208c9d
--- /dev/null
+++ b/docs_src/header_param_models/tutorial002_an_py39.py
@@ -0,0 +1,21 @@
+from typing import Annotated, Union
+
+from fastapi import FastAPI, Header
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class CommonHeaders(BaseModel):
+ model_config = {"extra": "forbid"}
+
+ host: str
+ save_data: bool
+ if_modified_since: Union[str, None] = None
+ traceparent: Union[str, None] = None
+ x_tag: list[str] = []
+
+
+@app.get("/items/")
+async def read_items(headers: Annotated[CommonHeaders, Header()]):
+ return headers
diff --git a/docs_src/header_param_models/tutorial002_pv1.py b/docs_src/header_param_models/tutorial002_pv1.py
new file mode 100644
index 000000000..7e56cd993
--- /dev/null
+++ b/docs_src/header_param_models/tutorial002_pv1.py
@@ -0,0 +1,22 @@
+from typing import List, Union
+
+from fastapi import FastAPI, Header
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class CommonHeaders(BaseModel):
+ class Config:
+ extra = "forbid"
+
+ host: str
+ save_data: bool
+ if_modified_since: Union[str, None] = None
+ traceparent: Union[str, None] = None
+ x_tag: List[str] = []
+
+
+@app.get("/items/")
+async def read_items(headers: CommonHeaders = Header()):
+ return headers
diff --git a/docs_src/header_param_models/tutorial002_pv1_an.py b/docs_src/header_param_models/tutorial002_pv1_an.py
new file mode 100644
index 000000000..236778231
--- /dev/null
+++ b/docs_src/header_param_models/tutorial002_pv1_an.py
@@ -0,0 +1,23 @@
+from typing import List, Union
+
+from fastapi import FastAPI, Header
+from pydantic import BaseModel
+from typing_extensions import Annotated
+
+app = FastAPI()
+
+
+class CommonHeaders(BaseModel):
+ class Config:
+ extra = "forbid"
+
+ host: str
+ save_data: bool
+ if_modified_since: Union[str, None] = None
+ traceparent: Union[str, None] = None
+ x_tag: List[str] = []
+
+
+@app.get("/items/")
+async def read_items(headers: Annotated[CommonHeaders, Header()]):
+ return headers
diff --git a/docs_src/header_param_models/tutorial002_pv1_an_py310.py b/docs_src/header_param_models/tutorial002_pv1_an_py310.py
new file mode 100644
index 000000000..e99e24ea5
--- /dev/null
+++ b/docs_src/header_param_models/tutorial002_pv1_an_py310.py
@@ -0,0 +1,22 @@
+from typing import Annotated
+
+from fastapi import FastAPI, Header
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class CommonHeaders(BaseModel):
+ class Config:
+ extra = "forbid"
+
+ host: str
+ save_data: bool
+ if_modified_since: str | None = None
+ traceparent: str | None = None
+ x_tag: list[str] = []
+
+
+@app.get("/items/")
+async def read_items(headers: Annotated[CommonHeaders, Header()]):
+ return headers
diff --git a/docs_src/header_param_models/tutorial002_pv1_an_py39.py b/docs_src/header_param_models/tutorial002_pv1_an_py39.py
new file mode 100644
index 000000000..18398b726
--- /dev/null
+++ b/docs_src/header_param_models/tutorial002_pv1_an_py39.py
@@ -0,0 +1,22 @@
+from typing import Annotated, Union
+
+from fastapi import FastAPI, Header
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class CommonHeaders(BaseModel):
+ class Config:
+ extra = "forbid"
+
+ host: str
+ save_data: bool
+ if_modified_since: Union[str, None] = None
+ traceparent: Union[str, None] = None
+ x_tag: list[str] = []
+
+
+@app.get("/items/")
+async def read_items(headers: Annotated[CommonHeaders, Header()]):
+ return headers
diff --git a/docs_src/header_param_models/tutorial002_pv1_py310.py b/docs_src/header_param_models/tutorial002_pv1_py310.py
new file mode 100644
index 000000000..3dbff9d7b
--- /dev/null
+++ b/docs_src/header_param_models/tutorial002_pv1_py310.py
@@ -0,0 +1,20 @@
+from fastapi import FastAPI, Header
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class CommonHeaders(BaseModel):
+ class Config:
+ extra = "forbid"
+
+ host: str
+ save_data: bool
+ if_modified_since: str | None = None
+ traceparent: str | None = None
+ x_tag: list[str] = []
+
+
+@app.get("/items/")
+async def read_items(headers: CommonHeaders = Header()):
+ return headers
diff --git a/docs_src/header_param_models/tutorial002_pv1_py39.py b/docs_src/header_param_models/tutorial002_pv1_py39.py
new file mode 100644
index 000000000..86e19be0d
--- /dev/null
+++ b/docs_src/header_param_models/tutorial002_pv1_py39.py
@@ -0,0 +1,22 @@
+from typing import Union
+
+from fastapi import FastAPI, Header
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class CommonHeaders(BaseModel):
+ class Config:
+ extra = "forbid"
+
+ host: str
+ save_data: bool
+ if_modified_since: Union[str, None] = None
+ traceparent: Union[str, None] = None
+ x_tag: list[str] = []
+
+
+@app.get("/items/")
+async def read_items(headers: CommonHeaders = Header()):
+ return headers
diff --git a/docs_src/header_param_models/tutorial002_py310.py b/docs_src/header_param_models/tutorial002_py310.py
new file mode 100644
index 000000000..3d2296345
--- /dev/null
+++ b/docs_src/header_param_models/tutorial002_py310.py
@@ -0,0 +1,19 @@
+from fastapi import FastAPI, Header
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class CommonHeaders(BaseModel):
+ model_config = {"extra": "forbid"}
+
+ host: str
+ save_data: bool
+ if_modified_since: str | None = None
+ traceparent: str | None = None
+ x_tag: list[str] = []
+
+
+@app.get("/items/")
+async def read_items(headers: CommonHeaders = Header()):
+ return headers
diff --git a/docs_src/header_param_models/tutorial002_py39.py b/docs_src/header_param_models/tutorial002_py39.py
new file mode 100644
index 000000000..f8ce559a7
--- /dev/null
+++ b/docs_src/header_param_models/tutorial002_py39.py
@@ -0,0 +1,21 @@
+from typing import Union
+
+from fastapi import FastAPI, Header
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class CommonHeaders(BaseModel):
+ model_config = {"extra": "forbid"}
+
+ host: str
+ save_data: bool
+ if_modified_since: Union[str, None] = None
+ traceparent: Union[str, None] = None
+ x_tag: list[str] = []
+
+
+@app.get("/items/")
+async def read_items(headers: CommonHeaders = Header()):
+ return headers
diff --git a/docs_src/middleware/tutorial001.py b/docs_src/middleware/tutorial001.py
index 6bab3410a..e65a7dade 100644
--- a/docs_src/middleware/tutorial001.py
+++ b/docs_src/middleware/tutorial001.py
@@ -7,8 +7,8 @@ app = FastAPI()
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
- start_time = time.time()
+ start_time = time.perf_counter()
response = await call_next(request)
- process_time = time.time() - start_time
+ process_time = time.perf_counter() - start_time
response.headers["X-Process-Time"] = str(process_time)
return response
diff --git a/docs_src/nosql_databases/tutorial001.py b/docs_src/nosql_databases/tutorial001.py
deleted file mode 100644
index 91893e528..000000000
--- a/docs_src/nosql_databases/tutorial001.py
+++ /dev/null
@@ -1,53 +0,0 @@
-from typing import Union
-
-from couchbase import LOCKMODE_WAIT
-from couchbase.bucket import Bucket
-from couchbase.cluster import Cluster, PasswordAuthenticator
-from fastapi import FastAPI
-from pydantic import BaseModel
-
-USERPROFILE_DOC_TYPE = "userprofile"
-
-
-def get_bucket():
- cluster = Cluster(
- "couchbase://couchbasehost:8091?fetch_mutation_tokens=1&operation_timeout=30&n1ql_timeout=300"
- )
- authenticator = PasswordAuthenticator("username", "password")
- cluster.authenticate(authenticator)
- bucket: Bucket = cluster.open_bucket("bucket_name", lockmode=LOCKMODE_WAIT)
- bucket.timeout = 30
- bucket.n1ql_timeout = 300
- return bucket
-
-
-class User(BaseModel):
- username: str
- email: Union[str, None] = None
- full_name: Union[str, None] = None
- disabled: Union[bool, None] = None
-
-
-class UserInDB(User):
- type: str = USERPROFILE_DOC_TYPE
- hashed_password: str
-
-
-def get_user(bucket: Bucket, username: str):
- doc_id = f"userprofile::{username}"
- result = bucket.get(doc_id, quiet=True)
- if not result.value:
- return None
- user = UserInDB(**result.value)
- return user
-
-
-# FastAPI specific code
-app = FastAPI()
-
-
-@app.get("/users/{username}", response_model=User)
-def read_user(username: str):
- bucket = get_bucket()
- user = get_user(bucket=bucket, username=username)
- return user
diff --git a/docs_src/path_params_numeric_validations/tutorial006.py b/docs_src/path_params_numeric_validations/tutorial006.py
index 0ea32694a..f07629aa0 100644
--- a/docs_src/path_params_numeric_validations/tutorial006.py
+++ b/docs_src/path_params_numeric_validations/tutorial006.py
@@ -13,4 +13,6 @@ async def read_items(
results = {"item_id": item_id}
if q:
results.update({"q": q})
+ if size:
+ results.update({"size": size})
return results
diff --git a/docs_src/path_params_numeric_validations/tutorial006_an.py b/docs_src/path_params_numeric_validations/tutorial006_an.py
index 22a143623..ac4732573 100644
--- a/docs_src/path_params_numeric_validations/tutorial006_an.py
+++ b/docs_src/path_params_numeric_validations/tutorial006_an.py
@@ -14,4 +14,6 @@ async def read_items(
results = {"item_id": item_id}
if q:
results.update({"q": q})
+ if size:
+ results.update({"size": size})
return results
diff --git a/docs_src/path_params_numeric_validations/tutorial006_an_py39.py b/docs_src/path_params_numeric_validations/tutorial006_an_py39.py
index 804751893..426ec3776 100644
--- a/docs_src/path_params_numeric_validations/tutorial006_an_py39.py
+++ b/docs_src/path_params_numeric_validations/tutorial006_an_py39.py
@@ -15,4 +15,6 @@ async def read_items(
results = {"item_id": item_id}
if q:
results.update({"q": q})
+ if size:
+ results.update({"size": size})
return results
diff --git a/docs_src/query_param_models/tutorial001.py b/docs_src/query_param_models/tutorial001.py
new file mode 100644
index 000000000..0c0ab315e
--- /dev/null
+++ b/docs_src/query_param_models/tutorial001.py
@@ -0,0 +1,19 @@
+from typing import List
+
+from fastapi import FastAPI, Query
+from pydantic import BaseModel, Field
+from typing_extensions import Literal
+
+app = FastAPI()
+
+
+class FilterParams(BaseModel):
+ limit: int = Field(100, gt=0, le=100)
+ offset: int = Field(0, ge=0)
+ order_by: Literal["created_at", "updated_at"] = "created_at"
+ tags: List[str] = []
+
+
+@app.get("/items/")
+async def read_items(filter_query: FilterParams = Query()):
+ return filter_query
diff --git a/docs_src/query_param_models/tutorial001_an.py b/docs_src/query_param_models/tutorial001_an.py
new file mode 100644
index 000000000..28375057c
--- /dev/null
+++ b/docs_src/query_param_models/tutorial001_an.py
@@ -0,0 +1,19 @@
+from typing import List
+
+from fastapi import FastAPI, Query
+from pydantic import BaseModel, Field
+from typing_extensions import Annotated, Literal
+
+app = FastAPI()
+
+
+class FilterParams(BaseModel):
+ limit: int = Field(100, gt=0, le=100)
+ offset: int = Field(0, ge=0)
+ order_by: Literal["created_at", "updated_at"] = "created_at"
+ tags: List[str] = []
+
+
+@app.get("/items/")
+async def read_items(filter_query: Annotated[FilterParams, Query()]):
+ return filter_query
diff --git a/docs_src/query_param_models/tutorial001_an_py310.py b/docs_src/query_param_models/tutorial001_an_py310.py
new file mode 100644
index 000000000..71427acae
--- /dev/null
+++ b/docs_src/query_param_models/tutorial001_an_py310.py
@@ -0,0 +1,18 @@
+from typing import Annotated, Literal
+
+from fastapi import FastAPI, Query
+from pydantic import BaseModel, Field
+
+app = FastAPI()
+
+
+class FilterParams(BaseModel):
+ limit: int = Field(100, gt=0, le=100)
+ offset: int = Field(0, ge=0)
+ order_by: Literal["created_at", "updated_at"] = "created_at"
+ tags: list[str] = []
+
+
+@app.get("/items/")
+async def read_items(filter_query: Annotated[FilterParams, Query()]):
+ return filter_query
diff --git a/docs_src/query_param_models/tutorial001_an_py39.py b/docs_src/query_param_models/tutorial001_an_py39.py
new file mode 100644
index 000000000..ba690d3e3
--- /dev/null
+++ b/docs_src/query_param_models/tutorial001_an_py39.py
@@ -0,0 +1,17 @@
+from fastapi import FastAPI, Query
+from pydantic import BaseModel, Field
+from typing_extensions import Annotated, Literal
+
+app = FastAPI()
+
+
+class FilterParams(BaseModel):
+ limit: int = Field(100, gt=0, le=100)
+ offset: int = Field(0, ge=0)
+ order_by: Literal["created_at", "updated_at"] = "created_at"
+ tags: list[str] = []
+
+
+@app.get("/items/")
+async def read_items(filter_query: Annotated[FilterParams, Query()]):
+ return filter_query
diff --git a/docs_src/query_param_models/tutorial001_py310.py b/docs_src/query_param_models/tutorial001_py310.py
new file mode 100644
index 000000000..3ebf9f4d7
--- /dev/null
+++ b/docs_src/query_param_models/tutorial001_py310.py
@@ -0,0 +1,18 @@
+from typing import Literal
+
+from fastapi import FastAPI, Query
+from pydantic import BaseModel, Field
+
+app = FastAPI()
+
+
+class FilterParams(BaseModel):
+ limit: int = Field(100, gt=0, le=100)
+ offset: int = Field(0, ge=0)
+ order_by: Literal["created_at", "updated_at"] = "created_at"
+ tags: list[str] = []
+
+
+@app.get("/items/")
+async def read_items(filter_query: FilterParams = Query()):
+ return filter_query
diff --git a/docs_src/query_param_models/tutorial001_py39.py b/docs_src/query_param_models/tutorial001_py39.py
new file mode 100644
index 000000000..54b52a054
--- /dev/null
+++ b/docs_src/query_param_models/tutorial001_py39.py
@@ -0,0 +1,17 @@
+from fastapi import FastAPI, Query
+from pydantic import BaseModel, Field
+from typing_extensions import Literal
+
+app = FastAPI()
+
+
+class FilterParams(BaseModel):
+ limit: int = Field(100, gt=0, le=100)
+ offset: int = Field(0, ge=0)
+ order_by: Literal["created_at", "updated_at"] = "created_at"
+ tags: list[str] = []
+
+
+@app.get("/items/")
+async def read_items(filter_query: FilterParams = Query()):
+ return filter_query
diff --git a/docs_src/query_param_models/tutorial002.py b/docs_src/query_param_models/tutorial002.py
new file mode 100644
index 000000000..1633bc464
--- /dev/null
+++ b/docs_src/query_param_models/tutorial002.py
@@ -0,0 +1,21 @@
+from typing import List
+
+from fastapi import FastAPI, Query
+from pydantic import BaseModel, Field
+from typing_extensions import Literal
+
+app = FastAPI()
+
+
+class FilterParams(BaseModel):
+ model_config = {"extra": "forbid"}
+
+ limit: int = Field(100, gt=0, le=100)
+ offset: int = Field(0, ge=0)
+ order_by: Literal["created_at", "updated_at"] = "created_at"
+ tags: List[str] = []
+
+
+@app.get("/items/")
+async def read_items(filter_query: FilterParams = Query()):
+ return filter_query
diff --git a/docs_src/query_param_models/tutorial002_an.py b/docs_src/query_param_models/tutorial002_an.py
new file mode 100644
index 000000000..69705d4b4
--- /dev/null
+++ b/docs_src/query_param_models/tutorial002_an.py
@@ -0,0 +1,21 @@
+from typing import List
+
+from fastapi import FastAPI, Query
+from pydantic import BaseModel, Field
+from typing_extensions import Annotated, Literal
+
+app = FastAPI()
+
+
+class FilterParams(BaseModel):
+ model_config = {"extra": "forbid"}
+
+ limit: int = Field(100, gt=0, le=100)
+ offset: int = Field(0, ge=0)
+ order_by: Literal["created_at", "updated_at"] = "created_at"
+ tags: List[str] = []
+
+
+@app.get("/items/")
+async def read_items(filter_query: Annotated[FilterParams, Query()]):
+ return filter_query
diff --git a/docs_src/query_param_models/tutorial002_an_py310.py b/docs_src/query_param_models/tutorial002_an_py310.py
new file mode 100644
index 000000000..975956502
--- /dev/null
+++ b/docs_src/query_param_models/tutorial002_an_py310.py
@@ -0,0 +1,20 @@
+from typing import Annotated, Literal
+
+from fastapi import FastAPI, Query
+from pydantic import BaseModel, Field
+
+app = FastAPI()
+
+
+class FilterParams(BaseModel):
+ model_config = {"extra": "forbid"}
+
+ limit: int = Field(100, gt=0, le=100)
+ offset: int = Field(0, ge=0)
+ order_by: Literal["created_at", "updated_at"] = "created_at"
+ tags: list[str] = []
+
+
+@app.get("/items/")
+async def read_items(filter_query: Annotated[FilterParams, Query()]):
+ return filter_query
diff --git a/docs_src/query_param_models/tutorial002_an_py39.py b/docs_src/query_param_models/tutorial002_an_py39.py
new file mode 100644
index 000000000..2d4c1a62b
--- /dev/null
+++ b/docs_src/query_param_models/tutorial002_an_py39.py
@@ -0,0 +1,19 @@
+from fastapi import FastAPI, Query
+from pydantic import BaseModel, Field
+from typing_extensions import Annotated, Literal
+
+app = FastAPI()
+
+
+class FilterParams(BaseModel):
+ model_config = {"extra": "forbid"}
+
+ limit: int = Field(100, gt=0, le=100)
+ offset: int = Field(0, ge=0)
+ order_by: Literal["created_at", "updated_at"] = "created_at"
+ tags: list[str] = []
+
+
+@app.get("/items/")
+async def read_items(filter_query: Annotated[FilterParams, Query()]):
+ return filter_query
diff --git a/docs_src/query_param_models/tutorial002_pv1.py b/docs_src/query_param_models/tutorial002_pv1.py
new file mode 100644
index 000000000..71ccd961d
--- /dev/null
+++ b/docs_src/query_param_models/tutorial002_pv1.py
@@ -0,0 +1,22 @@
+from typing import List
+
+from fastapi import FastAPI, Query
+from pydantic import BaseModel, Field
+from typing_extensions import Literal
+
+app = FastAPI()
+
+
+class FilterParams(BaseModel):
+ class Config:
+ extra = "forbid"
+
+ limit: int = Field(100, gt=0, le=100)
+ offset: int = Field(0, ge=0)
+ order_by: Literal["created_at", "updated_at"] = "created_at"
+ tags: List[str] = []
+
+
+@app.get("/items/")
+async def read_items(filter_query: FilterParams = Query()):
+ return filter_query
diff --git a/docs_src/query_param_models/tutorial002_pv1_an.py b/docs_src/query_param_models/tutorial002_pv1_an.py
new file mode 100644
index 000000000..1dd29157a
--- /dev/null
+++ b/docs_src/query_param_models/tutorial002_pv1_an.py
@@ -0,0 +1,22 @@
+from typing import List
+
+from fastapi import FastAPI, Query
+from pydantic import BaseModel, Field
+from typing_extensions import Annotated, Literal
+
+app = FastAPI()
+
+
+class FilterParams(BaseModel):
+ class Config:
+ extra = "forbid"
+
+ limit: int = Field(100, gt=0, le=100)
+ offset: int = Field(0, ge=0)
+ order_by: Literal["created_at", "updated_at"] = "created_at"
+ tags: List[str] = []
+
+
+@app.get("/items/")
+async def read_items(filter_query: Annotated[FilterParams, Query()]):
+ return filter_query
diff --git a/docs_src/query_param_models/tutorial002_pv1_an_py310.py b/docs_src/query_param_models/tutorial002_pv1_an_py310.py
new file mode 100644
index 000000000..d635aae88
--- /dev/null
+++ b/docs_src/query_param_models/tutorial002_pv1_an_py310.py
@@ -0,0 +1,21 @@
+from typing import Annotated, Literal
+
+from fastapi import FastAPI, Query
+from pydantic import BaseModel, Field
+
+app = FastAPI()
+
+
+class FilterParams(BaseModel):
+ class Config:
+ extra = "forbid"
+
+ limit: int = Field(100, gt=0, le=100)
+ offset: int = Field(0, ge=0)
+ order_by: Literal["created_at", "updated_at"] = "created_at"
+ tags: list[str] = []
+
+
+@app.get("/items/")
+async def read_items(filter_query: Annotated[FilterParams, Query()]):
+ return filter_query
diff --git a/docs_src/query_param_models/tutorial002_pv1_an_py39.py b/docs_src/query_param_models/tutorial002_pv1_an_py39.py
new file mode 100644
index 000000000..494fef11f
--- /dev/null
+++ b/docs_src/query_param_models/tutorial002_pv1_an_py39.py
@@ -0,0 +1,20 @@
+from fastapi import FastAPI, Query
+from pydantic import BaseModel, Field
+from typing_extensions import Annotated, Literal
+
+app = FastAPI()
+
+
+class FilterParams(BaseModel):
+ class Config:
+ extra = "forbid"
+
+ limit: int = Field(100, gt=0, le=100)
+ offset: int = Field(0, ge=0)
+ order_by: Literal["created_at", "updated_at"] = "created_at"
+ tags: list[str] = []
+
+
+@app.get("/items/")
+async def read_items(filter_query: Annotated[FilterParams, Query()]):
+ return filter_query
diff --git a/docs_src/query_param_models/tutorial002_pv1_py310.py b/docs_src/query_param_models/tutorial002_pv1_py310.py
new file mode 100644
index 000000000..9ffdeefc0
--- /dev/null
+++ b/docs_src/query_param_models/tutorial002_pv1_py310.py
@@ -0,0 +1,21 @@
+from typing import Literal
+
+from fastapi import FastAPI, Query
+from pydantic import BaseModel, Field
+
+app = FastAPI()
+
+
+class FilterParams(BaseModel):
+ class Config:
+ extra = "forbid"
+
+ limit: int = Field(100, gt=0, le=100)
+ offset: int = Field(0, ge=0)
+ order_by: Literal["created_at", "updated_at"] = "created_at"
+ tags: list[str] = []
+
+
+@app.get("/items/")
+async def read_items(filter_query: FilterParams = Query()):
+ return filter_query
diff --git a/docs_src/query_param_models/tutorial002_pv1_py39.py b/docs_src/query_param_models/tutorial002_pv1_py39.py
new file mode 100644
index 000000000..7fa456a79
--- /dev/null
+++ b/docs_src/query_param_models/tutorial002_pv1_py39.py
@@ -0,0 +1,20 @@
+from fastapi import FastAPI, Query
+from pydantic import BaseModel, Field
+from typing_extensions import Literal
+
+app = FastAPI()
+
+
+class FilterParams(BaseModel):
+ class Config:
+ extra = "forbid"
+
+ limit: int = Field(100, gt=0, le=100)
+ offset: int = Field(0, ge=0)
+ order_by: Literal["created_at", "updated_at"] = "created_at"
+ tags: list[str] = []
+
+
+@app.get("/items/")
+async def read_items(filter_query: FilterParams = Query()):
+ return filter_query
diff --git a/docs_src/query_param_models/tutorial002_py310.py b/docs_src/query_param_models/tutorial002_py310.py
new file mode 100644
index 000000000..6ec418499
--- /dev/null
+++ b/docs_src/query_param_models/tutorial002_py310.py
@@ -0,0 +1,20 @@
+from typing import Literal
+
+from fastapi import FastAPI, Query
+from pydantic import BaseModel, Field
+
+app = FastAPI()
+
+
+class FilterParams(BaseModel):
+ model_config = {"extra": "forbid"}
+
+ limit: int = Field(100, gt=0, le=100)
+ offset: int = Field(0, ge=0)
+ order_by: Literal["created_at", "updated_at"] = "created_at"
+ tags: list[str] = []
+
+
+@app.get("/items/")
+async def read_items(filter_query: FilterParams = Query()):
+ return filter_query
diff --git a/docs_src/query_param_models/tutorial002_py39.py b/docs_src/query_param_models/tutorial002_py39.py
new file mode 100644
index 000000000..f9bba028c
--- /dev/null
+++ b/docs_src/query_param_models/tutorial002_py39.py
@@ -0,0 +1,19 @@
+from fastapi import FastAPI, Query
+from pydantic import BaseModel, Field
+from typing_extensions import Literal
+
+app = FastAPI()
+
+
+class FilterParams(BaseModel):
+ model_config = {"extra": "forbid"}
+
+ limit: int = Field(100, gt=0, le=100)
+ offset: int = Field(0, ge=0)
+ order_by: Literal["created_at", "updated_at"] = "created_at"
+ tags: list[str] = []
+
+
+@app.get("/items/")
+async def read_items(filter_query: FilterParams = Query()):
+ return filter_query
diff --git a/docs_src/query_params_str_validations/tutorial006d.py b/docs_src/query_params_str_validations/tutorial006d.py
index 42c5bf4eb..a8d69c889 100644
--- a/docs_src/query_params_str_validations/tutorial006d.py
+++ b/docs_src/query_params_str_validations/tutorial006d.py
@@ -1,11 +1,10 @@
from fastapi import FastAPI, Query
-from pydantic import Required
app = FastAPI()
@app.get("/items/")
-async def read_items(q: str = Query(default=Required, min_length=3)):
+async def read_items(q: str = Query(default=..., min_length=3)):
results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
if q:
results.update({"q": q})
diff --git a/docs_src/query_params_str_validations/tutorial006d_an.py b/docs_src/query_params_str_validations/tutorial006d_an.py
index bc8283e15..ea3b02583 100644
--- a/docs_src/query_params_str_validations/tutorial006d_an.py
+++ b/docs_src/query_params_str_validations/tutorial006d_an.py
@@ -1,12 +1,11 @@
from fastapi import FastAPI, Query
-from pydantic import Required
from typing_extensions import Annotated
app = FastAPI()
@app.get("/items/")
-async def read_items(q: Annotated[str, Query(min_length=3)] = Required):
+async def read_items(q: Annotated[str, Query(min_length=3)] = ...):
results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
if q:
results.update({"q": q})
diff --git a/docs_src/query_params_str_validations/tutorial006d_an_py39.py b/docs_src/query_params_str_validations/tutorial006d_an_py39.py
index 035d9e3bd..687a9f544 100644
--- a/docs_src/query_params_str_validations/tutorial006d_an_py39.py
+++ b/docs_src/query_params_str_validations/tutorial006d_an_py39.py
@@ -1,13 +1,12 @@
from typing import Annotated
from fastapi import FastAPI, Query
-from pydantic import Required
app = FastAPI()
@app.get("/items/")
-async def read_items(q: Annotated[str, Query(min_length=3)] = Required):
+async def read_items(q: Annotated[str, Query(min_length=3)] = ...):
results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
if q:
results.update({"q": q})
diff --git a/docs_src/request_form_models/tutorial001.py b/docs_src/request_form_models/tutorial001.py
new file mode 100644
index 000000000..98feff0b9
--- /dev/null
+++ b/docs_src/request_form_models/tutorial001.py
@@ -0,0 +1,14 @@
+from fastapi import FastAPI, Form
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class FormData(BaseModel):
+ username: str
+ password: str
+
+
+@app.post("/login/")
+async def login(data: FormData = Form()):
+ return data
diff --git a/docs_src/request_form_models/tutorial001_an.py b/docs_src/request_form_models/tutorial001_an.py
new file mode 100644
index 000000000..30483d445
--- /dev/null
+++ b/docs_src/request_form_models/tutorial001_an.py
@@ -0,0 +1,15 @@
+from fastapi import FastAPI, Form
+from pydantic import BaseModel
+from typing_extensions import Annotated
+
+app = FastAPI()
+
+
+class FormData(BaseModel):
+ username: str
+ password: str
+
+
+@app.post("/login/")
+async def login(data: Annotated[FormData, Form()]):
+ return data
diff --git a/docs_src/request_form_models/tutorial001_an_py39.py b/docs_src/request_form_models/tutorial001_an_py39.py
new file mode 100644
index 000000000..7cc81aae9
--- /dev/null
+++ b/docs_src/request_form_models/tutorial001_an_py39.py
@@ -0,0 +1,16 @@
+from typing import Annotated
+
+from fastapi import FastAPI, Form
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class FormData(BaseModel):
+ username: str
+ password: str
+
+
+@app.post("/login/")
+async def login(data: Annotated[FormData, Form()]):
+ return data
diff --git a/docs_src/request_form_models/tutorial002.py b/docs_src/request_form_models/tutorial002.py
new file mode 100644
index 000000000..59b329e8d
--- /dev/null
+++ b/docs_src/request_form_models/tutorial002.py
@@ -0,0 +1,15 @@
+from fastapi import FastAPI, Form
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class FormData(BaseModel):
+ username: str
+ password: str
+ model_config = {"extra": "forbid"}
+
+
+@app.post("/login/")
+async def login(data: FormData = Form()):
+ return data
diff --git a/docs_src/request_form_models/tutorial002_an.py b/docs_src/request_form_models/tutorial002_an.py
new file mode 100644
index 000000000..bcb022795
--- /dev/null
+++ b/docs_src/request_form_models/tutorial002_an.py
@@ -0,0 +1,16 @@
+from fastapi import FastAPI, Form
+from pydantic import BaseModel
+from typing_extensions import Annotated
+
+app = FastAPI()
+
+
+class FormData(BaseModel):
+ username: str
+ password: str
+ model_config = {"extra": "forbid"}
+
+
+@app.post("/login/")
+async def login(data: Annotated[FormData, Form()]):
+ return data
diff --git a/docs_src/request_form_models/tutorial002_an_py39.py b/docs_src/request_form_models/tutorial002_an_py39.py
new file mode 100644
index 000000000..3004e0852
--- /dev/null
+++ b/docs_src/request_form_models/tutorial002_an_py39.py
@@ -0,0 +1,17 @@
+from typing import Annotated
+
+from fastapi import FastAPI, Form
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class FormData(BaseModel):
+ username: str
+ password: str
+ model_config = {"extra": "forbid"}
+
+
+@app.post("/login/")
+async def login(data: Annotated[FormData, Form()]):
+ return data
diff --git a/docs_src/request_form_models/tutorial002_pv1.py b/docs_src/request_form_models/tutorial002_pv1.py
new file mode 100644
index 000000000..d5f7db2a6
--- /dev/null
+++ b/docs_src/request_form_models/tutorial002_pv1.py
@@ -0,0 +1,17 @@
+from fastapi import FastAPI, Form
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class FormData(BaseModel):
+ username: str
+ password: str
+
+ class Config:
+ extra = "forbid"
+
+
+@app.post("/login/")
+async def login(data: FormData = Form()):
+ return data
diff --git a/docs_src/request_form_models/tutorial002_pv1_an.py b/docs_src/request_form_models/tutorial002_pv1_an.py
new file mode 100644
index 000000000..fe9dbc344
--- /dev/null
+++ b/docs_src/request_form_models/tutorial002_pv1_an.py
@@ -0,0 +1,18 @@
+from fastapi import FastAPI, Form
+from pydantic import BaseModel
+from typing_extensions import Annotated
+
+app = FastAPI()
+
+
+class FormData(BaseModel):
+ username: str
+ password: str
+
+ class Config:
+ extra = "forbid"
+
+
+@app.post("/login/")
+async def login(data: Annotated[FormData, Form()]):
+ return data
diff --git a/docs_src/request_form_models/tutorial002_pv1_an_py39.py b/docs_src/request_form_models/tutorial002_pv1_an_py39.py
new file mode 100644
index 000000000..942d5d411
--- /dev/null
+++ b/docs_src/request_form_models/tutorial002_pv1_an_py39.py
@@ -0,0 +1,19 @@
+from typing import Annotated
+
+from fastapi import FastAPI, Form
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class FormData(BaseModel):
+ username: str
+ password: str
+
+ class Config:
+ extra = "forbid"
+
+
+@app.post("/login/")
+async def login(data: Annotated[FormData, Form()]):
+ return data
diff --git a/docs_src/sql_databases/sql_app/alt_main.py b/docs_src/sql_databases/sql_app/alt_main.py
deleted file mode 100644
index f7206bcb4..000000000
--- a/docs_src/sql_databases/sql_app/alt_main.py
+++ /dev/null
@@ -1,62 +0,0 @@
-from typing import List
-
-from fastapi import Depends, FastAPI, HTTPException, Request, Response
-from sqlalchemy.orm import Session
-
-from . import crud, models, schemas
-from .database import SessionLocal, engine
-
-models.Base.metadata.create_all(bind=engine)
-
-app = FastAPI()
-
-
-@app.middleware("http")
-async def db_session_middleware(request: Request, call_next):
- response = Response("Internal server error", status_code=500)
- try:
- request.state.db = SessionLocal()
- response = await call_next(request)
- finally:
- request.state.db.close()
- return response
-
-
-# Dependency
-def get_db(request: Request):
- return request.state.db
-
-
-@app.post("/users/", response_model=schemas.User)
-def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)):
- db_user = crud.get_user_by_email(db, email=user.email)
- if db_user:
- raise HTTPException(status_code=400, detail="Email already registered")
- return crud.create_user(db=db, user=user)
-
-
-@app.get("/users/", response_model=List[schemas.User])
-def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
- users = crud.get_users(db, skip=skip, limit=limit)
- return users
-
-
-@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)
- if db_user is None:
- raise HTTPException(status_code=404, detail="User not found")
- return db_user
-
-
-@app.post("/users/{user_id}/items/", response_model=schemas.Item)
-def create_item_for_user(
- user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db)
-):
- return crud.create_user_item(db=db, item=item, user_id=user_id)
-
-
-@app.get("/items/", response_model=List[schemas.Item])
-def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
- items = crud.get_items(db, skip=skip, limit=limit)
- return items
diff --git a/docs_src/sql_databases/sql_app/crud.py b/docs_src/sql_databases/sql_app/crud.py
deleted file mode 100644
index 679acdb5c..000000000
--- a/docs_src/sql_databases/sql_app/crud.py
+++ /dev/null
@@ -1,36 +0,0 @@
-from sqlalchemy.orm import Session
-
-from . import models, schemas
-
-
-def get_user(db: Session, user_id: int):
- return db.query(models.User).filter(models.User.id == user_id).first()
-
-
-def get_user_by_email(db: Session, email: str):
- return db.query(models.User).filter(models.User.email == email).first()
-
-
-def get_users(db: Session, skip: int = 0, limit: int = 100):
- return db.query(models.User).offset(skip).limit(limit).all()
-
-
-def create_user(db: Session, user: schemas.UserCreate):
- fake_hashed_password = user.password + "notreallyhashed"
- db_user = models.User(email=user.email, hashed_password=fake_hashed_password)
- db.add(db_user)
- db.commit()
- db.refresh(db_user)
- return db_user
-
-
-def get_items(db: Session, skip: int = 0, limit: int = 100):
- return db.query(models.Item).offset(skip).limit(limit).all()
-
-
-def create_user_item(db: Session, item: schemas.ItemCreate, user_id: int):
- db_item = models.Item(**item.dict(), owner_id=user_id)
- db.add(db_item)
- db.commit()
- db.refresh(db_item)
- return db_item
diff --git a/docs_src/sql_databases/sql_app/database.py b/docs_src/sql_databases/sql_app/database.py
deleted file mode 100644
index 45a8b9f69..000000000
--- a/docs_src/sql_databases/sql_app/database.py
+++ /dev/null
@@ -1,13 +0,0 @@
-from sqlalchemy import create_engine
-from sqlalchemy.ext.declarative import declarative_base
-from sqlalchemy.orm import sessionmaker
-
-SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db"
-# SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db"
-
-engine = create_engine(
- SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
-)
-SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
-
-Base = declarative_base()
diff --git a/docs_src/sql_databases/sql_app/main.py b/docs_src/sql_databases/sql_app/main.py
deleted file mode 100644
index e7508c59d..000000000
--- a/docs_src/sql_databases/sql_app/main.py
+++ /dev/null
@@ -1,55 +0,0 @@
-from typing import List
-
-from fastapi import Depends, FastAPI, HTTPException
-from sqlalchemy.orm import Session
-
-from . import crud, models, schemas
-from .database import SessionLocal, engine
-
-models.Base.metadata.create_all(bind=engine)
-
-app = FastAPI()
-
-
-# Dependency
-def get_db():
- db = SessionLocal()
- try:
- yield db
- finally:
- db.close()
-
-
-@app.post("/users/", response_model=schemas.User)
-def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)):
- db_user = crud.get_user_by_email(db, email=user.email)
- if db_user:
- raise HTTPException(status_code=400, detail="Email already registered")
- return crud.create_user(db=db, user=user)
-
-
-@app.get("/users/", response_model=List[schemas.User])
-def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
- users = crud.get_users(db, skip=skip, limit=limit)
- return users
-
-
-@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)
- if db_user is None:
- raise HTTPException(status_code=404, detail="User not found")
- return db_user
-
-
-@app.post("/users/{user_id}/items/", response_model=schemas.Item)
-def create_item_for_user(
- user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db)
-):
- return crud.create_user_item(db=db, item=item, user_id=user_id)
-
-
-@app.get("/items/", response_model=List[schemas.Item])
-def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
- items = crud.get_items(db, skip=skip, limit=limit)
- return items
diff --git a/docs_src/sql_databases/sql_app/models.py b/docs_src/sql_databases/sql_app/models.py
deleted file mode 100644
index 09ae2a807..000000000
--- a/docs_src/sql_databases/sql_app/models.py
+++ /dev/null
@@ -1,26 +0,0 @@
-from sqlalchemy import Boolean, Column, ForeignKey, Integer, String
-from sqlalchemy.orm import relationship
-
-from .database import Base
-
-
-class User(Base):
- __tablename__ = "users"
-
- id = Column(Integer, primary_key=True)
- email = Column(String, unique=True, index=True)
- hashed_password = Column(String)
- is_active = Column(Boolean, default=True)
-
- items = relationship("Item", back_populates="owner")
-
-
-class Item(Base):
- __tablename__ = "items"
-
- id = Column(Integer, primary_key=True)
- title = Column(String, index=True)
- description = Column(String, index=True)
- owner_id = Column(Integer, ForeignKey("users.id"))
-
- owner = relationship("User", back_populates="items")
diff --git a/docs_src/sql_databases/sql_app/schemas.py b/docs_src/sql_databases/sql_app/schemas.py
deleted file mode 100644
index c49beba88..000000000
--- a/docs_src/sql_databases/sql_app/schemas.py
+++ /dev/null
@@ -1,37 +0,0 @@
-from typing import List, Union
-
-from pydantic import BaseModel
-
-
-class ItemBase(BaseModel):
- title: str
- description: Union[str, None] = None
-
-
-class ItemCreate(ItemBase):
- pass
-
-
-class Item(ItemBase):
- id: int
- owner_id: int
-
- class Config:
- orm_mode = True
-
-
-class UserBase(BaseModel):
- email: str
-
-
-class UserCreate(UserBase):
- password: str
-
-
-class User(UserBase):
- id: int
- is_active: bool
- items: List[Item] = []
-
- class Config:
- orm_mode = True
diff --git a/docs_src/sql_databases/sql_app/tests/test_sql_app.py b/docs_src/sql_databases/sql_app/tests/test_sql_app.py
deleted file mode 100644
index 5f55add0a..000000000
--- a/docs_src/sql_databases/sql_app/tests/test_sql_app.py
+++ /dev/null
@@ -1,50 +0,0 @@
-from fastapi.testclient import TestClient
-from sqlalchemy import create_engine
-from sqlalchemy.orm import sessionmaker
-from sqlalchemy.pool import StaticPool
-
-from ..database import Base
-from ..main import app, get_db
-
-SQLALCHEMY_DATABASE_URL = "sqlite://"
-
-engine = create_engine(
- SQLALCHEMY_DATABASE_URL,
- connect_args={"check_same_thread": False},
- poolclass=StaticPool,
-)
-TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
-
-
-Base.metadata.create_all(bind=engine)
-
-
-def override_get_db():
- try:
- db = TestingSessionLocal()
- yield db
- finally:
- db.close()
-
-
-app.dependency_overrides[get_db] = override_get_db
-
-client = TestClient(app)
-
-
-def test_create_user():
- response = client.post(
- "/users/",
- json={"email": "deadpool@example.com", "password": "chimichangas4life"},
- )
- assert response.status_code == 200, response.text
- data = response.json()
- assert data["email"] == "deadpool@example.com"
- assert "id" in data
- user_id = data["id"]
-
- response = client.get(f"/users/{user_id}")
- assert response.status_code == 200, response.text
- data = response.json()
- assert data["email"] == "deadpool@example.com"
- assert data["id"] == user_id
diff --git a/docs_src/sql_databases/sql_app_py310/alt_main.py b/docs_src/sql_databases/sql_app_py310/alt_main.py
deleted file mode 100644
index 5de88ec3a..000000000
--- a/docs_src/sql_databases/sql_app_py310/alt_main.py
+++ /dev/null
@@ -1,60 +0,0 @@
-from fastapi import Depends, FastAPI, HTTPException, Request, Response
-from sqlalchemy.orm import Session
-
-from . import crud, models, schemas
-from .database import SessionLocal, engine
-
-models.Base.metadata.create_all(bind=engine)
-
-app = FastAPI()
-
-
-@app.middleware("http")
-async def db_session_middleware(request: Request, call_next):
- response = Response("Internal server error", status_code=500)
- try:
- request.state.db = SessionLocal()
- response = await call_next(request)
- finally:
- request.state.db.close()
- return response
-
-
-# Dependency
-def get_db(request: Request):
- return request.state.db
-
-
-@app.post("/users/", response_model=schemas.User)
-def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)):
- db_user = crud.get_user_by_email(db, email=user.email)
- if db_user:
- raise HTTPException(status_code=400, detail="Email already registered")
- return crud.create_user(db=db, user=user)
-
-
-@app.get("/users/", response_model=list[schemas.User])
-def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
- users = crud.get_users(db, skip=skip, limit=limit)
- return users
-
-
-@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)
- if db_user is None:
- raise HTTPException(status_code=404, detail="User not found")
- return db_user
-
-
-@app.post("/users/{user_id}/items/", response_model=schemas.Item)
-def create_item_for_user(
- user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db)
-):
- return crud.create_user_item(db=db, item=item, user_id=user_id)
-
-
-@app.get("/items/", response_model=list[schemas.Item])
-def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
- items = crud.get_items(db, skip=skip, limit=limit)
- return items
diff --git a/docs_src/sql_databases/sql_app_py310/crud.py b/docs_src/sql_databases/sql_app_py310/crud.py
deleted file mode 100644
index 679acdb5c..000000000
--- a/docs_src/sql_databases/sql_app_py310/crud.py
+++ /dev/null
@@ -1,36 +0,0 @@
-from sqlalchemy.orm import Session
-
-from . import models, schemas
-
-
-def get_user(db: Session, user_id: int):
- return db.query(models.User).filter(models.User.id == user_id).first()
-
-
-def get_user_by_email(db: Session, email: str):
- return db.query(models.User).filter(models.User.email == email).first()
-
-
-def get_users(db: Session, skip: int = 0, limit: int = 100):
- return db.query(models.User).offset(skip).limit(limit).all()
-
-
-def create_user(db: Session, user: schemas.UserCreate):
- fake_hashed_password = user.password + "notreallyhashed"
- db_user = models.User(email=user.email, hashed_password=fake_hashed_password)
- db.add(db_user)
- db.commit()
- db.refresh(db_user)
- return db_user
-
-
-def get_items(db: Session, skip: int = 0, limit: int = 100):
- return db.query(models.Item).offset(skip).limit(limit).all()
-
-
-def create_user_item(db: Session, item: schemas.ItemCreate, user_id: int):
- db_item = models.Item(**item.dict(), owner_id=user_id)
- db.add(db_item)
- db.commit()
- db.refresh(db_item)
- return db_item
diff --git a/docs_src/sql_databases/sql_app_py310/database.py b/docs_src/sql_databases/sql_app_py310/database.py
deleted file mode 100644
index 45a8b9f69..000000000
--- a/docs_src/sql_databases/sql_app_py310/database.py
+++ /dev/null
@@ -1,13 +0,0 @@
-from sqlalchemy import create_engine
-from sqlalchemy.ext.declarative import declarative_base
-from sqlalchemy.orm import sessionmaker
-
-SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db"
-# SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db"
-
-engine = create_engine(
- SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
-)
-SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
-
-Base = declarative_base()
diff --git a/docs_src/sql_databases/sql_app_py310/main.py b/docs_src/sql_databases/sql_app_py310/main.py
deleted file mode 100644
index a9856d0b6..000000000
--- a/docs_src/sql_databases/sql_app_py310/main.py
+++ /dev/null
@@ -1,53 +0,0 @@
-from fastapi import Depends, FastAPI, HTTPException
-from sqlalchemy.orm import Session
-
-from . import crud, models, schemas
-from .database import SessionLocal, engine
-
-models.Base.metadata.create_all(bind=engine)
-
-app = FastAPI()
-
-
-# Dependency
-def get_db():
- db = SessionLocal()
- try:
- yield db
- finally:
- db.close()
-
-
-@app.post("/users/", response_model=schemas.User)
-def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)):
- db_user = crud.get_user_by_email(db, email=user.email)
- if db_user:
- raise HTTPException(status_code=400, detail="Email already registered")
- return crud.create_user(db=db, user=user)
-
-
-@app.get("/users/", response_model=list[schemas.User])
-def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
- users = crud.get_users(db, skip=skip, limit=limit)
- return users
-
-
-@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)
- if db_user is None:
- raise HTTPException(status_code=404, detail="User not found")
- return db_user
-
-
-@app.post("/users/{user_id}/items/", response_model=schemas.Item)
-def create_item_for_user(
- user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db)
-):
- return crud.create_user_item(db=db, item=item, user_id=user_id)
-
-
-@app.get("/items/", response_model=list[schemas.Item])
-def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
- items = crud.get_items(db, skip=skip, limit=limit)
- return items
diff --git a/docs_src/sql_databases/sql_app_py310/models.py b/docs_src/sql_databases/sql_app_py310/models.py
deleted file mode 100644
index 09ae2a807..000000000
--- a/docs_src/sql_databases/sql_app_py310/models.py
+++ /dev/null
@@ -1,26 +0,0 @@
-from sqlalchemy import Boolean, Column, ForeignKey, Integer, String
-from sqlalchemy.orm import relationship
-
-from .database import Base
-
-
-class User(Base):
- __tablename__ = "users"
-
- id = Column(Integer, primary_key=True)
- email = Column(String, unique=True, index=True)
- hashed_password = Column(String)
- is_active = Column(Boolean, default=True)
-
- items = relationship("Item", back_populates="owner")
-
-
-class Item(Base):
- __tablename__ = "items"
-
- id = Column(Integer, primary_key=True)
- title = Column(String, index=True)
- description = Column(String, index=True)
- owner_id = Column(Integer, ForeignKey("users.id"))
-
- owner = relationship("User", back_populates="items")
diff --git a/docs_src/sql_databases/sql_app_py310/schemas.py b/docs_src/sql_databases/sql_app_py310/schemas.py
deleted file mode 100644
index aea2e3f10..000000000
--- a/docs_src/sql_databases/sql_app_py310/schemas.py
+++ /dev/null
@@ -1,35 +0,0 @@
-from pydantic import BaseModel
-
-
-class ItemBase(BaseModel):
- title: str
- description: str | None = None
-
-
-class ItemCreate(ItemBase):
- pass
-
-
-class Item(ItemBase):
- id: int
- owner_id: int
-
- class Config:
- orm_mode = True
-
-
-class UserBase(BaseModel):
- email: str
-
-
-class UserCreate(UserBase):
- password: str
-
-
-class User(UserBase):
- id: int
- is_active: bool
- items: list[Item] = []
-
- class Config:
- orm_mode = True
diff --git a/docs_src/sql_databases/sql_app_py310/tests/test_sql_app.py b/docs_src/sql_databases/sql_app_py310/tests/test_sql_app.py
deleted file mode 100644
index c60c3356f..000000000
--- a/docs_src/sql_databases/sql_app_py310/tests/test_sql_app.py
+++ /dev/null
@@ -1,47 +0,0 @@
-from fastapi.testclient import TestClient
-from sqlalchemy import create_engine
-from sqlalchemy.orm import sessionmaker
-
-from ..database import Base
-from ..main import app, get_db
-
-SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db"
-
-engine = create_engine(
- SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
-)
-TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
-
-
-Base.metadata.create_all(bind=engine)
-
-
-def override_get_db():
- try:
- db = TestingSessionLocal()
- yield db
- finally:
- db.close()
-
-
-app.dependency_overrides[get_db] = override_get_db
-
-client = TestClient(app)
-
-
-def test_create_user():
- response = client.post(
- "/users/",
- json={"email": "deadpool@example.com", "password": "chimichangas4life"},
- )
- assert response.status_code == 200, response.text
- data = response.json()
- assert data["email"] == "deadpool@example.com"
- assert "id" in data
- user_id = data["id"]
-
- response = client.get(f"/users/{user_id}")
- assert response.status_code == 200, response.text
- data = response.json()
- assert data["email"] == "deadpool@example.com"
- assert data["id"] == user_id
diff --git a/docs_src/sql_databases/sql_app_py39/__init__.py b/docs_src/sql_databases/sql_app_py39/__init__.py
deleted file mode 100644
index e69de29bb..000000000
diff --git a/docs_src/sql_databases/sql_app_py39/alt_main.py b/docs_src/sql_databases/sql_app_py39/alt_main.py
deleted file mode 100644
index 5de88ec3a..000000000
--- a/docs_src/sql_databases/sql_app_py39/alt_main.py
+++ /dev/null
@@ -1,60 +0,0 @@
-from fastapi import Depends, FastAPI, HTTPException, Request, Response
-from sqlalchemy.orm import Session
-
-from . import crud, models, schemas
-from .database import SessionLocal, engine
-
-models.Base.metadata.create_all(bind=engine)
-
-app = FastAPI()
-
-
-@app.middleware("http")
-async def db_session_middleware(request: Request, call_next):
- response = Response("Internal server error", status_code=500)
- try:
- request.state.db = SessionLocal()
- response = await call_next(request)
- finally:
- request.state.db.close()
- return response
-
-
-# Dependency
-def get_db(request: Request):
- return request.state.db
-
-
-@app.post("/users/", response_model=schemas.User)
-def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)):
- db_user = crud.get_user_by_email(db, email=user.email)
- if db_user:
- raise HTTPException(status_code=400, detail="Email already registered")
- return crud.create_user(db=db, user=user)
-
-
-@app.get("/users/", response_model=list[schemas.User])
-def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
- users = crud.get_users(db, skip=skip, limit=limit)
- return users
-
-
-@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)
- if db_user is None:
- raise HTTPException(status_code=404, detail="User not found")
- return db_user
-
-
-@app.post("/users/{user_id}/items/", response_model=schemas.Item)
-def create_item_for_user(
- user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db)
-):
- return crud.create_user_item(db=db, item=item, user_id=user_id)
-
-
-@app.get("/items/", response_model=list[schemas.Item])
-def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
- items = crud.get_items(db, skip=skip, limit=limit)
- return items
diff --git a/docs_src/sql_databases/sql_app_py39/crud.py b/docs_src/sql_databases/sql_app_py39/crud.py
deleted file mode 100644
index 679acdb5c..000000000
--- a/docs_src/sql_databases/sql_app_py39/crud.py
+++ /dev/null
@@ -1,36 +0,0 @@
-from sqlalchemy.orm import Session
-
-from . import models, schemas
-
-
-def get_user(db: Session, user_id: int):
- return db.query(models.User).filter(models.User.id == user_id).first()
-
-
-def get_user_by_email(db: Session, email: str):
- return db.query(models.User).filter(models.User.email == email).first()
-
-
-def get_users(db: Session, skip: int = 0, limit: int = 100):
- return db.query(models.User).offset(skip).limit(limit).all()
-
-
-def create_user(db: Session, user: schemas.UserCreate):
- fake_hashed_password = user.password + "notreallyhashed"
- db_user = models.User(email=user.email, hashed_password=fake_hashed_password)
- db.add(db_user)
- db.commit()
- db.refresh(db_user)
- return db_user
-
-
-def get_items(db: Session, skip: int = 0, limit: int = 100):
- return db.query(models.Item).offset(skip).limit(limit).all()
-
-
-def create_user_item(db: Session, item: schemas.ItemCreate, user_id: int):
- db_item = models.Item(**item.dict(), owner_id=user_id)
- db.add(db_item)
- db.commit()
- db.refresh(db_item)
- return db_item
diff --git a/docs_src/sql_databases/sql_app_py39/database.py b/docs_src/sql_databases/sql_app_py39/database.py
deleted file mode 100644
index 45a8b9f69..000000000
--- a/docs_src/sql_databases/sql_app_py39/database.py
+++ /dev/null
@@ -1,13 +0,0 @@
-from sqlalchemy import create_engine
-from sqlalchemy.ext.declarative import declarative_base
-from sqlalchemy.orm import sessionmaker
-
-SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db"
-# SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db"
-
-engine = create_engine(
- SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
-)
-SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
-
-Base = declarative_base()
diff --git a/docs_src/sql_databases/sql_app_py39/main.py b/docs_src/sql_databases/sql_app_py39/main.py
deleted file mode 100644
index a9856d0b6..000000000
--- a/docs_src/sql_databases/sql_app_py39/main.py
+++ /dev/null
@@ -1,53 +0,0 @@
-from fastapi import Depends, FastAPI, HTTPException
-from sqlalchemy.orm import Session
-
-from . import crud, models, schemas
-from .database import SessionLocal, engine
-
-models.Base.metadata.create_all(bind=engine)
-
-app = FastAPI()
-
-
-# Dependency
-def get_db():
- db = SessionLocal()
- try:
- yield db
- finally:
- db.close()
-
-
-@app.post("/users/", response_model=schemas.User)
-def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)):
- db_user = crud.get_user_by_email(db, email=user.email)
- if db_user:
- raise HTTPException(status_code=400, detail="Email already registered")
- return crud.create_user(db=db, user=user)
-
-
-@app.get("/users/", response_model=list[schemas.User])
-def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
- users = crud.get_users(db, skip=skip, limit=limit)
- return users
-
-
-@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)
- if db_user is None:
- raise HTTPException(status_code=404, detail="User not found")
- return db_user
-
-
-@app.post("/users/{user_id}/items/", response_model=schemas.Item)
-def create_item_for_user(
- user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db)
-):
- return crud.create_user_item(db=db, item=item, user_id=user_id)
-
-
-@app.get("/items/", response_model=list[schemas.Item])
-def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
- items = crud.get_items(db, skip=skip, limit=limit)
- return items
diff --git a/docs_src/sql_databases/sql_app_py39/models.py b/docs_src/sql_databases/sql_app_py39/models.py
deleted file mode 100644
index 09ae2a807..000000000
--- a/docs_src/sql_databases/sql_app_py39/models.py
+++ /dev/null
@@ -1,26 +0,0 @@
-from sqlalchemy import Boolean, Column, ForeignKey, Integer, String
-from sqlalchemy.orm import relationship
-
-from .database import Base
-
-
-class User(Base):
- __tablename__ = "users"
-
- id = Column(Integer, primary_key=True)
- email = Column(String, unique=True, index=True)
- hashed_password = Column(String)
- is_active = Column(Boolean, default=True)
-
- items = relationship("Item", back_populates="owner")
-
-
-class Item(Base):
- __tablename__ = "items"
-
- id = Column(Integer, primary_key=True)
- title = Column(String, index=True)
- description = Column(String, index=True)
- owner_id = Column(Integer, ForeignKey("users.id"))
-
- owner = relationship("User", back_populates="items")
diff --git a/docs_src/sql_databases/sql_app_py39/schemas.py b/docs_src/sql_databases/sql_app_py39/schemas.py
deleted file mode 100644
index dadc403d9..000000000
--- a/docs_src/sql_databases/sql_app_py39/schemas.py
+++ /dev/null
@@ -1,37 +0,0 @@
-from typing import Union
-
-from pydantic import BaseModel
-
-
-class ItemBase(BaseModel):
- title: str
- description: Union[str, None] = None
-
-
-class ItemCreate(ItemBase):
- pass
-
-
-class Item(ItemBase):
- id: int
- owner_id: int
-
- class Config:
- orm_mode = True
-
-
-class UserBase(BaseModel):
- email: str
-
-
-class UserCreate(UserBase):
- password: str
-
-
-class User(UserBase):
- id: int
- is_active: bool
- items: list[Item] = []
-
- class Config:
- orm_mode = True
diff --git a/docs_src/sql_databases/sql_app_py39/tests/__init__.py b/docs_src/sql_databases/sql_app_py39/tests/__init__.py
deleted file mode 100644
index e69de29bb..000000000
diff --git a/docs_src/sql_databases/sql_app_py39/tests/test_sql_app.py b/docs_src/sql_databases/sql_app_py39/tests/test_sql_app.py
deleted file mode 100644
index c60c3356f..000000000
--- a/docs_src/sql_databases/sql_app_py39/tests/test_sql_app.py
+++ /dev/null
@@ -1,47 +0,0 @@
-from fastapi.testclient import TestClient
-from sqlalchemy import create_engine
-from sqlalchemy.orm import sessionmaker
-
-from ..database import Base
-from ..main import app, get_db
-
-SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db"
-
-engine = create_engine(
- SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
-)
-TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
-
-
-Base.metadata.create_all(bind=engine)
-
-
-def override_get_db():
- try:
- db = TestingSessionLocal()
- yield db
- finally:
- db.close()
-
-
-app.dependency_overrides[get_db] = override_get_db
-
-client = TestClient(app)
-
-
-def test_create_user():
- response = client.post(
- "/users/",
- json={"email": "deadpool@example.com", "password": "chimichangas4life"},
- )
- assert response.status_code == 200, response.text
- data = response.json()
- assert data["email"] == "deadpool@example.com"
- assert "id" in data
- user_id = data["id"]
-
- response = client.get(f"/users/{user_id}")
- assert response.status_code == 200, response.text
- data = response.json()
- assert data["email"] == "deadpool@example.com"
- assert data["id"] == user_id
diff --git a/docs_src/sql_databases/tutorial001.py b/docs_src/sql_databases/tutorial001.py
new file mode 100644
index 000000000..be86ec0ee
--- /dev/null
+++ b/docs_src/sql_databases/tutorial001.py
@@ -0,0 +1,71 @@
+from typing import List, Union
+
+from fastapi import Depends, FastAPI, HTTPException, Query
+from sqlmodel import Field, Session, SQLModel, create_engine, select
+
+
+class Hero(SQLModel, table=True):
+ id: Union[int, None] = Field(default=None, primary_key=True)
+ name: str = Field(index=True)
+ age: Union[int, None] = Field(default=None, index=True)
+ secret_name: str
+
+
+sqlite_file_name = "database.db"
+sqlite_url = f"sqlite:///{sqlite_file_name}"
+
+connect_args = {"check_same_thread": False}
+engine = create_engine(sqlite_url, connect_args=connect_args)
+
+
+def create_db_and_tables():
+ SQLModel.metadata.create_all(engine)
+
+
+def get_session():
+ with Session(engine) as session:
+ yield session
+
+
+app = FastAPI()
+
+
+@app.on_event("startup")
+def on_startup():
+ create_db_and_tables()
+
+
+@app.post("/heroes/")
+def create_hero(hero: Hero, session: Session = Depends(get_session)) -> Hero:
+ session.add(hero)
+ session.commit()
+ session.refresh(hero)
+ return hero
+
+
+@app.get("/heroes/")
+def read_heroes(
+ session: Session = Depends(get_session),
+ offset: int = 0,
+ limit: int = Query(default=100, le=100),
+) -> List[Hero]:
+ heroes = session.exec(select(Hero).offset(offset).limit(limit)).all()
+ return heroes
+
+
+@app.get("/heroes/{hero_id}")
+def read_hero(hero_id: int, session: Session = Depends(get_session)) -> Hero:
+ hero = session.get(Hero, hero_id)
+ if not hero:
+ raise HTTPException(status_code=404, detail="Hero not found")
+ return hero
+
+
+@app.delete("/heroes/{hero_id}")
+def delete_hero(hero_id: int, session: Session = Depends(get_session)):
+ hero = session.get(Hero, hero_id)
+ if not hero:
+ raise HTTPException(status_code=404, detail="Hero not found")
+ session.delete(hero)
+ session.commit()
+ return {"ok": True}
diff --git a/docs_src/sql_databases/tutorial001_an.py b/docs_src/sql_databases/tutorial001_an.py
new file mode 100644
index 000000000..8c000d31c
--- /dev/null
+++ b/docs_src/sql_databases/tutorial001_an.py
@@ -0,0 +1,74 @@
+from typing import List, Union
+
+from fastapi import Depends, FastAPI, HTTPException, Query
+from sqlmodel import Field, Session, SQLModel, create_engine, select
+from typing_extensions import Annotated
+
+
+class Hero(SQLModel, table=True):
+ id: Union[int, None] = Field(default=None, primary_key=True)
+ name: str = Field(index=True)
+ age: Union[int, None] = Field(default=None, index=True)
+ secret_name: str
+
+
+sqlite_file_name = "database.db"
+sqlite_url = f"sqlite:///{sqlite_file_name}"
+
+connect_args = {"check_same_thread": False}
+engine = create_engine(sqlite_url, connect_args=connect_args)
+
+
+def create_db_and_tables():
+ SQLModel.metadata.create_all(engine)
+
+
+def get_session():
+ with Session(engine) as session:
+ yield session
+
+
+SessionDep = Annotated[Session, Depends(get_session)]
+
+app = FastAPI()
+
+
+@app.on_event("startup")
+def on_startup():
+ create_db_and_tables()
+
+
+@app.post("/heroes/")
+def create_hero(hero: Hero, session: SessionDep) -> Hero:
+ session.add(hero)
+ session.commit()
+ session.refresh(hero)
+ return hero
+
+
+@app.get("/heroes/")
+def read_heroes(
+ session: SessionDep,
+ offset: int = 0,
+ limit: Annotated[int, Query(le=100)] = 100,
+) -> List[Hero]:
+ heroes = session.exec(select(Hero).offset(offset).limit(limit)).all()
+ return heroes
+
+
+@app.get("/heroes/{hero_id}")
+def read_hero(hero_id: int, session: SessionDep) -> Hero:
+ hero = session.get(Hero, hero_id)
+ if not hero:
+ raise HTTPException(status_code=404, detail="Hero not found")
+ return hero
+
+
+@app.delete("/heroes/{hero_id}")
+def delete_hero(hero_id: int, session: SessionDep):
+ hero = session.get(Hero, hero_id)
+ if not hero:
+ raise HTTPException(status_code=404, detail="Hero not found")
+ session.delete(hero)
+ session.commit()
+ return {"ok": True}
diff --git a/docs_src/sql_databases/tutorial001_an_py310.py b/docs_src/sql_databases/tutorial001_an_py310.py
new file mode 100644
index 000000000..de1fb81fa
--- /dev/null
+++ b/docs_src/sql_databases/tutorial001_an_py310.py
@@ -0,0 +1,73 @@
+from typing import Annotated
+
+from fastapi import Depends, FastAPI, HTTPException, Query
+from sqlmodel import Field, Session, SQLModel, create_engine, select
+
+
+class Hero(SQLModel, table=True):
+ id: int | None = Field(default=None, primary_key=True)
+ name: str = Field(index=True)
+ age: int | None = Field(default=None, index=True)
+ secret_name: str
+
+
+sqlite_file_name = "database.db"
+sqlite_url = f"sqlite:///{sqlite_file_name}"
+
+connect_args = {"check_same_thread": False}
+engine = create_engine(sqlite_url, connect_args=connect_args)
+
+
+def create_db_and_tables():
+ SQLModel.metadata.create_all(engine)
+
+
+def get_session():
+ with Session(engine) as session:
+ yield session
+
+
+SessionDep = Annotated[Session, Depends(get_session)]
+
+app = FastAPI()
+
+
+@app.on_event("startup")
+def on_startup():
+ create_db_and_tables()
+
+
+@app.post("/heroes/")
+def create_hero(hero: Hero, session: SessionDep) -> Hero:
+ session.add(hero)
+ session.commit()
+ session.refresh(hero)
+ return hero
+
+
+@app.get("/heroes/")
+def read_heroes(
+ session: SessionDep,
+ offset: int = 0,
+ limit: Annotated[int, Query(le=100)] = 100,
+) -> list[Hero]:
+ heroes = session.exec(select(Hero).offset(offset).limit(limit)).all()
+ return heroes
+
+
+@app.get("/heroes/{hero_id}")
+def read_hero(hero_id: int, session: SessionDep) -> Hero:
+ hero = session.get(Hero, hero_id)
+ if not hero:
+ raise HTTPException(status_code=404, detail="Hero not found")
+ return hero
+
+
+@app.delete("/heroes/{hero_id}")
+def delete_hero(hero_id: int, session: SessionDep):
+ hero = session.get(Hero, hero_id)
+ if not hero:
+ raise HTTPException(status_code=404, detail="Hero not found")
+ session.delete(hero)
+ session.commit()
+ return {"ok": True}
diff --git a/docs_src/sql_databases/tutorial001_an_py39.py b/docs_src/sql_databases/tutorial001_an_py39.py
new file mode 100644
index 000000000..595892746
--- /dev/null
+++ b/docs_src/sql_databases/tutorial001_an_py39.py
@@ -0,0 +1,73 @@
+from typing import Annotated, Union
+
+from fastapi import Depends, FastAPI, HTTPException, Query
+from sqlmodel import Field, Session, SQLModel, create_engine, select
+
+
+class Hero(SQLModel, table=True):
+ id: Union[int, None] = Field(default=None, primary_key=True)
+ name: str = Field(index=True)
+ age: Union[int, None] = Field(default=None, index=True)
+ secret_name: str
+
+
+sqlite_file_name = "database.db"
+sqlite_url = f"sqlite:///{sqlite_file_name}"
+
+connect_args = {"check_same_thread": False}
+engine = create_engine(sqlite_url, connect_args=connect_args)
+
+
+def create_db_and_tables():
+ SQLModel.metadata.create_all(engine)
+
+
+def get_session():
+ with Session(engine) as session:
+ yield session
+
+
+SessionDep = Annotated[Session, Depends(get_session)]
+
+app = FastAPI()
+
+
+@app.on_event("startup")
+def on_startup():
+ create_db_and_tables()
+
+
+@app.post("/heroes/")
+def create_hero(hero: Hero, session: SessionDep) -> Hero:
+ session.add(hero)
+ session.commit()
+ session.refresh(hero)
+ return hero
+
+
+@app.get("/heroes/")
+def read_heroes(
+ session: SessionDep,
+ offset: int = 0,
+ limit: Annotated[int, Query(le=100)] = 100,
+) -> list[Hero]:
+ heroes = session.exec(select(Hero).offset(offset).limit(limit)).all()
+ return heroes
+
+
+@app.get("/heroes/{hero_id}")
+def read_hero(hero_id: int, session: SessionDep) -> Hero:
+ hero = session.get(Hero, hero_id)
+ if not hero:
+ raise HTTPException(status_code=404, detail="Hero not found")
+ return hero
+
+
+@app.delete("/heroes/{hero_id}")
+def delete_hero(hero_id: int, session: SessionDep):
+ hero = session.get(Hero, hero_id)
+ if not hero:
+ raise HTTPException(status_code=404, detail="Hero not found")
+ session.delete(hero)
+ session.commit()
+ return {"ok": True}
diff --git a/docs_src/sql_databases/tutorial001_py310.py b/docs_src/sql_databases/tutorial001_py310.py
new file mode 100644
index 000000000..b58462e6a
--- /dev/null
+++ b/docs_src/sql_databases/tutorial001_py310.py
@@ -0,0 +1,69 @@
+from fastapi import Depends, FastAPI, HTTPException, Query
+from sqlmodel import Field, Session, SQLModel, create_engine, select
+
+
+class Hero(SQLModel, table=True):
+ id: int | None = Field(default=None, primary_key=True)
+ name: str = Field(index=True)
+ age: int | None = Field(default=None, index=True)
+ secret_name: str
+
+
+sqlite_file_name = "database.db"
+sqlite_url = f"sqlite:///{sqlite_file_name}"
+
+connect_args = {"check_same_thread": False}
+engine = create_engine(sqlite_url, connect_args=connect_args)
+
+
+def create_db_and_tables():
+ SQLModel.metadata.create_all(engine)
+
+
+def get_session():
+ with Session(engine) as session:
+ yield session
+
+
+app = FastAPI()
+
+
+@app.on_event("startup")
+def on_startup():
+ create_db_and_tables()
+
+
+@app.post("/heroes/")
+def create_hero(hero: Hero, session: Session = Depends(get_session)) -> Hero:
+ session.add(hero)
+ session.commit()
+ session.refresh(hero)
+ return hero
+
+
+@app.get("/heroes/")
+def read_heroes(
+ session: Session = Depends(get_session),
+ offset: int = 0,
+ limit: int = Query(default=100, le=100),
+) -> list[Hero]:
+ heroes = session.exec(select(Hero).offset(offset).limit(limit)).all()
+ return heroes
+
+
+@app.get("/heroes/{hero_id}")
+def read_hero(hero_id: int, session: Session = Depends(get_session)) -> Hero:
+ hero = session.get(Hero, hero_id)
+ if not hero:
+ raise HTTPException(status_code=404, detail="Hero not found")
+ return hero
+
+
+@app.delete("/heroes/{hero_id}")
+def delete_hero(hero_id: int, session: Session = Depends(get_session)):
+ hero = session.get(Hero, hero_id)
+ if not hero:
+ raise HTTPException(status_code=404, detail="Hero not found")
+ session.delete(hero)
+ session.commit()
+ return {"ok": True}
diff --git a/docs_src/sql_databases/tutorial001_py39.py b/docs_src/sql_databases/tutorial001_py39.py
new file mode 100644
index 000000000..410a52d0c
--- /dev/null
+++ b/docs_src/sql_databases/tutorial001_py39.py
@@ -0,0 +1,71 @@
+from typing import Union
+
+from fastapi import Depends, FastAPI, HTTPException, Query
+from sqlmodel import Field, Session, SQLModel, create_engine, select
+
+
+class Hero(SQLModel, table=True):
+ id: Union[int, None] = Field(default=None, primary_key=True)
+ name: str = Field(index=True)
+ age: Union[int, None] = Field(default=None, index=True)
+ secret_name: str
+
+
+sqlite_file_name = "database.db"
+sqlite_url = f"sqlite:///{sqlite_file_name}"
+
+connect_args = {"check_same_thread": False}
+engine = create_engine(sqlite_url, connect_args=connect_args)
+
+
+def create_db_and_tables():
+ SQLModel.metadata.create_all(engine)
+
+
+def get_session():
+ with Session(engine) as session:
+ yield session
+
+
+app = FastAPI()
+
+
+@app.on_event("startup")
+def on_startup():
+ create_db_and_tables()
+
+
+@app.post("/heroes/")
+def create_hero(hero: Hero, session: Session = Depends(get_session)) -> Hero:
+ session.add(hero)
+ session.commit()
+ session.refresh(hero)
+ return hero
+
+
+@app.get("/heroes/")
+def read_heroes(
+ session: Session = Depends(get_session),
+ offset: int = 0,
+ limit: int = Query(default=100, le=100),
+) -> list[Hero]:
+ heroes = session.exec(select(Hero).offset(offset).limit(limit)).all()
+ return heroes
+
+
+@app.get("/heroes/{hero_id}")
+def read_hero(hero_id: int, session: Session = Depends(get_session)) -> Hero:
+ hero = session.get(Hero, hero_id)
+ if not hero:
+ raise HTTPException(status_code=404, detail="Hero not found")
+ return hero
+
+
+@app.delete("/heroes/{hero_id}")
+def delete_hero(hero_id: int, session: Session = Depends(get_session)):
+ hero = session.get(Hero, hero_id)
+ if not hero:
+ raise HTTPException(status_code=404, detail="Hero not found")
+ session.delete(hero)
+ session.commit()
+ return {"ok": True}
diff --git a/docs_src/sql_databases/tutorial002.py b/docs_src/sql_databases/tutorial002.py
new file mode 100644
index 000000000..4350d19c6
--- /dev/null
+++ b/docs_src/sql_databases/tutorial002.py
@@ -0,0 +1,104 @@
+from typing import List, Union
+
+from fastapi import Depends, FastAPI, HTTPException, Query
+from sqlmodel import Field, Session, SQLModel, create_engine, select
+
+
+class HeroBase(SQLModel):
+ name: str = Field(index=True)
+ age: Union[int, None] = Field(default=None, index=True)
+
+
+class Hero(HeroBase, table=True):
+ id: Union[int, None] = Field(default=None, primary_key=True)
+ secret_name: str
+
+
+class HeroPublic(HeroBase):
+ id: int
+
+
+class HeroCreate(HeroBase):
+ secret_name: str
+
+
+class HeroUpdate(HeroBase):
+ name: Union[str, None] = None
+ age: Union[int, None] = None
+ secret_name: Union[str, None] = None
+
+
+sqlite_file_name = "database.db"
+sqlite_url = f"sqlite:///{sqlite_file_name}"
+
+connect_args = {"check_same_thread": False}
+engine = create_engine(sqlite_url, connect_args=connect_args)
+
+
+def create_db_and_tables():
+ SQLModel.metadata.create_all(engine)
+
+
+def get_session():
+ with Session(engine) as session:
+ yield session
+
+
+app = FastAPI()
+
+
+@app.on_event("startup")
+def on_startup():
+ create_db_and_tables()
+
+
+@app.post("/heroes/", response_model=HeroPublic)
+def create_hero(hero: HeroCreate, session: Session = Depends(get_session)):
+ db_hero = Hero.model_validate(hero)
+ session.add(db_hero)
+ session.commit()
+ session.refresh(db_hero)
+ return db_hero
+
+
+@app.get("/heroes/", response_model=List[HeroPublic])
+def read_heroes(
+ session: Session = Depends(get_session),
+ offset: int = 0,
+ limit: int = Query(default=100, le=100),
+):
+ heroes = session.exec(select(Hero).offset(offset).limit(limit)).all()
+ return heroes
+
+
+@app.get("/heroes/{hero_id}", response_model=HeroPublic)
+def read_hero(hero_id: int, session: Session = Depends(get_session)):
+ hero = session.get(Hero, hero_id)
+ if not hero:
+ raise HTTPException(status_code=404, detail="Hero not found")
+ return hero
+
+
+@app.patch("/heroes/{hero_id}", response_model=HeroPublic)
+def update_hero(
+ hero_id: int, hero: HeroUpdate, session: Session = Depends(get_session)
+):
+ hero_db = session.get(Hero, hero_id)
+ if not hero_db:
+ raise HTTPException(status_code=404, detail="Hero not found")
+ hero_data = hero.model_dump(exclude_unset=True)
+ hero_db.sqlmodel_update(hero_data)
+ session.add(hero_db)
+ session.commit()
+ session.refresh(hero_db)
+ return hero_db
+
+
+@app.delete("/heroes/{hero_id}")
+def delete_hero(hero_id: int, session: Session = Depends(get_session)):
+ hero = session.get(Hero, hero_id)
+ if not hero:
+ raise HTTPException(status_code=404, detail="Hero not found")
+ session.delete(hero)
+ session.commit()
+ return {"ok": True}
diff --git a/docs_src/sql_databases/tutorial002_an.py b/docs_src/sql_databases/tutorial002_an.py
new file mode 100644
index 000000000..15e3d7c3a
--- /dev/null
+++ b/docs_src/sql_databases/tutorial002_an.py
@@ -0,0 +1,104 @@
+from typing import List, Union
+
+from fastapi import Depends, FastAPI, HTTPException, Query
+from sqlmodel import Field, Session, SQLModel, create_engine, select
+from typing_extensions import Annotated
+
+
+class HeroBase(SQLModel):
+ name: str = Field(index=True)
+ age: Union[int, None] = Field(default=None, index=True)
+
+
+class Hero(HeroBase, table=True):
+ id: Union[int, None] = Field(default=None, primary_key=True)
+ secret_name: str
+
+
+class HeroPublic(HeroBase):
+ id: int
+
+
+class HeroCreate(HeroBase):
+ secret_name: str
+
+
+class HeroUpdate(HeroBase):
+ name: Union[str, None] = None
+ age: Union[int, None] = None
+ secret_name: Union[str, None] = None
+
+
+sqlite_file_name = "database.db"
+sqlite_url = f"sqlite:///{sqlite_file_name}"
+
+connect_args = {"check_same_thread": False}
+engine = create_engine(sqlite_url, connect_args=connect_args)
+
+
+def create_db_and_tables():
+ SQLModel.metadata.create_all(engine)
+
+
+def get_session():
+ with Session(engine) as session:
+ yield session
+
+
+SessionDep = Annotated[Session, Depends(get_session)]
+app = FastAPI()
+
+
+@app.on_event("startup")
+def on_startup():
+ create_db_and_tables()
+
+
+@app.post("/heroes/", response_model=HeroPublic)
+def create_hero(hero: HeroCreate, session: SessionDep):
+ db_hero = Hero.model_validate(hero)
+ session.add(db_hero)
+ session.commit()
+ session.refresh(db_hero)
+ return db_hero
+
+
+@app.get("/heroes/", response_model=List[HeroPublic])
+def read_heroes(
+ session: SessionDep,
+ offset: int = 0,
+ limit: Annotated[int, Query(le=100)] = 100,
+):
+ heroes = session.exec(select(Hero).offset(offset).limit(limit)).all()
+ return heroes
+
+
+@app.get("/heroes/{hero_id}", response_model=HeroPublic)
+def read_hero(hero_id: int, session: SessionDep):
+ hero = session.get(Hero, hero_id)
+ if not hero:
+ raise HTTPException(status_code=404, detail="Hero not found")
+ return hero
+
+
+@app.patch("/heroes/{hero_id}", response_model=HeroPublic)
+def update_hero(hero_id: int, hero: HeroUpdate, session: SessionDep):
+ hero_db = session.get(Hero, hero_id)
+ if not hero_db:
+ raise HTTPException(status_code=404, detail="Hero not found")
+ hero_data = hero.model_dump(exclude_unset=True)
+ hero_db.sqlmodel_update(hero_data)
+ session.add(hero_db)
+ session.commit()
+ session.refresh(hero_db)
+ return hero_db
+
+
+@app.delete("/heroes/{hero_id}")
+def delete_hero(hero_id: int, session: SessionDep):
+ hero = session.get(Hero, hero_id)
+ if not hero:
+ raise HTTPException(status_code=404, detail="Hero not found")
+ session.delete(hero)
+ session.commit()
+ return {"ok": True}
diff --git a/docs_src/sql_databases/tutorial002_an_py310.py b/docs_src/sql_databases/tutorial002_an_py310.py
new file mode 100644
index 000000000..64c554b8a
--- /dev/null
+++ b/docs_src/sql_databases/tutorial002_an_py310.py
@@ -0,0 +1,103 @@
+from typing import Annotated
+
+from fastapi import Depends, FastAPI, HTTPException, Query
+from sqlmodel import Field, Session, SQLModel, create_engine, select
+
+
+class HeroBase(SQLModel):
+ name: str = Field(index=True)
+ age: int | None = Field(default=None, index=True)
+
+
+class Hero(HeroBase, table=True):
+ id: int | None = Field(default=None, primary_key=True)
+ secret_name: str
+
+
+class HeroPublic(HeroBase):
+ id: int
+
+
+class HeroCreate(HeroBase):
+ secret_name: str
+
+
+class HeroUpdate(HeroBase):
+ name: str | None = None
+ age: int | None = None
+ secret_name: str | None = None
+
+
+sqlite_file_name = "database.db"
+sqlite_url = f"sqlite:///{sqlite_file_name}"
+
+connect_args = {"check_same_thread": False}
+engine = create_engine(sqlite_url, connect_args=connect_args)
+
+
+def create_db_and_tables():
+ SQLModel.metadata.create_all(engine)
+
+
+def get_session():
+ with Session(engine) as session:
+ yield session
+
+
+SessionDep = Annotated[Session, Depends(get_session)]
+app = FastAPI()
+
+
+@app.on_event("startup")
+def on_startup():
+ create_db_and_tables()
+
+
+@app.post("/heroes/", response_model=HeroPublic)
+def create_hero(hero: HeroCreate, session: SessionDep):
+ db_hero = Hero.model_validate(hero)
+ session.add(db_hero)
+ session.commit()
+ session.refresh(db_hero)
+ return db_hero
+
+
+@app.get("/heroes/", response_model=list[HeroPublic])
+def read_heroes(
+ session: SessionDep,
+ offset: int = 0,
+ limit: Annotated[int, Query(le=100)] = 100,
+):
+ heroes = session.exec(select(Hero).offset(offset).limit(limit)).all()
+ return heroes
+
+
+@app.get("/heroes/{hero_id}", response_model=HeroPublic)
+def read_hero(hero_id: int, session: SessionDep):
+ hero = session.get(Hero, hero_id)
+ if not hero:
+ raise HTTPException(status_code=404, detail="Hero not found")
+ return hero
+
+
+@app.patch("/heroes/{hero_id}", response_model=HeroPublic)
+def update_hero(hero_id: int, hero: HeroUpdate, session: SessionDep):
+ hero_db = session.get(Hero, hero_id)
+ if not hero_db:
+ raise HTTPException(status_code=404, detail="Hero not found")
+ hero_data = hero.model_dump(exclude_unset=True)
+ hero_db.sqlmodel_update(hero_data)
+ session.add(hero_db)
+ session.commit()
+ session.refresh(hero_db)
+ return hero_db
+
+
+@app.delete("/heroes/{hero_id}")
+def delete_hero(hero_id: int, session: SessionDep):
+ hero = session.get(Hero, hero_id)
+ if not hero:
+ raise HTTPException(status_code=404, detail="Hero not found")
+ session.delete(hero)
+ session.commit()
+ return {"ok": True}
diff --git a/docs_src/sql_databases/tutorial002_an_py39.py b/docs_src/sql_databases/tutorial002_an_py39.py
new file mode 100644
index 000000000..a8a0721ff
--- /dev/null
+++ b/docs_src/sql_databases/tutorial002_an_py39.py
@@ -0,0 +1,103 @@
+from typing import Annotated, Union
+
+from fastapi import Depends, FastAPI, HTTPException, Query
+from sqlmodel import Field, Session, SQLModel, create_engine, select
+
+
+class HeroBase(SQLModel):
+ name: str = Field(index=True)
+ age: Union[int, None] = Field(default=None, index=True)
+
+
+class Hero(HeroBase, table=True):
+ id: Union[int, None] = Field(default=None, primary_key=True)
+ secret_name: str
+
+
+class HeroPublic(HeroBase):
+ id: int
+
+
+class HeroCreate(HeroBase):
+ secret_name: str
+
+
+class HeroUpdate(HeroBase):
+ name: Union[str, None] = None
+ age: Union[int, None] = None
+ secret_name: Union[str, None] = None
+
+
+sqlite_file_name = "database.db"
+sqlite_url = f"sqlite:///{sqlite_file_name}"
+
+connect_args = {"check_same_thread": False}
+engine = create_engine(sqlite_url, connect_args=connect_args)
+
+
+def create_db_and_tables():
+ SQLModel.metadata.create_all(engine)
+
+
+def get_session():
+ with Session(engine) as session:
+ yield session
+
+
+SessionDep = Annotated[Session, Depends(get_session)]
+app = FastAPI()
+
+
+@app.on_event("startup")
+def on_startup():
+ create_db_and_tables()
+
+
+@app.post("/heroes/", response_model=HeroPublic)
+def create_hero(hero: HeroCreate, session: SessionDep):
+ db_hero = Hero.model_validate(hero)
+ session.add(db_hero)
+ session.commit()
+ session.refresh(db_hero)
+ return db_hero
+
+
+@app.get("/heroes/", response_model=list[HeroPublic])
+def read_heroes(
+ session: SessionDep,
+ offset: int = 0,
+ limit: Annotated[int, Query(le=100)] = 100,
+):
+ heroes = session.exec(select(Hero).offset(offset).limit(limit)).all()
+ return heroes
+
+
+@app.get("/heroes/{hero_id}", response_model=HeroPublic)
+def read_hero(hero_id: int, session: SessionDep):
+ hero = session.get(Hero, hero_id)
+ if not hero:
+ raise HTTPException(status_code=404, detail="Hero not found")
+ return hero
+
+
+@app.patch("/heroes/{hero_id}", response_model=HeroPublic)
+def update_hero(hero_id: int, hero: HeroUpdate, session: SessionDep):
+ hero_db = session.get(Hero, hero_id)
+ if not hero_db:
+ raise HTTPException(status_code=404, detail="Hero not found")
+ hero_data = hero.model_dump(exclude_unset=True)
+ hero_db.sqlmodel_update(hero_data)
+ session.add(hero_db)
+ session.commit()
+ session.refresh(hero_db)
+ return hero_db
+
+
+@app.delete("/heroes/{hero_id}")
+def delete_hero(hero_id: int, session: SessionDep):
+ hero = session.get(Hero, hero_id)
+ if not hero:
+ raise HTTPException(status_code=404, detail="Hero not found")
+ session.delete(hero)
+ session.commit()
+ return {"ok": True}
diff --git a/docs_src/sql_databases/tutorial002_py310.py b/docs_src/sql_databases/tutorial002_py310.py
new file mode 100644
index 000000000..ec3d68db5
--- /dev/null
+++ b/docs_src/sql_databases/tutorial002_py310.py
@@ -0,0 +1,102 @@
+from fastapi import Depends, FastAPI, HTTPException, Query
+from sqlmodel import Field, Session, SQLModel, create_engine, select
+
+
+class HeroBase(SQLModel):
+ name: str = Field(index=True)
+ age: int | None = Field(default=None, index=True)
+
+
+class Hero(HeroBase, table=True):
+ id: int | None = Field(default=None, primary_key=True)
+ secret_name: str
+
+
+class HeroPublic(HeroBase):
+ id: int
+
+
+class HeroCreate(HeroBase):
+ secret_name: str
+
+
+class HeroUpdate(HeroBase):
+ name: str | None = None
+ age: int | None = None
+ secret_name: str | None = None
+
+
+sqlite_file_name = "database.db"
+sqlite_url = f"sqlite:///{sqlite_file_name}"
+
+connect_args = {"check_same_thread": False}
+engine = create_engine(sqlite_url, connect_args=connect_args)
+
+
+def create_db_and_tables():
+ SQLModel.metadata.create_all(engine)
+
+
+def get_session():
+ with Session(engine) as session:
+ yield session
+
+
+app = FastAPI()
+
+
+@app.on_event("startup")
+def on_startup():
+ create_db_and_tables()
+
+
+@app.post("/heroes/", response_model=HeroPublic)
+def create_hero(hero: HeroCreate, session: Session = Depends(get_session)):
+ db_hero = Hero.model_validate(hero)
+ session.add(db_hero)
+ session.commit()
+ session.refresh(db_hero)
+ return db_hero
+
+
+@app.get("/heroes/", response_model=list[HeroPublic])
+def read_heroes(
+ session: Session = Depends(get_session),
+ offset: int = 0,
+ limit: int = Query(default=100, le=100),
+):
+ heroes = session.exec(select(Hero).offset(offset).limit(limit)).all()
+ return heroes
+
+
+@app.get("/heroes/{hero_id}", response_model=HeroPublic)
+def read_hero(hero_id: int, session: Session = Depends(get_session)):
+ hero = session.get(Hero, hero_id)
+ if not hero:
+ raise HTTPException(status_code=404, detail="Hero not found")
+ return hero
+
+
+@app.patch("/heroes/{hero_id}", response_model=HeroPublic)
+def update_hero(
+ hero_id: int, hero: HeroUpdate, session: Session = Depends(get_session)
+):
+ hero_db = session.get(Hero, hero_id)
+ if not hero_db:
+ raise HTTPException(status_code=404, detail="Hero not found")
+ hero_data = hero.model_dump(exclude_unset=True)
+ hero_db.sqlmodel_update(hero_data)
+ session.add(hero_db)
+ session.commit()
+ session.refresh(hero_db)
+ return hero_db
+
+
+@app.delete("/heroes/{hero_id}")
+def delete_hero(hero_id: int, session: Session = Depends(get_session)):
+ hero = session.get(Hero, hero_id)
+ if not hero:
+ raise HTTPException(status_code=404, detail="Hero not found")
+ session.delete(hero)
+ session.commit()
+ return {"ok": True}
diff --git a/docs_src/sql_databases/tutorial002_py39.py b/docs_src/sql_databases/tutorial002_py39.py
new file mode 100644
index 000000000..d8f5dd090
--- /dev/null
+++ b/docs_src/sql_databases/tutorial002_py39.py
@@ -0,0 +1,104 @@
+from typing import Union
+
+from fastapi import Depends, FastAPI, HTTPException, Query
+from sqlmodel import Field, Session, SQLModel, create_engine, select
+
+
+class HeroBase(SQLModel):
+ name: str = Field(index=True)
+ age: Union[int, None] = Field(default=None, index=True)
+
+
+class Hero(HeroBase, table=True):
+ id: Union[int, None] = Field(default=None, primary_key=True)
+ secret_name: str
+
+
+class HeroPublic(HeroBase):
+ id: int
+
+
+class HeroCreate(HeroBase):
+ secret_name: str
+
+
+class HeroUpdate(HeroBase):
+ name: Union[str, None] = None
+ age: Union[int, None] = None
+ secret_name: Union[str, None] = None
+
+
+sqlite_file_name = "database.db"
+sqlite_url = f"sqlite:///{sqlite_file_name}"
+
+connect_args = {"check_same_thread": False}
+engine = create_engine(sqlite_url, connect_args=connect_args)
+
+
+def create_db_and_tables():
+ SQLModel.metadata.create_all(engine)
+
+
+def get_session():
+ with Session(engine) as session:
+ yield session
+
+
+app = FastAPI()
+
+
+@app.on_event("startup")
+def on_startup():
+ create_db_and_tables()
+
+
+@app.post("/heroes/", response_model=HeroPublic)
+def create_hero(hero: HeroCreate, session: Session = Depends(get_session)):
+ db_hero = Hero.model_validate(hero)
+ session.add(db_hero)
+ session.commit()
+ session.refresh(db_hero)
+ return db_hero
+
+
+@app.get("/heroes/", response_model=list[HeroPublic])
+def read_heroes(
+ session: Session = Depends(get_session),
+ offset: int = 0,
+ limit: int = Query(default=100, le=100),
+):
+ heroes = session.exec(select(Hero).offset(offset).limit(limit)).all()
+ return heroes
+
+
+@app.get("/heroes/{hero_id}", response_model=HeroPublic)
+def read_hero(hero_id: int, session: Session = Depends(get_session)):
+ hero = session.get(Hero, hero_id)
+ if not hero:
+ raise HTTPException(status_code=404, detail="Hero not found")
+ return hero
+
+
+@app.patch("/heroes/{hero_id}", response_model=HeroPublic)
+def update_hero(
+ hero_id: int, hero: HeroUpdate, session: Session = Depends(get_session)
+):
+ hero_db = session.get(Hero, hero_id)
+ if not hero_db:
+ raise HTTPException(status_code=404, detail="Hero not found")
+ hero_data = hero.model_dump(exclude_unset=True)
+ hero_db.sqlmodel_update(hero_data)
+ session.add(hero_db)
+ session.commit()
+ session.refresh(hero_db)
+ return hero_db
+
+
+@app.delete("/heroes/{hero_id}")
+def delete_hero(hero_id: int, session: Session = Depends(get_session)):
+ hero = session.get(Hero, hero_id)
+ if not hero:
+ raise HTTPException(status_code=404, detail="Hero not found")
+ session.delete(hero)
+ session.commit()
+ return {"ok": True}
diff --git a/fastapi/__init__.py b/fastapi/__init__.py
index 3413dffc8..77b52f35b 100644
--- a/fastapi/__init__.py
+++ b/fastapi/__init__.py
@@ -1,6 +1,6 @@
"""FastAPI framework, high performance, easy to learn, fast to code, ready for production"""
-__version__ = "0.112.0"
+__version__ = "0.115.2"
from starlette import status as status
diff --git a/fastapi/_compat.py b/fastapi/_compat.py
index 06b847b4f..56c5d744e 100644
--- a/fastapi/_compat.py
+++ b/fastapi/_compat.py
@@ -2,6 +2,7 @@ from collections import deque
from copy import copy
from dataclasses import dataclass, is_dataclass
from enum import Enum
+from functools import lru_cache
from typing import (
Any,
Callable,
@@ -70,7 +71,7 @@ if PYDANTIC_V2:
general_plain_validator_function as with_info_plain_validator_function, # noqa: F401
)
- Required = PydanticUndefined
+ RequiredParam = PydanticUndefined
Undefined = PydanticUndefined
UndefinedType = PydanticUndefinedType
evaluate_forwardref = eval_type_lenient
@@ -279,6 +280,12 @@ if PYDANTIC_V2:
BodyModel: Type[BaseModel] = create_model(model_name, **field_params) # type: ignore[call-overload]
return BodyModel
+ def get_model_fields(model: Type[BaseModel]) -> List[ModelField]:
+ return [
+ ModelField(field_info=field_info, name=name)
+ for name, field_info in model.model_fields.items()
+ ]
+
else:
from fastapi.openapi.constants import REF_PREFIX as REF_PREFIX
from pydantic import AnyUrl as Url # noqa: F401
@@ -306,9 +313,10 @@ else:
from pydantic.fields import ( # type: ignore[no-redef,attr-defined]
ModelField as ModelField, # noqa: F401
)
- from pydantic.fields import ( # type: ignore[no-redef,attr-defined]
- Required as Required, # noqa: F401
- )
+
+ # Keeping old "Required" functionality from Pydantic V1, without
+ # shadowing typing.Required.
+ RequiredParam: Any = Ellipsis # type: ignore[no-redef]
from pydantic.fields import ( # type: ignore[no-redef,attr-defined]
Undefined as Undefined,
)
@@ -513,6 +521,9 @@ else:
BodyModel.__fields__[f.name] = f # type: ignore[index]
return BodyModel
+ def get_model_fields(model: Type[BaseModel]) -> List[ModelField]:
+ return list(model.__fields__.values()) # type: ignore[attr-defined]
+
def _regenerate_error_with_loc(
*, errors: Sequence[Any], loc_prefix: Tuple[Union[str, int], ...]
@@ -532,6 +543,12 @@ def _annotation_is_sequence(annotation: Union[Type[Any], None]) -> bool:
def field_annotation_is_sequence(annotation: Union[Type[Any], None]) -> bool:
+ origin = get_origin(annotation)
+ if origin is Union or origin is UnionType:
+ for arg in get_args(annotation):
+ if field_annotation_is_sequence(arg):
+ return True
+ return False
return _annotation_is_sequence(annotation) or _annotation_is_sequence(
get_origin(annotation)
)
@@ -634,3 +651,8 @@ def is_uploadfile_sequence_annotation(annotation: Any) -> bool:
is_uploadfile_or_nonable_uploadfile_annotation(sub_annotation)
for sub_annotation in get_args(annotation)
)
+
+
+@lru_cache
+def get_cached_model_fields(model: Type[BaseModel]) -> List[ModelField]:
+ return get_model_fields(model)
diff --git a/fastapi/applications.py b/fastapi/applications.py
index 6da05c2f0..2c73c5663 100644
--- a/fastapi/applications.py
+++ b/fastapi/applications.py
@@ -1056,7 +1056,7 @@ class FastAPI(Starlette):
def add_api_route(
self,
path: str,
- endpoint: Callable[..., Coroutine[Any, Any, Response]],
+ endpoint: Callable[..., Any],
*,
response_model: Any = Default(None),
status_code: Optional[int] = None,
diff --git a/fastapi/dependencies/models.py b/fastapi/dependencies/models.py
index 61ef00638..418c11725 100644
--- a/fastapi/dependencies/models.py
+++ b/fastapi/dependencies/models.py
@@ -1,58 +1,37 @@
-from typing import Any, Callable, List, Optional, Sequence
+from dataclasses import dataclass, field
+from typing import Any, Callable, List, Optional, Sequence, Tuple
from fastapi._compat import ModelField
from fastapi.security.base import SecurityBase
+@dataclass
class SecurityRequirement:
- def __init__(
- self, security_scheme: SecurityBase, scopes: Optional[Sequence[str]] = None
- ):
- self.security_scheme = security_scheme
- self.scopes = scopes
+ security_scheme: SecurityBase
+ scopes: Optional[Sequence[str]] = None
+@dataclass
class Dependant:
- def __init__(
- self,
- *,
- path_params: Optional[List[ModelField]] = None,
- query_params: Optional[List[ModelField]] = None,
- header_params: Optional[List[ModelField]] = None,
- cookie_params: Optional[List[ModelField]] = None,
- body_params: Optional[List[ModelField]] = None,
- dependencies: Optional[List["Dependant"]] = None,
- security_schemes: Optional[List[SecurityRequirement]] = None,
- name: Optional[str] = None,
- call: Optional[Callable[..., Any]] = None,
- request_param_name: Optional[str] = None,
- websocket_param_name: Optional[str] = None,
- http_connection_param_name: Optional[str] = None,
- response_param_name: Optional[str] = None,
- background_tasks_param_name: Optional[str] = None,
- security_scopes_param_name: Optional[str] = None,
- security_scopes: Optional[List[str]] = None,
- use_cache: bool = True,
- path: Optional[str] = None,
- ) -> None:
- self.path_params = path_params or []
- self.query_params = query_params or []
- self.header_params = header_params or []
- self.cookie_params = cookie_params or []
- self.body_params = body_params or []
- self.dependencies = dependencies or []
- self.security_requirements = security_schemes or []
- self.request_param_name = request_param_name
- self.websocket_param_name = websocket_param_name
- self.http_connection_param_name = http_connection_param_name
- self.response_param_name = response_param_name
- self.background_tasks_param_name = background_tasks_param_name
- self.security_scopes = security_scopes
- self.security_scopes_param_name = security_scopes_param_name
- self.name = name
- self.call = call
- self.use_cache = use_cache
- # Store the path to be able to re-generate a dependable from it in overrides
- self.path = path
- # Save the cache key at creation to optimize performance
+ path_params: List[ModelField] = field(default_factory=list)
+ query_params: List[ModelField] = field(default_factory=list)
+ header_params: List[ModelField] = field(default_factory=list)
+ cookie_params: List[ModelField] = field(default_factory=list)
+ body_params: List[ModelField] = field(default_factory=list)
+ dependencies: List["Dependant"] = field(default_factory=list)
+ security_requirements: List[SecurityRequirement] = field(default_factory=list)
+ name: Optional[str] = None
+ call: Optional[Callable[..., Any]] = None
+ request_param_name: Optional[str] = None
+ websocket_param_name: Optional[str] = None
+ http_connection_param_name: Optional[str] = None
+ response_param_name: Optional[str] = None
+ background_tasks_param_name: Optional[str] = None
+ security_scopes_param_name: Optional[str] = None
+ security_scopes: Optional[List[str]] = None
+ use_cache: bool = True
+ path: Optional[str] = None
+ cache_key: Tuple[Optional[Callable[..., Any]], Tuple[str, ...]] = field(init=False)
+
+ def __post_init__(self) -> None:
self.cache_key = (self.call, tuple(sorted(set(self.security_scopes or []))))
diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py
index 4f984177a..87653c80d 100644
--- a/fastapi/dependencies/utils.py
+++ b/fastapi/dependencies/utils.py
@@ -1,6 +1,7 @@
import inspect
from contextlib import AsyncExitStack, contextmanager
from copy import copy, deepcopy
+from dataclasses import dataclass
from typing import (
Any,
Callable,
@@ -23,7 +24,7 @@ from fastapi._compat import (
PYDANTIC_V2,
ErrorWrapper,
ModelField,
- Required,
+ RequiredParam,
Undefined,
_regenerate_error_with_loc,
copy_field_info,
@@ -31,6 +32,7 @@ from fastapi._compat import (
evaluate_forwardref,
field_annotation_is_scalar,
get_annotation_from_field_info,
+ get_cached_model_fields,
get_missing_field_error,
is_bytes_field,
is_bytes_sequence_field,
@@ -54,11 +56,18 @@ from fastapi.logger import logger
from fastapi.security.base import SecurityBase
from fastapi.security.oauth2 import OAuth2, SecurityScopes
from fastapi.security.open_id_connect_url import OpenIdConnect
-from fastapi.utils import create_response_field, get_path_param_names
+from fastapi.utils import create_model_field, get_path_param_names
+from pydantic import BaseModel
from pydantic.fields import FieldInfo
from starlette.background import BackgroundTasks as StarletteBackgroundTasks
from starlette.concurrency import run_in_threadpool
-from starlette.datastructures import FormData, Headers, QueryParams, UploadFile
+from starlette.datastructures import (
+ FormData,
+ Headers,
+ ImmutableMultiDict,
+ QueryParams,
+ UploadFile,
+)
from starlette.requests import HTTPConnection, Request
from starlette.responses import Response
from starlette.websockets import WebSocket
@@ -79,25 +88,23 @@ multipart_incorrect_install_error = (
)
-def check_file_field(field: ModelField) -> None:
- field_info = field.field_info
- if isinstance(field_info, params.Form):
+def ensure_multipart_is_installed() -> None:
+ try:
+ # __version__ is available in both multiparts, and can be mocked
+ from multipart import __version__
+
+ assert __version__
try:
- # __version__ is available in both multiparts, and can be mocked
- from multipart import __version__ # type: ignore
+ # parse_options_header is only available in the right multipart
+ from multipart.multipart import parse_options_header
- assert __version__
- try:
- # parse_options_header is only available in the right multipart
- from multipart.multipart import parse_options_header # type: ignore
-
- assert parse_options_header
- except ImportError:
- logger.error(multipart_incorrect_install_error)
- raise RuntimeError(multipart_incorrect_install_error) from None
+ assert parse_options_header # type: ignore[truthy-function]
except ImportError:
- logger.error(multipart_not_installed_error)
- raise RuntimeError(multipart_not_installed_error) from None
+ logger.error(multipart_incorrect_install_error)
+ raise RuntimeError(multipart_incorrect_install_error) from None
+ except ImportError:
+ logger.error(multipart_not_installed_error)
+ raise RuntimeError(multipart_not_installed_error) from None
def get_param_sub_dependant(
@@ -175,7 +182,7 @@ def get_flat_dependant(
header_params=dependant.header_params.copy(),
cookie_params=dependant.cookie_params.copy(),
body_params=dependant.body_params.copy(),
- security_schemes=dependant.security_requirements.copy(),
+ security_requirements=dependant.security_requirements.copy(),
use_cache=dependant.use_cache,
path=dependant.path,
)
@@ -194,14 +201,23 @@ def get_flat_dependant(
return flat_dependant
+def _get_flat_fields_from_params(fields: List[ModelField]) -> List[ModelField]:
+ if not fields:
+ return fields
+ first_field = fields[0]
+ if len(fields) == 1 and lenient_issubclass(first_field.type_, BaseModel):
+ fields_to_extract = get_cached_model_fields(first_field.type_)
+ return fields_to_extract
+ return fields
+
+
def get_flat_params(dependant: Dependant) -> List[ModelField]:
flat_dependant = get_flat_dependant(dependant, skip_repeats=True)
- return (
- flat_dependant.path_params
- + flat_dependant.query_params
- + flat_dependant.header_params
- + flat_dependant.cookie_params
- )
+ path_params = _get_flat_fields_from_params(flat_dependant.path_params)
+ query_params = _get_flat_fields_from_params(flat_dependant.query_params)
+ header_params = _get_flat_fields_from_params(flat_dependant.header_params)
+ cookie_params = _get_flat_fields_from_params(flat_dependant.cookie_params)
+ return path_params + query_params + header_params + cookie_params
def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature:
@@ -258,16 +274,16 @@ def get_dependant(
)
for param_name, param in signature_params.items():
is_path_param = param_name in path_param_names
- type_annotation, depends, param_field = analyze_param(
+ param_details = analyze_param(
param_name=param_name,
annotation=param.annotation,
value=param.default,
is_path_param=is_path_param,
)
- if depends is not None:
+ if param_details.depends is not None:
sub_dependant = get_param_sub_dependant(
param_name=param_name,
- depends=depends,
+ depends=param_details.depends,
path=path,
security_scopes=security_scopes,
)
@@ -275,18 +291,18 @@ def get_dependant(
continue
if add_non_field_param_to_dependency(
param_name=param_name,
- type_annotation=type_annotation,
+ type_annotation=param_details.type_annotation,
dependant=dependant,
):
assert (
- param_field is None
+ param_details.field is None
), f"Cannot specify multiple FastAPI annotations for {param_name!r}"
continue
- assert param_field is not None
- if is_body_param(param_field=param_field, is_path_param=is_path_param):
- dependant.body_params.append(param_field)
+ assert param_details.field is not None
+ if isinstance(param_details.field.field_info, params.Body):
+ dependant.body_params.append(param_details.field)
else:
- add_param_to_fields(field=param_field, dependant=dependant)
+ add_param_to_fields(field=param_details.field, dependant=dependant)
return dependant
@@ -314,13 +330,20 @@ def add_non_field_param_to_dependency(
return None
+@dataclass
+class ParamDetails:
+ type_annotation: Any
+ depends: Optional[params.Depends]
+ field: Optional[ModelField]
+
+
def analyze_param(
*,
param_name: str,
annotation: Any,
value: Any,
is_path_param: bool,
-) -> Tuple[Any, Optional[params.Depends], Optional[ModelField]]:
+) -> ParamDetails:
field_info = None
depends = None
type_annotation: Any = Any
@@ -328,6 +351,7 @@ def analyze_param(
if annotation is not inspect.Signature.empty:
use_annotation = annotation
type_annotation = annotation
+ # Extract Annotated info
if get_origin(use_annotation) is Annotated:
annotated_args = get_args(annotation)
type_annotation = annotated_args[0]
@@ -342,17 +366,20 @@ def analyze_param(
if isinstance(arg, (params.Param, params.Body, params.Depends))
]
if fastapi_specific_annotations:
- fastapi_annotation: Union[
- FieldInfo, params.Depends, None
- ] = fastapi_specific_annotations[-1]
+ fastapi_annotation: Union[FieldInfo, params.Depends, None] = (
+ fastapi_specific_annotations[-1]
+ )
else:
fastapi_annotation = None
+ # Set default for Annotated FieldInfo
if isinstance(fastapi_annotation, FieldInfo):
# Copy `field_info` because we mutate `field_info.default` below.
field_info = copy_field_info(
field_info=fastapi_annotation, annotation=use_annotation
)
- assert field_info.default is Undefined or field_info.default is Required, (
+ assert (
+ field_info.default is Undefined or field_info.default is RequiredParam
+ ), (
f"`{field_info.__class__.__name__}` default value cannot be set in"
f" `Annotated` for {param_name!r}. Set the default value with `=` instead."
)
@@ -360,10 +387,11 @@ def analyze_param(
assert not is_path_param, "Path parameters cannot have default values"
field_info.default = value
else:
- field_info.default = Required
+ field_info.default = RequiredParam
+ # Get Annotated Depends
elif isinstance(fastapi_annotation, params.Depends):
depends = fastapi_annotation
-
+ # Get Depends from default value
if isinstance(value, params.Depends):
assert depends is None, (
"Cannot specify `Depends` in `Annotated` and default value"
@@ -374,6 +402,7 @@ def analyze_param(
f" default value together for {param_name!r}"
)
depends = value
+ # Get FieldInfo from default value
elif isinstance(value, FieldInfo):
assert field_info is None, (
"Cannot specify FastAPI annotations in `Annotated` and default value"
@@ -383,11 +412,13 @@ def analyze_param(
if PYDANTIC_V2:
field_info.annotation = type_annotation
+ # Get Depends from type annotation
if depends is not None and depends.dependency is None:
# Copy `depends` before mutating it
depends = copy(depends)
depends.dependency = type_annotation
+ # Handle non-param type annotations like Request
if lenient_issubclass(
type_annotation,
(
@@ -403,10 +434,11 @@ def analyze_param(
assert (
field_info is None
), f"Cannot specify FastAPI annotation for type {type_annotation!r}"
+ # Handle default assignations, neither field_info nor depends was not found in Annotated nor default value
elif field_info is None and depends is None:
- default_value = value if value is not inspect.Signature.empty else Required
+ default_value = value if value is not inspect.Signature.empty else RequiredParam
if is_path_param:
- # We might check here that `default_value is Required`, but the fact is that the same
+ # We might check here that `default_value is RequiredParam`, but the fact is that the same
# parameter might sometimes be a path parameter and sometimes not. See
# `tests/test_infer_param_optionality.py` for an example.
field_info = params.Path(annotation=use_annotation)
@@ -420,7 +452,9 @@ def analyze_param(
field_info = params.Query(annotation=use_annotation, default=default_value)
field = None
+ # It's a field_info, not a dependency
if field_info is not None:
+ # Handle field_info.in_
if is_path_param:
assert isinstance(field_info, params.Path), (
f"Cannot use `{field_info.__class__.__name__}` for path param"
@@ -436,40 +470,37 @@ def analyze_param(
field_info,
param_name,
)
+ if isinstance(field_info, params.Form):
+ ensure_multipart_is_installed()
if not field_info.alias and getattr(field_info, "convert_underscores", None):
alias = param_name.replace("_", "-")
else:
alias = field_info.alias or param_name
field_info.alias = alias
- field = create_response_field(
+ field = create_model_field(
name=param_name,
type_=use_annotation_from_field_info,
default=field_info.default,
alias=alias,
- required=field_info.default in (Required, Undefined),
+ required=field_info.default in (RequiredParam, Undefined),
field_info=field_info,
)
+ if is_path_param:
+ assert is_scalar_field(
+ field=field
+ ), "Path params must be of one of the supported types"
+ elif isinstance(field_info, params.Query):
+ assert (
+ is_scalar_field(field)
+ or is_scalar_sequence_field(field)
+ or (
+ lenient_issubclass(field.type_, BaseModel)
+ # For Pydantic v1
+ and getattr(field, "shape", 1) == 1
+ )
+ )
- return type_annotation, depends, field
-
-
-def is_body_param(*, param_field: ModelField, is_path_param: bool) -> bool:
- if is_path_param:
- assert is_scalar_field(
- field=param_field
- ), "Path params must be of one of the supported types"
- return False
- elif is_scalar_field(field=param_field):
- return False
- elif isinstance(
- param_field.field_info, (params.Query, params.Header)
- ) and is_scalar_sequence_field(param_field):
- return False
- else:
- assert isinstance(
- param_field.field_info, params.Body
- ), f"Param: {param_field.name} can only be a request body, using Body()"
- return True
+ return ParamDetails(type_annotation=type_annotation, depends=depends, field=field)
def add_param_to_fields(*, field: ModelField, dependant: Dependant) -> None:
@@ -521,6 +552,15 @@ async def solve_generator(
return await stack.enter_async_context(cm)
+@dataclass
+class SolvedDependency:
+ values: Dict[str, Any]
+ errors: List[Any]
+ background_tasks: Optional[StarletteBackgroundTasks]
+ response: Response
+ dependency_cache: Dict[Tuple[Callable[..., Any], Tuple[str]], Any]
+
+
async def solve_dependencies(
*,
request: Union[Request, WebSocket],
@@ -531,13 +571,8 @@ async def solve_dependencies(
dependency_overrides_provider: Optional[Any] = None,
dependency_cache: Optional[Dict[Tuple[Callable[..., Any], Tuple[str]], Any]] = None,
async_exit_stack: AsyncExitStack,
-) -> Tuple[
- Dict[str, Any],
- List[Any],
- Optional[StarletteBackgroundTasks],
- Response,
- Dict[Tuple[Callable[..., Any], Tuple[str]], Any],
-]:
+ embed_body_fields: bool,
+) -> SolvedDependency:
values: Dict[str, Any] = {}
errors: List[Any] = []
if response is None:
@@ -578,28 +613,23 @@ async def solve_dependencies(
dependency_overrides_provider=dependency_overrides_provider,
dependency_cache=dependency_cache,
async_exit_stack=async_exit_stack,
+ embed_body_fields=embed_body_fields,
)
- (
- sub_values,
- sub_errors,
- background_tasks,
- _, # the subdependency returns the same response we have
- sub_dependency_cache,
- ) = solved_result
- dependency_cache.update(sub_dependency_cache)
- if sub_errors:
- errors.extend(sub_errors)
+ background_tasks = solved_result.background_tasks
+ dependency_cache.update(solved_result.dependency_cache)
+ if solved_result.errors:
+ errors.extend(solved_result.errors)
continue
if sub_dependant.use_cache and sub_dependant.cache_key in dependency_cache:
solved = dependency_cache[sub_dependant.cache_key]
elif is_gen_callable(call) or is_async_gen_callable(call):
solved = await solve_generator(
- call=call, stack=async_exit_stack, sub_values=sub_values
+ call=call, stack=async_exit_stack, sub_values=solved_result.values
)
elif is_coroutine_callable(call):
- solved = await call(**sub_values)
+ solved = await call(**solved_result.values)
else:
- solved = await run_in_threadpool(call, **sub_values)
+ solved = await run_in_threadpool(call, **solved_result.values)
if sub_dependant.name is not None:
values[sub_dependant.name] = solved
if sub_dependant.cache_key not in dependency_cache:
@@ -626,7 +656,9 @@ async def solve_dependencies(
body_values,
body_errors,
) = await request_body_to_args( # body_params checked above
- required_params=dependant.body_params, received_body=body
+ body_fields=dependant.body_params,
+ received_body=body,
+ embed_body_fields=embed_body_fields,
)
values.update(body_values)
errors.extend(body_errors)
@@ -646,142 +678,257 @@ async def solve_dependencies(
values[dependant.security_scopes_param_name] = SecurityScopes(
scopes=dependant.security_scopes
)
- return values, errors, background_tasks, response, dependency_cache
+ return SolvedDependency(
+ values=values,
+ errors=errors,
+ background_tasks=background_tasks,
+ response=response,
+ dependency_cache=dependency_cache,
+ )
+
+
+def _validate_value_with_model_field(
+ *, field: ModelField, value: Any, values: Dict[str, Any], loc: Tuple[str, ...]
+) -> Tuple[Any, List[Any]]:
+ if value is None:
+ if field.required:
+ return None, [get_missing_field_error(loc=loc)]
+ else:
+ return deepcopy(field.default), []
+ v_, errors_ = field.validate(value, values, loc=loc)
+ if isinstance(errors_, ErrorWrapper):
+ return None, [errors_]
+ elif isinstance(errors_, list):
+ new_errors = _regenerate_error_with_loc(errors=errors_, loc_prefix=())
+ return None, new_errors
+ else:
+ return v_, []
+
+
+def _get_multidict_value(
+ field: ModelField, values: Mapping[str, Any], alias: Union[str, None] = None
+) -> Any:
+ alias = alias or field.alias
+ if is_sequence_field(field) and isinstance(values, (ImmutableMultiDict, Headers)):
+ value = values.getlist(alias)
+ else:
+ value = values.get(alias, None)
+ if (
+ value is None
+ or (
+ isinstance(field.field_info, params.Form)
+ and isinstance(value, str) # For type checks
+ and value == ""
+ )
+ or (is_sequence_field(field) and len(value) == 0)
+ ):
+ if field.required:
+ return
+ else:
+ return deepcopy(field.default)
+ return value
def request_params_to_args(
- required_params: Sequence[ModelField],
+ fields: Sequence[ModelField],
received_params: Union[Mapping[str, Any], QueryParams, Headers],
) -> Tuple[Dict[str, Any], List[Any]]:
- values = {}
- errors = []
- for field in required_params:
- if is_scalar_sequence_field(field) and isinstance(
- received_params, (QueryParams, Headers)
- ):
- value = received_params.getlist(field.alias) or field.default
- else:
- value = received_params.get(field.alias)
+ values: Dict[str, Any] = {}
+ errors: List[Dict[str, Any]] = []
+
+ if not fields:
+ return values, errors
+
+ first_field = fields[0]
+ fields_to_extract = fields
+ single_not_embedded_field = False
+ if len(fields) == 1 and lenient_issubclass(first_field.type_, BaseModel):
+ fields_to_extract = get_cached_model_fields(first_field.type_)
+ single_not_embedded_field = True
+
+ params_to_process: Dict[str, Any] = {}
+
+ processed_keys = set()
+
+ for field in fields_to_extract:
+ alias = None
+ if isinstance(received_params, Headers):
+ # Handle fields extracted from a Pydantic Model for a header, each field
+ # doesn't have a FieldInfo of type Header with the default convert_underscores=True
+ convert_underscores = getattr(field.field_info, "convert_underscores", True)
+ if convert_underscores:
+ alias = (
+ field.alias
+ if field.alias != field.name
+ else field.name.replace("_", "-")
+ )
+ value = _get_multidict_value(field, received_params, alias=alias)
+ if value is not None:
+ params_to_process[field.name] = value
+ processed_keys.add(alias or field.alias)
+ processed_keys.add(field.name)
+
+ for key, value in received_params.items():
+ if key not in processed_keys:
+ params_to_process[key] = value
+
+ if single_not_embedded_field:
+ field_info = first_field.field_info
+ assert isinstance(
+ field_info, params.Param
+ ), "Params must be subclasses of Param"
+ loc: Tuple[str, ...] = (field_info.in_.value,)
+ v_, errors_ = _validate_value_with_model_field(
+ field=first_field, value=params_to_process, values=values, loc=loc
+ )
+ return {first_field.name: v_}, errors_
+
+ for field in fields:
+ value = _get_multidict_value(field, received_params)
field_info = field.field_info
assert isinstance(
field_info, params.Param
), "Params must be subclasses of Param"
loc = (field_info.in_.value, field.alias)
- if value is None:
- if field.required:
- errors.append(get_missing_field_error(loc=loc))
- else:
- values[field.name] = deepcopy(field.default)
- continue
- v_, errors_ = field.validate(value, values, loc=loc)
- if isinstance(errors_, ErrorWrapper):
- errors.append(errors_)
- elif isinstance(errors_, list):
- new_errors = _regenerate_error_with_loc(errors=errors_, loc_prefix=())
- errors.extend(new_errors)
+ v_, errors_ = _validate_value_with_model_field(
+ field=field, value=value, values=values, loc=loc
+ )
+ if errors_:
+ errors.extend(errors_)
else:
values[field.name] = v_
return values, errors
-async def request_body_to_args(
- required_params: List[ModelField],
- received_body: Optional[Union[Dict[str, Any], FormData]],
-) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]:
+def _should_embed_body_fields(fields: List[ModelField]) -> bool:
+ if not fields:
+ return False
+ # More than one dependency could have the same field, it would show up as multiple
+ # fields but it's the same one, so count them by name
+ body_param_names_set = {field.name for field in fields}
+ # A top level field has to be a single field, not multiple
+ if len(body_param_names_set) > 1:
+ return True
+ first_field = fields[0]
+ # If it explicitly specifies it is embedded, it has to be embedded
+ if getattr(first_field.field_info, "embed", None):
+ return True
+ # If it's a Form (or File) field, it has to be a BaseModel to be top level
+ # otherwise it has to be embedded, so that the key value pair can be extracted
+ if isinstance(first_field.field_info, params.Form) and not lenient_issubclass(
+ first_field.type_, BaseModel
+ ):
+ return True
+ return False
+
+
+async def _extract_form_body(
+ body_fields: List[ModelField],
+ received_body: FormData,
+) -> Dict[str, Any]:
values = {}
+ first_field = body_fields[0]
+ first_field_info = first_field.field_info
+
+ for field in body_fields:
+ value = _get_multidict_value(field, received_body)
+ if (
+ isinstance(first_field_info, params.File)
+ and is_bytes_field(field)
+ and isinstance(value, UploadFile)
+ ):
+ value = await value.read()
+ elif (
+ is_bytes_sequence_field(field)
+ and isinstance(first_field_info, params.File)
+ and value_is_sequence(value)
+ ):
+ # For types
+ assert isinstance(value, sequence_types) # type: ignore[arg-type]
+ results: List[Union[bytes, str]] = []
+
+ async def process_fn(
+ fn: Callable[[], Coroutine[Any, Any, Any]],
+ ) -> None:
+ result = await fn()
+ results.append(result) # noqa: B023
+
+ async with anyio.create_task_group() as tg:
+ for sub_value in value:
+ tg.start_soon(process_fn, sub_value.read)
+ value = serialize_sequence_value(field=field, value=results)
+ if value is not None:
+ values[field.alias] = value
+ for key, value in received_body.items():
+ if key not in values:
+ values[key] = value
+ return values
+
+
+async def request_body_to_args(
+ body_fields: List[ModelField],
+ received_body: Optional[Union[Dict[str, Any], FormData]],
+ embed_body_fields: bool,
+) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]:
+ values: Dict[str, Any] = {}
errors: List[Dict[str, Any]] = []
- if required_params:
- field = required_params[0]
- field_info = field.field_info
- embed = getattr(field_info, "embed", None)
- field_alias_omitted = len(required_params) == 1 and not embed
- if field_alias_omitted:
- received_body = {field.alias: received_body}
+ assert body_fields, "request_body_to_args() should be called with fields"
+ single_not_embedded_field = len(body_fields) == 1 and not embed_body_fields
+ first_field = body_fields[0]
+ body_to_process = received_body
- for field in required_params:
- loc: Tuple[str, ...]
- if field_alias_omitted:
- loc = ("body",)
- else:
- loc = ("body", field.alias)
+ fields_to_extract: List[ModelField] = body_fields
- value: Optional[Any] = None
- if received_body is not None:
- if (is_sequence_field(field)) and isinstance(received_body, FormData):
- value = received_body.getlist(field.alias)
- else:
- try:
- value = received_body.get(field.alias)
- except AttributeError:
- errors.append(get_missing_field_error(loc))
- continue
- if (
- value is None
- or (isinstance(field_info, params.Form) and value == "")
- or (
- isinstance(field_info, params.Form)
- and is_sequence_field(field)
- and len(value) == 0
- )
- ):
- if field.required:
- errors.append(get_missing_field_error(loc))
- else:
- values[field.name] = deepcopy(field.default)
+ if single_not_embedded_field and lenient_issubclass(first_field.type_, BaseModel):
+ fields_to_extract = get_cached_model_fields(first_field.type_)
+
+ if isinstance(received_body, FormData):
+ body_to_process = await _extract_form_body(fields_to_extract, received_body)
+
+ if single_not_embedded_field:
+ loc: Tuple[str, ...] = ("body",)
+ v_, errors_ = _validate_value_with_model_field(
+ field=first_field, value=body_to_process, values=values, loc=loc
+ )
+ return {first_field.name: v_}, errors_
+ for field in body_fields:
+ loc = ("body", field.alias)
+ value: Optional[Any] = None
+ if body_to_process is not None:
+ try:
+ value = body_to_process.get(field.alias)
+ # If the received body is a list, not a dict
+ except AttributeError:
+ errors.append(get_missing_field_error(loc))
continue
- if (
- isinstance(field_info, params.File)
- and is_bytes_field(field)
- and isinstance(value, UploadFile)
- ):
- value = await value.read()
- elif (
- is_bytes_sequence_field(field)
- and isinstance(field_info, params.File)
- and value_is_sequence(value)
- ):
- # For types
- assert isinstance(value, sequence_types) # type: ignore[arg-type]
- results: List[Union[bytes, str]] = []
-
- async def process_fn(
- fn: Callable[[], Coroutine[Any, Any, Any]],
- ) -> None:
- result = await fn()
- results.append(result) # noqa: B023
-
- async with anyio.create_task_group() as tg:
- for sub_value in value:
- tg.start_soon(process_fn, sub_value.read)
- value = serialize_sequence_value(field=field, value=results)
-
- v_, errors_ = field.validate(value, values, loc=loc)
-
- if isinstance(errors_, list):
- errors.extend(errors_)
- elif errors_:
- errors.append(errors_)
- else:
- values[field.name] = v_
+ v_, errors_ = _validate_value_with_model_field(
+ field=field, value=value, values=values, loc=loc
+ )
+ if errors_:
+ errors.extend(errors_)
+ else:
+ values[field.name] = v_
return values, errors
-def get_body_field(*, dependant: Dependant, name: str) -> Optional[ModelField]:
- flat_dependant = get_flat_dependant(dependant)
+def get_body_field(
+ *, flat_dependant: Dependant, name: str, embed_body_fields: bool
+) -> Optional[ModelField]:
+ """
+ Get a ModelField representing the request body for a path operation, combining
+ all body parameters into a single field if necessary.
+
+ Used to check if it's form data (with `isinstance(body_field, params.Form)`)
+ or JSON and to generate the JSON Schema for a request body.
+
+ This is **not** used to validate/parse the request body, that's done with each
+ individual body parameter.
+ """
if not flat_dependant.body_params:
return None
first_param = flat_dependant.body_params[0]
- field_info = first_param.field_info
- embed = getattr(field_info, "embed", None)
- body_param_names_set = {param.name for param in flat_dependant.body_params}
- if len(body_param_names_set) == 1 and not embed:
- check_file_field(first_param)
+ if not embed_body_fields:
return first_param
- # If one field requires to embed, all have to be embedded
- # in case a sub-dependency is evaluated with a single unique body field
- # That is combined (embedded) with other body fields
- for param in flat_dependant.body_params:
- setattr(param.field_info, "embed", True) # noqa: B010
model_name = "Body_" + name
BodyModel = create_body_model(
fields=flat_dependant.body_params, model_name=model_name
@@ -807,12 +954,11 @@ def get_body_field(*, dependant: Dependant, name: str) -> Optional[ModelField]:
]
if len(set(body_param_media_types)) == 1:
BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0]
- final_field = create_response_field(
+ final_field = create_model_field(
name="body",
type_=BodyModel,
required=required,
alias="body",
field_info=BodyFieldInfo(**BodyFieldInfo_kwargs),
)
- check_file_field(final_field)
return final_field
diff --git a/fastapi/openapi/utils.py b/fastapi/openapi/utils.py
index 79ad9f83f..947eca948 100644
--- a/fastapi/openapi/utils.py
+++ b/fastapi/openapi/utils.py
@@ -16,11 +16,15 @@ from fastapi._compat import (
)
from fastapi.datastructures import DefaultPlaceholder
from fastapi.dependencies.models import Dependant
-from fastapi.dependencies.utils import get_flat_dependant, get_flat_params
+from fastapi.dependencies.utils import (
+ _get_flat_fields_from_params,
+ get_flat_dependant,
+ get_flat_params,
+)
from fastapi.encoders import jsonable_encoder
from fastapi.openapi.constants import METHODS_WITH_BODY, REF_PREFIX, REF_TEMPLATE
from fastapi.openapi.models import OpenAPI
-from fastapi.params import Body, Param
+from fastapi.params import Body, ParamTypes
from fastapi.responses import Response
from fastapi.types import ModelNameMap
from fastapi.utils import (
@@ -87,9 +91,9 @@ def get_openapi_security_definitions(
return security_definitions, operation_security
-def get_openapi_operation_parameters(
+def _get_openapi_operation_parameters(
*,
- all_route_params: Sequence[ModelField],
+ dependant: Dependant,
schema_generator: GenerateJsonSchema,
model_name_map: ModelNameMap,
field_mapping: Dict[
@@ -98,33 +102,47 @@ def get_openapi_operation_parameters(
separate_input_output_schemas: bool = True,
) -> List[Dict[str, Any]]:
parameters = []
- for param in all_route_params:
- field_info = param.field_info
- field_info = cast(Param, field_info)
- if not field_info.include_in_schema:
- continue
- param_schema = get_schema_from_model_field(
- field=param,
- schema_generator=schema_generator,
- model_name_map=model_name_map,
- field_mapping=field_mapping,
- separate_input_output_schemas=separate_input_output_schemas,
- )
- parameter = {
- "name": param.alias,
- "in": field_info.in_.value,
- "required": param.required,
- "schema": param_schema,
- }
- if field_info.description:
- parameter["description"] = field_info.description
- if field_info.openapi_examples:
- parameter["examples"] = jsonable_encoder(field_info.openapi_examples)
- elif field_info.example != Undefined:
- parameter["example"] = jsonable_encoder(field_info.example)
- if field_info.deprecated:
- parameter["deprecated"] = True
- parameters.append(parameter)
+ flat_dependant = get_flat_dependant(dependant, skip_repeats=True)
+ path_params = _get_flat_fields_from_params(flat_dependant.path_params)
+ query_params = _get_flat_fields_from_params(flat_dependant.query_params)
+ header_params = _get_flat_fields_from_params(flat_dependant.header_params)
+ cookie_params = _get_flat_fields_from_params(flat_dependant.cookie_params)
+ parameter_groups = [
+ (ParamTypes.path, path_params),
+ (ParamTypes.query, query_params),
+ (ParamTypes.header, header_params),
+ (ParamTypes.cookie, cookie_params),
+ ]
+ for param_type, param_group in parameter_groups:
+ for param in param_group:
+ field_info = param.field_info
+ # field_info = cast(Param, field_info)
+ if not getattr(field_info, "include_in_schema", True):
+ continue
+ param_schema = get_schema_from_model_field(
+ field=param,
+ schema_generator=schema_generator,
+ model_name_map=model_name_map,
+ field_mapping=field_mapping,
+ separate_input_output_schemas=separate_input_output_schemas,
+ )
+ parameter = {
+ "name": param.alias,
+ "in": param_type.value,
+ "required": param.required,
+ "schema": param_schema,
+ }
+ if field_info.description:
+ parameter["description"] = field_info.description
+ openapi_examples = getattr(field_info, "openapi_examples", None)
+ example = getattr(field_info, "example", None)
+ if openapi_examples:
+ parameter["examples"] = jsonable_encoder(openapi_examples)
+ elif example != Undefined:
+ parameter["example"] = jsonable_encoder(example)
+ if getattr(field_info, "deprecated", None):
+ parameter["deprecated"] = True
+ parameters.append(parameter)
return parameters
@@ -247,9 +265,8 @@ def get_openapi_path(
operation.setdefault("security", []).extend(operation_security)
if security_definitions:
security_schemes.update(security_definitions)
- all_route_params = get_flat_params(route.dependant)
- operation_parameters = get_openapi_operation_parameters(
- all_route_params=all_route_params,
+ operation_parameters = _get_openapi_operation_parameters(
+ dependant=route.dependant,
schema_generator=schema_generator,
model_name_map=model_name_map,
field_mapping=field_mapping,
@@ -379,6 +396,7 @@ def get_openapi_path(
deep_dict_update(openapi_response, process_response)
openapi_response["description"] = description
http422 = str(HTTP_422_UNPROCESSABLE_ENTITY)
+ all_route_params = get_flat_params(route.dependant)
if (all_route_params or route.body_field) and not any(
status in operation["responses"]
for status in [http422, "4XX", "default"]
diff --git a/fastapi/param_functions.py b/fastapi/param_functions.py
index 3b25d774a..7ddaace25 100644
--- a/fastapi/param_functions.py
+++ b/fastapi/param_functions.py
@@ -1282,7 +1282,7 @@ def Body( # noqa: N802
),
] = _Unset,
embed: Annotated[
- bool,
+ Union[bool, None],
Doc(
"""
When `embed` is `True`, the parameter will be expected in a JSON body as a
@@ -1294,7 +1294,7 @@ def Body( # noqa: N802
[FastAPI docs for Body - Multiple Parameters](https://fastapi.tiangolo.com/tutorial/body-multiple-params/#embed-a-single-body-parameter).
"""
),
- ] = False,
+ ] = None,
media_type: Annotated[
str,
Doc(
@@ -2343,7 +2343,7 @@ def Security( # noqa: N802
```python
from typing import Annotated
- from fastapi import Depends, FastAPI
+ from fastapi import Security, FastAPI
from .db import User
from .security import get_current_active_user
diff --git a/fastapi/params.py b/fastapi/params.py
index 860146531..90ca7cb01 100644
--- a/fastapi/params.py
+++ b/fastapi/params.py
@@ -91,7 +91,7 @@ class Param(FieldInfo):
max_length=max_length,
discriminator=discriminator,
multiple_of=multiple_of,
- allow_nan=allow_inf_nan,
+ allow_inf_nan=allow_inf_nan,
max_digits=max_digits,
decimal_places=decimal_places,
**extra,
@@ -479,7 +479,7 @@ class Body(FieldInfo):
*,
default_factory: Union[Callable[[], Any], None] = _Unset,
annotation: Optional[Any] = None,
- embed: bool = False,
+ embed: Union[bool, None] = None,
media_type: str = "application/json",
alias: Optional[str] = None,
alias_priority: Union[int, None] = _Unset,
@@ -547,7 +547,7 @@ class Body(FieldInfo):
max_length=max_length,
discriminator=discriminator,
multiple_of=multiple_of,
- allow_nan=allow_inf_nan,
+ allow_inf_nan=allow_inf_nan,
max_digits=max_digits,
decimal_places=decimal_places,
**extra,
@@ -556,7 +556,7 @@ class Body(FieldInfo):
kwargs["examples"] = examples
if regex is not None:
warnings.warn(
- "`regex` has been depreacated, please use `pattern` instead",
+ "`regex` has been deprecated, please use `pattern` instead",
category=DeprecationWarning,
stacklevel=4,
)
@@ -642,7 +642,6 @@ class Form(Body):
default=default,
default_factory=default_factory,
annotation=annotation,
- embed=True,
media_type=media_type,
alias=alias,
alias_priority=alias_priority,
diff --git a/fastapi/routing.py b/fastapi/routing.py
index a34042540..a3c020a02 100644
--- a/fastapi/routing.py
+++ b/fastapi/routing.py
@@ -3,14 +3,16 @@ import dataclasses
import email.message
import inspect
import json
-from contextlib import AsyncExitStack
+from contextlib import AsyncExitStack, asynccontextmanager
from enum import Enum, IntEnum
from typing import (
Any,
+ AsyncIterator,
Callable,
Coroutine,
Dict,
List,
+ Mapping,
Optional,
Sequence,
Set,
@@ -31,8 +33,10 @@ from fastapi._compat import (
from fastapi.datastructures import Default, DefaultPlaceholder
from fastapi.dependencies.models import Dependant
from fastapi.dependencies.utils import (
+ _should_embed_body_fields,
get_body_field,
get_dependant,
+ get_flat_dependant,
get_parameterless_sub_dependant,
get_typed_return_annotation,
solve_dependencies,
@@ -47,7 +51,7 @@ from fastapi.exceptions import (
from fastapi.types import DecoratedCallable, IncEx
from fastapi.utils import (
create_cloned_field,
- create_response_field,
+ create_model_field,
generate_unique_id,
get_value_or_default,
is_body_allowed_for_status_code,
@@ -67,7 +71,7 @@ from starlette.routing import (
websocket_session,
)
from starlette.routing import Mount as Mount # noqa
-from starlette.types import ASGIApp, Lifespan, Scope
+from starlette.types import AppType, ASGIApp, Lifespan, Scope
from starlette.websockets import WebSocket
from typing_extensions import Annotated, Doc, deprecated
@@ -119,6 +123,23 @@ def _prepare_response_content(
return res
+def _merge_lifespan_context(
+ original_context: Lifespan[Any], nested_context: Lifespan[Any]
+) -> Lifespan[Any]:
+ @asynccontextmanager
+ async def merged_lifespan(
+ app: AppType,
+ ) -> AsyncIterator[Optional[Mapping[str, Any]]]:
+ async with original_context(app) as maybe_original_state:
+ async with nested_context(app) as maybe_nested_state:
+ if maybe_nested_state is None and maybe_original_state is None:
+ yield None # old ASGI compatibility
+ else:
+ yield {**(maybe_nested_state or {}), **(maybe_original_state or {})}
+
+ return merged_lifespan # type: ignore[return-value]
+
+
async def serialize_response(
*,
field: Optional[ModelField] = None,
@@ -206,6 +227,7 @@ def get_request_handler(
response_model_exclude_defaults: bool = False,
response_model_exclude_none: bool = False,
dependency_overrides_provider: Optional[Any] = None,
+ embed_body_fields: bool = False,
) -> Callable[[Request], Coroutine[Any, Any, Response]]:
assert dependant.call is not None, "dependant.call must be a function"
is_coroutine = asyncio.iscoroutinefunction(dependant.call)
@@ -272,27 +294,36 @@ def get_request_handler(
body=body,
dependency_overrides_provider=dependency_overrides_provider,
async_exit_stack=async_exit_stack,
+ embed_body_fields=embed_body_fields,
)
- values, errors, background_tasks, sub_response, _ = solved_result
+ errors = solved_result.errors
if not errors:
raw_response = await run_endpoint_function(
- dependant=dependant, values=values, is_coroutine=is_coroutine
+ dependant=dependant,
+ values=solved_result.values,
+ is_coroutine=is_coroutine,
)
if isinstance(raw_response, Response):
if raw_response.background is None:
- raw_response.background = background_tasks
+ raw_response.background = solved_result.background_tasks
response = raw_response
else:
- response_args: Dict[str, Any] = {"background": background_tasks}
+ response_args: Dict[str, Any] = {
+ "background": solved_result.background_tasks
+ }
# If status_code was set, use it, otherwise use the default from the
# response class, in the case of redirect it's 307
current_status_code = (
- status_code if status_code else sub_response.status_code
+ status_code
+ if status_code
+ else solved_result.response.status_code
)
if current_status_code is not None:
response_args["status_code"] = current_status_code
- if sub_response.status_code:
- response_args["status_code"] = sub_response.status_code
+ if solved_result.response.status_code:
+ response_args["status_code"] = (
+ solved_result.response.status_code
+ )
content = await serialize_response(
field=response_field,
response_content=raw_response,
@@ -307,7 +338,7 @@ def get_request_handler(
response = actual_response_class(content, **response_args)
if not is_body_allowed_for_status_code(response.status_code):
response.body = b""
- response.headers.raw.extend(sub_response.headers.raw)
+ response.headers.raw.extend(solved_result.response.headers.raw)
if errors:
validation_error = RequestValidationError(
_normalize_errors(errors), body=body
@@ -327,7 +358,9 @@ def get_request_handler(
def get_websocket_app(
- dependant: Dependant, dependency_overrides_provider: Optional[Any] = None
+ dependant: Dependant,
+ dependency_overrides_provider: Optional[Any] = None,
+ embed_body_fields: bool = False,
) -> Callable[[WebSocket], Coroutine[Any, Any, Any]]:
async def app(websocket: WebSocket) -> None:
async with AsyncExitStack() as async_exit_stack:
@@ -340,12 +373,14 @@ def get_websocket_app(
dependant=dependant,
dependency_overrides_provider=dependency_overrides_provider,
async_exit_stack=async_exit_stack,
+ embed_body_fields=embed_body_fields,
)
- values, errors, _, _2, _3 = solved_result
- if errors:
- raise WebSocketRequestValidationError(_normalize_errors(errors))
+ if solved_result.errors:
+ raise WebSocketRequestValidationError(
+ _normalize_errors(solved_result.errors)
+ )
assert dependant.call is not None, "dependant.call must be a function"
- await dependant.call(**values)
+ await dependant.call(**solved_result.values)
return app
@@ -371,11 +406,15 @@ class APIWebSocketRoute(routing.WebSocketRoute):
0,
get_parameterless_sub_dependant(depends=depends, path=self.path_format),
)
-
+ self._flat_dependant = get_flat_dependant(self.dependant)
+ self._embed_body_fields = _should_embed_body_fields(
+ self._flat_dependant.body_params
+ )
self.app = websocket_session(
get_websocket_app(
dependant=self.dependant,
dependency_overrides_provider=dependency_overrides_provider,
+ embed_body_fields=self._embed_body_fields,
)
)
@@ -455,9 +494,9 @@ class APIRoute(routing.Route):
methods = ["GET"]
self.methods: Set[str] = {method.upper() for method in methods}
if isinstance(generate_unique_id_function, DefaultPlaceholder):
- current_generate_unique_id: Callable[
- ["APIRoute"], str
- ] = generate_unique_id_function.value
+ current_generate_unique_id: Callable[[APIRoute], str] = (
+ generate_unique_id_function.value
+ )
else:
current_generate_unique_id = generate_unique_id_function
self.unique_id = self.operation_id or current_generate_unique_id(self)
@@ -470,7 +509,7 @@ class APIRoute(routing.Route):
status_code
), f"Status code {status_code} must not have a response body"
response_name = "Response_" + self.unique_id
- self.response_field = create_response_field(
+ self.response_field = create_model_field(
name=response_name,
type_=self.response_model,
mode="serialization",
@@ -483,9 +522,9 @@ class APIRoute(routing.Route):
# By being a new field, no inheritance will be passed as is. A new model
# will always be created.
# TODO: remove when deprecating Pydantic v1
- self.secure_cloned_response_field: Optional[
- ModelField
- ] = create_cloned_field(self.response_field)
+ self.secure_cloned_response_field: Optional[ModelField] = (
+ create_cloned_field(self.response_field)
+ )
else:
self.response_field = None # type: ignore
self.secure_cloned_response_field = None
@@ -503,7 +542,9 @@ class APIRoute(routing.Route):
additional_status_code
), f"Status code {additional_status_code} must not have a response body"
response_name = f"Response_{additional_status_code}_{self.unique_id}"
- response_field = create_response_field(name=response_name, type_=model)
+ response_field = create_model_field(
+ name=response_name, type_=model, mode="serialization"
+ )
response_fields[additional_status_code] = response_field
if response_fields:
self.response_fields: Dict[Union[int, str], ModelField] = response_fields
@@ -517,7 +558,15 @@ class APIRoute(routing.Route):
0,
get_parameterless_sub_dependant(depends=depends, path=self.path_format),
)
- self.body_field = get_body_field(dependant=self.dependant, name=self.unique_id)
+ self._flat_dependant = get_flat_dependant(self.dependant)
+ self._embed_body_fields = _should_embed_body_fields(
+ self._flat_dependant.body_params
+ )
+ self.body_field = get_body_field(
+ flat_dependant=self._flat_dependant,
+ name=self.unique_id,
+ embed_body_fields=self._embed_body_fields,
+ )
self.app = request_response(self.get_route_handler())
def get_route_handler(self) -> Callable[[Request], Coroutine[Any, Any, Response]]:
@@ -534,6 +583,7 @@ class APIRoute(routing.Route):
response_model_exclude_defaults=self.response_model_exclude_defaults,
response_model_exclude_none=self.response_model_exclude_none,
dependency_overrides_provider=self.dependency_overrides_provider,
+ embed_body_fields=self._embed_body_fields,
)
def matches(self, scope: Scope) -> Tuple[Match, Scope]:
@@ -1319,6 +1369,10 @@ class APIRouter(routing.Router):
self.add_event_handler("startup", handler)
for handler in router.on_shutdown:
self.add_event_handler("shutdown", handler)
+ self.lifespan_context = _merge_lifespan_context(
+ self.lifespan_context,
+ router.lifespan_context,
+ )
def get(
self,
diff --git a/fastapi/security/http.py b/fastapi/security/http.py
index a142b135d..e06f3d66d 100644
--- a/fastapi/security/http.py
+++ b/fastapi/security/http.py
@@ -277,7 +277,7 @@ class HTTPBearer(HTTPBase):
bool,
Doc(
"""
- By default, if the HTTP Bearer token not provided (in an
+ By default, if the HTTP Bearer token is not provided (in an
`Authorization` header), `HTTPBearer` will automatically cancel the
request and send the client an error.
@@ -380,7 +380,7 @@ class HTTPDigest(HTTPBase):
bool,
Doc(
"""
- By default, if the HTTP Digest not provided, `HTTPDigest` will
+ By default, if the HTTP Digest is not provided, `HTTPDigest` will
automatically cancel the request and send the client an error.
If `auto_error` is set to `False`, when the HTTP Digest is not
diff --git a/fastapi/utils.py b/fastapi/utils.py
index dfda4e678..4c7350fea 100644
--- a/fastapi/utils.py
+++ b/fastapi/utils.py
@@ -34,9 +34,9 @@ if TYPE_CHECKING: # pragma: nocover
from .routing import APIRoute
# Cache for `create_cloned_field`
-_CLONED_TYPES_CACHE: MutableMapping[
- Type[BaseModel], Type[BaseModel]
-] = WeakKeyDictionary()
+_CLONED_TYPES_CACHE: MutableMapping[Type[BaseModel], Type[BaseModel]] = (
+ WeakKeyDictionary()
+)
def is_body_allowed_for_status_code(status_code: Union[int, str, None]) -> bool:
@@ -60,9 +60,9 @@ def get_path_param_names(path: str) -> Set[str]:
return set(re.findall("{(.*?)}", path))
-def create_response_field(
+def create_model_field(
name: str,
- type_: Type[Any],
+ type_: Any,
class_validators: Optional[Dict[str, Validator]] = None,
default: Optional[Any] = Undefined,
required: Union[bool, UndefinedType] = Undefined,
@@ -71,9 +71,6 @@ def create_response_field(
alias: Optional[str] = None,
mode: Literal["validation", "serialization"] = "validation",
) -> ModelField:
- """
- Create a new response field. Raises if type_ is invalid.
- """
class_validators = class_validators or {}
if PYDANTIC_V2:
field_info = field_info or FieldInfo(
@@ -135,7 +132,7 @@ def create_cloned_field(
use_type.__fields__[f.name] = create_cloned_field(
f, cloned_types=cloned_types
)
- new_field = create_response_field(name=field.name, type_=use_type)
+ new_field = create_model_field(name=field.name, type_=use_type)
new_field.has_alias = field.has_alias # type: ignore[attr-defined]
new_field.alias = field.alias # type: ignore[misc]
new_field.class_validators = field.class_validators # type: ignore[attr-defined]
diff --git a/pyproject.toml b/pyproject.toml
index 3601e6322..c934356d8 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -41,7 +41,7 @@ classifiers = [
"Topic :: Internet :: WWW/HTTP",
]
dependencies = [
- "starlette>=0.37.2,<0.38.0",
+ "starlette>=0.37.2,<0.41.0",
"pydantic>=1.7.4,!=1.8,!=1.8.1,!=2.0.0,!=2.0.1,!=2.1.0,<3.0.0",
"typing-extensions>=4.8.0",
]
@@ -50,6 +50,8 @@ dependencies = [
Homepage = "https://github.com/fastapi/fastapi"
Documentation = "https://fastapi.tiangolo.com/"
Repository = "https://github.com/fastapi/fastapi"
+Issues = "https://github.com/fastapi/fastapi/issues"
+Changelog = "https://fastapi.tiangolo.com/release-notes/"
[project.optional-dependencies]
@@ -62,7 +64,7 @@ standard = [
# For forms and file uploads
"python-multipart >=0.0.7",
# To validate email fields
- "email_validator >=2.0.0",
+ "email-validator >=2.0.0",
# Uvicorn with uvloop
"uvicorn[standard] >=0.12.0",
# TODO: this should be part of some pydantic optional extra dependencies
@@ -89,7 +91,7 @@ all = [
# For ORJSONResponse
"orjson >=3.2.1",
# To validate email fields
- "email_validator >=2.0.0",
+ "email-validator >=2.0.0",
# Uvicorn with uvloop
"uvicorn[standard] >=0.12.0",
# Settings management
@@ -147,43 +149,42 @@ xfail_strict = true
junit_family = "xunit2"
filterwarnings = [
"error",
- # TODO: needed by asyncio in Python 3.9.7 https://bugs.python.org/issue45097, try to remove on 3.9.8
- 'ignore:The loop argument is deprecated since Python 3\.8, and scheduled for removal in Python 3\.10:DeprecationWarning:asyncio',
'ignore:starlette.middleware.wsgi is deprecated and will be removed in a future release\..*:DeprecationWarning:starlette',
- # TODO: remove after upgrading HTTPX to a version newer than 0.23.0
- # Including PR: https://github.com/encode/httpx/pull/2309
- "ignore:'cgi' is deprecated:DeprecationWarning",
# For passlib
"ignore:'crypt' is deprecated and slated for removal in Python 3.13:DeprecationWarning",
# see https://trio.readthedocs.io/en/stable/history.html#trio-0-22-0-2022-09-28
"ignore:You seem to already have a custom.*:RuntimeWarning:trio",
- "ignore::trio.TrioDeprecationWarning",
- # TODO remove pytest-cov
- 'ignore::pytest.PytestDeprecationWarning:pytest_cov',
# TODO: remove after upgrading SQLAlchemy to a version that includes the following changes
# https://github.com/sqlalchemy/sqlalchemy/commit/59521abcc0676e936b31a523bd968fc157fef0c2
'ignore:datetime\.datetime\.utcfromtimestamp\(\) is deprecated and scheduled for removal in a future version\..*:DeprecationWarning:sqlalchemy',
- # TODO: remove after upgrading python-jose to a version that explicitly supports Python 3.12
- # also, if it won't receive an update, consider replacing python-jose with some alternative
- # related issues:
- # - https://github.com/mpdavis/python-jose/issues/332
- # - https://github.com/mpdavis/python-jose/issues/334
- 'ignore:datetime\.datetime\.utcnow\(\) is deprecated and scheduled for removal in a future version\..*:DeprecationWarning:jose',
+ # Trio 24.1.0 raises a warning from attrs
+ # Ref: https://github.com/python-trio/trio/pull/3054
+ # Remove once there's a new version of Trio
+ 'ignore:The `hash` argument is deprecated*:DeprecationWarning:trio',
]
[tool.coverage.run]
parallel = true
+data_file = "coverage/.coverage"
source = [
"docs_src",
"tests",
"fastapi"
]
context = '${CONTEXT}'
+dynamic_context = "test_function"
omit = [
"docs_src/response_model/tutorial003_04.py",
"docs_src/response_model/tutorial003_04_py310.py",
]
+[tool.coverage.report]
+show_missing = true
+sort = "-Cover"
+
+[tool.coverage.html]
+show_contexts = true
+
[tool.ruff.lint]
select = [
"E", # pycodestyle errors
@@ -240,3 +241,7 @@ known-third-party = ["fastapi", "pydantic", "starlette"]
[tool.ruff.lint.pyupgrade]
# Preserve types, even if a file imports `from __future__ import annotations`.
keep-runtime-typing = true
+
+[tool.inline-snapshot]
+# default-flags=["fix"]
+# default-flags=["create"]
diff --git a/requirements-docs-insiders.txt b/requirements-docs-insiders.txt
new file mode 100644
index 000000000..d8d3c37a9
--- /dev/null
+++ b/requirements-docs-insiders.txt
@@ -0,0 +1,3 @@
+git+https://${TOKEN}@github.com/squidfunk/mkdocs-material-insiders.git@9.5.30-insiders-4.53.11
+git+https://${TOKEN}@github.com/pawamoy-insiders/griffe-typing-deprecated.git
+git+https://${TOKEN}@github.com/pawamoy-insiders/mkdocstrings-python.git
diff --git a/requirements-docs-tests.txt b/requirements-docs-tests.txt
index b82df4933..331d2a5b3 100644
--- a/requirements-docs-tests.txt
+++ b/requirements-docs-tests.txt
@@ -1,2 +1,4 @@
# For mkdocstrings and tests
-httpx >=0.23.0,<0.25.0
+httpx >=0.23.0,<0.28.0
+# For linting and generating docs versions
+ruff ==0.6.4
diff --git a/requirements-docs.txt b/requirements-docs.txt
index c672f0ef7..1639159af 100644
--- a/requirements-docs.txt
+++ b/requirements-docs.txt
@@ -3,16 +3,17 @@
mkdocs-material==9.5.18
mdx-include >=1.4.1,<2.0.0
mkdocs-redirects>=1.2.1,<1.3.0
-typer >=0.12.0
+typer == 0.12.3
pyyaml >=5.3.1,<7.0.0
# For Material for MkDocs, Chinese search
jieba==0.42.1
# For image processing by Material for MkDocs
-pillow==10.3.0
+pillow==10.4.0
# For image processing by Material for MkDocs
-cairosvg==2.7.0
-mkdocstrings[python]==0.24.3
-griffe-typingdoc==0.2.2
+cairosvg==2.7.1
+mkdocstrings[python]==0.26.1
+griffe-typingdoc==0.2.7
# For griffe, it formats with black
black==24.3.0
mkdocs-macros-plugin==1.0.5
+markdown-include-variants==0.0.3
diff --git a/requirements-tests.txt b/requirements-tests.txt
index bfe70f2f5..189fcaf7e 100644
--- a/requirements-tests.txt
+++ b/requirements-tests.txt
@@ -3,18 +3,14 @@
pytest >=7.1.3,<8.0.0
coverage[toml] >= 6.5.0,< 8.0
mypy ==1.8.0
-ruff ==0.2.0
dirty-equals ==0.6.0
-# TODO: once removing databases from tutorial, upgrade SQLAlchemy
-# probably when including SQLModel
-sqlalchemy >=1.3.18,<1.4.43
-databases[sqlite] >=0.3.2,<0.7.0
+sqlmodel==0.0.22
flask >=1.1.2,<3.0.0
anyio[trio] >=3.2.1,<4.0.0
PyJWT==2.8.0
pyyaml >=5.3.1,<7.0.0
passlib[bcrypt] >=1.7.2,<2.0.0
-
+inline-snapshot==0.13.0
# types
types-ujson ==5.7.0.1
types-orjson ==3.6.2
diff --git a/scripts/comment_docs_deploy_url_in_pr.py b/scripts/comment_docs_deploy_url_in_pr.py
deleted file mode 100644
index 3148a3bb4..000000000
--- a/scripts/comment_docs_deploy_url_in_pr.py
+++ /dev/null
@@ -1,31 +0,0 @@
-import logging
-import sys
-
-from github import Github
-from pydantic import SecretStr
-from pydantic_settings import BaseSettings
-
-
-class Settings(BaseSettings):
- github_repository: str
- github_token: SecretStr
- deploy_url: str
- commit_sha: str
-
-
-if __name__ == "__main__":
- logging.basicConfig(level=logging.INFO)
- settings = Settings()
- logging.info(f"Using config: {settings.model_dump_json()}")
- g = Github(settings.github_token.get_secret_value())
- repo = g.get_repo(settings.github_repository)
- use_pr = next(
- (pr for pr in repo.get_pulls() if pr.head.sha == settings.commit_sha), None
- )
- if not use_pr:
- logging.error(f"No PR found for hash: {settings.commit_sha}")
- sys.exit(0)
- use_pr.as_issue().create_comment(
- f"📝 Docs preview for commit {settings.commit_sha} at: {settings.deploy_url}"
- )
- logging.info("Finished")
diff --git a/scripts/deploy_docs_status.py b/scripts/deploy_docs_status.py
new file mode 100644
index 000000000..19dffbcb9
--- /dev/null
+++ b/scripts/deploy_docs_status.py
@@ -0,0 +1,107 @@
+import logging
+import re
+
+from github import Github
+from pydantic import SecretStr
+from pydantic_settings import BaseSettings
+
+
+class Settings(BaseSettings):
+ github_repository: str
+ github_token: SecretStr
+ deploy_url: str | None = None
+ commit_sha: str
+ run_id: int
+ is_done: bool = False
+
+
+def main():
+ logging.basicConfig(level=logging.INFO)
+ settings = Settings()
+
+ logging.info(f"Using config: {settings.model_dump_json()}")
+ g = Github(settings.github_token.get_secret_value())
+ repo = g.get_repo(settings.github_repository)
+ use_pr = next(
+ (pr for pr in repo.get_pulls() if pr.head.sha == settings.commit_sha), None
+ )
+ if not use_pr:
+ logging.error(f"No PR found for hash: {settings.commit_sha}")
+ return
+ commits = list(use_pr.get_commits())
+ current_commit = [c for c in commits if c.sha == settings.commit_sha][0]
+ run_url = f"https://github.com/{settings.github_repository}/actions/runs/{settings.run_id}"
+ if settings.is_done and not settings.deploy_url:
+ current_commit.create_status(
+ state="success",
+ description="No Docs Changes",
+ context="deploy-docs",
+ target_url=run_url,
+ )
+ logging.info("No docs changes found")
+ return
+ if not settings.deploy_url:
+ current_commit.create_status(
+ state="pending",
+ description="Deploying Docs",
+ context="deploy-docs",
+ target_url=run_url,
+ )
+ logging.info("No deploy URL available yet")
+ return
+ current_commit.create_status(
+ state="success",
+ description="Docs Deployed",
+ context="deploy-docs",
+ target_url=run_url,
+ )
+
+ files = list(use_pr.get_files())
+ docs_files = [f for f in files if f.filename.startswith("docs/")]
+
+ deploy_url = settings.deploy_url.rstrip("/")
+ lang_links: dict[str, list[str]] = {}
+ for f in docs_files:
+ match = re.match(r"docs/([^/]+)/docs/(.*)", f.filename)
+ if not match:
+ continue
+ lang = match.group(1)
+ path = match.group(2)
+ if path.endswith("index.md"):
+ path = path.replace("index.md", "")
+ else:
+ path = path.replace(".md", "/")
+ if lang == "en":
+ link = f"{deploy_url}/{path}"
+ else:
+ link = f"{deploy_url}/{lang}/{path}"
+ lang_links.setdefault(lang, []).append(link)
+
+ links: list[str] = []
+ en_links = lang_links.get("en", [])
+ en_links.sort()
+ links.extend(en_links)
+
+ langs = list(lang_links.keys())
+ langs.sort()
+ for lang in langs:
+ if lang == "en":
+ continue
+ current_lang_links = lang_links[lang]
+ current_lang_links.sort()
+ links.extend(current_lang_links)
+
+ message = f"📝 Docs preview for commit {settings.commit_sha} at: {deploy_url}"
+
+ if links:
+ message += "\n\n### Modified Pages\n\n"
+ message += "\n".join([f"* {link}" for link in links])
+
+ print(message)
+ use_pr.as_issue().create_comment(message)
+
+ logging.info("Finished")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/docs.py b/scripts/docs.py
index 59578a820..f26f96d85 100644
--- a/scripts/docs.py
+++ b/scripts/docs.py
@@ -11,13 +11,11 @@ from multiprocessing import Pool
from pathlib import Path
from typing import Any, Dict, List, Optional, Union
-import mkdocs.commands.build
-import mkdocs.commands.serve
-import mkdocs.config
import mkdocs.utils
import typer
import yaml
from jinja2 import Template
+from ruff.__main__ import find_ruff_bin
logging.basicConfig(level=logging.INFO)
@@ -26,9 +24,19 @@ app = typer.Typer()
mkdocs_name = "mkdocs.yml"
missing_translation_snippet = """
-{!../../../docs/missing-translation.md!}
+{!../../docs/missing-translation.md!}
"""
+non_translated_sections = [
+ "reference/",
+ "release-notes.md",
+ "fastapi-people.md",
+ "external-links.md",
+ "newsletter.md",
+ "management-tasks.md",
+ "management.md",
+]
+
docs_path = Path("docs")
en_docs_path = Path("docs/en")
en_config_path: Path = en_docs_path / mkdocs_name
@@ -165,6 +173,13 @@ def generate_readme_content() -> str:
pre_content = content[frontmatter_end:pre_end]
post_content = content[post_start:]
new_content = pre_content + message + post_content
+ # Remove content between and
+ new_content = re.sub(
+ r".*?",
+ "",
+ new_content,
+ flags=re.DOTALL,
+ )
return new_content
@@ -247,6 +262,7 @@ def live(
lang: str = typer.Argument(
None, callback=lang_callback, autocompletion=complete_existing_lang
),
+ dirty: bool = False,
) -> None:
"""
Serve with livereload a docs site for a specific language.
@@ -258,12 +274,16 @@ def live(
en.
"""
# Enable line numbers during local development to make it easier to highlight
- os.environ["LINENUMS"] = "true"
if lang is None:
lang = "en"
lang_path: Path = docs_path / lang
- os.chdir(lang_path)
- mkdocs.commands.serve.serve(dev_addr="127.0.0.1:8008")
+ # Enable line numbers during local development to make it easier to highlight
+ args = ["mkdocs", "serve", "--dev-addr", "127.0.0.1:8008"]
+ if dirty:
+ args.append("--dirty")
+ subprocess.run(
+ args, env={**os.environ, "LINENUMS": "true"}, cwd=lang_path, check=True
+ )
def get_updated_config_content() -> Dict[str, Any]:
@@ -324,10 +344,34 @@ def verify_config() -> None:
typer.echo("Valid mkdocs.yml ✅")
+@app.command()
+def verify_non_translated() -> None:
+ """
+ Verify there are no files in the non translatable pages.
+ """
+ print("Verifying non translated pages")
+ lang_paths = get_lang_paths()
+ error_paths = []
+ for lang in lang_paths:
+ if lang.name == "en":
+ continue
+ for non_translatable in non_translated_sections:
+ non_translatable_path = lang / "docs" / non_translatable
+ if non_translatable_path.exists():
+ error_paths.append(non_translatable_path)
+ if error_paths:
+ print("Non-translated pages found, remove them:")
+ for error_path in error_paths:
+ print(error_path)
+ raise typer.Abort()
+ print("No non-translated pages found ✅")
+
+
@app.command()
def verify_docs():
verify_readme()
verify_config()
+ verify_non_translated()
@app.command()
@@ -339,5 +383,41 @@ def langs_json():
print(json.dumps(langs))
+@app.command()
+def generate_docs_src_versions_for_file(file_path: Path) -> None:
+ target_versions = ["py39", "py310"]
+ base_content = file_path.read_text(encoding="utf-8")
+ previous_content = {base_content}
+ for target_version in target_versions:
+ version_result = subprocess.run(
+ [
+ find_ruff_bin(),
+ "check",
+ "--target-version",
+ target_version,
+ "--fix",
+ "--unsafe-fixes",
+ "-",
+ ],
+ input=base_content.encode("utf-8"),
+ capture_output=True,
+ )
+ content_target = version_result.stdout.decode("utf-8")
+ format_result = subprocess.run(
+ [find_ruff_bin(), "format", "-"],
+ input=content_target.encode("utf-8"),
+ capture_output=True,
+ )
+ content_format = format_result.stdout.decode("utf-8")
+ if content_format in previous_content:
+ continue
+ previous_content.add(content_format)
+ version_file = file_path.with_name(
+ file_path.name.replace(".py", f"_{target_version}.py")
+ )
+ logging.info(f"Writing to {version_file}")
+ version_file.write_text(content_format, encoding="utf-8")
+
+
if __name__ == "__main__":
app()
diff --git a/scripts/format.sh b/scripts/format.sh
index 45742f79a..bf70f42e5 100755
--- a/scripts/format.sh
+++ b/scripts/format.sh
@@ -1,4 +1,4 @@
-#!/bin/sh -e
+#!/usr/bin/env bash
set -x
ruff check fastapi tests docs_src scripts --fix
diff --git a/scripts/mkdocs_hooks.py b/scripts/mkdocs_hooks.py
index 24ffecf46..0bc4929a4 100644
--- a/scripts/mkdocs_hooks.py
+++ b/scripts/mkdocs_hooks.py
@@ -8,9 +8,14 @@ from mkdocs.structure.files import File, Files
from mkdocs.structure.nav import Link, Navigation, Section
from mkdocs.structure.pages import Page
-non_traslated_sections = [
+non_translated_sections = [
"reference/",
"release-notes.md",
+ "fastapi-people.md",
+ "external-links.md",
+ "newsletter.md",
+ "management-tasks.md",
+ "management.md",
]
@@ -128,7 +133,7 @@ def on_page_markdown(
markdown: str, *, page: Page, config: MkDocsConfig, files: Files
) -> str:
if isinstance(page.file, EnFile):
- for excluded_section in non_traslated_sections:
+ for excluded_section in non_translated_sections:
if page.file.src_path.startswith(excluded_section):
return markdown
missing_translation_content = get_missing_translation_content(config.docs_dir)
diff --git a/scripts/playwright/cookie_param_models/image01.py b/scripts/playwright/cookie_param_models/image01.py
new file mode 100644
index 000000000..77c91bfe2
--- /dev/null
+++ b/scripts/playwright/cookie_param_models/image01.py
@@ -0,0 +1,39 @@
+import subprocess
+import time
+
+import httpx
+from playwright.sync_api import Playwright, sync_playwright
+
+
+# Run playwright codegen to generate the code below, copy paste the sections in run()
+def run(playwright: Playwright) -> None:
+ browser = playwright.chromium.launch(headless=False)
+ # Update the viewport manually
+ context = browser.new_context(viewport={"width": 960, "height": 1080})
+ browser = playwright.chromium.launch(headless=False)
+ context = browser.new_context()
+ page = context.new_page()
+ page.goto("http://localhost:8000/docs")
+ page.get_by_role("link", name="/items/").click()
+ # Manually add the screenshot
+ page.screenshot(path="docs/en/docs/img/tutorial/cookie-param-models/image01.png")
+
+ # ---------------------
+ context.close()
+ browser.close()
+
+
+process = subprocess.Popen(
+ ["fastapi", "run", "docs_src/cookie_param_models/tutorial001.py"]
+)
+try:
+ for _ in range(3):
+ try:
+ response = httpx.get("http://localhost:8000/docs")
+ except httpx.ConnectError:
+ time.sleep(1)
+ break
+ with sync_playwright() as playwright:
+ run(playwright)
+finally:
+ process.terminate()
diff --git a/scripts/playwright/header_param_models/image01.py b/scripts/playwright/header_param_models/image01.py
new file mode 100644
index 000000000..53914251e
--- /dev/null
+++ b/scripts/playwright/header_param_models/image01.py
@@ -0,0 +1,38 @@
+import subprocess
+import time
+
+import httpx
+from playwright.sync_api import Playwright, sync_playwright
+
+
+# Run playwright codegen to generate the code below, copy paste the sections in run()
+def run(playwright: Playwright) -> None:
+ browser = playwright.chromium.launch(headless=False)
+ # Update the viewport manually
+ context = browser.new_context(viewport={"width": 960, "height": 1080})
+ page = context.new_page()
+ page.goto("http://localhost:8000/docs")
+ page.get_by_role("button", name="GET /items/ Read Items").click()
+ page.get_by_role("button", name="Try it out").click()
+ # Manually add the screenshot
+ page.screenshot(path="docs/en/docs/img/tutorial/header-param-models/image01.png")
+
+ # ---------------------
+ context.close()
+ browser.close()
+
+
+process = subprocess.Popen(
+ ["fastapi", "run", "docs_src/header_param_models/tutorial001.py"]
+)
+try:
+ for _ in range(3):
+ try:
+ response = httpx.get("http://localhost:8000/docs")
+ except httpx.ConnectError:
+ time.sleep(1)
+ break
+ with sync_playwright() as playwright:
+ run(playwright)
+finally:
+ process.terminate()
diff --git a/scripts/playwright/query_param_models/image01.py b/scripts/playwright/query_param_models/image01.py
new file mode 100644
index 000000000..0ea1d0df4
--- /dev/null
+++ b/scripts/playwright/query_param_models/image01.py
@@ -0,0 +1,41 @@
+import subprocess
+import time
+
+import httpx
+from playwright.sync_api import Playwright, sync_playwright
+
+
+# Run playwright codegen to generate the code below, copy paste the sections in run()
+def run(playwright: Playwright) -> None:
+ browser = playwright.chromium.launch(headless=False)
+ # Update the viewport manually
+ context = browser.new_context(viewport={"width": 960, "height": 1080})
+ browser = playwright.chromium.launch(headless=False)
+ context = browser.new_context()
+ page = context.new_page()
+ page.goto("http://localhost:8000/docs")
+ page.get_by_role("button", name="GET /items/ Read Items").click()
+ page.get_by_role("button", name="Try it out").click()
+ page.get_by_role("heading", name="Servers").click()
+ # Manually add the screenshot
+ page.screenshot(path="docs/en/docs/img/tutorial/query-param-models/image01.png")
+
+ # ---------------------
+ context.close()
+ browser.close()
+
+
+process = subprocess.Popen(
+ ["fastapi", "run", "docs_src/query_param_models/tutorial001.py"]
+)
+try:
+ for _ in range(3):
+ try:
+ response = httpx.get("http://localhost:8000/docs")
+ except httpx.ConnectError:
+ time.sleep(1)
+ break
+ with sync_playwright() as playwright:
+ run(playwright)
+finally:
+ process.terminate()
diff --git a/scripts/playwright/request_form_models/image01.py b/scripts/playwright/request_form_models/image01.py
new file mode 100644
index 000000000..fe4da32fc
--- /dev/null
+++ b/scripts/playwright/request_form_models/image01.py
@@ -0,0 +1,38 @@
+import subprocess
+import time
+
+import httpx
+from playwright.sync_api import Playwright, sync_playwright
+
+
+# Run playwright codegen to generate the code below, copy paste the sections in run()
+def run(playwright: Playwright) -> None:
+ browser = playwright.chromium.launch(headless=False)
+ # Update the viewport manually
+ context = browser.new_context(viewport={"width": 960, "height": 1080})
+ page = context.new_page()
+ page.goto("http://localhost:8000/docs")
+ page.get_by_role("button", name="POST /login/ Login").click()
+ page.get_by_role("button", name="Try it out").click()
+ # Manually add the screenshot
+ page.screenshot(path="docs/en/docs/img/tutorial/request-form-models/image01.png")
+
+ # ---------------------
+ context.close()
+ browser.close()
+
+
+process = subprocess.Popen(
+ ["fastapi", "run", "docs_src/request_form_models/tutorial001.py"]
+)
+try:
+ for _ in range(3):
+ try:
+ response = httpx.get("http://localhost:8000/docs")
+ except httpx.ConnectError:
+ time.sleep(1)
+ break
+ with sync_playwright() as playwright:
+ run(playwright)
+finally:
+ process.terminate()
diff --git a/scripts/playwright/separate_openapi_schemas/image01.py b/scripts/playwright/separate_openapi_schemas/image01.py
index 0b40f3bbc..0eb55fb73 100644
--- a/scripts/playwright/separate_openapi_schemas/image01.py
+++ b/scripts/playwright/separate_openapi_schemas/image01.py
@@ -3,13 +3,16 @@ import subprocess
from playwright.sync_api import Playwright, sync_playwright
+# Run playwright codegen to generate the code below, copy paste the sections in run()
def run(playwright: Playwright) -> None:
browser = playwright.chromium.launch(headless=False)
+ # Update the viewport manually
context = browser.new_context(viewport={"width": 960, "height": 1080})
page = context.new_page()
page.goto("http://localhost:8000/docs")
page.get_by_text("POST/items/Create Item").click()
page.get_by_role("tab", name="Schema").first.click()
+ # Manually add the screenshot
page.screenshot(
path="docs/en/docs/img/tutorial/separate-openapi-schemas/image01.png"
)
diff --git a/scripts/playwright/separate_openapi_schemas/image02.py b/scripts/playwright/separate_openapi_schemas/image02.py
index f76af7ee2..0eb6c3c79 100644
--- a/scripts/playwright/separate_openapi_schemas/image02.py
+++ b/scripts/playwright/separate_openapi_schemas/image02.py
@@ -3,14 +3,17 @@ import subprocess
from playwright.sync_api import Playwright, sync_playwright
+# Run playwright codegen to generate the code below, copy paste the sections in run()
def run(playwright: Playwright) -> None:
browser = playwright.chromium.launch(headless=False)
+ # Update the viewport manually
context = browser.new_context(viewport={"width": 960, "height": 1080})
page = context.new_page()
page.goto("http://localhost:8000/docs")
page.get_by_text("GET/items/Read Items").click()
page.get_by_role("button", name="Try it out").click()
page.get_by_role("button", name="Execute").click()
+ # Manually add the screenshot
page.screenshot(
path="docs/en/docs/img/tutorial/separate-openapi-schemas/image02.png"
)
diff --git a/scripts/playwright/separate_openapi_schemas/image03.py b/scripts/playwright/separate_openapi_schemas/image03.py
index 127f5c428..b68e9d7db 100644
--- a/scripts/playwright/separate_openapi_schemas/image03.py
+++ b/scripts/playwright/separate_openapi_schemas/image03.py
@@ -3,14 +3,17 @@ import subprocess
from playwright.sync_api import Playwright, sync_playwright
+# Run playwright codegen to generate the code below, copy paste the sections in run()
def run(playwright: Playwright) -> None:
browser = playwright.chromium.launch(headless=False)
+ # Update the viewport manually
context = browser.new_context(viewport={"width": 960, "height": 1080})
page = context.new_page()
page.goto("http://localhost:8000/docs")
page.get_by_text("GET/items/Read Items").click()
page.get_by_role("tab", name="Schema").click()
page.get_by_label("Schema").get_by_role("button", name="Expand all").click()
+ # Manually add the screenshot
page.screenshot(
path="docs/en/docs/img/tutorial/separate-openapi-schemas/image03.png"
)
diff --git a/scripts/playwright/separate_openapi_schemas/image04.py b/scripts/playwright/separate_openapi_schemas/image04.py
index 208eaf8a0..a36c2f6b2 100644
--- a/scripts/playwright/separate_openapi_schemas/image04.py
+++ b/scripts/playwright/separate_openapi_schemas/image04.py
@@ -3,14 +3,17 @@ import subprocess
from playwright.sync_api import Playwright, sync_playwright
+# Run playwright codegen to generate the code below, copy paste the sections in run()
def run(playwright: Playwright) -> None:
browser = playwright.chromium.launch(headless=False)
+ # Update the viewport manually
context = browser.new_context(viewport={"width": 960, "height": 1080})
page = context.new_page()
page.goto("http://localhost:8000/docs")
page.get_by_role("button", name="Item-Input").click()
page.get_by_role("button", name="Item-Output").click()
page.set_viewport_size({"width": 960, "height": 820})
+ # Manually add the screenshot
page.screenshot(
path="docs/en/docs/img/tutorial/separate-openapi-schemas/image04.png"
)
diff --git a/scripts/playwright/separate_openapi_schemas/image05.py b/scripts/playwright/separate_openapi_schemas/image05.py
index 83966b449..0da5db0cf 100644
--- a/scripts/playwright/separate_openapi_schemas/image05.py
+++ b/scripts/playwright/separate_openapi_schemas/image05.py
@@ -3,13 +3,16 @@ import subprocess
from playwright.sync_api import Playwright, sync_playwright
+# Run playwright codegen to generate the code below, copy paste the sections in run()
def run(playwright: Playwright) -> None:
browser = playwright.chromium.launch(headless=False)
+ # Update the viewport manually
context = browser.new_context(viewport={"width": 960, "height": 1080})
page = context.new_page()
page.goto("http://localhost:8000/docs")
page.get_by_role("button", name="Item", exact=True).click()
page.set_viewport_size({"width": 960, "height": 700})
+ # Manually add the screenshot
page.screenshot(
path="docs/en/docs/img/tutorial/separate-openapi-schemas/image05.png"
)
diff --git a/scripts/playwright/sql_databases/image01.py b/scripts/playwright/sql_databases/image01.py
new file mode 100644
index 000000000..0dd6f2514
--- /dev/null
+++ b/scripts/playwright/sql_databases/image01.py
@@ -0,0 +1,37 @@
+import subprocess
+import time
+
+import httpx
+from playwright.sync_api import Playwright, sync_playwright
+
+
+# Run playwright codegen to generate the code below, copy paste the sections in run()
+def run(playwright: Playwright) -> None:
+ browser = playwright.chromium.launch(headless=False)
+ # Update the viewport manually
+ context = browser.new_context(viewport={"width": 960, "height": 1080})
+ page = context.new_page()
+ page.goto("http://localhost:8000/docs")
+ page.get_by_label("post /heroes/").click()
+ # Manually add the screenshot
+ page.screenshot(path="docs/en/docs/img/tutorial/sql-databases/image01.png")
+
+ # ---------------------
+ context.close()
+ browser.close()
+
+
+process = subprocess.Popen(
+ ["fastapi", "run", "docs_src/sql_databases/tutorial001.py"],
+)
+try:
+ for _ in range(3):
+ try:
+ response = httpx.get("http://localhost:8000/docs")
+ except httpx.ConnectError:
+ time.sleep(1)
+ break
+ with sync_playwright() as playwright:
+ run(playwright)
+finally:
+ process.terminate()
diff --git a/scripts/playwright/sql_databases/image02.py b/scripts/playwright/sql_databases/image02.py
new file mode 100644
index 000000000..6c4f685e8
--- /dev/null
+++ b/scripts/playwright/sql_databases/image02.py
@@ -0,0 +1,37 @@
+import subprocess
+import time
+
+import httpx
+from playwright.sync_api import Playwright, sync_playwright
+
+
+# Run playwright codegen to generate the code below, copy paste the sections in run()
+def run(playwright: Playwright) -> None:
+ browser = playwright.chromium.launch(headless=False)
+ # Update the viewport manually
+ context = browser.new_context(viewport={"width": 960, "height": 1080})
+ page = context.new_page()
+ page.goto("http://localhost:8000/docs")
+ page.get_by_label("post /heroes/").click()
+ # Manually add the screenshot
+ page.screenshot(path="docs/en/docs/img/tutorial/sql-databases/image02.png")
+
+ # ---------------------
+ context.close()
+ browser.close()
+
+
+process = subprocess.Popen(
+ ["fastapi", "run", "docs_src/sql_databases/tutorial002.py"],
+)
+try:
+ for _ in range(3):
+ try:
+ response = httpx.get("http://localhost:8000/docs")
+ except httpx.ConnectError:
+ time.sleep(1)
+ break
+ with sync_playwright() as playwright:
+ run(playwright)
+finally:
+ process.terminate()
diff --git a/scripts/test-cov-html.sh b/scripts/test-cov-html.sh
index d1bdfced2..517ac6422 100755
--- a/scripts/test-cov-html.sh
+++ b/scripts/test-cov-html.sh
@@ -5,5 +5,5 @@ set -x
bash scripts/test.sh ${@}
coverage combine
-coverage report --show-missing
+coverage report
coverage html
diff --git a/tests/test_allow_inf_nan_in_enforcing.py b/tests/test_allow_inf_nan_in_enforcing.py
new file mode 100644
index 000000000..9e855fdf8
--- /dev/null
+++ b/tests/test_allow_inf_nan_in_enforcing.py
@@ -0,0 +1,83 @@
+import pytest
+from fastapi import Body, FastAPI, Query
+from fastapi.testclient import TestClient
+from typing_extensions import Annotated
+
+app = FastAPI()
+
+
+@app.post("/")
+async def get(
+ x: Annotated[float, Query(allow_inf_nan=True)] = 0,
+ y: Annotated[float, Query(allow_inf_nan=False)] = 0,
+ z: Annotated[float, Query()] = 0,
+ b: Annotated[float, Body(allow_inf_nan=False)] = 0,
+) -> str:
+ return "OK"
+
+
+client = TestClient(app)
+
+
+@pytest.mark.parametrize(
+ "value,code",
+ [
+ ("-1", 200),
+ ("inf", 200),
+ ("-inf", 200),
+ ("nan", 200),
+ ("0", 200),
+ ("342", 200),
+ ],
+)
+def test_allow_inf_nan_param_true(value: str, code: int):
+ response = client.post(f"/?x={value}")
+ assert response.status_code == code, response.text
+
+
+@pytest.mark.parametrize(
+ "value,code",
+ [
+ ("-1", 200),
+ ("inf", 422),
+ ("-inf", 422),
+ ("nan", 422),
+ ("0", 200),
+ ("342", 200),
+ ],
+)
+def test_allow_inf_nan_param_false(value: str, code: int):
+ response = client.post(f"/?y={value}")
+ assert response.status_code == code, response.text
+
+
+@pytest.mark.parametrize(
+ "value,code",
+ [
+ ("-1", 200),
+ ("inf", 200),
+ ("-inf", 200),
+ ("nan", 200),
+ ("0", 200),
+ ("342", 200),
+ ],
+)
+def test_allow_inf_nan_param_default(value: str, code: int):
+ response = client.post(f"/?z={value}")
+ assert response.status_code == code, response.text
+
+
+@pytest.mark.parametrize(
+ "value,code",
+ [
+ ("-1", 200),
+ ("inf", 422),
+ ("-inf", 422),
+ ("nan", 422),
+ ("0", 200),
+ ("342", 200),
+ ],
+)
+def test_allow_inf_nan_body(value: str, code: int):
+ response = client.post("/", json=value)
+ assert response.status_code == code, response.text
diff --git a/tests/test_compat.py b/tests/test_compat.py
index bf268b860..f4a3093c5 100644
--- a/tests/test_compat.py
+++ b/tests/test_compat.py
@@ -1,11 +1,14 @@
-from typing import List, Union
+from typing import Any, Dict, List, Union
from fastapi import FastAPI, UploadFile
from fastapi._compat import (
ModelField,
Undefined,
_get_model_config,
+ get_cached_model_fields,
+ get_model_fields,
is_bytes_sequence_annotation,
+ is_scalar_field,
is_uploadfile_sequence_annotation,
)
from fastapi.testclient import TestClient
@@ -91,3 +94,27 @@ def test_is_uploadfile_sequence_annotation():
# and other types, but I'm not even sure it's a good idea to support it as a first
# class "feature"
assert is_uploadfile_sequence_annotation(Union[List[str], List[UploadFile]])
+
+
+def test_is_pv1_scalar_field():
+ # For coverage
+ class Model(BaseModel):
+ foo: Union[str, Dict[str, Any]]
+
+ fields = get_model_fields(Model)
+ assert not is_scalar_field(fields[0])
+
+
+def test_get_model_fields_cached():
+ class Model(BaseModel):
+ foo: str
+
+ non_cached_fields = get_model_fields(Model)
+ non_cached_fields2 = get_model_fields(Model)
+ cached_fields = get_cached_model_fields(Model)
+ cached_fields2 = get_cached_model_fields(Model)
+ for f1, f2 in zip(cached_fields, cached_fields2):
+ assert f1 is f2
+
+ assert non_cached_fields is not non_cached_fields2
+ assert cached_fields is cached_fields2
diff --git a/tests/test_computed_fields.py b/tests/test_computed_fields.py
index 5286507b2..a1b412168 100644
--- a/tests/test_computed_fields.py
+++ b/tests/test_computed_fields.py
@@ -24,13 +24,18 @@ def get_client():
def read_root() -> Rectangle:
return Rectangle(width=3, length=4)
+ @app.get("/responses", responses={200: {"model": Rectangle}})
+ def read_responses() -> Rectangle:
+ return Rectangle(width=3, length=4)
+
client = TestClient(app)
return client
+@pytest.mark.parametrize("path", ["/", "/responses"])
@needs_pydanticv2
-def test_get(client: TestClient):
- response = client.get("/")
+def test_get(client: TestClient, path: str):
+ response = client.get(path)
assert response.status_code == 200, response.text
assert response.json() == {"width": 3, "length": 4, "area": 12}
@@ -58,7 +63,23 @@ def test_openapi_schema(client: TestClient):
}
},
}
- }
+ },
+ "/responses": {
+ "get": {
+ "summary": "Read Responses",
+ "operationId": "read_responses_responses_get",
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {"$ref": "#/components/schemas/Rectangle"}
+ }
+ },
+ }
+ },
+ }
+ },
},
"components": {
"schemas": {
diff --git a/tests/test_dependency_contextmanager.py b/tests/test_dependency_contextmanager.py
index 008dab7bc..039c423b9 100644
--- a/tests/test_dependency_contextmanager.py
+++ b/tests/test_dependency_contextmanager.py
@@ -196,9 +196,9 @@ async def get_sync_context_b_bg(
tasks: BackgroundTasks, state: dict = Depends(context_b)
):
async def bg(state: dict):
- state[
- "sync_bg"
- ] = f"sync_bg set - b: {state['context_b']} - a: {state['context_a']}"
+ state["sync_bg"] = (
+ f"sync_bg set - b: {state['context_b']} - a: {state['context_a']}"
+ )
tasks.add_task(bg, state)
return state
diff --git a/tests/test_forms_single_model.py b/tests/test_forms_single_model.py
new file mode 100644
index 000000000..880ab3820
--- /dev/null
+++ b/tests/test_forms_single_model.py
@@ -0,0 +1,133 @@
+from typing import List, Optional
+
+from dirty_equals import IsDict
+from fastapi import FastAPI, Form
+from fastapi.testclient import TestClient
+from pydantic import BaseModel, Field
+from typing_extensions import Annotated
+
+app = FastAPI()
+
+
+class FormModel(BaseModel):
+ username: str
+ lastname: str
+ age: Optional[int] = None
+ tags: List[str] = ["foo", "bar"]
+ alias_with: str = Field(alias="with", default="nothing")
+
+
+@app.post("/form/")
+def post_form(user: Annotated[FormModel, Form()]):
+ return user
+
+
+client = TestClient(app)
+
+
+def test_send_all_data():
+ response = client.post(
+ "/form/",
+ data={
+ "username": "Rick",
+ "lastname": "Sanchez",
+ "age": "70",
+ "tags": ["plumbus", "citadel"],
+ "with": "something",
+ },
+ )
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "username": "Rick",
+ "lastname": "Sanchez",
+ "age": 70,
+ "tags": ["plumbus", "citadel"],
+ "with": "something",
+ }
+
+
+def test_defaults():
+ response = client.post("/form/", data={"username": "Rick", "lastname": "Sanchez"})
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "username": "Rick",
+ "lastname": "Sanchez",
+ "age": None,
+ "tags": ["foo", "bar"],
+ "with": "nothing",
+ }
+
+
+def test_invalid_data():
+ response = client.post(
+ "/form/",
+ data={
+ "username": "Rick",
+ "lastname": "Sanchez",
+ "age": "seventy",
+ "tags": ["plumbus", "citadel"],
+ },
+ )
+ assert response.status_code == 422, response.text
+ assert response.json() == IsDict(
+ {
+ "detail": [
+ {
+ "type": "int_parsing",
+ "loc": ["body", "age"],
+ "msg": "Input should be a valid integer, unable to parse string as an integer",
+ "input": "seventy",
+ }
+ ]
+ }
+ ) | IsDict(
+ # TODO: remove when deprecating Pydantic v1
+ {
+ "detail": [
+ {
+ "loc": ["body", "age"],
+ "msg": "value is not a valid integer",
+ "type": "type_error.integer",
+ }
+ ]
+ }
+ )
+
+
+def test_no_data():
+ response = client.post("/form/")
+ assert response.status_code == 422, response.text
+ assert response.json() == IsDict(
+ {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "username"],
+ "msg": "Field required",
+ "input": {"tags": ["foo", "bar"], "with": "nothing"},
+ },
+ {
+ "type": "missing",
+ "loc": ["body", "lastname"],
+ "msg": "Field required",
+ "input": {"tags": ["foo", "bar"], "with": "nothing"},
+ },
+ ]
+ }
+ ) | IsDict(
+ # TODO: remove when deprecating Pydantic v1
+ {
+ "detail": [
+ {
+ "loc": ["body", "username"],
+ "msg": "field required",
+ "type": "value_error.missing",
+ },
+ {
+ "loc": ["body", "lastname"],
+ "msg": "field required",
+ "type": "value_error.missing",
+ },
+ ]
+ }
+ )
diff --git a/tests/test_forms_single_param.py b/tests/test_forms_single_param.py
new file mode 100644
index 000000000..3bb951441
--- /dev/null
+++ b/tests/test_forms_single_param.py
@@ -0,0 +1,99 @@
+from fastapi import FastAPI, Form
+from fastapi.testclient import TestClient
+from typing_extensions import Annotated
+
+app = FastAPI()
+
+
+@app.post("/form/")
+def post_form(username: Annotated[str, Form()]):
+ return username
+
+
+client = TestClient(app)
+
+
+def test_single_form_field():
+ response = client.post("/form/", data={"username": "Rick"})
+ assert response.status_code == 200, response.text
+ assert response.json() == "Rick"
+
+
+def test_openapi_schema():
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/form/": {
+ "post": {
+ "summary": "Post Form",
+ "operationId": "post_form_form__post",
+ "requestBody": {
+ "content": {
+ "application/x-www-form-urlencoded": {
+ "schema": {
+ "$ref": "#/components/schemas/Body_post_form_form__post"
+ }
+ }
+ },
+ "required": True,
+ },
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "Body_post_form_form__post": {
+ "properties": {"username": {"type": "string", "title": "Username"}},
+ "type": "object",
+ "required": ["username"],
+ "title": "Body_post_form_form__post",
+ },
+ "HTTPValidationError": {
+ "properties": {
+ "detail": {
+ "items": {"$ref": "#/components/schemas/ValidationError"},
+ "type": "array",
+ "title": "Detail",
+ }
+ },
+ "type": "object",
+ "title": "HTTPValidationError",
+ },
+ "ValidationError": {
+ "properties": {
+ "loc": {
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ "type": "array",
+ "title": "Location",
+ },
+ "msg": {"type": "string", "title": "Message"},
+ "type": {"type": "string", "title": "Error Type"},
+ },
+ "type": "object",
+ "required": ["loc", "msg", "type"],
+ "title": "ValidationError",
+ },
+ }
+ },
+ }
diff --git a/tests/test_inherited_custom_class.py b/tests/test_inherited_custom_class.py
index 42b249211..fe9350f4e 100644
--- a/tests/test_inherited_custom_class.py
+++ b/tests/test_inherited_custom_class.py
@@ -36,7 +36,7 @@ def test_pydanticv2():
def return_fast_uuid():
asyncpg_uuid = MyUuid("a10ff360-3b1e-4984-a26f-d3ab460bdb51")
assert isinstance(asyncpg_uuid, uuid.UUID)
- assert type(asyncpg_uuid) != uuid.UUID
+ assert type(asyncpg_uuid) is not uuid.UUID
with pytest.raises(TypeError):
vars(asyncpg_uuid)
return {"fast_uuid": asyncpg_uuid}
@@ -79,7 +79,7 @@ def test_pydanticv1():
def return_fast_uuid():
asyncpg_uuid = MyUuid("a10ff360-3b1e-4984-a26f-d3ab460bdb51")
assert isinstance(asyncpg_uuid, uuid.UUID)
- assert type(asyncpg_uuid) != uuid.UUID
+ assert type(asyncpg_uuid) is not uuid.UUID
with pytest.raises(TypeError):
vars(asyncpg_uuid)
return {"fast_uuid": asyncpg_uuid}
diff --git a/tests/test_openapi_examples.py b/tests/test_openapi_examples.py
index 6597e5058..b3f83ae23 100644
--- a/tests/test_openapi_examples.py
+++ b/tests/test_openapi_examples.py
@@ -155,13 +155,26 @@ def test_openapi_schema():
"requestBody": {
"content": {
"application/json": {
- "schema": {
- "allOf": [{"$ref": "#/components/schemas/Item"}],
- "title": "Item",
- "examples": [
- {"data": "Data in Body examples, example1"}
- ],
- },
+ "schema": IsDict(
+ {
+ "$ref": "#/components/schemas/Item",
+ "examples": [
+ {"data": "Data in Body examples, example1"}
+ ],
+ }
+ )
+ | IsDict(
+ {
+ # TODO: remove when deprecating Pydantic v1
+ "allOf": [
+ {"$ref": "#/components/schemas/Item"}
+ ],
+ "title": "Item",
+ "examples": [
+ {"data": "Data in Body examples, example1"}
+ ],
+ }
+ ),
"examples": {
"Example One": {
"summary": "Example One Summary",
diff --git a/tests/test_openapi_separate_input_output_schemas.py b/tests/test_openapi_separate_input_output_schemas.py
index aeb85f735..f7e045259 100644
--- a/tests/test_openapi_separate_input_output_schemas.py
+++ b/tests/test_openapi_separate_input_output_schemas.py
@@ -26,8 +26,8 @@ class Item(BaseModel):
def get_app_client(separate_input_output_schemas: bool = True) -> TestClient:
app = FastAPI(separate_input_output_schemas=separate_input_output_schemas)
- @app.post("/items/")
- def create_item(item: Item):
+ @app.post("/items/", responses={402: {"model": Item}})
+ def create_item(item: Item) -> Item:
return item
@app.post("/items-list/")
@@ -174,7 +174,23 @@ def test_openapi_schema():
"responses": {
"200": {
"description": "Successful Response",
- "content": {"application/json": {"schema": {}}},
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Item-Output"
+ }
+ }
+ },
+ },
+ "402": {
+ "description": "Payment Required",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Item-Output"
+ }
+ }
+ },
},
"422": {
"description": "Validation Error",
@@ -374,7 +390,19 @@ def test_openapi_schema_no_separate():
"responses": {
"200": {
"description": "Successful Response",
- "content": {"application/json": {"schema": {}}},
+ "content": {
+ "application/json": {
+ "schema": {"$ref": "#/components/schemas/Item"}
+ }
+ },
+ },
+ "402": {
+ "description": "Payment Required",
+ "content": {
+ "application/json": {
+ "schema": {"$ref": "#/components/schemas/Item"}
+ }
+ },
},
"422": {
"description": "Validation Error",
diff --git a/tests/test_router_events.py b/tests/test_router_events.py
index 1b9de18ae..dd7ff3314 100644
--- a/tests/test_router_events.py
+++ b/tests/test_router_events.py
@@ -1,8 +1,8 @@
from contextlib import asynccontextmanager
-from typing import AsyncGenerator, Dict
+from typing import AsyncGenerator, Dict, Union
import pytest
-from fastapi import APIRouter, FastAPI
+from fastapi import APIRouter, FastAPI, Request
from fastapi.testclient import TestClient
from pydantic import BaseModel
@@ -109,3 +109,134 @@ def test_app_lifespan_state(state: State) -> None:
assert response.json() == {"message": "Hello World"}
assert state.app_startup is True
assert state.app_shutdown is True
+
+
+def test_router_nested_lifespan_state(state: State) -> None:
+ @asynccontextmanager
+ async def lifespan(app: FastAPI) -> AsyncGenerator[Dict[str, bool], None]:
+ state.app_startup = True
+ yield {"app": True}
+ state.app_shutdown = True
+
+ @asynccontextmanager
+ async def router_lifespan(app: FastAPI) -> AsyncGenerator[Dict[str, bool], None]:
+ state.router_startup = True
+ yield {"router": True}
+ state.router_shutdown = True
+
+ @asynccontextmanager
+ async def subrouter_lifespan(app: FastAPI) -> AsyncGenerator[Dict[str, bool], None]:
+ state.sub_router_startup = True
+ yield {"sub_router": True}
+ state.sub_router_shutdown = True
+
+ sub_router = APIRouter(lifespan=subrouter_lifespan)
+
+ router = APIRouter(lifespan=router_lifespan)
+ router.include_router(sub_router)
+
+ app = FastAPI(lifespan=lifespan)
+ app.include_router(router)
+
+ @app.get("/")
+ def main(request: Request) -> Dict[str, str]:
+ assert request.state.app
+ assert request.state.router
+ assert request.state.sub_router
+ return {"message": "Hello World"}
+
+ assert state.app_startup is False
+ assert state.router_startup is False
+ assert state.sub_router_startup is False
+ assert state.app_shutdown is False
+ assert state.router_shutdown is False
+ assert state.sub_router_shutdown is False
+
+ with TestClient(app) as client:
+ assert state.app_startup is True
+ assert state.router_startup is True
+ assert state.sub_router_startup is True
+ assert state.app_shutdown is False
+ assert state.router_shutdown is False
+ assert state.sub_router_shutdown is False
+ response = client.get("/")
+ assert response.status_code == 200, response.text
+ assert response.json() == {"message": "Hello World"}
+
+ assert state.app_startup is True
+ assert state.router_startup is True
+ assert state.sub_router_startup is True
+ assert state.app_shutdown is True
+ assert state.router_shutdown is True
+ assert state.sub_router_shutdown is True
+
+
+def test_router_nested_lifespan_state_overriding_by_parent() -> None:
+ @asynccontextmanager
+ async def lifespan(
+ app: FastAPI,
+ ) -> AsyncGenerator[Dict[str, Union[str, bool]], None]:
+ yield {
+ "app_specific": True,
+ "overridden": "app",
+ }
+
+ @asynccontextmanager
+ async def router_lifespan(
+ app: FastAPI,
+ ) -> AsyncGenerator[Dict[str, Union[str, bool]], None]:
+ yield {
+ "router_specific": True,
+ "overridden": "router", # should override parent
+ }
+
+ router = APIRouter(lifespan=router_lifespan)
+ app = FastAPI(lifespan=lifespan)
+ app.include_router(router)
+
+ with TestClient(app) as client:
+ assert client.app_state == {
+ "app_specific": True,
+ "router_specific": True,
+ "overridden": "app",
+ }
+
+
+def test_merged_no_return_lifespans_return_none() -> None:
+ @asynccontextmanager
+ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
+ yield
+
+ @asynccontextmanager
+ async def router_lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
+ yield
+
+ router = APIRouter(lifespan=router_lifespan)
+ app = FastAPI(lifespan=lifespan)
+ app.include_router(router)
+
+ with TestClient(app) as client:
+ assert not client.app_state
+
+
+def test_merged_mixed_state_lifespans() -> None:
+ @asynccontextmanager
+ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
+ yield
+
+ @asynccontextmanager
+ async def router_lifespan(app: FastAPI) -> AsyncGenerator[Dict[str, bool], None]:
+ yield {"router": True}
+
+ @asynccontextmanager
+ async def sub_router_lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
+ yield
+
+ sub_router = APIRouter(lifespan=sub_router_lifespan)
+ router = APIRouter(lifespan=router_lifespan)
+ app = FastAPI(lifespan=lifespan)
+ router.include_router(sub_router)
+ app.include_router(router)
+
+ with TestClient(app) as client:
+ assert client.app_state == {"router": True}
diff --git a/tests/test_tutorial/test_async_sql_databases/__init__.py b/tests/test_tutorial/test_async_sql_databases/__init__.py
deleted file mode 100644
index e69de29bb..000000000
diff --git a/tests/test_tutorial/test_async_sql_databases/test_tutorial001.py b/tests/test_tutorial/test_async_sql_databases/test_tutorial001.py
deleted file mode 100644
index 13568a532..000000000
--- a/tests/test_tutorial/test_async_sql_databases/test_tutorial001.py
+++ /dev/null
@@ -1,146 +0,0 @@
-import pytest
-from fastapi import FastAPI
-from fastapi.testclient import TestClient
-
-from ...utils import needs_pydanticv1
-
-
-@pytest.fixture(name="app", scope="module")
-def get_app():
- with pytest.warns(DeprecationWarning):
- from docs_src.async_sql_databases.tutorial001 import app
- yield app
-
-
-# TODO: pv2 add version with Pydantic v2
-@needs_pydanticv1
-def test_create_read(app: FastAPI):
- with TestClient(app) as client:
- note = {"text": "Foo bar", "completed": False}
- response = client.post("/notes/", json=note)
- assert response.status_code == 200, response.text
- data = response.json()
- assert data["text"] == note["text"]
- assert data["completed"] == note["completed"]
- assert "id" in data
- response = client.get("/notes/")
- assert response.status_code == 200, response.text
- assert data in response.json()
-
-
-def test_openapi_schema(app: FastAPI):
- with TestClient(app) as client:
- response = client.get("/openapi.json")
- assert response.status_code == 200, response.text
- assert response.json() == {
- "openapi": "3.1.0",
- "info": {"title": "FastAPI", "version": "0.1.0"},
- "paths": {
- "/notes/": {
- "get": {
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {
- "title": "Response Read Notes Notes Get",
- "type": "array",
- "items": {
- "$ref": "#/components/schemas/Note"
- },
- }
- }
- },
- }
- },
- "summary": "Read Notes",
- "operationId": "read_notes_notes__get",
- },
- "post": {
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/Note"}
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- "summary": "Create Note",
- "operationId": "create_note_notes__post",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/NoteIn"}
- }
- },
- "required": True,
- },
- },
- }
- },
- "components": {
- "schemas": {
- "NoteIn": {
- "title": "NoteIn",
- "required": ["text", "completed"],
- "type": "object",
- "properties": {
- "text": {"title": "Text", "type": "string"},
- "completed": {"title": "Completed", "type": "boolean"},
- },
- },
- "Note": {
- "title": "Note",
- "required": ["id", "text", "completed"],
- "type": "object",
- "properties": {
- "id": {"title": "Id", "type": "integer"},
- "text": {"title": "Text", "type": "string"},
- "completed": {"title": "Completed", "type": "boolean"},
- },
- },
- "ValidationError": {
- "title": "ValidationError",
- "required": ["loc", "msg", "type"],
- "type": "object",
- "properties": {
- "loc": {
- "title": "Location",
- "type": "array",
- "items": {
- "anyOf": [{"type": "string"}, {"type": "integer"}]
- },
- },
- "msg": {"title": "Message", "type": "string"},
- "type": {"title": "Error Type", "type": "string"},
- },
- },
- "HTTPValidationError": {
- "title": "HTTPValidationError",
- "type": "object",
- "properties": {
- "detail": {
- "title": "Detail",
- "type": "array",
- "items": {
- "$ref": "#/components/schemas/ValidationError"
- },
- }
- },
- },
- }
- },
- }
diff --git a/docs_src/sql_databases/sql_app/__init__.py b/tests/test_tutorial/test_cookie_param_models/__init__.py
similarity index 100%
rename from docs_src/sql_databases/sql_app/__init__.py
rename to tests/test_tutorial/test_cookie_param_models/__init__.py
diff --git a/tests/test_tutorial/test_cookie_param_models/test_tutorial001.py b/tests/test_tutorial/test_cookie_param_models/test_tutorial001.py
new file mode 100644
index 000000000..60643185a
--- /dev/null
+++ b/tests/test_tutorial/test_cookie_param_models/test_tutorial001.py
@@ -0,0 +1,205 @@
+import importlib
+
+import pytest
+from dirty_equals import IsDict
+from fastapi.testclient import TestClient
+from inline_snapshot import snapshot
+
+from tests.utils import needs_py39, needs_py310
+
+
+@pytest.fixture(
+ name="client",
+ params=[
+ "tutorial001",
+ pytest.param("tutorial001_py310", marks=needs_py310),
+ "tutorial001_an",
+ pytest.param("tutorial001_an_py39", marks=needs_py39),
+ pytest.param("tutorial001_an_py310", marks=needs_py310),
+ ],
+)
+def get_client(request: pytest.FixtureRequest):
+ mod = importlib.import_module(f"docs_src.cookie_param_models.{request.param}")
+
+ client = TestClient(mod.app)
+ return client
+
+
+def test_cookie_param_model(client: TestClient):
+ with client as c:
+ c.cookies.set("session_id", "123")
+ c.cookies.set("fatebook_tracker", "456")
+ c.cookies.set("googall_tracker", "789")
+ response = c.get("/items/")
+ assert response.status_code == 200
+ assert response.json() == {
+ "session_id": "123",
+ "fatebook_tracker": "456",
+ "googall_tracker": "789",
+ }
+
+
+def test_cookie_param_model_defaults(client: TestClient):
+ with client as c:
+ c.cookies.set("session_id", "123")
+ response = c.get("/items/")
+ assert response.status_code == 200
+ assert response.json() == {
+ "session_id": "123",
+ "fatebook_tracker": None,
+ "googall_tracker": None,
+ }
+
+
+def test_cookie_param_model_invalid(client: TestClient):
+ response = client.get("/items/")
+ assert response.status_code == 422
+ assert response.json() == snapshot(
+ IsDict(
+ {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["cookie", "session_id"],
+ "msg": "Field required",
+ "input": {},
+ }
+ ]
+ }
+ )
+ | IsDict(
+ # TODO: remove when deprecating Pydantic v1
+ {
+ "detail": [
+ {
+ "type": "value_error.missing",
+ "loc": ["cookie", "session_id"],
+ "msg": "field required",
+ }
+ ]
+ }
+ )
+ )
+
+
+def test_cookie_param_model_extra(client: TestClient):
+ with client as c:
+ c.cookies.set("session_id", "123")
+ c.cookies.set("extra", "track-me-here-too")
+ response = c.get("/items/")
+ assert response.status_code == 200
+ assert response.json() == snapshot(
+ {"session_id": "123", "fatebook_tracker": None, "googall_tracker": None}
+ )
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == snapshot(
+ {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/": {
+ "get": {
+ "summary": "Read Items",
+ "operationId": "read_items_items__get",
+ "parameters": [
+ {
+ "name": "session_id",
+ "in": "cookie",
+ "required": True,
+ "schema": {"type": "string", "title": "Session Id"},
+ },
+ {
+ "name": "fatebook_tracker",
+ "in": "cookie",
+ "required": False,
+ "schema": IsDict(
+ {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "Fatebook Tracker",
+ }
+ )
+ | IsDict(
+ # TODO: remove when deprecating Pydantic v1
+ {
+ "type": "string",
+ "title": "Fatebook Tracker",
+ }
+ ),
+ },
+ {
+ "name": "googall_tracker",
+ "in": "cookie",
+ "required": False,
+ "schema": IsDict(
+ {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "Googall Tracker",
+ }
+ )
+ | IsDict(
+ # TODO: remove when deprecating Pydantic v1
+ {
+ "type": "string",
+ "title": "Googall Tracker",
+ }
+ ),
+ },
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "HTTPValidationError": {
+ "properties": {
+ "detail": {
+ "items": {
+ "$ref": "#/components/schemas/ValidationError"
+ },
+ "type": "array",
+ "title": "Detail",
+ }
+ },
+ "type": "object",
+ "title": "HTTPValidationError",
+ },
+ "ValidationError": {
+ "properties": {
+ "loc": {
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ "type": "array",
+ "title": "Location",
+ },
+ "msg": {"type": "string", "title": "Message"},
+ "type": {"type": "string", "title": "Error Type"},
+ },
+ "type": "object",
+ "required": ["loc", "msg", "type"],
+ "title": "ValidationError",
+ },
+ }
+ },
+ }
+ )
diff --git a/tests/test_tutorial/test_cookie_param_models/test_tutorial002.py b/tests/test_tutorial/test_cookie_param_models/test_tutorial002.py
new file mode 100644
index 000000000..30adadc8a
--- /dev/null
+++ b/tests/test_tutorial/test_cookie_param_models/test_tutorial002.py
@@ -0,0 +1,233 @@
+import importlib
+
+import pytest
+from dirty_equals import IsDict
+from fastapi.testclient import TestClient
+from inline_snapshot import snapshot
+
+from tests.utils import needs_py39, needs_py310, needs_pydanticv1, needs_pydanticv2
+
+
+@pytest.fixture(
+ name="client",
+ params=[
+ pytest.param("tutorial002", marks=needs_pydanticv2),
+ pytest.param("tutorial002_py310", marks=[needs_py310, needs_pydanticv2]),
+ pytest.param("tutorial002_an", marks=needs_pydanticv2),
+ pytest.param("tutorial002_an_py39", marks=[needs_py39, needs_pydanticv2]),
+ pytest.param("tutorial002_an_py310", marks=[needs_py310, needs_pydanticv2]),
+ pytest.param("tutorial002_pv1", marks=[needs_pydanticv1, needs_pydanticv1]),
+ pytest.param("tutorial002_pv1_py310", marks=[needs_py310, needs_pydanticv1]),
+ pytest.param("tutorial002_pv1_an", marks=[needs_pydanticv1]),
+ pytest.param("tutorial002_pv1_an_py39", marks=[needs_py39, needs_pydanticv1]),
+ pytest.param("tutorial002_pv1_an_py310", marks=[needs_py310, needs_pydanticv1]),
+ ],
+)
+def get_client(request: pytest.FixtureRequest):
+ mod = importlib.import_module(f"docs_src.cookie_param_models.{request.param}")
+
+ client = TestClient(mod.app)
+ return client
+
+
+def test_cookie_param_model(client: TestClient):
+ with client as c:
+ c.cookies.set("session_id", "123")
+ c.cookies.set("fatebook_tracker", "456")
+ c.cookies.set("googall_tracker", "789")
+ response = c.get("/items/")
+ assert response.status_code == 200
+ assert response.json() == {
+ "session_id": "123",
+ "fatebook_tracker": "456",
+ "googall_tracker": "789",
+ }
+
+
+def test_cookie_param_model_defaults(client: TestClient):
+ with client as c:
+ c.cookies.set("session_id", "123")
+ response = c.get("/items/")
+ assert response.status_code == 200
+ assert response.json() == {
+ "session_id": "123",
+ "fatebook_tracker": None,
+ "googall_tracker": None,
+ }
+
+
+def test_cookie_param_model_invalid(client: TestClient):
+ response = client.get("/items/")
+ assert response.status_code == 422
+ assert response.json() == snapshot(
+ IsDict(
+ {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["cookie", "session_id"],
+ "msg": "Field required",
+ "input": {},
+ }
+ ]
+ }
+ )
+ | IsDict(
+ # TODO: remove when deprecating Pydantic v1
+ {
+ "detail": [
+ {
+ "type": "value_error.missing",
+ "loc": ["cookie", "session_id"],
+ "msg": "field required",
+ }
+ ]
+ }
+ )
+ )
+
+
+def test_cookie_param_model_extra(client: TestClient):
+ with client as c:
+ c.cookies.set("session_id", "123")
+ c.cookies.set("extra", "track-me-here-too")
+ response = c.get("/items/")
+ assert response.status_code == 422
+ assert response.json() == snapshot(
+ IsDict(
+ {
+ "detail": [
+ {
+ "type": "extra_forbidden",
+ "loc": ["cookie", "extra"],
+ "msg": "Extra inputs are not permitted",
+ "input": "track-me-here-too",
+ }
+ ]
+ }
+ )
+ | IsDict(
+ # TODO: remove when deprecating Pydantic v1
+ {
+ "detail": [
+ {
+ "type": "value_error.extra",
+ "loc": ["cookie", "extra"],
+ "msg": "extra fields not permitted",
+ }
+ ]
+ }
+ )
+ )
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == snapshot(
+ {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/": {
+ "get": {
+ "summary": "Read Items",
+ "operationId": "read_items_items__get",
+ "parameters": [
+ {
+ "name": "session_id",
+ "in": "cookie",
+ "required": True,
+ "schema": {"type": "string", "title": "Session Id"},
+ },
+ {
+ "name": "fatebook_tracker",
+ "in": "cookie",
+ "required": False,
+ "schema": IsDict(
+ {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "Fatebook Tracker",
+ }
+ )
+ | IsDict(
+ # TODO: remove when deprecating Pydantic v1
+ {
+ "type": "string",
+ "title": "Fatebook Tracker",
+ }
+ ),
+ },
+ {
+ "name": "googall_tracker",
+ "in": "cookie",
+ "required": False,
+ "schema": IsDict(
+ {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "Googall Tracker",
+ }
+ )
+ | IsDict(
+ # TODO: remove when deprecating Pydantic v1
+ {
+ "type": "string",
+ "title": "Googall Tracker",
+ }
+ ),
+ },
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "HTTPValidationError": {
+ "properties": {
+ "detail": {
+ "items": {
+ "$ref": "#/components/schemas/ValidationError"
+ },
+ "type": "array",
+ "title": "Detail",
+ }
+ },
+ "type": "object",
+ "title": "HTTPValidationError",
+ },
+ "ValidationError": {
+ "properties": {
+ "loc": {
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ "type": "array",
+ "title": "Location",
+ },
+ "msg": {"type": "string", "title": "Message"},
+ "type": {"type": "string", "title": "Error Type"},
+ },
+ "type": "object",
+ "required": ["loc", "msg", "type"],
+ "title": "ValidationError",
+ },
+ }
+ },
+ }
+ )
diff --git a/docs_src/sql_databases/sql_app/tests/__init__.py b/tests/test_tutorial/test_header_param_models/__init__.py
similarity index 100%
rename from docs_src/sql_databases/sql_app/tests/__init__.py
rename to tests/test_tutorial/test_header_param_models/__init__.py
diff --git a/tests/test_tutorial/test_header_param_models/test_tutorial001.py b/tests/test_tutorial/test_header_param_models/test_tutorial001.py
new file mode 100644
index 000000000..06b2404cf
--- /dev/null
+++ b/tests/test_tutorial/test_header_param_models/test_tutorial001.py
@@ -0,0 +1,238 @@
+import importlib
+
+import pytest
+from dirty_equals import IsDict
+from fastapi.testclient import TestClient
+from inline_snapshot import snapshot
+
+from tests.utils import needs_py39, needs_py310
+
+
+@pytest.fixture(
+ name="client",
+ params=[
+ "tutorial001",
+ pytest.param("tutorial001_py39", marks=needs_py39),
+ pytest.param("tutorial001_py310", marks=needs_py310),
+ "tutorial001_an",
+ pytest.param("tutorial001_an_py39", marks=needs_py39),
+ pytest.param("tutorial001_an_py310", marks=needs_py310),
+ ],
+)
+def get_client(request: pytest.FixtureRequest):
+ mod = importlib.import_module(f"docs_src.header_param_models.{request.param}")
+
+ client = TestClient(mod.app)
+ return client
+
+
+def test_header_param_model(client: TestClient):
+ response = client.get(
+ "/items/",
+ headers=[
+ ("save-data", "true"),
+ ("if-modified-since", "yesterday"),
+ ("traceparent", "123"),
+ ("x-tag", "one"),
+ ("x-tag", "two"),
+ ],
+ )
+ assert response.status_code == 200
+ assert response.json() == {
+ "host": "testserver",
+ "save_data": True,
+ "if_modified_since": "yesterday",
+ "traceparent": "123",
+ "x_tag": ["one", "two"],
+ }
+
+
+def test_header_param_model_defaults(client: TestClient):
+ response = client.get("/items/", headers=[("save-data", "true")])
+ assert response.status_code == 200
+ assert response.json() == {
+ "host": "testserver",
+ "save_data": True,
+ "if_modified_since": None,
+ "traceparent": None,
+ "x_tag": [],
+ }
+
+
+def test_header_param_model_invalid(client: TestClient):
+ response = client.get("/items/")
+ assert response.status_code == 422
+ assert response.json() == snapshot(
+ {
+ "detail": [
+ IsDict(
+ {
+ "type": "missing",
+ "loc": ["header", "save_data"],
+ "msg": "Field required",
+ "input": {
+ "x_tag": [],
+ "host": "testserver",
+ "accept": "*/*",
+ "accept-encoding": "gzip, deflate",
+ "connection": "keep-alive",
+ "user-agent": "testclient",
+ },
+ }
+ )
+ | IsDict(
+ # TODO: remove when deprecating Pydantic v1
+ {
+ "type": "value_error.missing",
+ "loc": ["header", "save_data"],
+ "msg": "field required",
+ }
+ )
+ ]
+ }
+ )
+
+
+def test_header_param_model_extra(client: TestClient):
+ response = client.get(
+ "/items/", headers=[("save-data", "true"), ("tool", "plumbus")]
+ )
+ assert response.status_code == 200, response.text
+ assert response.json() == snapshot(
+ {
+ "host": "testserver",
+ "save_data": True,
+ "if_modified_since": None,
+ "traceparent": None,
+ "x_tag": [],
+ }
+ )
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == snapshot(
+ {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/": {
+ "get": {
+ "summary": "Read Items",
+ "operationId": "read_items_items__get",
+ "parameters": [
+ {
+ "name": "host",
+ "in": "header",
+ "required": True,
+ "schema": {"type": "string", "title": "Host"},
+ },
+ {
+ "name": "save_data",
+ "in": "header",
+ "required": True,
+ "schema": {"type": "boolean", "title": "Save Data"},
+ },
+ {
+ "name": "if_modified_since",
+ "in": "header",
+ "required": False,
+ "schema": IsDict(
+ {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "If Modified Since",
+ }
+ )
+ | IsDict(
+ # TODO: remove when deprecating Pydantic v1
+ {
+ "type": "string",
+ "title": "If Modified Since",
+ }
+ ),
+ },
+ {
+ "name": "traceparent",
+ "in": "header",
+ "required": False,
+ "schema": IsDict(
+ {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "Traceparent",
+ }
+ )
+ | IsDict(
+ # TODO: remove when deprecating Pydantic v1
+ {
+ "type": "string",
+ "title": "Traceparent",
+ }
+ ),
+ },
+ {
+ "name": "x_tag",
+ "in": "header",
+ "required": False,
+ "schema": {
+ "type": "array",
+ "items": {"type": "string"},
+ "default": [],
+ "title": "X Tag",
+ },
+ },
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "HTTPValidationError": {
+ "properties": {
+ "detail": {
+ "items": {
+ "$ref": "#/components/schemas/ValidationError"
+ },
+ "type": "array",
+ "title": "Detail",
+ }
+ },
+ "type": "object",
+ "title": "HTTPValidationError",
+ },
+ "ValidationError": {
+ "properties": {
+ "loc": {
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ "type": "array",
+ "title": "Location",
+ },
+ "msg": {"type": "string", "title": "Message"},
+ "type": {"type": "string", "title": "Error Type"},
+ },
+ "type": "object",
+ "required": ["loc", "msg", "type"],
+ "title": "ValidationError",
+ },
+ }
+ },
+ }
+ )
diff --git a/tests/test_tutorial/test_header_param_models/test_tutorial002.py b/tests/test_tutorial/test_header_param_models/test_tutorial002.py
new file mode 100644
index 000000000..e07655a0c
--- /dev/null
+++ b/tests/test_tutorial/test_header_param_models/test_tutorial002.py
@@ -0,0 +1,249 @@
+import importlib
+
+import pytest
+from dirty_equals import IsDict
+from fastapi.testclient import TestClient
+from inline_snapshot import snapshot
+
+from tests.utils import needs_py39, needs_py310, needs_pydanticv1, needs_pydanticv2
+
+
+@pytest.fixture(
+ name="client",
+ params=[
+ pytest.param("tutorial002", marks=needs_pydanticv2),
+ pytest.param("tutorial002_py310", marks=[needs_py310, needs_pydanticv2]),
+ pytest.param("tutorial002_an", marks=needs_pydanticv2),
+ pytest.param("tutorial002_an_py39", marks=[needs_py39, needs_pydanticv2]),
+ pytest.param("tutorial002_an_py310", marks=[needs_py310, needs_pydanticv2]),
+ pytest.param("tutorial002_pv1", marks=[needs_pydanticv1, needs_pydanticv1]),
+ pytest.param("tutorial002_pv1_py310", marks=[needs_py310, needs_pydanticv1]),
+ pytest.param("tutorial002_pv1_an", marks=[needs_pydanticv1]),
+ pytest.param("tutorial002_pv1_an_py39", marks=[needs_py39, needs_pydanticv1]),
+ pytest.param("tutorial002_pv1_an_py310", marks=[needs_py310, needs_pydanticv1]),
+ ],
+)
+def get_client(request: pytest.FixtureRequest):
+ mod = importlib.import_module(f"docs_src.header_param_models.{request.param}")
+
+ client = TestClient(mod.app)
+ client.headers.clear()
+ return client
+
+
+def test_header_param_model(client: TestClient):
+ response = client.get(
+ "/items/",
+ headers=[
+ ("save-data", "true"),
+ ("if-modified-since", "yesterday"),
+ ("traceparent", "123"),
+ ("x-tag", "one"),
+ ("x-tag", "two"),
+ ],
+ )
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "host": "testserver",
+ "save_data": True,
+ "if_modified_since": "yesterday",
+ "traceparent": "123",
+ "x_tag": ["one", "two"],
+ }
+
+
+def test_header_param_model_defaults(client: TestClient):
+ response = client.get("/items/", headers=[("save-data", "true")])
+ assert response.status_code == 200
+ assert response.json() == {
+ "host": "testserver",
+ "save_data": True,
+ "if_modified_since": None,
+ "traceparent": None,
+ "x_tag": [],
+ }
+
+
+def test_header_param_model_invalid(client: TestClient):
+ response = client.get("/items/")
+ assert response.status_code == 422
+ assert response.json() == snapshot(
+ {
+ "detail": [
+ IsDict(
+ {
+ "type": "missing",
+ "loc": ["header", "save_data"],
+ "msg": "Field required",
+ "input": {"x_tag": [], "host": "testserver"},
+ }
+ )
+ | IsDict(
+ # TODO: remove when deprecating Pydantic v1
+ {
+ "type": "value_error.missing",
+ "loc": ["header", "save_data"],
+ "msg": "field required",
+ }
+ )
+ ]
+ }
+ )
+
+
+def test_header_param_model_extra(client: TestClient):
+ response = client.get(
+ "/items/", headers=[("save-data", "true"), ("tool", "plumbus")]
+ )
+ assert response.status_code == 422, response.text
+ assert response.json() == snapshot(
+ {
+ "detail": [
+ IsDict(
+ {
+ "type": "extra_forbidden",
+ "loc": ["header", "tool"],
+ "msg": "Extra inputs are not permitted",
+ "input": "plumbus",
+ }
+ )
+ | IsDict(
+ # TODO: remove when deprecating Pydantic v1
+ {
+ "type": "value_error.extra",
+ "loc": ["header", "tool"],
+ "msg": "extra fields not permitted",
+ }
+ )
+ ]
+ }
+ )
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == snapshot(
+ {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/": {
+ "get": {
+ "summary": "Read Items",
+ "operationId": "read_items_items__get",
+ "parameters": [
+ {
+ "name": "host",
+ "in": "header",
+ "required": True,
+ "schema": {"type": "string", "title": "Host"},
+ },
+ {
+ "name": "save_data",
+ "in": "header",
+ "required": True,
+ "schema": {"type": "boolean", "title": "Save Data"},
+ },
+ {
+ "name": "if_modified_since",
+ "in": "header",
+ "required": False,
+ "schema": IsDict(
+ {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "If Modified Since",
+ }
+ )
+ | IsDict(
+ # TODO: remove when deprecating Pydantic v1
+ {
+ "type": "string",
+ "title": "If Modified Since",
+ }
+ ),
+ },
+ {
+ "name": "traceparent",
+ "in": "header",
+ "required": False,
+ "schema": IsDict(
+ {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "Traceparent",
+ }
+ )
+ | IsDict(
+ # TODO: remove when deprecating Pydantic v1
+ {
+ "type": "string",
+ "title": "Traceparent",
+ }
+ ),
+ },
+ {
+ "name": "x_tag",
+ "in": "header",
+ "required": False,
+ "schema": {
+ "type": "array",
+ "items": {"type": "string"},
+ "default": [],
+ "title": "X Tag",
+ },
+ },
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "HTTPValidationError": {
+ "properties": {
+ "detail": {
+ "items": {
+ "$ref": "#/components/schemas/ValidationError"
+ },
+ "type": "array",
+ "title": "Detail",
+ }
+ },
+ "type": "object",
+ "title": "HTTPValidationError",
+ },
+ "ValidationError": {
+ "properties": {
+ "loc": {
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ "type": "array",
+ "title": "Location",
+ },
+ "msg": {"type": "string", "title": "Message"},
+ "type": {"type": "string", "title": "Error Type"},
+ },
+ "type": "object",
+ "required": ["loc", "msg", "type"],
+ "title": "ValidationError",
+ },
+ }
+ },
+ }
+ )
diff --git a/docs_src/sql_databases/sql_app_py310/__init__.py b/tests/test_tutorial/test_query_param_models/__init__.py
similarity index 100%
rename from docs_src/sql_databases/sql_app_py310/__init__.py
rename to tests/test_tutorial/test_query_param_models/__init__.py
diff --git a/tests/test_tutorial/test_query_param_models/test_tutorial001.py b/tests/test_tutorial/test_query_param_models/test_tutorial001.py
new file mode 100644
index 000000000..5b7bc7b42
--- /dev/null
+++ b/tests/test_tutorial/test_query_param_models/test_tutorial001.py
@@ -0,0 +1,260 @@
+import importlib
+
+import pytest
+from dirty_equals import IsDict
+from fastapi.testclient import TestClient
+from inline_snapshot import snapshot
+
+from tests.utils import needs_py39, needs_py310
+
+
+@pytest.fixture(
+ name="client",
+ params=[
+ "tutorial001",
+ pytest.param("tutorial001_py39", marks=needs_py39),
+ pytest.param("tutorial001_py310", marks=needs_py310),
+ "tutorial001_an",
+ pytest.param("tutorial001_an_py39", marks=needs_py39),
+ pytest.param("tutorial001_an_py310", marks=needs_py310),
+ ],
+)
+def get_client(request: pytest.FixtureRequest):
+ mod = importlib.import_module(f"docs_src.query_param_models.{request.param}")
+
+ client = TestClient(mod.app)
+ return client
+
+
+def test_query_param_model(client: TestClient):
+ response = client.get(
+ "/items/",
+ params={
+ "limit": 10,
+ "offset": 5,
+ "order_by": "updated_at",
+ "tags": ["tag1", "tag2"],
+ },
+ )
+ assert response.status_code == 200
+ assert response.json() == {
+ "limit": 10,
+ "offset": 5,
+ "order_by": "updated_at",
+ "tags": ["tag1", "tag2"],
+ }
+
+
+def test_query_param_model_defaults(client: TestClient):
+ response = client.get("/items/")
+ assert response.status_code == 200
+ assert response.json() == {
+ "limit": 100,
+ "offset": 0,
+ "order_by": "created_at",
+ "tags": [],
+ }
+
+
+def test_query_param_model_invalid(client: TestClient):
+ response = client.get(
+ "/items/",
+ params={
+ "limit": 150,
+ "offset": -1,
+ "order_by": "invalid",
+ },
+ )
+ assert response.status_code == 422
+ assert response.json() == snapshot(
+ IsDict(
+ {
+ "detail": [
+ {
+ "type": "less_than_equal",
+ "loc": ["query", "limit"],
+ "msg": "Input should be less than or equal to 100",
+ "input": "150",
+ "ctx": {"le": 100},
+ },
+ {
+ "type": "greater_than_equal",
+ "loc": ["query", "offset"],
+ "msg": "Input should be greater than or equal to 0",
+ "input": "-1",
+ "ctx": {"ge": 0},
+ },
+ {
+ "type": "literal_error",
+ "loc": ["query", "order_by"],
+ "msg": "Input should be 'created_at' or 'updated_at'",
+ "input": "invalid",
+ "ctx": {"expected": "'created_at' or 'updated_at'"},
+ },
+ ]
+ }
+ )
+ | IsDict(
+ # TODO: remove when deprecating Pydantic v1
+ {
+ "detail": [
+ {
+ "type": "value_error.number.not_le",
+ "loc": ["query", "limit"],
+ "msg": "ensure this value is less than or equal to 100",
+ "ctx": {"limit_value": 100},
+ },
+ {
+ "type": "value_error.number.not_ge",
+ "loc": ["query", "offset"],
+ "msg": "ensure this value is greater than or equal to 0",
+ "ctx": {"limit_value": 0},
+ },
+ {
+ "type": "value_error.const",
+ "loc": ["query", "order_by"],
+ "msg": "unexpected value; permitted: 'created_at', 'updated_at'",
+ "ctx": {
+ "given": "invalid",
+ "permitted": ["created_at", "updated_at"],
+ },
+ },
+ ]
+ }
+ )
+ )
+
+
+def test_query_param_model_extra(client: TestClient):
+ response = client.get(
+ "/items/",
+ params={
+ "limit": 10,
+ "offset": 5,
+ "order_by": "updated_at",
+ "tags": ["tag1", "tag2"],
+ "tool": "plumbus",
+ },
+ )
+ assert response.status_code == 200
+ assert response.json() == {
+ "limit": 10,
+ "offset": 5,
+ "order_by": "updated_at",
+ "tags": ["tag1", "tag2"],
+ }
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == snapshot(
+ {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/": {
+ "get": {
+ "summary": "Read Items",
+ "operationId": "read_items_items__get",
+ "parameters": [
+ {
+ "name": "limit",
+ "in": "query",
+ "required": False,
+ "schema": {
+ "type": "integer",
+ "maximum": 100,
+ "exclusiveMinimum": 0,
+ "default": 100,
+ "title": "Limit",
+ },
+ },
+ {
+ "name": "offset",
+ "in": "query",
+ "required": False,
+ "schema": {
+ "type": "integer",
+ "minimum": 0,
+ "default": 0,
+ "title": "Offset",
+ },
+ },
+ {
+ "name": "order_by",
+ "in": "query",
+ "required": False,
+ "schema": {
+ "enum": ["created_at", "updated_at"],
+ "type": "string",
+ "default": "created_at",
+ "title": "Order By",
+ },
+ },
+ {
+ "name": "tags",
+ "in": "query",
+ "required": False,
+ "schema": {
+ "type": "array",
+ "items": {"type": "string"},
+ "default": [],
+ "title": "Tags",
+ },
+ },
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "HTTPValidationError": {
+ "properties": {
+ "detail": {
+ "items": {
+ "$ref": "#/components/schemas/ValidationError"
+ },
+ "type": "array",
+ "title": "Detail",
+ }
+ },
+ "type": "object",
+ "title": "HTTPValidationError",
+ },
+ "ValidationError": {
+ "properties": {
+ "loc": {
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ "type": "array",
+ "title": "Location",
+ },
+ "msg": {"type": "string", "title": "Message"},
+ "type": {"type": "string", "title": "Error Type"},
+ },
+ "type": "object",
+ "required": ["loc", "msg", "type"],
+ "title": "ValidationError",
+ },
+ }
+ },
+ }
+ )
diff --git a/tests/test_tutorial/test_query_param_models/test_tutorial002.py b/tests/test_tutorial/test_query_param_models/test_tutorial002.py
new file mode 100644
index 000000000..4432c9d8a
--- /dev/null
+++ b/tests/test_tutorial/test_query_param_models/test_tutorial002.py
@@ -0,0 +1,282 @@
+import importlib
+
+import pytest
+from dirty_equals import IsDict
+from fastapi.testclient import TestClient
+from inline_snapshot import snapshot
+
+from tests.utils import needs_py39, needs_py310, needs_pydanticv1, needs_pydanticv2
+
+
+@pytest.fixture(
+ name="client",
+ params=[
+ pytest.param("tutorial002", marks=needs_pydanticv2),
+ pytest.param("tutorial002_py39", marks=[needs_py39, needs_pydanticv2]),
+ pytest.param("tutorial002_py310", marks=[needs_py310, needs_pydanticv2]),
+ pytest.param("tutorial002_an", marks=needs_pydanticv2),
+ pytest.param("tutorial002_an_py39", marks=[needs_py39, needs_pydanticv2]),
+ pytest.param("tutorial002_an_py310", marks=[needs_py310, needs_pydanticv2]),
+ pytest.param("tutorial002_pv1", marks=[needs_pydanticv1, needs_pydanticv1]),
+ pytest.param("tutorial002_pv1_py39", marks=[needs_py39, needs_pydanticv1]),
+ pytest.param("tutorial002_pv1_py310", marks=[needs_py310, needs_pydanticv1]),
+ pytest.param("tutorial002_pv1_an", marks=[needs_pydanticv1]),
+ pytest.param("tutorial002_pv1_an_py39", marks=[needs_py39, needs_pydanticv1]),
+ pytest.param("tutorial002_pv1_an_py310", marks=[needs_py310, needs_pydanticv1]),
+ ],
+)
+def get_client(request: pytest.FixtureRequest):
+ mod = importlib.import_module(f"docs_src.query_param_models.{request.param}")
+
+ client = TestClient(mod.app)
+ return client
+
+
+def test_query_param_model(client: TestClient):
+ response = client.get(
+ "/items/",
+ params={
+ "limit": 10,
+ "offset": 5,
+ "order_by": "updated_at",
+ "tags": ["tag1", "tag2"],
+ },
+ )
+ assert response.status_code == 200
+ assert response.json() == {
+ "limit": 10,
+ "offset": 5,
+ "order_by": "updated_at",
+ "tags": ["tag1", "tag2"],
+ }
+
+
+def test_query_param_model_defaults(client: TestClient):
+ response = client.get("/items/")
+ assert response.status_code == 200
+ assert response.json() == {
+ "limit": 100,
+ "offset": 0,
+ "order_by": "created_at",
+ "tags": [],
+ }
+
+
+def test_query_param_model_invalid(client: TestClient):
+ response = client.get(
+ "/items/",
+ params={
+ "limit": 150,
+ "offset": -1,
+ "order_by": "invalid",
+ },
+ )
+ assert response.status_code == 422
+ assert response.json() == snapshot(
+ IsDict(
+ {
+ "detail": [
+ {
+ "type": "less_than_equal",
+ "loc": ["query", "limit"],
+ "msg": "Input should be less than or equal to 100",
+ "input": "150",
+ "ctx": {"le": 100},
+ },
+ {
+ "type": "greater_than_equal",
+ "loc": ["query", "offset"],
+ "msg": "Input should be greater than or equal to 0",
+ "input": "-1",
+ "ctx": {"ge": 0},
+ },
+ {
+ "type": "literal_error",
+ "loc": ["query", "order_by"],
+ "msg": "Input should be 'created_at' or 'updated_at'",
+ "input": "invalid",
+ "ctx": {"expected": "'created_at' or 'updated_at'"},
+ },
+ ]
+ }
+ )
+ | IsDict(
+ # TODO: remove when deprecating Pydantic v1
+ {
+ "detail": [
+ {
+ "type": "value_error.number.not_le",
+ "loc": ["query", "limit"],
+ "msg": "ensure this value is less than or equal to 100",
+ "ctx": {"limit_value": 100},
+ },
+ {
+ "type": "value_error.number.not_ge",
+ "loc": ["query", "offset"],
+ "msg": "ensure this value is greater than or equal to 0",
+ "ctx": {"limit_value": 0},
+ },
+ {
+ "type": "value_error.const",
+ "loc": ["query", "order_by"],
+ "msg": "unexpected value; permitted: 'created_at', 'updated_at'",
+ "ctx": {
+ "given": "invalid",
+ "permitted": ["created_at", "updated_at"],
+ },
+ },
+ ]
+ }
+ )
+ )
+
+
+def test_query_param_model_extra(client: TestClient):
+ response = client.get(
+ "/items/",
+ params={
+ "limit": 10,
+ "offset": 5,
+ "order_by": "updated_at",
+ "tags": ["tag1", "tag2"],
+ "tool": "plumbus",
+ },
+ )
+ assert response.status_code == 422
+ assert response.json() == snapshot(
+ {
+ "detail": [
+ IsDict(
+ {
+ "type": "extra_forbidden",
+ "loc": ["query", "tool"],
+ "msg": "Extra inputs are not permitted",
+ "input": "plumbus",
+ }
+ )
+ | IsDict(
+ # TODO: remove when deprecating Pydantic v1
+ {
+ "type": "value_error.extra",
+ "loc": ["query", "tool"],
+ "msg": "extra fields not permitted",
+ }
+ )
+ ]
+ }
+ )
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == snapshot(
+ {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/items/": {
+ "get": {
+ "summary": "Read Items",
+ "operationId": "read_items_items__get",
+ "parameters": [
+ {
+ "name": "limit",
+ "in": "query",
+ "required": False,
+ "schema": {
+ "type": "integer",
+ "maximum": 100,
+ "exclusiveMinimum": 0,
+ "default": 100,
+ "title": "Limit",
+ },
+ },
+ {
+ "name": "offset",
+ "in": "query",
+ "required": False,
+ "schema": {
+ "type": "integer",
+ "minimum": 0,
+ "default": 0,
+ "title": "Offset",
+ },
+ },
+ {
+ "name": "order_by",
+ "in": "query",
+ "required": False,
+ "schema": {
+ "enum": ["created_at", "updated_at"],
+ "type": "string",
+ "default": "created_at",
+ "title": "Order By",
+ },
+ },
+ {
+ "name": "tags",
+ "in": "query",
+ "required": False,
+ "schema": {
+ "type": "array",
+ "items": {"type": "string"},
+ "default": [],
+ "title": "Tags",
+ },
+ },
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "HTTPValidationError": {
+ "properties": {
+ "detail": {
+ "items": {
+ "$ref": "#/components/schemas/ValidationError"
+ },
+ "type": "array",
+ "title": "Detail",
+ }
+ },
+ "type": "object",
+ "title": "HTTPValidationError",
+ },
+ "ValidationError": {
+ "properties": {
+ "loc": {
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ "type": "array",
+ "title": "Location",
+ },
+ "msg": {"type": "string", "title": "Message"},
+ "type": {"type": "string", "title": "Error Type"},
+ },
+ "type": "object",
+ "required": ["loc", "msg", "type"],
+ "title": "ValidationError",
+ },
+ }
+ },
+ }
+ )
diff --git a/docs_src/sql_databases/sql_app_py310/tests/__init__.py b/tests/test_tutorial/test_request_form_models/__init__.py
similarity index 100%
rename from docs_src/sql_databases/sql_app_py310/tests/__init__.py
rename to tests/test_tutorial/test_request_form_models/__init__.py
diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial001.py b/tests/test_tutorial/test_request_form_models/test_tutorial001.py
new file mode 100644
index 000000000..46c130ee8
--- /dev/null
+++ b/tests/test_tutorial/test_request_form_models/test_tutorial001.py
@@ -0,0 +1,232 @@
+import pytest
+from dirty_equals import IsDict
+from fastapi.testclient import TestClient
+
+
+@pytest.fixture(name="client")
+def get_client():
+ from docs_src.request_form_models.tutorial001 import app
+
+ client = TestClient(app)
+ return client
+
+
+def test_post_body_form(client: TestClient):
+ response = client.post("/login/", data={"username": "Foo", "password": "secret"})
+ assert response.status_code == 200
+ assert response.json() == {"username": "Foo", "password": "secret"}
+
+
+def test_post_body_form_no_password(client: TestClient):
+ response = client.post("/login/", data={"username": "Foo"})
+ assert response.status_code == 422
+ assert response.json() == IsDict(
+ {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "password"],
+ "msg": "Field required",
+ "input": {"username": "Foo"},
+ }
+ ]
+ }
+ ) | IsDict(
+ # TODO: remove when deprecating Pydantic v1
+ {
+ "detail": [
+ {
+ "loc": ["body", "password"],
+ "msg": "field required",
+ "type": "value_error.missing",
+ }
+ ]
+ }
+ )
+
+
+def test_post_body_form_no_username(client: TestClient):
+ response = client.post("/login/", data={"password": "secret"})
+ assert response.status_code == 422
+ assert response.json() == IsDict(
+ {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "username"],
+ "msg": "Field required",
+ "input": {"password": "secret"},
+ }
+ ]
+ }
+ ) | IsDict(
+ # TODO: remove when deprecating Pydantic v1
+ {
+ "detail": [
+ {
+ "loc": ["body", "username"],
+ "msg": "field required",
+ "type": "value_error.missing",
+ }
+ ]
+ }
+ )
+
+
+def test_post_body_form_no_data(client: TestClient):
+ response = client.post("/login/")
+ assert response.status_code == 422
+ assert response.json() == IsDict(
+ {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "username"],
+ "msg": "Field required",
+ "input": {},
+ },
+ {
+ "type": "missing",
+ "loc": ["body", "password"],
+ "msg": "Field required",
+ "input": {},
+ },
+ ]
+ }
+ ) | IsDict(
+ # TODO: remove when deprecating Pydantic v1
+ {
+ "detail": [
+ {
+ "loc": ["body", "username"],
+ "msg": "field required",
+ "type": "value_error.missing",
+ },
+ {
+ "loc": ["body", "password"],
+ "msg": "field required",
+ "type": "value_error.missing",
+ },
+ ]
+ }
+ )
+
+
+def test_post_body_json(client: TestClient):
+ response = client.post("/login/", json={"username": "Foo", "password": "secret"})
+ assert response.status_code == 422, response.text
+ assert response.json() == IsDict(
+ {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "username"],
+ "msg": "Field required",
+ "input": {},
+ },
+ {
+ "type": "missing",
+ "loc": ["body", "password"],
+ "msg": "Field required",
+ "input": {},
+ },
+ ]
+ }
+ ) | IsDict(
+ # TODO: remove when deprecating Pydantic v1
+ {
+ "detail": [
+ {
+ "loc": ["body", "username"],
+ "msg": "field required",
+ "type": "value_error.missing",
+ },
+ {
+ "loc": ["body", "password"],
+ "msg": "field required",
+ "type": "value_error.missing",
+ },
+ ]
+ }
+ )
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/login/": {
+ "post": {
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ "summary": "Login",
+ "operationId": "login_login__post",
+ "requestBody": {
+ "content": {
+ "application/x-www-form-urlencoded": {
+ "schema": {"$ref": "#/components/schemas/FormData"}
+ }
+ },
+ "required": True,
+ },
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "FormData": {
+ "properties": {
+ "username": {"type": "string", "title": "Username"},
+ "password": {"type": "string", "title": "Password"},
+ },
+ "type": "object",
+ "required": ["username", "password"],
+ "title": "FormData",
+ },
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/ValidationError"},
+ }
+ },
+ },
+ }
+ },
+ }
diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial001_an.py b/tests/test_tutorial/test_request_form_models/test_tutorial001_an.py
new file mode 100644
index 000000000..4e14d89c8
--- /dev/null
+++ b/tests/test_tutorial/test_request_form_models/test_tutorial001_an.py
@@ -0,0 +1,232 @@
+import pytest
+from dirty_equals import IsDict
+from fastapi.testclient import TestClient
+
+
+@pytest.fixture(name="client")
+def get_client():
+ from docs_src.request_form_models.tutorial001_an import app
+
+ client = TestClient(app)
+ return client
+
+
+def test_post_body_form(client: TestClient):
+ response = client.post("/login/", data={"username": "Foo", "password": "secret"})
+ assert response.status_code == 200
+ assert response.json() == {"username": "Foo", "password": "secret"}
+
+
+def test_post_body_form_no_password(client: TestClient):
+ response = client.post("/login/", data={"username": "Foo"})
+ assert response.status_code == 422
+ assert response.json() == IsDict(
+ {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "password"],
+ "msg": "Field required",
+ "input": {"username": "Foo"},
+ }
+ ]
+ }
+ ) | IsDict(
+ # TODO: remove when deprecating Pydantic v1
+ {
+ "detail": [
+ {
+ "loc": ["body", "password"],
+ "msg": "field required",
+ "type": "value_error.missing",
+ }
+ ]
+ }
+ )
+
+
+def test_post_body_form_no_username(client: TestClient):
+ response = client.post("/login/", data={"password": "secret"})
+ assert response.status_code == 422
+ assert response.json() == IsDict(
+ {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "username"],
+ "msg": "Field required",
+ "input": {"password": "secret"},
+ }
+ ]
+ }
+ ) | IsDict(
+ # TODO: remove when deprecating Pydantic v1
+ {
+ "detail": [
+ {
+ "loc": ["body", "username"],
+ "msg": "field required",
+ "type": "value_error.missing",
+ }
+ ]
+ }
+ )
+
+
+def test_post_body_form_no_data(client: TestClient):
+ response = client.post("/login/")
+ assert response.status_code == 422
+ assert response.json() == IsDict(
+ {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "username"],
+ "msg": "Field required",
+ "input": {},
+ },
+ {
+ "type": "missing",
+ "loc": ["body", "password"],
+ "msg": "Field required",
+ "input": {},
+ },
+ ]
+ }
+ ) | IsDict(
+ # TODO: remove when deprecating Pydantic v1
+ {
+ "detail": [
+ {
+ "loc": ["body", "username"],
+ "msg": "field required",
+ "type": "value_error.missing",
+ },
+ {
+ "loc": ["body", "password"],
+ "msg": "field required",
+ "type": "value_error.missing",
+ },
+ ]
+ }
+ )
+
+
+def test_post_body_json(client: TestClient):
+ response = client.post("/login/", json={"username": "Foo", "password": "secret"})
+ assert response.status_code == 422, response.text
+ assert response.json() == IsDict(
+ {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "username"],
+ "msg": "Field required",
+ "input": {},
+ },
+ {
+ "type": "missing",
+ "loc": ["body", "password"],
+ "msg": "Field required",
+ "input": {},
+ },
+ ]
+ }
+ ) | IsDict(
+ # TODO: remove when deprecating Pydantic v1
+ {
+ "detail": [
+ {
+ "loc": ["body", "username"],
+ "msg": "field required",
+ "type": "value_error.missing",
+ },
+ {
+ "loc": ["body", "password"],
+ "msg": "field required",
+ "type": "value_error.missing",
+ },
+ ]
+ }
+ )
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/login/": {
+ "post": {
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ "summary": "Login",
+ "operationId": "login_login__post",
+ "requestBody": {
+ "content": {
+ "application/x-www-form-urlencoded": {
+ "schema": {"$ref": "#/components/schemas/FormData"}
+ }
+ },
+ "required": True,
+ },
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "FormData": {
+ "properties": {
+ "username": {"type": "string", "title": "Username"},
+ "password": {"type": "string", "title": "Password"},
+ },
+ "type": "object",
+ "required": ["username", "password"],
+ "title": "FormData",
+ },
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/ValidationError"},
+ }
+ },
+ },
+ }
+ },
+ }
diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial001_an_py39.py b/tests/test_tutorial/test_request_form_models/test_tutorial001_an_py39.py
new file mode 100644
index 000000000..2e6426aa7
--- /dev/null
+++ b/tests/test_tutorial/test_request_form_models/test_tutorial001_an_py39.py
@@ -0,0 +1,240 @@
+import pytest
+from dirty_equals import IsDict
+from fastapi.testclient import TestClient
+
+from tests.utils import needs_py39
+
+
+@pytest.fixture(name="client")
+def get_client():
+ from docs_src.request_form_models.tutorial001_an_py39 import app
+
+ client = TestClient(app)
+ return client
+
+
+@needs_py39
+def test_post_body_form(client: TestClient):
+ response = client.post("/login/", data={"username": "Foo", "password": "secret"})
+ assert response.status_code == 200
+ assert response.json() == {"username": "Foo", "password": "secret"}
+
+
+@needs_py39
+def test_post_body_form_no_password(client: TestClient):
+ response = client.post("/login/", data={"username": "Foo"})
+ assert response.status_code == 422
+ assert response.json() == IsDict(
+ {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "password"],
+ "msg": "Field required",
+ "input": {"username": "Foo"},
+ }
+ ]
+ }
+ ) | IsDict(
+ # TODO: remove when deprecating Pydantic v1
+ {
+ "detail": [
+ {
+ "loc": ["body", "password"],
+ "msg": "field required",
+ "type": "value_error.missing",
+ }
+ ]
+ }
+ )
+
+
+@needs_py39
+def test_post_body_form_no_username(client: TestClient):
+ response = client.post("/login/", data={"password": "secret"})
+ assert response.status_code == 422
+ assert response.json() == IsDict(
+ {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "username"],
+ "msg": "Field required",
+ "input": {"password": "secret"},
+ }
+ ]
+ }
+ ) | IsDict(
+ # TODO: remove when deprecating Pydantic v1
+ {
+ "detail": [
+ {
+ "loc": ["body", "username"],
+ "msg": "field required",
+ "type": "value_error.missing",
+ }
+ ]
+ }
+ )
+
+
+@needs_py39
+def test_post_body_form_no_data(client: TestClient):
+ response = client.post("/login/")
+ assert response.status_code == 422
+ assert response.json() == IsDict(
+ {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "username"],
+ "msg": "Field required",
+ "input": {},
+ },
+ {
+ "type": "missing",
+ "loc": ["body", "password"],
+ "msg": "Field required",
+ "input": {},
+ },
+ ]
+ }
+ ) | IsDict(
+ # TODO: remove when deprecating Pydantic v1
+ {
+ "detail": [
+ {
+ "loc": ["body", "username"],
+ "msg": "field required",
+ "type": "value_error.missing",
+ },
+ {
+ "loc": ["body", "password"],
+ "msg": "field required",
+ "type": "value_error.missing",
+ },
+ ]
+ }
+ )
+
+
+@needs_py39
+def test_post_body_json(client: TestClient):
+ response = client.post("/login/", json={"username": "Foo", "password": "secret"})
+ assert response.status_code == 422, response.text
+ assert response.json() == IsDict(
+ {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "username"],
+ "msg": "Field required",
+ "input": {},
+ },
+ {
+ "type": "missing",
+ "loc": ["body", "password"],
+ "msg": "Field required",
+ "input": {},
+ },
+ ]
+ }
+ ) | IsDict(
+ # TODO: remove when deprecating Pydantic v1
+ {
+ "detail": [
+ {
+ "loc": ["body", "username"],
+ "msg": "field required",
+ "type": "value_error.missing",
+ },
+ {
+ "loc": ["body", "password"],
+ "msg": "field required",
+ "type": "value_error.missing",
+ },
+ ]
+ }
+ )
+
+
+@needs_py39
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/login/": {
+ "post": {
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ "summary": "Login",
+ "operationId": "login_login__post",
+ "requestBody": {
+ "content": {
+ "application/x-www-form-urlencoded": {
+ "schema": {"$ref": "#/components/schemas/FormData"}
+ }
+ },
+ "required": True,
+ },
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "FormData": {
+ "properties": {
+ "username": {"type": "string", "title": "Username"},
+ "password": {"type": "string", "title": "Password"},
+ },
+ "type": "object",
+ "required": ["username", "password"],
+ "title": "FormData",
+ },
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/ValidationError"},
+ }
+ },
+ },
+ }
+ },
+ }
diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial002.py b/tests/test_tutorial/test_request_form_models/test_tutorial002.py
new file mode 100644
index 000000000..76f480001
--- /dev/null
+++ b/tests/test_tutorial/test_request_form_models/test_tutorial002.py
@@ -0,0 +1,196 @@
+import pytest
+from fastapi.testclient import TestClient
+
+from tests.utils import needs_pydanticv2
+
+
+@pytest.fixture(name="client")
+def get_client():
+ from docs_src.request_form_models.tutorial002 import app
+
+ client = TestClient(app)
+ return client
+
+
+@needs_pydanticv2
+def test_post_body_form(client: TestClient):
+ response = client.post("/login/", data={"username": "Foo", "password": "secret"})
+ assert response.status_code == 200
+ assert response.json() == {"username": "Foo", "password": "secret"}
+
+
+@needs_pydanticv2
+def test_post_body_extra_form(client: TestClient):
+ response = client.post(
+ "/login/", data={"username": "Foo", "password": "secret", "extra": "extra"}
+ )
+ assert response.status_code == 422
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "extra_forbidden",
+ "loc": ["body", "extra"],
+ "msg": "Extra inputs are not permitted",
+ "input": "extra",
+ }
+ ]
+ }
+
+
+@needs_pydanticv2
+def test_post_body_form_no_password(client: TestClient):
+ response = client.post("/login/", data={"username": "Foo"})
+ assert response.status_code == 422
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "password"],
+ "msg": "Field required",
+ "input": {"username": "Foo"},
+ }
+ ]
+ }
+
+
+@needs_pydanticv2
+def test_post_body_form_no_username(client: TestClient):
+ response = client.post("/login/", data={"password": "secret"})
+ assert response.status_code == 422
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "username"],
+ "msg": "Field required",
+ "input": {"password": "secret"},
+ }
+ ]
+ }
+
+
+@needs_pydanticv2
+def test_post_body_form_no_data(client: TestClient):
+ response = client.post("/login/")
+ assert response.status_code == 422
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "username"],
+ "msg": "Field required",
+ "input": {},
+ },
+ {
+ "type": "missing",
+ "loc": ["body", "password"],
+ "msg": "Field required",
+ "input": {},
+ },
+ ]
+ }
+
+
+@needs_pydanticv2
+def test_post_body_json(client: TestClient):
+ response = client.post("/login/", json={"username": "Foo", "password": "secret"})
+ assert response.status_code == 422, response.text
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "username"],
+ "msg": "Field required",
+ "input": {},
+ },
+ {
+ "type": "missing",
+ "loc": ["body", "password"],
+ "msg": "Field required",
+ "input": {},
+ },
+ ]
+ }
+
+
+@needs_pydanticv2
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/login/": {
+ "post": {
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ "summary": "Login",
+ "operationId": "login_login__post",
+ "requestBody": {
+ "content": {
+ "application/x-www-form-urlencoded": {
+ "schema": {"$ref": "#/components/schemas/FormData"}
+ }
+ },
+ "required": True,
+ },
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "FormData": {
+ "properties": {
+ "username": {"type": "string", "title": "Username"},
+ "password": {"type": "string", "title": "Password"},
+ },
+ "additionalProperties": False,
+ "type": "object",
+ "required": ["username", "password"],
+ "title": "FormData",
+ },
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/ValidationError"},
+ }
+ },
+ },
+ }
+ },
+ }
diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial002_an.py b/tests/test_tutorial/test_request_form_models/test_tutorial002_an.py
new file mode 100644
index 000000000..179b2977d
--- /dev/null
+++ b/tests/test_tutorial/test_request_form_models/test_tutorial002_an.py
@@ -0,0 +1,196 @@
+import pytest
+from fastapi.testclient import TestClient
+
+from tests.utils import needs_pydanticv2
+
+
+@pytest.fixture(name="client")
+def get_client():
+ from docs_src.request_form_models.tutorial002_an import app
+
+ client = TestClient(app)
+ return client
+
+
+@needs_pydanticv2
+def test_post_body_form(client: TestClient):
+ response = client.post("/login/", data={"username": "Foo", "password": "secret"})
+ assert response.status_code == 200
+ assert response.json() == {"username": "Foo", "password": "secret"}
+
+
+@needs_pydanticv2
+def test_post_body_extra_form(client: TestClient):
+ response = client.post(
+ "/login/", data={"username": "Foo", "password": "secret", "extra": "extra"}
+ )
+ assert response.status_code == 422
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "extra_forbidden",
+ "loc": ["body", "extra"],
+ "msg": "Extra inputs are not permitted",
+ "input": "extra",
+ }
+ ]
+ }
+
+
+@needs_pydanticv2
+def test_post_body_form_no_password(client: TestClient):
+ response = client.post("/login/", data={"username": "Foo"})
+ assert response.status_code == 422
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "password"],
+ "msg": "Field required",
+ "input": {"username": "Foo"},
+ }
+ ]
+ }
+
+
+@needs_pydanticv2
+def test_post_body_form_no_username(client: TestClient):
+ response = client.post("/login/", data={"password": "secret"})
+ assert response.status_code == 422
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "username"],
+ "msg": "Field required",
+ "input": {"password": "secret"},
+ }
+ ]
+ }
+
+
+@needs_pydanticv2
+def test_post_body_form_no_data(client: TestClient):
+ response = client.post("/login/")
+ assert response.status_code == 422
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "username"],
+ "msg": "Field required",
+ "input": {},
+ },
+ {
+ "type": "missing",
+ "loc": ["body", "password"],
+ "msg": "Field required",
+ "input": {},
+ },
+ ]
+ }
+
+
+@needs_pydanticv2
+def test_post_body_json(client: TestClient):
+ response = client.post("/login/", json={"username": "Foo", "password": "secret"})
+ assert response.status_code == 422, response.text
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "username"],
+ "msg": "Field required",
+ "input": {},
+ },
+ {
+ "type": "missing",
+ "loc": ["body", "password"],
+ "msg": "Field required",
+ "input": {},
+ },
+ ]
+ }
+
+
+@needs_pydanticv2
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/login/": {
+ "post": {
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ "summary": "Login",
+ "operationId": "login_login__post",
+ "requestBody": {
+ "content": {
+ "application/x-www-form-urlencoded": {
+ "schema": {"$ref": "#/components/schemas/FormData"}
+ }
+ },
+ "required": True,
+ },
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "FormData": {
+ "properties": {
+ "username": {"type": "string", "title": "Username"},
+ "password": {"type": "string", "title": "Password"},
+ },
+ "additionalProperties": False,
+ "type": "object",
+ "required": ["username", "password"],
+ "title": "FormData",
+ },
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/ValidationError"},
+ }
+ },
+ },
+ }
+ },
+ }
diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial002_an_py39.py b/tests/test_tutorial/test_request_form_models/test_tutorial002_an_py39.py
new file mode 100644
index 000000000..510ad9d7c
--- /dev/null
+++ b/tests/test_tutorial/test_request_form_models/test_tutorial002_an_py39.py
@@ -0,0 +1,203 @@
+import pytest
+from fastapi.testclient import TestClient
+
+from tests.utils import needs_py39, needs_pydanticv2
+
+
+@pytest.fixture(name="client")
+def get_client():
+ from docs_src.request_form_models.tutorial002_an_py39 import app
+
+ client = TestClient(app)
+ return client
+
+
+@needs_pydanticv2
+@needs_py39
+def test_post_body_form(client: TestClient):
+ response = client.post("/login/", data={"username": "Foo", "password": "secret"})
+ assert response.status_code == 200
+ assert response.json() == {"username": "Foo", "password": "secret"}
+
+
+@needs_pydanticv2
+@needs_py39
+def test_post_body_extra_form(client: TestClient):
+ response = client.post(
+ "/login/", data={"username": "Foo", "password": "secret", "extra": "extra"}
+ )
+ assert response.status_code == 422
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "extra_forbidden",
+ "loc": ["body", "extra"],
+ "msg": "Extra inputs are not permitted",
+ "input": "extra",
+ }
+ ]
+ }
+
+
+@needs_pydanticv2
+@needs_py39
+def test_post_body_form_no_password(client: TestClient):
+ response = client.post("/login/", data={"username": "Foo"})
+ assert response.status_code == 422
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "password"],
+ "msg": "Field required",
+ "input": {"username": "Foo"},
+ }
+ ]
+ }
+
+
+@needs_pydanticv2
+@needs_py39
+def test_post_body_form_no_username(client: TestClient):
+ response = client.post("/login/", data={"password": "secret"})
+ assert response.status_code == 422
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "username"],
+ "msg": "Field required",
+ "input": {"password": "secret"},
+ }
+ ]
+ }
+
+
+@needs_pydanticv2
+@needs_py39
+def test_post_body_form_no_data(client: TestClient):
+ response = client.post("/login/")
+ assert response.status_code == 422
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "username"],
+ "msg": "Field required",
+ "input": {},
+ },
+ {
+ "type": "missing",
+ "loc": ["body", "password"],
+ "msg": "Field required",
+ "input": {},
+ },
+ ]
+ }
+
+
+@needs_pydanticv2
+@needs_py39
+def test_post_body_json(client: TestClient):
+ response = client.post("/login/", json={"username": "Foo", "password": "secret"})
+ assert response.status_code == 422, response.text
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "missing",
+ "loc": ["body", "username"],
+ "msg": "Field required",
+ "input": {},
+ },
+ {
+ "type": "missing",
+ "loc": ["body", "password"],
+ "msg": "Field required",
+ "input": {},
+ },
+ ]
+ }
+
+
+@needs_pydanticv2
+@needs_py39
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/login/": {
+ "post": {
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ "summary": "Login",
+ "operationId": "login_login__post",
+ "requestBody": {
+ "content": {
+ "application/x-www-form-urlencoded": {
+ "schema": {"$ref": "#/components/schemas/FormData"}
+ }
+ },
+ "required": True,
+ },
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "FormData": {
+ "properties": {
+ "username": {"type": "string", "title": "Username"},
+ "password": {"type": "string", "title": "Password"},
+ },
+ "additionalProperties": False,
+ "type": "object",
+ "required": ["username", "password"],
+ "title": "FormData",
+ },
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/ValidationError"},
+ }
+ },
+ },
+ }
+ },
+ }
diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial002_pv1.py b/tests/test_tutorial/test_request_form_models/test_tutorial002_pv1.py
new file mode 100644
index 000000000..249b9379d
--- /dev/null
+++ b/tests/test_tutorial/test_request_form_models/test_tutorial002_pv1.py
@@ -0,0 +1,189 @@
+import pytest
+from fastapi.testclient import TestClient
+
+from tests.utils import needs_pydanticv1
+
+
+@pytest.fixture(name="client")
+def get_client():
+ from docs_src.request_form_models.tutorial002_pv1 import app
+
+ client = TestClient(app)
+ return client
+
+
+@needs_pydanticv1
+def test_post_body_form(client: TestClient):
+ response = client.post("/login/", data={"username": "Foo", "password": "secret"})
+ assert response.status_code == 200
+ assert response.json() == {"username": "Foo", "password": "secret"}
+
+
+@needs_pydanticv1
+def test_post_body_extra_form(client: TestClient):
+ response = client.post(
+ "/login/", data={"username": "Foo", "password": "secret", "extra": "extra"}
+ )
+ assert response.status_code == 422
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "value_error.extra",
+ "loc": ["body", "extra"],
+ "msg": "extra fields not permitted",
+ }
+ ]
+ }
+
+
+@needs_pydanticv1
+def test_post_body_form_no_password(client: TestClient):
+ response = client.post("/login/", data={"username": "Foo"})
+ assert response.status_code == 422
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "value_error.missing",
+ "loc": ["body", "password"],
+ "msg": "field required",
+ }
+ ]
+ }
+
+
+@needs_pydanticv1
+def test_post_body_form_no_username(client: TestClient):
+ response = client.post("/login/", data={"password": "secret"})
+ assert response.status_code == 422
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "value_error.missing",
+ "loc": ["body", "username"],
+ "msg": "field required",
+ }
+ ]
+ }
+
+
+@needs_pydanticv1
+def test_post_body_form_no_data(client: TestClient):
+ response = client.post("/login/")
+ assert response.status_code == 422
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "value_error.missing",
+ "loc": ["body", "username"],
+ "msg": "field required",
+ },
+ {
+ "type": "value_error.missing",
+ "loc": ["body", "password"],
+ "msg": "field required",
+ },
+ ]
+ }
+
+
+@needs_pydanticv1
+def test_post_body_json(client: TestClient):
+ response = client.post("/login/", json={"username": "Foo", "password": "secret"})
+ assert response.status_code == 422, response.text
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "value_error.missing",
+ "loc": ["body", "username"],
+ "msg": "field required",
+ },
+ {
+ "type": "value_error.missing",
+ "loc": ["body", "password"],
+ "msg": "field required",
+ },
+ ]
+ }
+
+
+@needs_pydanticv1
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/login/": {
+ "post": {
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ "summary": "Login",
+ "operationId": "login_login__post",
+ "requestBody": {
+ "content": {
+ "application/x-www-form-urlencoded": {
+ "schema": {"$ref": "#/components/schemas/FormData"}
+ }
+ },
+ "required": True,
+ },
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "FormData": {
+ "properties": {
+ "username": {"type": "string", "title": "Username"},
+ "password": {"type": "string", "title": "Password"},
+ },
+ "additionalProperties": False,
+ "type": "object",
+ "required": ["username", "password"],
+ "title": "FormData",
+ },
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/ValidationError"},
+ }
+ },
+ },
+ }
+ },
+ }
diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial002_pv1_an.py b/tests/test_tutorial/test_request_form_models/test_tutorial002_pv1_an.py
new file mode 100644
index 000000000..44cb3c32b
--- /dev/null
+++ b/tests/test_tutorial/test_request_form_models/test_tutorial002_pv1_an.py
@@ -0,0 +1,196 @@
+import pytest
+from fastapi.testclient import TestClient
+
+from tests.utils import needs_pydanticv1
+
+
+@pytest.fixture(name="client")
+def get_client():
+ from docs_src.request_form_models.tutorial002_pv1_an import app
+
+ client = TestClient(app)
+ return client
+
+
+# TODO: remove when deprecating Pydantic v1
+@needs_pydanticv1
+def test_post_body_form(client: TestClient):
+ response = client.post("/login/", data={"username": "Foo", "password": "secret"})
+ assert response.status_code == 200
+ assert response.json() == {"username": "Foo", "password": "secret"}
+
+
+# TODO: remove when deprecating Pydantic v1
+@needs_pydanticv1
+def test_post_body_extra_form(client: TestClient):
+ response = client.post(
+ "/login/", data={"username": "Foo", "password": "secret", "extra": "extra"}
+ )
+ assert response.status_code == 422
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "value_error.extra",
+ "loc": ["body", "extra"],
+ "msg": "extra fields not permitted",
+ }
+ ]
+ }
+
+
+# TODO: remove when deprecating Pydantic v1
+@needs_pydanticv1
+def test_post_body_form_no_password(client: TestClient):
+ response = client.post("/login/", data={"username": "Foo"})
+ assert response.status_code == 422
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "value_error.missing",
+ "loc": ["body", "password"],
+ "msg": "field required",
+ }
+ ]
+ }
+
+
+# TODO: remove when deprecating Pydantic v1
+@needs_pydanticv1
+def test_post_body_form_no_username(client: TestClient):
+ response = client.post("/login/", data={"password": "secret"})
+ assert response.status_code == 422
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "value_error.missing",
+ "loc": ["body", "username"],
+ "msg": "field required",
+ }
+ ]
+ }
+
+
+# TODO: remove when deprecating Pydantic v1
+@needs_pydanticv1
+def test_post_body_form_no_data(client: TestClient):
+ response = client.post("/login/")
+ assert response.status_code == 422
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "value_error.missing",
+ "loc": ["body", "username"],
+ "msg": "field required",
+ },
+ {
+ "type": "value_error.missing",
+ "loc": ["body", "password"],
+ "msg": "field required",
+ },
+ ]
+ }
+
+
+# TODO: remove when deprecating Pydantic v1
+@needs_pydanticv1
+def test_post_body_json(client: TestClient):
+ response = client.post("/login/", json={"username": "Foo", "password": "secret"})
+ assert response.status_code == 422, response.text
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "value_error.missing",
+ "loc": ["body", "username"],
+ "msg": "field required",
+ },
+ {
+ "type": "value_error.missing",
+ "loc": ["body", "password"],
+ "msg": "field required",
+ },
+ ]
+ }
+
+
+# TODO: remove when deprecating Pydantic v1
+@needs_pydanticv1
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/login/": {
+ "post": {
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ "summary": "Login",
+ "operationId": "login_login__post",
+ "requestBody": {
+ "content": {
+ "application/x-www-form-urlencoded": {
+ "schema": {"$ref": "#/components/schemas/FormData"}
+ }
+ },
+ "required": True,
+ },
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "FormData": {
+ "properties": {
+ "username": {"type": "string", "title": "Username"},
+ "password": {"type": "string", "title": "Password"},
+ },
+ "additionalProperties": False,
+ "type": "object",
+ "required": ["username", "password"],
+ "title": "FormData",
+ },
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/ValidationError"},
+ }
+ },
+ },
+ }
+ },
+ }
diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial002_pv1_an_p39.py b/tests/test_tutorial/test_request_form_models/test_tutorial002_pv1_an_p39.py
new file mode 100644
index 000000000..899549e40
--- /dev/null
+++ b/tests/test_tutorial/test_request_form_models/test_tutorial002_pv1_an_p39.py
@@ -0,0 +1,203 @@
+import pytest
+from fastapi.testclient import TestClient
+
+from tests.utils import needs_py39, needs_pydanticv1
+
+
+@pytest.fixture(name="client")
+def get_client():
+ from docs_src.request_form_models.tutorial002_pv1_an_py39 import app
+
+ client = TestClient(app)
+ return client
+
+
+# TODO: remove when deprecating Pydantic v1
+@needs_pydanticv1
+@needs_py39
+def test_post_body_form(client: TestClient):
+ response = client.post("/login/", data={"username": "Foo", "password": "secret"})
+ assert response.status_code == 200
+ assert response.json() == {"username": "Foo", "password": "secret"}
+
+
+# TODO: remove when deprecating Pydantic v1
+@needs_pydanticv1
+@needs_py39
+def test_post_body_extra_form(client: TestClient):
+ response = client.post(
+ "/login/", data={"username": "Foo", "password": "secret", "extra": "extra"}
+ )
+ assert response.status_code == 422
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "value_error.extra",
+ "loc": ["body", "extra"],
+ "msg": "extra fields not permitted",
+ }
+ ]
+ }
+
+
+# TODO: remove when deprecating Pydantic v1
+@needs_pydanticv1
+@needs_py39
+def test_post_body_form_no_password(client: TestClient):
+ response = client.post("/login/", data={"username": "Foo"})
+ assert response.status_code == 422
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "value_error.missing",
+ "loc": ["body", "password"],
+ "msg": "field required",
+ }
+ ]
+ }
+
+
+# TODO: remove when deprecating Pydantic v1
+@needs_pydanticv1
+@needs_py39
+def test_post_body_form_no_username(client: TestClient):
+ response = client.post("/login/", data={"password": "secret"})
+ assert response.status_code == 422
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "value_error.missing",
+ "loc": ["body", "username"],
+ "msg": "field required",
+ }
+ ]
+ }
+
+
+# TODO: remove when deprecating Pydantic v1
+@needs_pydanticv1
+@needs_py39
+def test_post_body_form_no_data(client: TestClient):
+ response = client.post("/login/")
+ assert response.status_code == 422
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "value_error.missing",
+ "loc": ["body", "username"],
+ "msg": "field required",
+ },
+ {
+ "type": "value_error.missing",
+ "loc": ["body", "password"],
+ "msg": "field required",
+ },
+ ]
+ }
+
+
+# TODO: remove when deprecating Pydantic v1
+@needs_pydanticv1
+@needs_py39
+def test_post_body_json(client: TestClient):
+ response = client.post("/login/", json={"username": "Foo", "password": "secret"})
+ assert response.status_code == 422, response.text
+ assert response.json() == {
+ "detail": [
+ {
+ "type": "value_error.missing",
+ "loc": ["body", "username"],
+ "msg": "field required",
+ },
+ {
+ "type": "value_error.missing",
+ "loc": ["body", "password"],
+ "msg": "field required",
+ },
+ ]
+ }
+
+
+# TODO: remove when deprecating Pydantic v1
+@needs_pydanticv1
+@needs_py39
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/login/": {
+ "post": {
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ "summary": "Login",
+ "operationId": "login_login__post",
+ "requestBody": {
+ "content": {
+ "application/x-www-form-urlencoded": {
+ "schema": {"$ref": "#/components/schemas/FormData"}
+ }
+ },
+ "required": True,
+ },
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "FormData": {
+ "properties": {
+ "username": {"type": "string", "title": "Username"},
+ "password": {"type": "string", "title": "Password"},
+ },
+ "additionalProperties": False,
+ "type": "object",
+ "required": ["username", "password"],
+ "title": "FormData",
+ },
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/ValidationError"},
+ }
+ },
+ },
+ }
+ },
+ }
diff --git a/tests/test_tutorial/test_sql_databases/test_sql_databases.py b/tests/test_tutorial/test_sql_databases/test_sql_databases.py
deleted file mode 100644
index e3e2b36a8..000000000
--- a/tests/test_tutorial/test_sql_databases/test_sql_databases.py
+++ /dev/null
@@ -1,419 +0,0 @@
-import importlib
-import os
-from pathlib import Path
-
-import pytest
-from dirty_equals import IsDict
-from fastapi.testclient import TestClient
-
-from ...utils import needs_pydanticv1
-
-
-@pytest.fixture(scope="module")
-def client(tmp_path_factory: pytest.TempPathFactory):
- tmp_path = tmp_path_factory.mktemp("data")
- cwd = os.getcwd()
- os.chdir(tmp_path)
- test_db = Path("./sql_app.db")
- if test_db.is_file(): # pragma: nocover
- test_db.unlink()
- # Import while creating the client to create the DB after starting the test session
- from docs_src.sql_databases.sql_app import main
-
- # Ensure import side effects are re-executed
- importlib.reload(main)
- with TestClient(main.app) as c:
- yield c
- if test_db.is_file(): # pragma: nocover
- test_db.unlink()
- os.chdir(cwd)
-
-
-# TODO: pv2 add version with Pydantic v2
-@needs_pydanticv1
-def test_create_user(client):
- test_user = {"email": "johndoe@example.com", "password": "secret"}
- response = client.post("/users/", json=test_user)
- assert response.status_code == 200, response.text
- data = response.json()
- assert test_user["email"] == data["email"]
- assert "id" in data
- response = client.post("/users/", json=test_user)
- assert response.status_code == 400, response.text
-
-
-# TODO: pv2 add version with Pydantic v2
-@needs_pydanticv1
-def test_get_user(client):
- response = client.get("/users/1")
- assert response.status_code == 200, response.text
- data = response.json()
- assert "email" in data
- assert "id" in data
-
-
-# TODO: pv2 add version with Pydantic v2
-@needs_pydanticv1
-def test_nonexistent_user(client):
- response = client.get("/users/999")
- assert response.status_code == 404, response.text
-
-
-# TODO: pv2 add version with Pydantic v2
-@needs_pydanticv1
-def test_get_users(client):
- response = client.get("/users/")
- assert response.status_code == 200, response.text
- data = response.json()
- assert "email" in data[0]
- assert "id" in data[0]
-
-
-# TODO: pv2 add Pydantic v2 version
-@needs_pydanticv1
-def test_create_item(client):
- item = {"title": "Foo", "description": "Something that fights"}
- response = client.post("/users/1/items/", json=item)
- assert response.status_code == 200, response.text
- item_data = response.json()
- assert item["title"] == item_data["title"]
- assert item["description"] == item_data["description"]
- assert "id" in item_data
- assert "owner_id" in item_data
- response = client.get("/users/1")
- assert response.status_code == 200, response.text
- user_data = response.json()
- item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0]
- assert item_to_check["title"] == item["title"]
- assert item_to_check["description"] == item["description"]
-
-
-# TODO: pv2 add Pydantic v2 version
-@needs_pydanticv1
-def test_read_items(client):
- response = client.get("/items/")
- assert response.status_code == 200, response.text
- data = response.json()
- assert data
- first_item = data[0]
- assert "title" in first_item
- assert "description" in first_item
-
-
-# TODO: pv2 add version with Pydantic v2
-@needs_pydanticv1
-def test_openapi_schema(client: TestClient):
- response = client.get("/openapi.json")
- assert response.status_code == 200, response.text
- assert response.json() == {
- "openapi": "3.1.0",
- "info": {"title": "FastAPI", "version": "0.1.0"},
- "paths": {
- "/users/": {
- "get": {
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {
- "title": "Response Read Users Users Get",
- "type": "array",
- "items": {"$ref": "#/components/schemas/User"},
- }
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- "summary": "Read Users",
- "operationId": "read_users_users__get",
- "parameters": [
- {
- "required": False,
- "schema": {
- "title": "Skip",
- "type": "integer",
- "default": 0,
- },
- "name": "skip",
- "in": "query",
- },
- {
- "required": False,
- "schema": {
- "title": "Limit",
- "type": "integer",
- "default": 100,
- },
- "name": "limit",
- "in": "query",
- },
- ],
- },
- "post": {
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/User"}
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- "summary": "Create User",
- "operationId": "create_user_users__post",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/UserCreate"}
- }
- },
- "required": True,
- },
- },
- },
- "/users/{user_id}": {
- "get": {
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/User"}
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- "summary": "Read User",
- "operationId": "read_user_users__user_id__get",
- "parameters": [
- {
- "required": True,
- "schema": {"title": "User Id", "type": "integer"},
- "name": "user_id",
- "in": "path",
- }
- ],
- }
- },
- "/users/{user_id}/items/": {
- "post": {
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/Item"}
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- "summary": "Create Item For User",
- "operationId": "create_item_for_user_users__user_id__items__post",
- "parameters": [
- {
- "required": True,
- "schema": {"title": "User Id", "type": "integer"},
- "name": "user_id",
- "in": "path",
- }
- ],
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/ItemCreate"}
- }
- },
- "required": True,
- },
- }
- },
- "/items/": {
- "get": {
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {
- "title": "Response Read Items Items Get",
- "type": "array",
- "items": {"$ref": "#/components/schemas/Item"},
- }
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- "summary": "Read Items",
- "operationId": "read_items_items__get",
- "parameters": [
- {
- "required": False,
- "schema": {
- "title": "Skip",
- "type": "integer",
- "default": 0,
- },
- "name": "skip",
- "in": "query",
- },
- {
- "required": False,
- "schema": {
- "title": "Limit",
- "type": "integer",
- "default": 100,
- },
- "name": "limit",
- "in": "query",
- },
- ],
- }
- },
- },
- "components": {
- "schemas": {
- "ItemCreate": {
- "title": "ItemCreate",
- "required": ["title"],
- "type": "object",
- "properties": {
- "title": {"title": "Title", "type": "string"},
- "description": IsDict(
- {
- "title": "Description",
- "anyOf": [{"type": "string"}, {"type": "null"}],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Description", "type": "string"}
- ),
- },
- },
- "Item": {
- "title": "Item",
- "required": ["title", "id", "owner_id"],
- "type": "object",
- "properties": {
- "title": {"title": "Title", "type": "string"},
- "description": IsDict(
- {
- "title": "Description",
- "anyOf": [{"type": "string"}, {"type": "null"}],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Description", "type": "string"},
- ),
- "id": {"title": "Id", "type": "integer"},
- "owner_id": {"title": "Owner Id", "type": "integer"},
- },
- },
- "User": {
- "title": "User",
- "required": ["email", "id", "is_active"],
- "type": "object",
- "properties": {
- "email": {"title": "Email", "type": "string"},
- "id": {"title": "Id", "type": "integer"},
- "is_active": {"title": "Is Active", "type": "boolean"},
- "items": {
- "title": "Items",
- "type": "array",
- "items": {"$ref": "#/components/schemas/Item"},
- "default": [],
- },
- },
- },
- "UserCreate": {
- "title": "UserCreate",
- "required": ["email", "password"],
- "type": "object",
- "properties": {
- "email": {"title": "Email", "type": "string"},
- "password": {"title": "Password", "type": "string"},
- },
- },
- "ValidationError": {
- "title": "ValidationError",
- "required": ["loc", "msg", "type"],
- "type": "object",
- "properties": {
- "loc": {
- "title": "Location",
- "type": "array",
- "items": {
- "anyOf": [{"type": "string"}, {"type": "integer"}]
- },
- },
- "msg": {"title": "Message", "type": "string"},
- "type": {"title": "Error Type", "type": "string"},
- },
- },
- "HTTPValidationError": {
- "title": "HTTPValidationError",
- "type": "object",
- "properties": {
- "detail": {
- "title": "Detail",
- "type": "array",
- "items": {"$ref": "#/components/schemas/ValidationError"},
- }
- },
- },
- }
- },
- }
diff --git a/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware.py b/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware.py
deleted file mode 100644
index 73b97e09d..000000000
--- a/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware.py
+++ /dev/null
@@ -1,421 +0,0 @@
-import importlib
-from pathlib import Path
-
-import pytest
-from dirty_equals import IsDict
-from fastapi.testclient import TestClient
-
-from ...utils import needs_pydanticv1
-
-
-@pytest.fixture(scope="module")
-def client():
- test_db = Path("./sql_app.db")
- if test_db.is_file(): # pragma: nocover
- test_db.unlink()
- # Import while creating the client to create the DB after starting the test session
- from docs_src.sql_databases.sql_app import alt_main
-
- # Ensure import side effects are re-executed
- importlib.reload(alt_main)
-
- with TestClient(alt_main.app) as c:
- yield c
- if test_db.is_file(): # pragma: nocover
- test_db.unlink()
-
-
-# TODO: pv2 add version with Pydantic v2
-@needs_pydanticv1
-def test_create_user(client):
- test_user = {"email": "johndoe@example.com", "password": "secret"}
- response = client.post("/users/", json=test_user)
- assert response.status_code == 200, response.text
- data = response.json()
- assert test_user["email"] == data["email"]
- assert "id" in data
- response = client.post("/users/", json=test_user)
- assert response.status_code == 400, response.text
-
-
-# TODO: pv2 add version with Pydantic v2
-@needs_pydanticv1
-def test_get_user(client):
- response = client.get("/users/1")
- assert response.status_code == 200, response.text
- data = response.json()
- assert "email" in data
- assert "id" in data
-
-
-# TODO: pv2 add version with Pydantic v2
-@needs_pydanticv1
-def test_nonexistent_user(client):
- response = client.get("/users/999")
- assert response.status_code == 404, response.text
-
-
-# TODO: pv2 add version with Pydantic v2
-@needs_pydanticv1
-def test_get_users(client):
- response = client.get("/users/")
- assert response.status_code == 200, response.text
- data = response.json()
- assert "email" in data[0]
- assert "id" in data[0]
-
-
-# TODO: pv2 add Pydantic v2 version
-@needs_pydanticv1
-def test_create_item(client):
- item = {"title": "Foo", "description": "Something that fights"}
- response = client.post("/users/1/items/", json=item)
- assert response.status_code == 200, response.text
- item_data = response.json()
- assert item["title"] == item_data["title"]
- assert item["description"] == item_data["description"]
- assert "id" in item_data
- assert "owner_id" in item_data
- response = client.get("/users/1")
- assert response.status_code == 200, response.text
- user_data = response.json()
- item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0]
- assert item_to_check["title"] == item["title"]
- assert item_to_check["description"] == item["description"]
- response = client.get("/users/1")
- assert response.status_code == 200, response.text
- user_data = response.json()
- item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0]
- assert item_to_check["title"] == item["title"]
- assert item_to_check["description"] == item["description"]
-
-
-# TODO: pv2 add Pydantic v2 version
-@needs_pydanticv1
-def test_read_items(client):
- response = client.get("/items/")
- assert response.status_code == 200, response.text
- data = response.json()
- assert data
- first_item = data[0]
- assert "title" in first_item
- assert "description" in first_item
-
-
-# TODO: pv2 add version with Pydantic v2
-@needs_pydanticv1
-def test_openapi_schema(client: TestClient):
- response = client.get("/openapi.json")
- assert response.status_code == 200, response.text
- assert response.json() == {
- "openapi": "3.1.0",
- "info": {"title": "FastAPI", "version": "0.1.0"},
- "paths": {
- "/users/": {
- "get": {
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {
- "title": "Response Read Users Users Get",
- "type": "array",
- "items": {"$ref": "#/components/schemas/User"},
- }
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- "summary": "Read Users",
- "operationId": "read_users_users__get",
- "parameters": [
- {
- "required": False,
- "schema": {
- "title": "Skip",
- "type": "integer",
- "default": 0,
- },
- "name": "skip",
- "in": "query",
- },
- {
- "required": False,
- "schema": {
- "title": "Limit",
- "type": "integer",
- "default": 100,
- },
- "name": "limit",
- "in": "query",
- },
- ],
- },
- "post": {
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/User"}
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- "summary": "Create User",
- "operationId": "create_user_users__post",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/UserCreate"}
- }
- },
- "required": True,
- },
- },
- },
- "/users/{user_id}": {
- "get": {
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/User"}
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- "summary": "Read User",
- "operationId": "read_user_users__user_id__get",
- "parameters": [
- {
- "required": True,
- "schema": {"title": "User Id", "type": "integer"},
- "name": "user_id",
- "in": "path",
- }
- ],
- }
- },
- "/users/{user_id}/items/": {
- "post": {
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/Item"}
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- "summary": "Create Item For User",
- "operationId": "create_item_for_user_users__user_id__items__post",
- "parameters": [
- {
- "required": True,
- "schema": {"title": "User Id", "type": "integer"},
- "name": "user_id",
- "in": "path",
- }
- ],
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/ItemCreate"}
- }
- },
- "required": True,
- },
- }
- },
- "/items/": {
- "get": {
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {
- "title": "Response Read Items Items Get",
- "type": "array",
- "items": {"$ref": "#/components/schemas/Item"},
- }
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- "summary": "Read Items",
- "operationId": "read_items_items__get",
- "parameters": [
- {
- "required": False,
- "schema": {
- "title": "Skip",
- "type": "integer",
- "default": 0,
- },
- "name": "skip",
- "in": "query",
- },
- {
- "required": False,
- "schema": {
- "title": "Limit",
- "type": "integer",
- "default": 100,
- },
- "name": "limit",
- "in": "query",
- },
- ],
- }
- },
- },
- "components": {
- "schemas": {
- "ItemCreate": {
- "title": "ItemCreate",
- "required": ["title"],
- "type": "object",
- "properties": {
- "title": {"title": "Title", "type": "string"},
- "description": IsDict(
- {
- "title": "Description",
- "anyOf": [{"type": "string"}, {"type": "null"}],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Description", "type": "string"}
- ),
- },
- },
- "Item": {
- "title": "Item",
- "required": ["title", "id", "owner_id"],
- "type": "object",
- "properties": {
- "title": {"title": "Title", "type": "string"},
- "description": IsDict(
- {
- "title": "Description",
- "anyOf": [{"type": "string"}, {"type": "null"}],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Description", "type": "string"},
- ),
- "id": {"title": "Id", "type": "integer"},
- "owner_id": {"title": "Owner Id", "type": "integer"},
- },
- },
- "User": {
- "title": "User",
- "required": ["email", "id", "is_active"],
- "type": "object",
- "properties": {
- "email": {"title": "Email", "type": "string"},
- "id": {"title": "Id", "type": "integer"},
- "is_active": {"title": "Is Active", "type": "boolean"},
- "items": {
- "title": "Items",
- "type": "array",
- "items": {"$ref": "#/components/schemas/Item"},
- "default": [],
- },
- },
- },
- "UserCreate": {
- "title": "UserCreate",
- "required": ["email", "password"],
- "type": "object",
- "properties": {
- "email": {"title": "Email", "type": "string"},
- "password": {"title": "Password", "type": "string"},
- },
- },
- "ValidationError": {
- "title": "ValidationError",
- "required": ["loc", "msg", "type"],
- "type": "object",
- "properties": {
- "loc": {
- "title": "Location",
- "type": "array",
- "items": {
- "anyOf": [{"type": "string"}, {"type": "integer"}]
- },
- },
- "msg": {"title": "Message", "type": "string"},
- "type": {"title": "Error Type", "type": "string"},
- },
- },
- "HTTPValidationError": {
- "title": "HTTPValidationError",
- "type": "object",
- "properties": {
- "detail": {
- "title": "Detail",
- "type": "array",
- "items": {"$ref": "#/components/schemas/ValidationError"},
- }
- },
- },
- }
- },
- }
diff --git a/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware_py310.py b/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware_py310.py
deleted file mode 100644
index a078f012a..000000000
--- a/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware_py310.py
+++ /dev/null
@@ -1,433 +0,0 @@
-import importlib
-import os
-from pathlib import Path
-
-import pytest
-from dirty_equals import IsDict
-from fastapi.testclient import TestClient
-
-from ...utils import needs_py310, needs_pydanticv1
-
-
-@pytest.fixture(scope="module")
-def client(tmp_path_factory: pytest.TempPathFactory):
- tmp_path = tmp_path_factory.mktemp("data")
- cwd = os.getcwd()
- os.chdir(tmp_path)
- test_db = Path("./sql_app.db")
- if test_db.is_file(): # pragma: nocover
- test_db.unlink()
- # Import while creating the client to create the DB after starting the test session
- from docs_src.sql_databases.sql_app_py310 import alt_main
-
- # Ensure import side effects are re-executed
- importlib.reload(alt_main)
-
- with TestClient(alt_main.app) as c:
- yield c
- if test_db.is_file(): # pragma: nocover
- test_db.unlink()
- os.chdir(cwd)
-
-
-@needs_py310
-# TODO: pv2 add version with Pydantic v2
-@needs_pydanticv1
-def test_create_user(client):
- test_user = {"email": "johndoe@example.com", "password": "secret"}
- response = client.post("/users/", json=test_user)
- assert response.status_code == 200, response.text
- data = response.json()
- assert test_user["email"] == data["email"]
- assert "id" in data
- response = client.post("/users/", json=test_user)
- assert response.status_code == 400, response.text
-
-
-@needs_py310
-# TODO: pv2 add version with Pydantic v2
-@needs_pydanticv1
-def test_get_user(client):
- response = client.get("/users/1")
- assert response.status_code == 200, response.text
- data = response.json()
- assert "email" in data
- assert "id" in data
-
-
-@needs_py310
-# TODO: pv2 add version with Pydantic v2
-@needs_pydanticv1
-def test_nonexistent_user(client):
- response = client.get("/users/999")
- assert response.status_code == 404, response.text
-
-
-@needs_py310
-# TODO: pv2 add version with Pydantic v2
-@needs_pydanticv1
-def test_get_users(client):
- response = client.get("/users/")
- assert response.status_code == 200, response.text
- data = response.json()
- assert "email" in data[0]
- assert "id" in data[0]
-
-
-@needs_py310
-# TODO: pv2 add Pydantic v2 version
-@needs_pydanticv1
-def test_create_item(client):
- item = {"title": "Foo", "description": "Something that fights"}
- response = client.post("/users/1/items/", json=item)
- assert response.status_code == 200, response.text
- item_data = response.json()
- assert item["title"] == item_data["title"]
- assert item["description"] == item_data["description"]
- assert "id" in item_data
- assert "owner_id" in item_data
- response = client.get("/users/1")
- assert response.status_code == 200, response.text
- user_data = response.json()
- item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0]
- assert item_to_check["title"] == item["title"]
- assert item_to_check["description"] == item["description"]
- response = client.get("/users/1")
- assert response.status_code == 200, response.text
- user_data = response.json()
- item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0]
- assert item_to_check["title"] == item["title"]
- assert item_to_check["description"] == item["description"]
-
-
-@needs_py310
-# TODO: pv2 add Pydantic v2 version
-@needs_pydanticv1
-def test_read_items(client):
- response = client.get("/items/")
- assert response.status_code == 200, response.text
- data = response.json()
- assert data
- first_item = data[0]
- assert "title" in first_item
- assert "description" in first_item
-
-
-@needs_py310
-# TODO: pv2 add version with Pydantic v2
-@needs_pydanticv1
-def test_openapi_schema(client: TestClient):
- response = client.get("/openapi.json")
- assert response.status_code == 200, response.text
- assert response.json() == {
- "openapi": "3.1.0",
- "info": {"title": "FastAPI", "version": "0.1.0"},
- "paths": {
- "/users/": {
- "get": {
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {
- "title": "Response Read Users Users Get",
- "type": "array",
- "items": {"$ref": "#/components/schemas/User"},
- }
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- "summary": "Read Users",
- "operationId": "read_users_users__get",
- "parameters": [
- {
- "required": False,
- "schema": {
- "title": "Skip",
- "type": "integer",
- "default": 0,
- },
- "name": "skip",
- "in": "query",
- },
- {
- "required": False,
- "schema": {
- "title": "Limit",
- "type": "integer",
- "default": 100,
- },
- "name": "limit",
- "in": "query",
- },
- ],
- },
- "post": {
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/User"}
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- "summary": "Create User",
- "operationId": "create_user_users__post",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/UserCreate"}
- }
- },
- "required": True,
- },
- },
- },
- "/users/{user_id}": {
- "get": {
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/User"}
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- "summary": "Read User",
- "operationId": "read_user_users__user_id__get",
- "parameters": [
- {
- "required": True,
- "schema": {"title": "User Id", "type": "integer"},
- "name": "user_id",
- "in": "path",
- }
- ],
- }
- },
- "/users/{user_id}/items/": {
- "post": {
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/Item"}
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- "summary": "Create Item For User",
- "operationId": "create_item_for_user_users__user_id__items__post",
- "parameters": [
- {
- "required": True,
- "schema": {"title": "User Id", "type": "integer"},
- "name": "user_id",
- "in": "path",
- }
- ],
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/ItemCreate"}
- }
- },
- "required": True,
- },
- }
- },
- "/items/": {
- "get": {
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {
- "title": "Response Read Items Items Get",
- "type": "array",
- "items": {"$ref": "#/components/schemas/Item"},
- }
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- "summary": "Read Items",
- "operationId": "read_items_items__get",
- "parameters": [
- {
- "required": False,
- "schema": {
- "title": "Skip",
- "type": "integer",
- "default": 0,
- },
- "name": "skip",
- "in": "query",
- },
- {
- "required": False,
- "schema": {
- "title": "Limit",
- "type": "integer",
- "default": 100,
- },
- "name": "limit",
- "in": "query",
- },
- ],
- }
- },
- },
- "components": {
- "schemas": {
- "ItemCreate": {
- "title": "ItemCreate",
- "required": ["title"],
- "type": "object",
- "properties": {
- "title": {"title": "Title", "type": "string"},
- "description": IsDict(
- {
- "title": "Description",
- "anyOf": [{"type": "string"}, {"type": "null"}],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Description", "type": "string"}
- ),
- },
- },
- "Item": {
- "title": "Item",
- "required": ["title", "id", "owner_id"],
- "type": "object",
- "properties": {
- "title": {"title": "Title", "type": "string"},
- "description": IsDict(
- {
- "title": "Description",
- "anyOf": [{"type": "string"}, {"type": "null"}],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Description", "type": "string"},
- ),
- "id": {"title": "Id", "type": "integer"},
- "owner_id": {"title": "Owner Id", "type": "integer"},
- },
- },
- "User": {
- "title": "User",
- "required": ["email", "id", "is_active"],
- "type": "object",
- "properties": {
- "email": {"title": "Email", "type": "string"},
- "id": {"title": "Id", "type": "integer"},
- "is_active": {"title": "Is Active", "type": "boolean"},
- "items": {
- "title": "Items",
- "type": "array",
- "items": {"$ref": "#/components/schemas/Item"},
- "default": [],
- },
- },
- },
- "UserCreate": {
- "title": "UserCreate",
- "required": ["email", "password"],
- "type": "object",
- "properties": {
- "email": {"title": "Email", "type": "string"},
- "password": {"title": "Password", "type": "string"},
- },
- },
- "ValidationError": {
- "title": "ValidationError",
- "required": ["loc", "msg", "type"],
- "type": "object",
- "properties": {
- "loc": {
- "title": "Location",
- "type": "array",
- "items": {
- "anyOf": [{"type": "string"}, {"type": "integer"}]
- },
- },
- "msg": {"title": "Message", "type": "string"},
- "type": {"title": "Error Type", "type": "string"},
- },
- },
- "HTTPValidationError": {
- "title": "HTTPValidationError",
- "type": "object",
- "properties": {
- "detail": {
- "title": "Detail",
- "type": "array",
- "items": {"$ref": "#/components/schemas/ValidationError"},
- }
- },
- },
- }
- },
- }
diff --git a/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware_py39.py b/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware_py39.py
deleted file mode 100644
index a5da07ac6..000000000
--- a/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware_py39.py
+++ /dev/null
@@ -1,433 +0,0 @@
-import importlib
-import os
-from pathlib import Path
-
-import pytest
-from dirty_equals import IsDict
-from fastapi.testclient import TestClient
-
-from ...utils import needs_py39, needs_pydanticv1
-
-
-@pytest.fixture(scope="module")
-def client(tmp_path_factory: pytest.TempPathFactory):
- tmp_path = tmp_path_factory.mktemp("data")
- cwd = os.getcwd()
- os.chdir(tmp_path)
- test_db = Path("./sql_app.db")
- if test_db.is_file(): # pragma: nocover
- test_db.unlink()
- # Import while creating the client to create the DB after starting the test session
- from docs_src.sql_databases.sql_app_py39 import alt_main
-
- # Ensure import side effects are re-executed
- importlib.reload(alt_main)
-
- with TestClient(alt_main.app) as c:
- yield c
- if test_db.is_file(): # pragma: nocover
- test_db.unlink()
- os.chdir(cwd)
-
-
-@needs_py39
-# TODO: pv2 add version with Pydantic v2
-@needs_pydanticv1
-def test_create_user(client):
- test_user = {"email": "johndoe@example.com", "password": "secret"}
- response = client.post("/users/", json=test_user)
- assert response.status_code == 200, response.text
- data = response.json()
- assert test_user["email"] == data["email"]
- assert "id" in data
- response = client.post("/users/", json=test_user)
- assert response.status_code == 400, response.text
-
-
-@needs_py39
-# TODO: pv2 add version with Pydantic v2
-@needs_pydanticv1
-def test_get_user(client):
- response = client.get("/users/1")
- assert response.status_code == 200, response.text
- data = response.json()
- assert "email" in data
- assert "id" in data
-
-
-@needs_py39
-# TODO: pv2 add version with Pydantic v2
-@needs_pydanticv1
-def test_nonexistent_user(client):
- response = client.get("/users/999")
- assert response.status_code == 404, response.text
-
-
-@needs_py39
-# TODO: pv2 add version with Pydantic v2
-@needs_pydanticv1
-def test_get_users(client):
- response = client.get("/users/")
- assert response.status_code == 200, response.text
- data = response.json()
- assert "email" in data[0]
- assert "id" in data[0]
-
-
-@needs_py39
-# TODO: pv2 add version with Pydantic v2
-@needs_pydanticv1
-def test_create_item(client):
- item = {"title": "Foo", "description": "Something that fights"}
- response = client.post("/users/1/items/", json=item)
- assert response.status_code == 200, response.text
- item_data = response.json()
- assert item["title"] == item_data["title"]
- assert item["description"] == item_data["description"]
- assert "id" in item_data
- assert "owner_id" in item_data
- response = client.get("/users/1")
- assert response.status_code == 200, response.text
- user_data = response.json()
- item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0]
- assert item_to_check["title"] == item["title"]
- assert item_to_check["description"] == item["description"]
- response = client.get("/users/1")
- assert response.status_code == 200, response.text
- user_data = response.json()
- item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0]
- assert item_to_check["title"] == item["title"]
- assert item_to_check["description"] == item["description"]
-
-
-@needs_py39
-# TODO: pv2 add version with Pydantic v2
-@needs_pydanticv1
-def test_read_items(client):
- response = client.get("/items/")
- assert response.status_code == 200, response.text
- data = response.json()
- assert data
- first_item = data[0]
- assert "title" in first_item
- assert "description" in first_item
-
-
-@needs_py39
-# TODO: pv2 add version with Pydantic v2
-@needs_pydanticv1
-def test_openapi_schema(client: TestClient):
- response = client.get("/openapi.json")
- assert response.status_code == 200, response.text
- assert response.json() == {
- "openapi": "3.1.0",
- "info": {"title": "FastAPI", "version": "0.1.0"},
- "paths": {
- "/users/": {
- "get": {
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {
- "title": "Response Read Users Users Get",
- "type": "array",
- "items": {"$ref": "#/components/schemas/User"},
- }
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- "summary": "Read Users",
- "operationId": "read_users_users__get",
- "parameters": [
- {
- "required": False,
- "schema": {
- "title": "Skip",
- "type": "integer",
- "default": 0,
- },
- "name": "skip",
- "in": "query",
- },
- {
- "required": False,
- "schema": {
- "title": "Limit",
- "type": "integer",
- "default": 100,
- },
- "name": "limit",
- "in": "query",
- },
- ],
- },
- "post": {
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/User"}
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- "summary": "Create User",
- "operationId": "create_user_users__post",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/UserCreate"}
- }
- },
- "required": True,
- },
- },
- },
- "/users/{user_id}": {
- "get": {
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/User"}
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- "summary": "Read User",
- "operationId": "read_user_users__user_id__get",
- "parameters": [
- {
- "required": True,
- "schema": {"title": "User Id", "type": "integer"},
- "name": "user_id",
- "in": "path",
- }
- ],
- }
- },
- "/users/{user_id}/items/": {
- "post": {
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/Item"}
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- "summary": "Create Item For User",
- "operationId": "create_item_for_user_users__user_id__items__post",
- "parameters": [
- {
- "required": True,
- "schema": {"title": "User Id", "type": "integer"},
- "name": "user_id",
- "in": "path",
- }
- ],
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/ItemCreate"}
- }
- },
- "required": True,
- },
- }
- },
- "/items/": {
- "get": {
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {
- "title": "Response Read Items Items Get",
- "type": "array",
- "items": {"$ref": "#/components/schemas/Item"},
- }
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- "summary": "Read Items",
- "operationId": "read_items_items__get",
- "parameters": [
- {
- "required": False,
- "schema": {
- "title": "Skip",
- "type": "integer",
- "default": 0,
- },
- "name": "skip",
- "in": "query",
- },
- {
- "required": False,
- "schema": {
- "title": "Limit",
- "type": "integer",
- "default": 100,
- },
- "name": "limit",
- "in": "query",
- },
- ],
- }
- },
- },
- "components": {
- "schemas": {
- "ItemCreate": {
- "title": "ItemCreate",
- "required": ["title"],
- "type": "object",
- "properties": {
- "title": {"title": "Title", "type": "string"},
- "description": IsDict(
- {
- "title": "Description",
- "anyOf": [{"type": "string"}, {"type": "null"}],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Description", "type": "string"}
- ),
- },
- },
- "Item": {
- "title": "Item",
- "required": ["title", "id", "owner_id"],
- "type": "object",
- "properties": {
- "title": {"title": "Title", "type": "string"},
- "description": IsDict(
- {
- "title": "Description",
- "anyOf": [{"type": "string"}, {"type": "null"}],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Description", "type": "string"},
- ),
- "id": {"title": "Id", "type": "integer"},
- "owner_id": {"title": "Owner Id", "type": "integer"},
- },
- },
- "User": {
- "title": "User",
- "required": ["email", "id", "is_active"],
- "type": "object",
- "properties": {
- "email": {"title": "Email", "type": "string"},
- "id": {"title": "Id", "type": "integer"},
- "is_active": {"title": "Is Active", "type": "boolean"},
- "items": {
- "title": "Items",
- "type": "array",
- "items": {"$ref": "#/components/schemas/Item"},
- "default": [],
- },
- },
- },
- "UserCreate": {
- "title": "UserCreate",
- "required": ["email", "password"],
- "type": "object",
- "properties": {
- "email": {"title": "Email", "type": "string"},
- "password": {"title": "Password", "type": "string"},
- },
- },
- "ValidationError": {
- "title": "ValidationError",
- "required": ["loc", "msg", "type"],
- "type": "object",
- "properties": {
- "loc": {
- "title": "Location",
- "type": "array",
- "items": {
- "anyOf": [{"type": "string"}, {"type": "integer"}]
- },
- },
- "msg": {"title": "Message", "type": "string"},
- "type": {"title": "Error Type", "type": "string"},
- },
- },
- "HTTPValidationError": {
- "title": "HTTPValidationError",
- "type": "object",
- "properties": {
- "detail": {
- "title": "Detail",
- "type": "array",
- "items": {"$ref": "#/components/schemas/ValidationError"},
- }
- },
- },
- }
- },
- }
diff --git a/tests/test_tutorial/test_sql_databases/test_sql_databases_py310.py b/tests/test_tutorial/test_sql_databases/test_sql_databases_py310.py
deleted file mode 100644
index 5a9106598..000000000
--- a/tests/test_tutorial/test_sql_databases/test_sql_databases_py310.py
+++ /dev/null
@@ -1,432 +0,0 @@
-import importlib
-import os
-from pathlib import Path
-
-import pytest
-from dirty_equals import IsDict
-from fastapi.testclient import TestClient
-
-from ...utils import needs_py310, needs_pydanticv1
-
-
-@pytest.fixture(scope="module", name="client")
-def get_client(tmp_path_factory: pytest.TempPathFactory):
- tmp_path = tmp_path_factory.mktemp("data")
- cwd = os.getcwd()
- os.chdir(tmp_path)
- test_db = Path("./sql_app.db")
- if test_db.is_file(): # pragma: nocover
- test_db.unlink()
- # Import while creating the client to create the DB after starting the test session
- from docs_src.sql_databases.sql_app_py310 import main
-
- # Ensure import side effects are re-executed
- importlib.reload(main)
- with TestClient(main.app) as c:
- yield c
- if test_db.is_file(): # pragma: nocover
- test_db.unlink()
- os.chdir(cwd)
-
-
-@needs_py310
-# TODO: pv2 add version with Pydantic v2
-@needs_pydanticv1
-def test_create_user(client):
- test_user = {"email": "johndoe@example.com", "password": "secret"}
- response = client.post("/users/", json=test_user)
- assert response.status_code == 200, response.text
- data = response.json()
- assert test_user["email"] == data["email"]
- assert "id" in data
- response = client.post("/users/", json=test_user)
- assert response.status_code == 400, response.text
-
-
-@needs_py310
-# TODO: pv2 add version with Pydantic v2
-@needs_pydanticv1
-def test_get_user(client):
- response = client.get("/users/1")
- assert response.status_code == 200, response.text
- data = response.json()
- assert "email" in data
- assert "id" in data
-
-
-@needs_py310
-# TODO: pv2 add version with Pydantic v2
-@needs_pydanticv1
-def test_nonexistent_user(client):
- response = client.get("/users/999")
- assert response.status_code == 404, response.text
-
-
-@needs_py310
-# TODO: pv2 add version with Pydantic v2
-@needs_pydanticv1
-def test_get_users(client):
- response = client.get("/users/")
- assert response.status_code == 200, response.text
- data = response.json()
- assert "email" in data[0]
- assert "id" in data[0]
-
-
-@needs_py310
-# TODO: pv2 add Pydantic v2 version
-@needs_pydanticv1
-def test_create_item(client):
- item = {"title": "Foo", "description": "Something that fights"}
- response = client.post("/users/1/items/", json=item)
- assert response.status_code == 200, response.text
- item_data = response.json()
- assert item["title"] == item_data["title"]
- assert item["description"] == item_data["description"]
- assert "id" in item_data
- assert "owner_id" in item_data
- response = client.get("/users/1")
- assert response.status_code == 200, response.text
- user_data = response.json()
- item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0]
- assert item_to_check["title"] == item["title"]
- assert item_to_check["description"] == item["description"]
- response = client.get("/users/1")
- assert response.status_code == 200, response.text
- user_data = response.json()
- item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0]
- assert item_to_check["title"] == item["title"]
- assert item_to_check["description"] == item["description"]
-
-
-@needs_py310
-# TODO: pv2 add Pydantic v2 version
-@needs_pydanticv1
-def test_read_items(client):
- response = client.get("/items/")
- assert response.status_code == 200, response.text
- data = response.json()
- assert data
- first_item = data[0]
- assert "title" in first_item
- assert "description" in first_item
-
-
-@needs_py310
-# TODO: pv2 add version with Pydantic v2
-@needs_pydanticv1
-def test_openapi_schema(client: TestClient):
- response = client.get("/openapi.json")
- assert response.status_code == 200, response.text
- assert response.json() == {
- "openapi": "3.1.0",
- "info": {"title": "FastAPI", "version": "0.1.0"},
- "paths": {
- "/users/": {
- "get": {
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {
- "title": "Response Read Users Users Get",
- "type": "array",
- "items": {"$ref": "#/components/schemas/User"},
- }
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- "summary": "Read Users",
- "operationId": "read_users_users__get",
- "parameters": [
- {
- "required": False,
- "schema": {
- "title": "Skip",
- "type": "integer",
- "default": 0,
- },
- "name": "skip",
- "in": "query",
- },
- {
- "required": False,
- "schema": {
- "title": "Limit",
- "type": "integer",
- "default": 100,
- },
- "name": "limit",
- "in": "query",
- },
- ],
- },
- "post": {
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/User"}
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- "summary": "Create User",
- "operationId": "create_user_users__post",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/UserCreate"}
- }
- },
- "required": True,
- },
- },
- },
- "/users/{user_id}": {
- "get": {
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/User"}
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- "summary": "Read User",
- "operationId": "read_user_users__user_id__get",
- "parameters": [
- {
- "required": True,
- "schema": {"title": "User Id", "type": "integer"},
- "name": "user_id",
- "in": "path",
- }
- ],
- }
- },
- "/users/{user_id}/items/": {
- "post": {
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/Item"}
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- "summary": "Create Item For User",
- "operationId": "create_item_for_user_users__user_id__items__post",
- "parameters": [
- {
- "required": True,
- "schema": {"title": "User Id", "type": "integer"},
- "name": "user_id",
- "in": "path",
- }
- ],
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/ItemCreate"}
- }
- },
- "required": True,
- },
- }
- },
- "/items/": {
- "get": {
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {
- "title": "Response Read Items Items Get",
- "type": "array",
- "items": {"$ref": "#/components/schemas/Item"},
- }
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- "summary": "Read Items",
- "operationId": "read_items_items__get",
- "parameters": [
- {
- "required": False,
- "schema": {
- "title": "Skip",
- "type": "integer",
- "default": 0,
- },
- "name": "skip",
- "in": "query",
- },
- {
- "required": False,
- "schema": {
- "title": "Limit",
- "type": "integer",
- "default": 100,
- },
- "name": "limit",
- "in": "query",
- },
- ],
- }
- },
- },
- "components": {
- "schemas": {
- "ItemCreate": {
- "title": "ItemCreate",
- "required": ["title"],
- "type": "object",
- "properties": {
- "title": {"title": "Title", "type": "string"},
- "description": IsDict(
- {
- "title": "Description",
- "anyOf": [{"type": "string"}, {"type": "null"}],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Description", "type": "string"}
- ),
- },
- },
- "Item": {
- "title": "Item",
- "required": ["title", "id", "owner_id"],
- "type": "object",
- "properties": {
- "title": {"title": "Title", "type": "string"},
- "description": IsDict(
- {
- "title": "Description",
- "anyOf": [{"type": "string"}, {"type": "null"}],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Description", "type": "string"},
- ),
- "id": {"title": "Id", "type": "integer"},
- "owner_id": {"title": "Owner Id", "type": "integer"},
- },
- },
- "User": {
- "title": "User",
- "required": ["email", "id", "is_active"],
- "type": "object",
- "properties": {
- "email": {"title": "Email", "type": "string"},
- "id": {"title": "Id", "type": "integer"},
- "is_active": {"title": "Is Active", "type": "boolean"},
- "items": {
- "title": "Items",
- "type": "array",
- "items": {"$ref": "#/components/schemas/Item"},
- "default": [],
- },
- },
- },
- "UserCreate": {
- "title": "UserCreate",
- "required": ["email", "password"],
- "type": "object",
- "properties": {
- "email": {"title": "Email", "type": "string"},
- "password": {"title": "Password", "type": "string"},
- },
- },
- "ValidationError": {
- "title": "ValidationError",
- "required": ["loc", "msg", "type"],
- "type": "object",
- "properties": {
- "loc": {
- "title": "Location",
- "type": "array",
- "items": {
- "anyOf": [{"type": "string"}, {"type": "integer"}]
- },
- },
- "msg": {"title": "Message", "type": "string"},
- "type": {"title": "Error Type", "type": "string"},
- },
- },
- "HTTPValidationError": {
- "title": "HTTPValidationError",
- "type": "object",
- "properties": {
- "detail": {
- "title": "Detail",
- "type": "array",
- "items": {"$ref": "#/components/schemas/ValidationError"},
- }
- },
- },
- }
- },
- }
diff --git a/tests/test_tutorial/test_sql_databases/test_sql_databases_py39.py b/tests/test_tutorial/test_sql_databases/test_sql_databases_py39.py
deleted file mode 100644
index a354ba905..000000000
--- a/tests/test_tutorial/test_sql_databases/test_sql_databases_py39.py
+++ /dev/null
@@ -1,432 +0,0 @@
-import importlib
-import os
-from pathlib import Path
-
-import pytest
-from dirty_equals import IsDict
-from fastapi.testclient import TestClient
-
-from ...utils import needs_py39, needs_pydanticv1
-
-
-@pytest.fixture(scope="module", name="client")
-def get_client(tmp_path_factory: pytest.TempPathFactory):
- tmp_path = tmp_path_factory.mktemp("data")
- cwd = os.getcwd()
- os.chdir(tmp_path)
- test_db = Path("./sql_app.db")
- if test_db.is_file(): # pragma: nocover
- test_db.unlink()
- # Import while creating the client to create the DB after starting the test session
- from docs_src.sql_databases.sql_app_py39 import main
-
- # Ensure import side effects are re-executed
- importlib.reload(main)
- with TestClient(main.app) as c:
- yield c
- if test_db.is_file(): # pragma: nocover
- test_db.unlink()
- os.chdir(cwd)
-
-
-@needs_py39
-# TODO: pv2 add version with Pydantic v2
-@needs_pydanticv1
-def test_create_user(client):
- test_user = {"email": "johndoe@example.com", "password": "secret"}
- response = client.post("/users/", json=test_user)
- assert response.status_code == 200, response.text
- data = response.json()
- assert test_user["email"] == data["email"]
- assert "id" in data
- response = client.post("/users/", json=test_user)
- assert response.status_code == 400, response.text
-
-
-@needs_py39
-# TODO: pv2 add version with Pydantic v2
-@needs_pydanticv1
-def test_get_user(client):
- response = client.get("/users/1")
- assert response.status_code == 200, response.text
- data = response.json()
- assert "email" in data
- assert "id" in data
-
-
-@needs_py39
-# TODO: pv2 add version with Pydantic v2
-@needs_pydanticv1
-def test_nonexistent_user(client):
- response = client.get("/users/999")
- assert response.status_code == 404, response.text
-
-
-@needs_py39
-# TODO: pv2 add version with Pydantic v2
-@needs_pydanticv1
-def test_get_users(client):
- response = client.get("/users/")
- assert response.status_code == 200, response.text
- data = response.json()
- assert "email" in data[0]
- assert "id" in data[0]
-
-
-@needs_py39
-# TODO: pv2 add Pydantic v2 version
-@needs_pydanticv1
-def test_create_item(client):
- item = {"title": "Foo", "description": "Something that fights"}
- response = client.post("/users/1/items/", json=item)
- assert response.status_code == 200, response.text
- item_data = response.json()
- assert item["title"] == item_data["title"]
- assert item["description"] == item_data["description"]
- assert "id" in item_data
- assert "owner_id" in item_data
- response = client.get("/users/1")
- assert response.status_code == 200, response.text
- user_data = response.json()
- item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0]
- assert item_to_check["title"] == item["title"]
- assert item_to_check["description"] == item["description"]
- response = client.get("/users/1")
- assert response.status_code == 200, response.text
- user_data = response.json()
- item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0]
- assert item_to_check["title"] == item["title"]
- assert item_to_check["description"] == item["description"]
-
-
-@needs_py39
-# TODO: pv2 add Pydantic v2 version
-@needs_pydanticv1
-def test_read_items(client):
- response = client.get("/items/")
- assert response.status_code == 200, response.text
- data = response.json()
- assert data
- first_item = data[0]
- assert "title" in first_item
- assert "description" in first_item
-
-
-@needs_py39
-# TODO: pv2 add version with Pydantic v2
-@needs_pydanticv1
-def test_openapi_schema(client: TestClient):
- response = client.get("/openapi.json")
- assert response.status_code == 200, response.text
- assert response.json() == {
- "openapi": "3.1.0",
- "info": {"title": "FastAPI", "version": "0.1.0"},
- "paths": {
- "/users/": {
- "get": {
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {
- "title": "Response Read Users Users Get",
- "type": "array",
- "items": {"$ref": "#/components/schemas/User"},
- }
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- "summary": "Read Users",
- "operationId": "read_users_users__get",
- "parameters": [
- {
- "required": False,
- "schema": {
- "title": "Skip",
- "type": "integer",
- "default": 0,
- },
- "name": "skip",
- "in": "query",
- },
- {
- "required": False,
- "schema": {
- "title": "Limit",
- "type": "integer",
- "default": 100,
- },
- "name": "limit",
- "in": "query",
- },
- ],
- },
- "post": {
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/User"}
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- "summary": "Create User",
- "operationId": "create_user_users__post",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/UserCreate"}
- }
- },
- "required": True,
- },
- },
- },
- "/users/{user_id}": {
- "get": {
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/User"}
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- "summary": "Read User",
- "operationId": "read_user_users__user_id__get",
- "parameters": [
- {
- "required": True,
- "schema": {"title": "User Id", "type": "integer"},
- "name": "user_id",
- "in": "path",
- }
- ],
- }
- },
- "/users/{user_id}/items/": {
- "post": {
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/Item"}
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- "summary": "Create Item For User",
- "operationId": "create_item_for_user_users__user_id__items__post",
- "parameters": [
- {
- "required": True,
- "schema": {"title": "User Id", "type": "integer"},
- "name": "user_id",
- "in": "path",
- }
- ],
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/ItemCreate"}
- }
- },
- "required": True,
- },
- }
- },
- "/items/": {
- "get": {
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {
- "title": "Response Read Items Items Get",
- "type": "array",
- "items": {"$ref": "#/components/schemas/Item"},
- }
- }
- },
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- },
- },
- "summary": "Read Items",
- "operationId": "read_items_items__get",
- "parameters": [
- {
- "required": False,
- "schema": {
- "title": "Skip",
- "type": "integer",
- "default": 0,
- },
- "name": "skip",
- "in": "query",
- },
- {
- "required": False,
- "schema": {
- "title": "Limit",
- "type": "integer",
- "default": 100,
- },
- "name": "limit",
- "in": "query",
- },
- ],
- }
- },
- },
- "components": {
- "schemas": {
- "ItemCreate": {
- "title": "ItemCreate",
- "required": ["title"],
- "type": "object",
- "properties": {
- "title": {"title": "Title", "type": "string"},
- "description": IsDict(
- {
- "title": "Description",
- "anyOf": [{"type": "string"}, {"type": "null"}],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Description", "type": "string"}
- ),
- },
- },
- "Item": {
- "title": "Item",
- "required": ["title", "id", "owner_id"],
- "type": "object",
- "properties": {
- "title": {"title": "Title", "type": "string"},
- "description": IsDict(
- {
- "title": "Description",
- "anyOf": [{"type": "string"}, {"type": "null"}],
- }
- )
- | IsDict(
- # TODO: remove when deprecating Pydantic v1
- {"title": "Description", "type": "string"},
- ),
- "id": {"title": "Id", "type": "integer"},
- "owner_id": {"title": "Owner Id", "type": "integer"},
- },
- },
- "User": {
- "title": "User",
- "required": ["email", "id", "is_active"],
- "type": "object",
- "properties": {
- "email": {"title": "Email", "type": "string"},
- "id": {"title": "Id", "type": "integer"},
- "is_active": {"title": "Is Active", "type": "boolean"},
- "items": {
- "title": "Items",
- "type": "array",
- "items": {"$ref": "#/components/schemas/Item"},
- "default": [],
- },
- },
- },
- "UserCreate": {
- "title": "UserCreate",
- "required": ["email", "password"],
- "type": "object",
- "properties": {
- "email": {"title": "Email", "type": "string"},
- "password": {"title": "Password", "type": "string"},
- },
- },
- "ValidationError": {
- "title": "ValidationError",
- "required": ["loc", "msg", "type"],
- "type": "object",
- "properties": {
- "loc": {
- "title": "Location",
- "type": "array",
- "items": {
- "anyOf": [{"type": "string"}, {"type": "integer"}]
- },
- },
- "msg": {"title": "Message", "type": "string"},
- "type": {"title": "Error Type", "type": "string"},
- },
- },
- "HTTPValidationError": {
- "title": "HTTPValidationError",
- "type": "object",
- "properties": {
- "detail": {
- "title": "Detail",
- "type": "array",
- "items": {"$ref": "#/components/schemas/ValidationError"},
- }
- },
- },
- }
- },
- }
diff --git a/tests/test_tutorial/test_sql_databases/test_testing_databases.py b/tests/test_tutorial/test_sql_databases/test_testing_databases.py
deleted file mode 100644
index ce6ce230c..000000000
--- a/tests/test_tutorial/test_sql_databases/test_testing_databases.py
+++ /dev/null
@@ -1,27 +0,0 @@
-import importlib
-import os
-from pathlib import Path
-
-import pytest
-
-from ...utils import needs_pydanticv1
-
-
-# TODO: pv2 add version with Pydantic v2
-@needs_pydanticv1
-def test_testing_dbs(tmp_path_factory: pytest.TempPathFactory):
- tmp_path = tmp_path_factory.mktemp("data")
- cwd = os.getcwd()
- os.chdir(tmp_path)
- test_db = Path("./test.db")
- if test_db.is_file(): # pragma: nocover
- test_db.unlink()
- # Import while creating the client to create the DB after starting the test session
- from docs_src.sql_databases.sql_app.tests import test_sql_app
-
- # Ensure import side effects are re-executed
- importlib.reload(test_sql_app)
- test_sql_app.test_create_user()
- if test_db.is_file(): # pragma: nocover
- test_db.unlink()
- os.chdir(cwd)
diff --git a/tests/test_tutorial/test_sql_databases/test_testing_databases_py310.py b/tests/test_tutorial/test_sql_databases/test_testing_databases_py310.py
deleted file mode 100644
index 545d63c2a..000000000
--- a/tests/test_tutorial/test_sql_databases/test_testing_databases_py310.py
+++ /dev/null
@@ -1,28 +0,0 @@
-import importlib
-import os
-from pathlib import Path
-
-import pytest
-
-from ...utils import needs_py310, needs_pydanticv1
-
-
-@needs_py310
-# TODO: pv2 add version with Pydantic v2
-@needs_pydanticv1
-def test_testing_dbs_py39(tmp_path_factory: pytest.TempPathFactory):
- tmp_path = tmp_path_factory.mktemp("data")
- cwd = os.getcwd()
- os.chdir(tmp_path)
- test_db = Path("./test.db")
- if test_db.is_file(): # pragma: nocover
- test_db.unlink()
- # Import while creating the client to create the DB after starting the test session
- from docs_src.sql_databases.sql_app_py310.tests import test_sql_app
-
- # Ensure import side effects are re-executed
- importlib.reload(test_sql_app)
- test_sql_app.test_create_user()
- if test_db.is_file(): # pragma: nocover
- test_db.unlink()
- os.chdir(cwd)
diff --git a/tests/test_tutorial/test_sql_databases/test_testing_databases_py39.py b/tests/test_tutorial/test_sql_databases/test_testing_databases_py39.py
deleted file mode 100644
index 99bfd3fa8..000000000
--- a/tests/test_tutorial/test_sql_databases/test_testing_databases_py39.py
+++ /dev/null
@@ -1,28 +0,0 @@
-import importlib
-import os
-from pathlib import Path
-
-import pytest
-
-from ...utils import needs_py39, needs_pydanticv1
-
-
-@needs_py39
-# TODO: pv2 add version with Pydantic v2
-@needs_pydanticv1
-def test_testing_dbs_py39(tmp_path_factory: pytest.TempPathFactory):
- tmp_path = tmp_path_factory.mktemp("data")
- cwd = os.getcwd()
- os.chdir(tmp_path)
- test_db = Path("./test.db")
- if test_db.is_file(): # pragma: nocover
- test_db.unlink()
- # Import while creating the client to create the DB after starting the test session
- from docs_src.sql_databases.sql_app_py39.tests import test_sql_app
-
- # Ensure import side effects are re-executed
- importlib.reload(test_sql_app)
- test_sql_app.test_create_user()
- if test_db.is_file(): # pragma: nocover
- test_db.unlink()
- os.chdir(cwd)
diff --git a/tests/test_tutorial/test_sql_databases/test_tutorial001.py b/tests/test_tutorial/test_sql_databases/test_tutorial001.py
new file mode 100644
index 000000000..cc7e590df
--- /dev/null
+++ b/tests/test_tutorial/test_sql_databases/test_tutorial001.py
@@ -0,0 +1,373 @@
+import importlib
+import warnings
+
+import pytest
+from dirty_equals import IsDict, IsInt
+from fastapi.testclient import TestClient
+from inline_snapshot import snapshot
+from sqlalchemy import StaticPool
+from sqlmodel import SQLModel, create_engine
+from sqlmodel.main import default_registry
+
+from tests.utils import needs_py39, needs_py310
+
+
+def clear_sqlmodel():
+ # Clear the tables in the metadata for the default base model
+ SQLModel.metadata.clear()
+ # Clear the Models associated with the registry, to avoid warnings
+ default_registry.dispose()
+
+
+@pytest.fixture(
+ name="client",
+ params=[
+ "tutorial001",
+ pytest.param("tutorial001_py39", marks=needs_py39),
+ pytest.param("tutorial001_py310", marks=needs_py310),
+ "tutorial001_an",
+ pytest.param("tutorial001_an_py39", marks=needs_py39),
+ pytest.param("tutorial001_an_py310", marks=needs_py310),
+ ],
+)
+def get_client(request: pytest.FixtureRequest):
+ clear_sqlmodel()
+ # TODO: remove when updating SQL tutorial to use new lifespan API
+ with warnings.catch_warnings(record=True):
+ warnings.simplefilter("always")
+ mod = importlib.import_module(f"docs_src.sql_databases.{request.param}")
+ clear_sqlmodel()
+ importlib.reload(mod)
+ mod.sqlite_url = "sqlite://"
+ mod.engine = create_engine(
+ mod.sqlite_url, connect_args={"check_same_thread": False}, poolclass=StaticPool
+ )
+
+ with TestClient(mod.app) as c:
+ yield c
+
+
+def test_crud_app(client: TestClient):
+ # TODO: this warns that SQLModel.from_orm is deprecated in Pydantic v1, refactor
+ # this if using obj.model_validate becomes independent of Pydantic v2
+ with warnings.catch_warnings(record=True):
+ warnings.simplefilter("always")
+ # No heroes before creating
+ response = client.get("heroes/")
+ assert response.status_code == 200, response.text
+ assert response.json() == []
+
+ # Create a hero
+ response = client.post(
+ "/heroes/",
+ json={
+ "id": 999,
+ "name": "Dead Pond",
+ "age": 30,
+ "secret_name": "Dive Wilson",
+ },
+ )
+ assert response.status_code == 200, response.text
+ assert response.json() == snapshot(
+ {"age": 30, "secret_name": "Dive Wilson", "id": 999, "name": "Dead Pond"}
+ )
+
+ # Read a hero
+ hero_id = response.json()["id"]
+ response = client.get(f"/heroes/{hero_id}")
+ assert response.status_code == 200, response.text
+ assert response.json() == snapshot(
+ {"name": "Dead Pond", "age": 30, "id": 999, "secret_name": "Dive Wilson"}
+ )
+
+ # Read all heroes
+ # Create more heroes first
+ response = client.post(
+ "/heroes/",
+ json={"name": "Spider-Boy", "age": 18, "secret_name": "Pedro Parqueador"},
+ )
+ assert response.status_code == 200, response.text
+ response = client.post(
+ "/heroes/", json={"name": "Rusty-Man", "secret_name": "Tommy Sharp"}
+ )
+ assert response.status_code == 200, response.text
+
+ response = client.get("/heroes/")
+ assert response.status_code == 200, response.text
+ assert response.json() == snapshot(
+ [
+ {
+ "name": "Dead Pond",
+ "age": 30,
+ "id": IsInt(),
+ "secret_name": "Dive Wilson",
+ },
+ {
+ "name": "Spider-Boy",
+ "age": 18,
+ "id": IsInt(),
+ "secret_name": "Pedro Parqueador",
+ },
+ {
+ "name": "Rusty-Man",
+ "age": None,
+ "id": IsInt(),
+ "secret_name": "Tommy Sharp",
+ },
+ ]
+ )
+
+ response = client.get("/heroes/?offset=1&limit=1")
+ assert response.status_code == 200, response.text
+ assert response.json() == snapshot(
+ [
+ {
+ "name": "Spider-Boy",
+ "age": 18,
+ "id": IsInt(),
+ "secret_name": "Pedro Parqueador",
+ }
+ ]
+ )
+
+ # Delete a hero
+ response = client.delete(f"/heroes/{hero_id}")
+ assert response.status_code == 200, response.text
+ assert response.json() == snapshot({"ok": True})
+
+ response = client.get(f"/heroes/{hero_id}")
+ assert response.status_code == 404, response.text
+
+ response = client.delete(f"/heroes/{hero_id}")
+ assert response.status_code == 404, response.text
+ assert response.json() == snapshot({"detail": "Hero not found"})
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == snapshot(
+ {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/heroes/": {
+ "post": {
+ "summary": "Create Hero",
+ "operationId": "create_hero_heroes__post",
+ "requestBody": {
+ "required": True,
+ "content": {
+ "application/json": {
+ "schema": {"$ref": "#/components/schemas/Hero"}
+ }
+ },
+ },
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {"$ref": "#/components/schemas/Hero"}
+ }
+ },
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ },
+ "get": {
+ "summary": "Read Heroes",
+ "operationId": "read_heroes_heroes__get",
+ "parameters": [
+ {
+ "name": "offset",
+ "in": "query",
+ "required": False,
+ "schema": {
+ "type": "integer",
+ "default": 0,
+ "title": "Offset",
+ },
+ },
+ {
+ "name": "limit",
+ "in": "query",
+ "required": False,
+ "schema": {
+ "type": "integer",
+ "maximum": 100,
+ "default": 100,
+ "title": "Limit",
+ },
+ },
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/Hero"
+ },
+ "title": "Response Read Heroes Heroes Get",
+ }
+ }
+ },
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ },
+ },
+ "/heroes/{hero_id}": {
+ "get": {
+ "summary": "Read Hero",
+ "operationId": "read_hero_heroes__hero_id__get",
+ "parameters": [
+ {
+ "name": "hero_id",
+ "in": "path",
+ "required": True,
+ "schema": {"type": "integer", "title": "Hero Id"},
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {"$ref": "#/components/schemas/Hero"}
+ }
+ },
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ },
+ "delete": {
+ "summary": "Delete Hero",
+ "operationId": "delete_hero_heroes__hero_id__delete",
+ "parameters": [
+ {
+ "name": "hero_id",
+ "in": "path",
+ "required": True,
+ "schema": {"type": "integer", "title": "Hero Id"},
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ },
+ },
+ },
+ "components": {
+ "schemas": {
+ "HTTPValidationError": {
+ "properties": {
+ "detail": {
+ "items": {
+ "$ref": "#/components/schemas/ValidationError"
+ },
+ "type": "array",
+ "title": "Detail",
+ }
+ },
+ "type": "object",
+ "title": "HTTPValidationError",
+ },
+ "Hero": {
+ "properties": {
+ "id": IsDict(
+ {
+ "anyOf": [{"type": "integer"}, {"type": "null"}],
+ "title": "Id",
+ }
+ )
+ | IsDict(
+ # TODO: remove when deprecating Pydantic v1
+ {
+ "type": "integer",
+ "title": "Id",
+ }
+ ),
+ "name": {"type": "string", "title": "Name"},
+ "age": IsDict(
+ {
+ "anyOf": [{"type": "integer"}, {"type": "null"}],
+ "title": "Age",
+ }
+ )
+ | IsDict(
+ # TODO: remove when deprecating Pydantic v1
+ {
+ "type": "integer",
+ "title": "Age",
+ }
+ ),
+ "secret_name": {"type": "string", "title": "Secret Name"},
+ },
+ "type": "object",
+ "required": ["name", "secret_name"],
+ "title": "Hero",
+ },
+ "ValidationError": {
+ "properties": {
+ "loc": {
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ "type": "array",
+ "title": "Location",
+ },
+ "msg": {"type": "string", "title": "Message"},
+ "type": {"type": "string", "title": "Error Type"},
+ },
+ "type": "object",
+ "required": ["loc", "msg", "type"],
+ "title": "ValidationError",
+ },
+ }
+ },
+ }
+ )
diff --git a/tests/test_tutorial/test_sql_databases/test_tutorial002.py b/tests/test_tutorial/test_sql_databases/test_tutorial002.py
new file mode 100644
index 000000000..68c1966f5
--- /dev/null
+++ b/tests/test_tutorial/test_sql_databases/test_tutorial002.py
@@ -0,0 +1,481 @@
+import importlib
+import warnings
+
+import pytest
+from dirty_equals import IsDict, IsInt
+from fastapi.testclient import TestClient
+from inline_snapshot import snapshot
+from sqlalchemy import StaticPool
+from sqlmodel import SQLModel, create_engine
+from sqlmodel.main import default_registry
+
+from tests.utils import needs_py39, needs_py310
+
+
+def clear_sqlmodel():
+ # Clear the tables in the metadata for the default base model
+ SQLModel.metadata.clear()
+ # Clear the Models associated with the registry, to avoid warnings
+ default_registry.dispose()
+
+
+@pytest.fixture(
+ name="client",
+ params=[
+ "tutorial002",
+ pytest.param("tutorial002_py39", marks=needs_py39),
+ pytest.param("tutorial002_py310", marks=needs_py310),
+ "tutorial002_an",
+ pytest.param("tutorial002_an_py39", marks=needs_py39),
+ pytest.param("tutorial002_an_py310", marks=needs_py310),
+ ],
+)
+def get_client(request: pytest.FixtureRequest):
+ clear_sqlmodel()
+ # TODO: remove when updating SQL tutorial to use new lifespan API
+ with warnings.catch_warnings(record=True):
+ warnings.simplefilter("always")
+ mod = importlib.import_module(f"docs_src.sql_databases.{request.param}")
+ clear_sqlmodel()
+ importlib.reload(mod)
+ mod.sqlite_url = "sqlite://"
+ mod.engine = create_engine(
+ mod.sqlite_url, connect_args={"check_same_thread": False}, poolclass=StaticPool
+ )
+
+ with TestClient(mod.app) as c:
+ yield c
+
+
+def test_crud_app(client: TestClient):
+ # TODO: this warns that SQLModel.from_orm is deprecated in Pydantic v1, refactor
+ # this if using obj.model_validate becomes independent of Pydantic v2
+ with warnings.catch_warnings(record=True):
+ warnings.simplefilter("always")
+ # No heroes before creating
+ response = client.get("heroes/")
+ assert response.status_code == 200, response.text
+ assert response.json() == []
+
+ # Create a hero
+ response = client.post(
+ "/heroes/",
+ json={
+ "id": 9000,
+ "name": "Dead Pond",
+ "age": 30,
+ "secret_name": "Dive Wilson",
+ },
+ )
+ assert response.status_code == 200, response.text
+ assert response.json() == snapshot(
+ {"age": 30, "id": IsInt(), "name": "Dead Pond"}
+ )
+ assert (
+ response.json()["id"] != 9000
+ ), "The ID should be generated by the database"
+
+ # Read a hero
+ hero_id = response.json()["id"]
+ response = client.get(f"/heroes/{hero_id}")
+ assert response.status_code == 200, response.text
+ assert response.json() == snapshot(
+ {"name": "Dead Pond", "age": 30, "id": IsInt()}
+ )
+
+ # Read all heroes
+ # Create more heroes first
+ response = client.post(
+ "/heroes/",
+ json={"name": "Spider-Boy", "age": 18, "secret_name": "Pedro Parqueador"},
+ )
+ assert response.status_code == 200, response.text
+ response = client.post(
+ "/heroes/", json={"name": "Rusty-Man", "secret_name": "Tommy Sharp"}
+ )
+ assert response.status_code == 200, response.text
+
+ response = client.get("/heroes/")
+ assert response.status_code == 200, response.text
+ assert response.json() == snapshot(
+ [
+ {"name": "Dead Pond", "age": 30, "id": IsInt()},
+ {"name": "Spider-Boy", "age": 18, "id": IsInt()},
+ {"name": "Rusty-Man", "age": None, "id": IsInt()},
+ ]
+ )
+
+ response = client.get("/heroes/?offset=1&limit=1")
+ assert response.status_code == 200, response.text
+ assert response.json() == snapshot(
+ [{"name": "Spider-Boy", "age": 18, "id": IsInt()}]
+ )
+
+ # Update a hero
+ response = client.patch(
+ f"/heroes/{hero_id}", json={"name": "Dog Pond", "age": None}
+ )
+ assert response.status_code == 200, response.text
+ assert response.json() == snapshot(
+ {"name": "Dog Pond", "age": None, "id": hero_id}
+ )
+
+ # Get updated hero
+ response = client.get(f"/heroes/{hero_id}")
+ assert response.status_code == 200, response.text
+ assert response.json() == snapshot(
+ {"name": "Dog Pond", "age": None, "id": hero_id}
+ )
+
+ # Delete a hero
+ response = client.delete(f"/heroes/{hero_id}")
+ assert response.status_code == 200, response.text
+ assert response.json() == snapshot({"ok": True})
+
+ # The hero is no longer found
+ response = client.get(f"/heroes/{hero_id}")
+ assert response.status_code == 404, response.text
+
+ # Delete a hero that does not exist
+ response = client.delete(f"/heroes/{hero_id}")
+ assert response.status_code == 404, response.text
+ assert response.json() == snapshot({"detail": "Hero not found"})
+
+ # Update a hero that does not exist
+ response = client.patch(f"/heroes/{hero_id}", json={"name": "Dog Pond"})
+ assert response.status_code == 404, response.text
+ assert response.json() == snapshot({"detail": "Hero not found"})
+
+
+def test_openapi_schema(client: TestClient):
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == snapshot(
+ {
+ "openapi": "3.1.0",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/heroes/": {
+ "post": {
+ "summary": "Create Hero",
+ "operationId": "create_hero_heroes__post",
+ "requestBody": {
+ "required": True,
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HeroCreate"
+ }
+ }
+ },
+ },
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HeroPublic"
+ }
+ }
+ },
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ },
+ "get": {
+ "summary": "Read Heroes",
+ "operationId": "read_heroes_heroes__get",
+ "parameters": [
+ {
+ "name": "offset",
+ "in": "query",
+ "required": False,
+ "schema": {
+ "type": "integer",
+ "default": 0,
+ "title": "Offset",
+ },
+ },
+ {
+ "name": "limit",
+ "in": "query",
+ "required": False,
+ "schema": {
+ "type": "integer",
+ "maximum": 100,
+ "default": 100,
+ "title": "Limit",
+ },
+ },
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/HeroPublic"
+ },
+ "title": "Response Read Heroes Heroes Get",
+ }
+ }
+ },
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ },
+ },
+ "/heroes/{hero_id}": {
+ "get": {
+ "summary": "Read Hero",
+ "operationId": "read_hero_heroes__hero_id__get",
+ "parameters": [
+ {
+ "name": "hero_id",
+ "in": "path",
+ "required": True,
+ "schema": {"type": "integer", "title": "Hero Id"},
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HeroPublic"
+ }
+ }
+ },
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ },
+ "patch": {
+ "summary": "Update Hero",
+ "operationId": "update_hero_heroes__hero_id__patch",
+ "parameters": [
+ {
+ "name": "hero_id",
+ "in": "path",
+ "required": True,
+ "schema": {"type": "integer", "title": "Hero Id"},
+ }
+ ],
+ "requestBody": {
+ "required": True,
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HeroUpdate"
+ }
+ }
+ },
+ },
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HeroPublic"
+ }
+ }
+ },
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ },
+ "delete": {
+ "summary": "Delete Hero",
+ "operationId": "delete_hero_heroes__hero_id__delete",
+ "parameters": [
+ {
+ "name": "hero_id",
+ "in": "path",
+ "required": True,
+ "schema": {"type": "integer", "title": "Hero Id"},
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ },
+ },
+ },
+ "components": {
+ "schemas": {
+ "HTTPValidationError": {
+ "properties": {
+ "detail": {
+ "items": {
+ "$ref": "#/components/schemas/ValidationError"
+ },
+ "type": "array",
+ "title": "Detail",
+ }
+ },
+ "type": "object",
+ "title": "HTTPValidationError",
+ },
+ "HeroCreate": {
+ "properties": {
+ "name": {"type": "string", "title": "Name"},
+ "age": IsDict(
+ {
+ "anyOf": [{"type": "integer"}, {"type": "null"}],
+ "title": "Age",
+ }
+ )
+ | IsDict(
+ # TODO: remove when deprecating Pydantic v1
+ {
+ "type": "integer",
+ "title": "Age",
+ }
+ ),
+ "secret_name": {"type": "string", "title": "Secret Name"},
+ },
+ "type": "object",
+ "required": ["name", "secret_name"],
+ "title": "HeroCreate",
+ },
+ "HeroPublic": {
+ "properties": {
+ "name": {"type": "string", "title": "Name"},
+ "age": IsDict(
+ {
+ "anyOf": [{"type": "integer"}, {"type": "null"}],
+ "title": "Age",
+ }
+ )
+ | IsDict(
+ # TODO: remove when deprecating Pydantic v1
+ {
+ "type": "integer",
+ "title": "Age",
+ }
+ ),
+ "id": {"type": "integer", "title": "Id"},
+ },
+ "type": "object",
+ "required": ["name", "id"],
+ "title": "HeroPublic",
+ },
+ "HeroUpdate": {
+ "properties": {
+ "name": IsDict(
+ {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "Name",
+ }
+ )
+ | IsDict(
+ # TODO: remove when deprecating Pydantic v1
+ {
+ "type": "string",
+ "title": "Name",
+ }
+ ),
+ "age": IsDict(
+ {
+ "anyOf": [{"type": "integer"}, {"type": "null"}],
+ "title": "Age",
+ }
+ )
+ | IsDict(
+ # TODO: remove when deprecating Pydantic v1
+ {
+ "type": "integer",
+ "title": "Age",
+ }
+ ),
+ "secret_name": IsDict(
+ {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "title": "Secret Name",
+ }
+ )
+ | IsDict(
+ # TODO: remove when deprecating Pydantic v1
+ {
+ "type": "string",
+ "title": "Secret Name",
+ }
+ ),
+ },
+ "type": "object",
+ "title": "HeroUpdate",
+ },
+ "ValidationError": {
+ "properties": {
+ "loc": {
+ "items": {
+ "anyOf": [{"type": "string"}, {"type": "integer"}]
+ },
+ "type": "array",
+ "title": "Location",
+ },
+ "msg": {"type": "string", "title": "Message"},
+ "type": {"type": "string", "title": "Error Type"},
+ },
+ "type": "object",
+ "required": ["loc", "msg", "type"],
+ "title": "ValidationError",
+ },
+ }
+ },
+ }
+ )