diff --git a/.github/actions/comment-docs-preview-in-pr/Dockerfile b/.github/actions/comment-docs-preview-in-pr/Dockerfile
index 4f20c5f10..42627fe19 100644
--- a/.github/actions/comment-docs-preview-in-pr/Dockerfile
+++ b/.github/actions/comment-docs-preview-in-pr/Dockerfile
@@ -1,6 +1,8 @@
-FROM python:3.7
+FROM python:3.10
-RUN pip install httpx "pydantic==1.5.1" pygithub
+COPY ./requirements.txt /app/requirements.txt
+
+RUN pip install -r /app/requirements.txt
COPY ./app /app
diff --git a/.github/actions/comment-docs-preview-in-pr/app/main.py b/.github/actions/comment-docs-preview-in-pr/app/main.py
index 68914fdb9..8cc119fe0 100644
--- a/.github/actions/comment-docs-preview-in-pr/app/main.py
+++ b/.github/actions/comment-docs-preview-in-pr/app/main.py
@@ -6,7 +6,8 @@ from typing import Union
import httpx
from github import Github
from github.PullRequest import PullRequest
-from pydantic import BaseModel, BaseSettings, SecretStr, ValidationError
+from pydantic import BaseModel, SecretStr, ValidationError
+from pydantic_settings import BaseSettings
github_api = "https://api.github.com"
diff --git a/.github/actions/comment-docs-preview-in-pr/requirements.txt b/.github/actions/comment-docs-preview-in-pr/requirements.txt
new file mode 100644
index 000000000..74a3631f4
--- /dev/null
+++ b/.github/actions/comment-docs-preview-in-pr/requirements.txt
@@ -0,0 +1,4 @@
+PyGithub
+pydantic>=2.5.3,<3.0.0
+pydantic-settings>=2.1.0,<3.0.0
+httpx
diff --git a/.github/actions/notify-translations/Dockerfile b/.github/actions/notify-translations/Dockerfile
index fa4197e6a..b68b4bb1a 100644
--- a/.github/actions/notify-translations/Dockerfile
+++ b/.github/actions/notify-translations/Dockerfile
@@ -1,4 +1,4 @@
-FROM python:3.7
+FROM python:3.9
RUN pip install httpx PyGithub "pydantic==1.5.1" "pyyaml>=5.3.1,<6.0.0"
diff --git a/.github/actions/notify-translations/app/main.py b/.github/actions/notify-translations/app/main.py
index 494fe6ad8..8ac1f233d 100644
--- a/.github/actions/notify-translations/app/main.py
+++ b/.github/actions/notify-translations/app/main.py
@@ -9,7 +9,7 @@ import httpx
from github import Github
from pydantic import BaseModel, BaseSettings, SecretStr
-awaiting_label = "awaiting review"
+awaiting_label = "awaiting-review"
lang_all_label = "lang-all"
approved_label = "approved-2"
translations_path = Path(__file__).parent / "translations.yml"
diff --git a/.github/dependabot.yml b/.github/dependabot.yml
index cd972a0ba..0a59adbd6 100644
--- a/.github/dependabot.yml
+++ b/.github/dependabot.yml
@@ -11,6 +11,10 @@ updates:
- package-ecosystem: "pip"
directory: "/"
schedule:
- interval: "daily"
+ interval: "monthly"
+ groups:
+ python-packages:
+ patterns:
+ - "*"
commit-message:
prefix: ⬆
diff --git a/.github/workflows/build-docs.yml b/.github/workflows/build-docs.yml
index dedf23fb9..7783161b9 100644
--- a/.github/workflows/build-docs.yml
+++ b/.github/workflows/build-docs.yml
@@ -17,7 +17,7 @@ jobs:
outputs:
docs: ${{ steps.filter.outputs.docs }}
steps:
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v4
# For pull requests it's not necessary to checkout the code but for master it is
- uses: dorny/paths-filter@v2
id: filter
@@ -28,6 +28,8 @@ jobs:
- docs/**
- docs_src/**
- requirements-docs.txt
+ - .github/workflows/build-docs.yml
+ - .github/workflows/deploy-docs.yml
langs:
needs:
- changes
@@ -35,23 +37,28 @@ jobs:
outputs:
langs: ${{ steps.show-langs.outputs.langs }}
steps:
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v4
- name: Set up Python
- uses: actions/setup-python@v4
+ uses: actions/setup-python@v5
with:
python-version: "3.11"
- uses: actions/cache@v3
id: cache
with:
path: ${{ env.pythonLocation }}
- key: ${{ runner.os }}-python-docs-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml', 'requirements-docs.txt') }}-v06
+ key: ${{ runner.os }}-python-docs-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml', 'requirements-docs.txt', 'requirements-docs-tests.txt') }}-v06
- 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.event.pull_request.head.repo.fork == false ) && steps.cache.outputs.cache-hit != 'true'
- run: pip install git+https://${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}@github.com/squidfunk/mkdocs-material-insiders.git
+ 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
+ - name: Verify Docs
+ run: python ./scripts/docs.py verify-docs
- name: Export Language Codes
id: show-langs
run: |
@@ -71,22 +78,25 @@ jobs:
env:
GITHUB_CONTEXT: ${{ toJson(github) }}
run: echo "$GITHUB_CONTEXT"
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v4
- name: Set up Python
- uses: actions/setup-python@v4
+ uses: actions/setup-python@v5
with:
python-version: "3.11"
- uses: actions/cache@v3
id: cache
with:
path: ${{ env.pythonLocation }}
- key: ${{ runner.os }}-python-docs-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml', 'requirements-docs.txt') }}-v06
+ key: ${{ runner.os }}-python-docs-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml', 'requirements-docs.txt', 'requirements-docs-tests.txt') }}-v06
- 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.event.pull_request.head.repo.fork == false ) && steps.cache.outputs.cache-hit != 'true'
- run: pip install git+https://${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}@github.com/squidfunk/mkdocs-material-insiders.git
+ 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
- name: Update Languages
run: python ./scripts/docs.py update-languages
- uses: actions/cache@v3
diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml
index dcd6d7107..2bec6682c 100644
--- a/.github/workflows/deploy-docs.yml
+++ b/.github/workflows/deploy-docs.yml
@@ -14,14 +14,14 @@ jobs:
env:
GITHUB_CONTEXT: ${{ toJson(github) }}
run: echo "$GITHUB_CONTEXT"
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v4
- name: Clean site
run: |
rm -rf ./site
mkdir ./site
- name: Download Artifact Docs
id: download
- uses: dawidd6/action-download-artifact@v2.27.0
+ uses: dawidd6/action-download-artifact@v3.0.0
with:
if_no_artifact_found: ignore
github_token: ${{ secrets.FASTAPI_PREVIEW_DOCS_DOWNLOAD_ARTIFACTS }}
diff --git a/.github/workflows/issue-manager.yml b/.github/workflows/issue-manager.yml
index bb967fa11..0f564d721 100644
--- a/.github/workflows/issue-manager.yml
+++ b/.github/workflows/issue-manager.yml
@@ -23,7 +23,7 @@ jobs:
env:
GITHUB_CONTEXT: ${{ toJson(github) }}
run: echo "$GITHUB_CONTEXT"
- - uses: tiangolo/issue-manager@0.4.0
+ - uses: tiangolo/issue-manager@0.5.0
with:
token: ${{ secrets.FASTAPI_ISSUE_MANAGER }}
config: >
@@ -31,5 +31,9 @@ jobs:
"answered": {
"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": {
+ "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."
}
}
diff --git a/.github/workflows/label-approved.yml b/.github/workflows/label-approved.yml
index 2113c468a..51be2413d 100644
--- a/.github/workflows/label-approved.yml
+++ b/.github/workflows/label-approved.yml
@@ -3,6 +3,7 @@ name: Label Approved
on:
schedule:
- cron: "0 12 * * *"
+ workflow_dispatch:
jobs:
label-approved:
@@ -13,6 +14,14 @@ jobs:
env:
GITHUB_CONTEXT: ${{ toJson(github) }}
run: echo "$GITHUB_CONTEXT"
- - uses: docker://tiangolo/label-approved:0.0.2
+ - uses: docker://tiangolo/label-approved:0.0.4
with:
token: ${{ secrets.FASTAPI_LABEL_APPROVED }}
+ config: >
+ {
+ "approved-1":
+ {
+ "number": 1,
+ "await_label": "awaiting-review"
+ }
+ }
diff --git a/.github/workflows/latest-changes.yml b/.github/workflows/latest-changes.yml
index e38870f46..27e062d09 100644
--- a/.github/workflows/latest-changes.yml
+++ b/.github/workflows/latest-changes.yml
@@ -24,7 +24,7 @@ jobs:
env:
GITHUB_CONTEXT: ${{ toJson(github) }}
run: echo "$GITHUB_CONTEXT"
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v4
with:
# To allow latest-changes to commit to the main branch
token: ${{ secrets.FASTAPI_LATEST_CHANGES }}
@@ -34,9 +34,12 @@ 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.0.3
+ - uses: docker://tiangolo/latest-changes:0.3.0
+ # - uses: tiangolo/latest-changes@main
with:
token: ${{ secrets.GITHUB_TOKEN }}
latest_changes_file: docs/en/docs/release-notes.md
- latest_changes_header: '## Latest Changes\n\n'
+ latest_changes_header: '## Latest Changes'
+ end_regex: '^## '
debug_logs: true
+ label_header_prefix: '### '
diff --git a/.github/workflows/notify-translations.yml b/.github/workflows/notify-translations.yml
index 44ee83ec0..c0904ce48 100644
--- a/.github/workflows/notify-translations.yml
+++ b/.github/workflows/notify-translations.yml
@@ -23,7 +23,7 @@ jobs:
env:
GITHUB_CONTEXT: ${{ toJson(github) }}
run: echo "$GITHUB_CONTEXT"
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v4
# Allow debugging with tmate
- name: Setup tmate session
uses: mxschmitt/action-tmate@v3
diff --git a/.github/workflows/people.yml b/.github/workflows/people.yml
index 4480a1427..b0868771d 100644
--- a/.github/workflows/people.yml
+++ b/.github/workflows/people.yml
@@ -19,7 +19,7 @@ jobs:
env:
GITHUB_CONTEXT: ${{ toJson(github) }}
run: echo "$GITHUB_CONTEXT"
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v4
# Ref: https://github.com/actions/runner/issues/2033
- name: Fix git safe.directory in container
run: mkdir -p /home/runner/work/_temp/_github_home && printf "[safe]\n\tdirectory = /github/workspace" > /home/runner/work/_temp/_github_home/.gitconfig
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml
index b84c5bf17..8ebb28a80 100644
--- a/.github/workflows/publish.yml
+++ b/.github/workflows/publish.yml
@@ -13,11 +13,11 @@ jobs:
env:
GITHUB_CONTEXT: ${{ toJson(github) }}
run: echo "$GITHUB_CONTEXT"
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v4
- name: Set up Python
- uses: actions/setup-python@v4
+ uses: actions/setup-python@v5
with:
- python-version: "3.7"
+ python-version: "3.10"
# Issue ref: https://github.com/actions/setup-python/issues/436
# cache: "pip"
cache-dependency-path: pyproject.toml
@@ -32,7 +32,7 @@ jobs:
- name: Build distribution
run: python -m build
- name: Publish
- uses: pypa/gh-action-pypi-publish@v1.8.6
+ uses: pypa/gh-action-pypi-publish@v1.8.11
with:
password: ${{ secrets.PYPI_API_TOKEN }}
- name: Dump GitHub context
diff --git a/.github/workflows/smokeshow.yml b/.github/workflows/smokeshow.yml
index 4e689d95c..10bff67ae 100644
--- a/.github/workflows/smokeshow.yml
+++ b/.github/workflows/smokeshow.yml
@@ -18,13 +18,13 @@ jobs:
env:
GITHUB_CONTEXT: ${{ toJson(github) }}
run: echo "$GITHUB_CONTEXT"
- - uses: actions/setup-python@v4
+ - uses: actions/setup-python@v5
with:
python-version: '3.9'
- run: pip install smokeshow
- - uses: dawidd6/action-download-artifact@v2.27.0
+ - uses: dawidd6/action-download-artifact@v3.0.0
with:
github_token: ${{ secrets.FASTAPI_SMOKESHOW_DOWNLOAD_ARTIFACTS }}
workflow: test.yml
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index c9723b25b..b6b173685 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -17,9 +17,9 @@ jobs:
env:
GITHUB_CONTEXT: ${{ toJson(github) }}
run: echo "$GITHUB_CONTEXT"
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v4
- name: Set up Python
- uses: actions/setup-python@v4
+ uses: actions/setup-python@v5
with:
python-version: "3.11"
# Issue ref: https://github.com/actions/setup-python/issues/436
@@ -29,7 +29,7 @@ jobs:
id: cache
with:
path: ${{ env.pythonLocation }}
- key: ${{ runner.os }}-python-${{ env.pythonLocation }}-pydantic-v2-${{ hashFiles('pyproject.toml', 'requirements-tests.txt') }}-test-v05
+ key: ${{ runner.os }}-python-${{ env.pythonLocation }}-pydantic-v2-${{ hashFiles('pyproject.toml', 'requirements-tests.txt', 'requirements-docs-tests.txt') }}-test-v07
- name: Install Dependencies
if: steps.cache.outputs.cache-hit != 'true'
run: pip install -r requirements-tests.txt
@@ -42,7 +42,12 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
- python-version: ["3.7", "3.8", "3.9", "3.10", "3.11"]
+ python-version:
+ - "3.12"
+ - "3.11"
+ - "3.10"
+ - "3.9"
+ - "3.8"
pydantic-version: ["pydantic-v1", "pydantic-v2"]
fail-fast: false
steps:
@@ -50,9 +55,9 @@ jobs:
env:
GITHUB_CONTEXT: ${{ toJson(github) }}
run: echo "$GITHUB_CONTEXT"
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v4
- name: Set up Python
- uses: actions/setup-python@v4
+ uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
# Issue ref: https://github.com/actions/setup-python/issues/436
@@ -62,7 +67,7 @@ jobs:
id: cache
with:
path: ${{ env.pythonLocation }}
- key: ${{ runner.os }}-python-${{ env.pythonLocation }}-${{ matrix.pydantic-version }}-${{ hashFiles('pyproject.toml', 'requirements-tests.txt') }}-test-v05
+ key: ${{ runner.os }}-python-${{ env.pythonLocation }}-${{ matrix.pydantic-version }}-${{ hashFiles('pyproject.toml', 'requirements-tests.txt', 'requirements-docs-tests.txt') }}-test-v07
- name: Install Dependencies
if: steps.cache.outputs.cache-hit != 'true'
run: pip install -r requirements-tests.txt
@@ -92,8 +97,8 @@ jobs:
env:
GITHUB_CONTEXT: ${{ toJson(github) }}
run: echo "$GITHUB_CONTEXT"
- - uses: actions/checkout@v3
- - uses: actions/setup-python@v4
+ - uses: actions/checkout@v4
+ - uses: actions/setup-python@v5
with:
python-version: '3.8'
# Issue ref: https://github.com/actions/setup-python/issues/436
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 9f7085f72..a7f2fb3f2 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -13,23 +13,13 @@ repos:
- --unsafe
- id: end-of-file-fixer
- id: trailing-whitespace
-- repo: https://github.com/asottile/pyupgrade
- rev: v3.7.0
- hooks:
- - id: pyupgrade
- args:
- - --py3-plus
- - --keep-runtime-typing
- repo: https://github.com/charliermarsh/ruff-pre-commit
- rev: v0.0.275
+ rev: v0.1.2
hooks:
- id: ruff
args:
- --fix
-- repo: https://github.com/psf/black
- rev: 23.3.0
- hooks:
- - id: black
+ - id: ruff-format
ci:
autofix_commit_msg: 🎨 [pre-commit.ci] Auto format from pre-commit.com hooks
autoupdate_commit_msg: ⬆ [pre-commit.ci] pre-commit autoupdate
diff --git a/CITATION.cff b/CITATION.cff
new file mode 100644
index 000000000..9028248b1
--- /dev/null
+++ b/CITATION.cff
@@ -0,0 +1,24 @@
+# This CITATION.cff file was generated with cffinit.
+# Visit https://bit.ly/cffinit to generate yours today!
+
+cff-version: 1.2.0
+title: FastAPI
+message: >-
+ If you use this software, please cite it using the
+ metadata from this file.
+type: software
+authors:
+ - given-names: Sebastián
+ family-names: Ramírez
+ email: tiangolo@gmail.com
+identifiers:
+repository-code: 'https://github.com/tiangolo/fastapi'
+url: 'https://fastapi.tiangolo.com'
+abstract: >-
+ FastAPI framework, high performance, easy to learn, fast to code,
+ ready for production
+keywords:
+ - fastapi
+ - pydantic
+ - starlette
+license: MIT
diff --git a/README.md b/README.md
index 266213426..874abf8c6 100644
--- a/README.md
+++ b/README.md
@@ -27,7 +27,7 @@
---
-FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints.
+FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.8+ based on standard Python type hints.
The key features are:
@@ -48,16 +48,20 @@ The key features are:
-
-
-
+
+
+
+
+
+
-
+
+
@@ -119,7 +123,7 @@ If you are building a CLI app to be
## Requirements
-Python 3.7+
+Python 3.8+
FastAPI stands on the shoulders of giants:
@@ -335,7 +339,7 @@ You do that with standard modern Python types.
You don't have to learn a new syntax, the methods or classes of a specific library, etc.
-Just standard **Python 3.7+**.
+Just standard **Python 3.8+**.
For example, for an `int`:
diff --git a/docs/az/docs/index.md b/docs/az/docs/index.md
new file mode 100644
index 000000000..a22706512
--- /dev/null
+++ b/docs/az/docs/index.md
@@ -0,0 +1,469 @@
+
+ FastAPI framework, yüksək məshuldarlı, öyrənməsi asan, çevik kodlama, istifadəyə hazırdır +
+ + +--- + +**Sənədlər**: https://fastapi.tiangolo.com + +**Qaynaq Kodu**: https://github.com/tiangolo/fastapi + +--- + +FastAPI Python 3.8+ ilə API yaratmaq üçün standart Python tip məsləhətlərinə əsaslanan, müasir, sürətli (yüksək performanslı) framework-dür. + +Əsas xüsusiyyətləri bunlardır: + +* **Sürətli**: Çox yüksək performans, **NodeJS** və **Go** səviyyəsində (Starlette və Pydantic-ə təşəkkürlər). [Ən sürətli Python frameworklərindən biridir](#performans). +* **Çevik kodlama**: Funksiyanallıqları inkişaf etdirmək sürətini təxminən 200%-dən 300%-ə qədər artırın. * +* **Daha az xəta**: İnsan (developer) tərəfindən törədilən səhvlərin təxminən 40% -ni azaldın. * +* **İntuitiv**: Əla redaktor dəstəyi. Hər yerdə otomatik tamamlama. Xətaları müəyyənləşdirməyə daha az vaxt sərf edəcəksiniz. +* **Asan**: İstifadəsi və öyrənilməsi asan olması üçün nəzərdə tutulmuşdur. Sənədləri oxumaq üçün daha az vaxt ayıracaqsınız. +* **Qısa**: Kod təkrarlanmasını minimuma endirin. Hər bir parametr tərifində birdən çox xüsusiyyət ilə və daha az səhvlə qarşılaşacaqsınız. +* **Güclü**: Avtomatik və interaktiv sənədlərlə birlikdə istifadəyə hazır kod əldə edə bilərsiniz. +* **Standartlara əsaslanan**: API-lar üçün açıq standartlara əsaslanır (və tam uyğun gəlir): OpenAPI (əvvəlki adı ilə Swagger) və JSON Schema. + +* Bu fikirlər daxili development komandasının hazırladıqları məhsulların sınaqlarına əsaslanır. + +## Sponsorlar + + + +{% if sponsors %} +{% for sponsor in sponsors.gold -%} +async def
...uvicorn main:app --reload
əmri haqqında...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.
+
+Starlette tərəfindən istifadə olunanlar:
+
+* httpx
- Əgər `TestClient` strukturundan istifadə edəcəksinizsə, tələb olunur.
+* jinja2
- Standart şablon konfiqurasiyasından istifadə etmək istəyirsinizsə, tələb olunur.
+* python-multipart
- `request.form()` ilə forma "çevirmə" dəstəyindən istifadə etmək istəyirsinizsə, tələb olunur.
+* itsdangerous
- `SessionMiddleware` dəstəyi üçün tələb olunur.
+* pyyaml
- `SchemaGenerator` dəstəyi üçün tələb olunur (Çox güman ki, FastAPI istifadə edərkən buna ehtiyacınız olmayacaq).
+* ujson
- `UJSONResponse` istifadə etmək istəyirsinizsə, tələb olunur.
+
+Həm FastAPI, həm də Starlette tərəfindən istifadə olunur:
+
+* uvicorn
- Yaratdığımız proqramı servis edəcək veb server kimi fəaliyyət göstərir.
+* orjson
- `ORJSONResponse` istifadə edəcəksinizsə tələb olunur.
+
+Bütün bunları `pip install fastapi[all]` ilə quraşdıra bilərsiniz.
+
+## Lisenziya
+
+Bu layihə MIT lisenziyasının şərtlərinə əsasən lisenziyalaşdırılıb.
diff --git a/docs/az/mkdocs.yml b/docs/az/mkdocs.yml
new file mode 100644
index 000000000..de18856f4
--- /dev/null
+++ b/docs/az/mkdocs.yml
@@ -0,0 +1 @@
+INHERIT: ../en/mkdocs.yml
diff --git a/docs/bn/docs/index.md b/docs/bn/docs/index.md
new file mode 100644
index 000000000..4f778e873
--- /dev/null
+++ b/docs/bn/docs/index.md
@@ -0,0 +1,464 @@
+
++ FastAPI উচ্চক্ষমতা সম্পন্ন, সহজে শেখার এবং দ্রুত কোড করে প্রোডাকশনের জন্য ফ্রামওয়ার্ক। +
+ + +--- + +**নির্দেশিকা নথি**: https://fastapi.tiangolo.com + +**সোর্স কোড**: https://github.com/tiangolo/fastapi + +--- + +FastAPI একটি আধুনিক, দ্রুত ( বেশি ক্ষমতা ) সম্পন্ন, Python 3.6+ দিয়ে API তৈরির জন্য স্ট্যান্ডার্ড পাইথন টাইপ ইঙ্গিত ভিত্তিক ওয়েব ফ্রেমওয়ার্ক। + +এর মূল বৈশিষ্ট্য গুলো হলঃ + +- **গতি**: এটি **NodeJS** এবং **Go** এর মত কার্যক্ষমতা সম্পন্ন (Starlette এবং Pydantic এর সাহায্যে)। [পাইথন এর দ্রুততম ফ্রেমওয়ার্ক গুলোর মধ্যে এটি একটি](#_11)। +- **দ্রুত কোড করা**:বৈশিষ্ট্য তৈরির গতি ২০০% থেকে ৩০০% বৃদ্ধি করে৷ \* +- **স্বল্প bugs**: মানুব (ডেভেলপার) সৃষ্ট ত্রুটির প্রায় ৪০% হ্রাস করে। \* +- **স্বজ্ঞাত**: দুর্দান্ত এডিটর সাহায্য Completion নামেও পরিচিত। দ্রুত ডিবাগ করা যায়। + +- **সহজ**: এটি এমন ভাবে সজানো হয়েছে যেন নির্দেশিকা নথি পড়ে সহজে শেখা এবং ব্যবহার করা যায়। +- **সংক্ষিপ্ত**: কোড পুনরাবৃত্তি কমানোর পাশাপাশি, bug কমায় এবং প্রতিটি প্যারামিটার ঘোষণা থেকে একাধিক ফিচার পাওয়া যায় । +- **জোরালো**: স্বয়ংক্রিয় ভাবে তৈরি ক্রিয়াশীল নির্দেশনা নথি (documentation) সহ উৎপাদন উপযোগি (Production-ready) কোড পাওয়া যায়। +- **মান-ভিত্তিক**: এর ভিত্তি OpenAPI (যা পুর্বে Swagger নামে পরিচিত ছিল) এবং JSON Schema এর আদর্শের মানের ওপর + +\* উৎপাদনমুখি এপ্লিকেশন বানানোর এক দল ডেভেলপার এর মতামত ভিত্তিক ফলাফল। + +## স্পনসর গণ + + + +{% if sponsors %} +{% for sponsor in sponsors.gold -%} +async def
...uvicorn main:app --reload
...ujson
- দ্রুত JSON এর জন্য "parsing".
+- email_validator
- ইমেল যাচাইকরণের জন্য।
+
+স্টারলেট দ্বারা ব্যবহৃত:
+
+- httpx
- আপনি যদি `TestClient` ব্যবহার করতে চান তাহলে আবশ্যক।
+- jinja2
- আপনি যদি প্রদত্ত টেমপ্লেট রূপরেখা ব্যবহার করতে চান তাহলে প্রয়োজন।
+- python-multipart
- আপনি যদি ফর্ম সহায়তা করতে চান তাহলে প্রয়োজন "parsing", `request.form()` সহ।
+- itsdangerous
- `SessionMiddleware` সহায়তার জন্য প্রয়োজন।
+- pyyaml
- স্টারলেটের SchemaGenerator সাপোর্ট এর জন্য প্রয়োজন (আপনার সম্ভাবত FastAPI প্রয়োজন নেই)।
+- graphene
- `GraphQLApp` সহায়তার জন্য প্রয়োজন।
+- ujson
- আপনি `UJSONResponse` ব্যবহার করতে চাইলে প্রয়োজন।
+
+FastAPI / Starlette দ্বারা ব্যবহৃত:
+
+- uvicorn
- সার্ভারের জন্য যা আপনার অ্যাপ্লিকেশন লোড করে এবং পরিবেশন করে।
+- orjson
- আপনি `ORJSONResponse` ব্যবহার করতে চাইলে প্রয়োজন।
+
+আপনি এই সব ইনস্টল করতে পারেন `pip install fastapi[all]` দিয়ে.
+
+## লাইসেন্স
+
+এই প্রজেক্ট MIT লাইসেন্স নীতিমালার অধীনে শর্তায়িত।
diff --git a/docs/bn/mkdocs.yml b/docs/bn/mkdocs.yml
new file mode 100644
index 000000000..de18856f4
--- /dev/null
+++ b/docs/bn/mkdocs.yml
@@ -0,0 +1 @@
+INHERIT: ../en/mkdocs.yml
diff --git a/docs/de/docs/about/index.md b/docs/de/docs/about/index.md
new file mode 100644
index 000000000..4c309e02a
--- /dev/null
+++ b/docs/de/docs/about/index.md
@@ -0,0 +1,3 @@
+# Über
+
+Über FastAPI, sein Design, seine Inspiration und mehr. 🤓
diff --git a/docs/de/docs/advanced/additional-status-codes.md b/docs/de/docs/advanced/additional-status-codes.md
new file mode 100644
index 000000000..e9de267cf
--- /dev/null
+++ b/docs/de/docs/advanced/additional-status-codes.md
@@ -0,0 +1,69 @@
+# Zusätzliche Statuscodes
+
+Standardmäßig liefert **FastAPI** die Rückgabewerte (Responses) als `JSONResponse` zurück und fügt den Inhalt der jeweiligen *Pfadoperation* in das `JSONResponse` Objekt ein.
+
+Es wird der Default-Statuscode oder derjenige verwendet, den Sie in Ihrer *Pfadoperation* festgelegt haben.
+
+## Zusätzliche Statuscodes
+
+Wenn Sie neben dem Hauptstatuscode weitere Statuscodes zurückgeben möchten, können Sie dies tun, indem Sie direkt eine `Response` zurückgeben, wie etwa eine `JSONResponse`, und den zusätzlichen Statuscode direkt festlegen.
+
+Angenommen, Sie möchten eine *Pfadoperation* haben, die das Aktualisieren von Artikeln ermöglicht und bei Erfolg den HTTP-Statuscode 200 „OK“ zurückgibt.
+
+Sie möchten aber auch, dass sie neue Artikel akzeptiert. Und wenn die Elemente vorher nicht vorhanden waren, werden diese Elemente erstellt und der HTTP-Statuscode 201 „Created“ zurückgegeben.
+
+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+"
+
+ ```Python hl_lines="4 25"
+ {!> ../../../docs_src/additional_status_codes/tutorial001_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="4 25"
+ {!> ../../../docs_src/additional_status_codes/tutorial001_an_py39.py!}
+ ```
+
+=== "Python 3.8+"
+
+ ```Python hl_lines="4 26"
+ {!> ../../../docs_src/additional_status_codes/tutorial001_an.py!}
+ ```
+
+=== "Python 3.10+ nicht annotiert"
+
+ !!! tip "Tipp"
+ Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+ ```Python hl_lines="2 23"
+ {!> ../../../docs_src/additional_status_codes/tutorial001_py310.py!}
+ ```
+
+=== "Python 3.8+ nicht annotiert"
+
+ !!! tip "Tipp"
+ Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+ ```Python hl_lines="4 25"
+ {!> ../../../docs_src/additional_status_codes/tutorial001.py!}
+ ```
+
+!!! warning "Achtung"
+ Wenn Sie eine `Response` direkt zurückgeben, wie im obigen Beispiel, wird sie direkt zurückgegeben.
+
+ Sie wird nicht mit einem Modell usw. serialisiert.
+
+ Stellen Sie sicher, dass sie die gewünschten Daten enthält und dass die Werte gültiges JSON sind (wenn Sie `JSONResponse` verwenden).
+
+!!! note "Technische Details"
+ Sie können auch `from starlette.responses import JSONResponse` verwenden.
+
+ **FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. Das Gleiche gilt für `status`.
+
+## OpenAPI- und API-Dokumentation
+
+Wenn Sie zusätzliche Statuscodes und Responses direkt zurückgeben, werden diese nicht in das OpenAPI-Schema (die API-Dokumentation) aufgenommen, da FastAPI keine Möglichkeit hat, im Voraus zu wissen, was Sie zurückgeben werden.
+
+Sie können das jedoch in Ihrem Code dokumentieren, indem Sie Folgendes verwenden: [Zusätzliche Responses](additional-responses.md){.internal-link target=_blank}.
diff --git a/docs/de/docs/advanced/custom-response.md b/docs/de/docs/advanced/custom-response.md
new file mode 100644
index 000000000..68c037ad7
--- /dev/null
+++ b/docs/de/docs/advanced/custom-response.md
@@ -0,0 +1,300 @@
+# Benutzerdefinierte Response – HTML, Stream, Datei, andere
+
+Standardmäßig gibt **FastAPI** die Responses mittels `JSONResponse` zurück.
+
+Sie können das überschreiben, indem Sie direkt eine `Response` zurückgeben, wie in [Eine Response direkt zurückgeben](response-directly.md){.internal-link target=_blank} gezeigt.
+
+Wenn Sie jedoch direkt eine `Response` zurückgeben, werden die Daten nicht automatisch konvertiert und die Dokumentation wird nicht automatisch generiert (zum Beispiel wird der spezifische „Medientyp“, der im HTTP-Header `Content-Type` angegeben ist, nicht Teil der generierten OpenAPI).
+
+Sie können aber auch die `Response`, die Sie verwenden möchten, im *Pfadoperation-Dekorator* deklarieren.
+
+Der Inhalt, den Sie von Ihrer *Pfadoperation-Funktion* zurückgeben, wird in diese `Response` eingefügt.
+
+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.
+
+## `ORJSONResponse` verwenden
+
+Um beispielsweise noch etwas Leistung herauszuholen, können Sie `orjson` installieren und verwenden, und die Response als `ORJSONResponse` deklarieren.
+
+Importieren Sie die `Response`-Klasse (-Unterklasse), die Sie verwenden möchten, und deklarieren Sie sie im *Pfadoperation-Dekorator*.
+
+Bei umfangreichen Responses ist die direkte Rückgabe einer `Response` viel schneller als ein Dictionary zurückzugeben.
+
+Das liegt daran, dass FastAPI standardmäßig jedes enthaltene Element überprüft und sicherstellt, dass es als JSON serialisierbar ist, und zwar unter Verwendung desselben [JSON-kompatiblen Encoders](../tutorial/encoder.md){.internal-link target=_blank}, der im Tutorial erläutert wurde. Dadurch können Sie **beliebige Objekte** zurückgeben, zum Beispiel Datenbankmodelle.
+
+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!}
+```
+
+!!! info
+ Der Parameter `response_class` wird auch verwendet, um den „Medientyp“ der Response zu definieren.
+
+ In diesem Fall wird der HTTP-Header `Content-Type` auf `application/json` gesetzt.
+
+ Und er wird als solcher in OpenAPI dokumentiert.
+
+!!! tip "Tipp"
+ Die `ORJSONResponse` ist derzeit nur in FastAPI verfügbar, nicht in Starlette.
+
+## HTML-Response
+
+Um eine Response mit HTML direkt von **FastAPI** zurückzugeben, verwenden Sie `HTMLResponse`.
+
+* Importieren Sie `HTMLResponse`.
+* Übergeben Sie `HTMLResponse` als den Parameter `response_class` Ihres *Pfadoperation-Dekorators*.
+
+```Python hl_lines="2 7"
+{!../../../docs_src/custom_response/tutorial002.py!}
+```
+
+!!! info
+ Der Parameter `response_class` wird auch verwendet, um den „Medientyp“ der Response zu definieren.
+
+ In diesem Fall wird der HTTP-Header `Content-Type` auf `text/html` gesetzt.
+
+ Und er wird als solcher in OpenAPI dokumentiert.
+
+### Eine `Response` zurückgeben
+
+Wie in [Eine Response direkt zurückgeben](response-directly.md){.internal-link target=_blank} gezeigt, können Sie die Response auch direkt in Ihrer *Pfadoperation* überschreiben, indem Sie diese zurückgeben.
+
+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!}
+```
+
+!!! warning "Achtung"
+ Eine `Response`, die direkt von Ihrer *Pfadoperation-Funktion* zurückgegeben wird, wird in OpenAPI nicht dokumentiert (zum Beispiel wird der `Content-Type` nicht dokumentiert) und ist in der automatischen interaktiven Dokumentation nicht sichtbar.
+
+!!! info
+ 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
+
+Wenn Sie die Response innerhalb der Funktion überschreiben und gleichzeitig den „Medientyp“ in OpenAPI dokumentieren möchten, können Sie den `response_class`-Parameter verwenden UND ein `Response`-Objekt zurückgeben.
+
+Die `response_class` wird dann nur zur Dokumentation der OpenAPI-Pfadoperation* verwendet, Ihre `Response` wird jedoch unverändert verwendet.
+
+#### Eine `HTMLResponse` direkt zurückgeben
+
+Es könnte zum Beispiel so etwas sein:
+
+```Python hl_lines="7 21 23"
+{!../../../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.
+
+Indem Sie das Ergebnis des Aufrufs von `generate_html_response()` zurückgeben, geben Sie bereits eine `Response` zurück, die das Standardverhalten von **FastAPI** überschreibt.
+
+Aber da Sie die `HTMLResponse` auch in der `response_class` übergeben haben, weiß **FastAPI**, dass sie in OpenAPI und der interaktiven Dokumentation als HTML mit `text/html` zu dokumentieren ist:
+
+get
-Operation gehen
+
+!!! info "`@decorator` Information"
+ Diese `@something`-Syntax wird in Python „Dekorator“ genannt.
+
+ Sie platzieren ihn über einer Funktion. Wie ein hübscher, dekorativer Hut (daher kommt wohl der Begriff).
+
+ Ein „Dekorator“ nimmt die darunter stehende Funktion und macht etwas damit.
+
+ In unserem Fall teilt dieser Dekorator **FastAPI** mit, dass die folgende Funktion mit dem **Pfad** `/` und der **Operation** `get` zusammenhängt.
+
+ Dies ist der „**Pfadoperation-Dekorator**“.
+
+Sie können auch die anderen Operationen verwenden:
+
+* `@app.post()`
+* `@app.put()`
+* `@app.delete()`
+
+Oder die exotischeren:
+
+* `@app.options()`
+* `@app.head()`
+* `@app.patch()`
+* `@app.trace()`
+
+!!! tip "Tipp"
+ Es steht Ihnen frei, jede Operation (HTTP-Methode) so zu verwenden, wie Sie es möchten.
+
+ **FastAPI** erzwingt keine bestimmte Bedeutung.
+
+ 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**
+
+Das ist unsere „**Pfadoperation-Funktion**“:
+
+* **Pfad**: ist `/`.
+* **Operation**: ist `get`.
+* **Funktion**: ist die Funktion direkt unter dem „Dekorator“ (unter `@app.get("/")`).
+
+```Python hl_lines="7"
+{!../../../docs_src/first_steps/tutorial001.py!}
+```
+
+Dies ist eine Python-Funktion.
+
+Sie wird von **FastAPI** immer dann aufgerufen, wenn sie eine Anfrage an die URL "`/`" mittels einer `GET`-Operation erhält.
+
+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!}
+```
+
+!!! 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!}
+```
+
+Sie können ein `dict`, eine `list`, einzelne Werte wie `str`, `int`, usw. zurückgeben.
+
+Sie können auch Pydantic-Modelle zurückgeben (dazu später mehr).
+
+Es gibt viele andere Objekte und Modelle, die automatisch zu JSON konvertiert werden (einschließlich ORMs usw.). Versuchen Sie, Ihre Lieblingsobjekte zu verwenden. Es ist sehr wahrscheinlich, dass sie bereits unterstützt werden.
+
+## Zusammenfassung
+
+* Importieren Sie `FastAPI`.
+* Erstellen Sie eine `app` Instanz.
+* Schreiben Sie einen **Pfadoperation-Dekorator** (wie z. B. `@app.get("/")`).
+* Schreiben Sie eine **Pfadoperation-Funktion** (wie z. B. oben `def root(): ...`).
+* Starten Sie den Entwicklungsserver (z. B. `uvicorn main:app --reload`).
diff --git a/docs/de/docs/tutorial/index.md b/docs/de/docs/tutorial/index.md
new file mode 100644
index 000000000..93a30d1b3
--- /dev/null
+++ b/docs/de/docs/tutorial/index.md
@@ -0,0 +1,80 @@
+# Tutorial – Benutzerhandbuch
+
+Dieses Tutorial zeigt Ihnen Schritt für Schritt, wie Sie **FastAPI** und die meisten seiner Funktionen verwenden können.
+
+Jeder Abschnitt baut schrittweise auf den vorhergehenden auf. Diese Abschnitte sind aber nach einzelnen Themen gegliedert, sodass Sie direkt zu einem bestimmten Thema übergehen können, um Ihre speziellen API-Anforderungen zu lösen.
+
+Außerdem dienen diese als zukünftige Referenz.
+
+Dadurch können Sie jederzeit zurückkommen und sehen genau das, was Sie benötigen.
+
+## Den Code ausführen
+
+Alle Codeblöcke können kopiert und direkt verwendet werden (da es sich um getestete Python-Dateien handelt).
+
+Um eines der Beispiele auszuführen, kopieren Sie den Code in eine Datei `main.py`, und starten Sie `uvicorn` mit:
+
+contact
fieldsParameter | Type | Description |
---|---|---|
name | str | The identifying name of the contact person/organization. |
url | str | The URL pointing to the contact information. MUST be in the format of a URL. |
email | str | The email address of the contact person/organization. MUST be in the format of an email address. |
license_info
fieldsParameter | Type | Description |
---|---|---|
name | str | REQUIRED (if a license_info is set). The license name used for the API. |
identifier | str | An SPDX license expression for the API. The identifier field is mutually exclusive of the url field. Available since OpenAPI 3.1.0, FastAPI 0.99.0. |
url | str | A URL to the license used for the API. MUST be in the format of a URL. |
license_info
fieldsParameter | Type | Description |
---|---|---|
name | str | REQUIRED (if a license_info is set). The license name used for the API. |
identifier | str | An SPDX license expression for the API. The identifier field is mutually exclusive of the url field. Available since OpenAPI 3.1.0, FastAPI 0.99.0. |
url | str | A URL to the license used for the API. MUST be in the format of a URL. |
lt
.
{!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="12"
{!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!}
```
-=== "Python 3.6+ non-Annotated"
+=== "Python 3.8+ non-Annotated"
!!! tip
Prefer to use the `Annotated` version if possible.
diff --git a/docs/en/docs/tutorial/path-params.md b/docs/en/docs/tutorial/path-params.md
index 6594a7a8b..847b56334 100644
--- a/docs/en/docs/tutorial/path-params.md
+++ b/docs/en/docs/tutorial/path-params.md
@@ -46,16 +46,18 @@ But if you go to the browser at ../../../docs_src/query_params_str_validations/tutorial001_py310.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="9"
{!> ../../../docs_src/query_params_str_validations/tutorial001.py!}
@@ -42,7 +42,7 @@ To achieve that, first import:
{!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
In versions of Python below Python 3.9 you import `Annotated` from `typing_extensions`.
@@ -73,7 +73,7 @@ We had this type annotation:
q: str | None = None
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python
q: Union[str, None] = None
@@ -87,7 +87,7 @@ What we will do is wrap that with `Annotated`, so it becomes:
q: Annotated[str | None] = None
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python
q: Annotated[Union[str, None]] = None
@@ -107,7 +107,7 @@ Now that we have this `Annotated` where we can put more metadata, add `Query` to
{!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="10"
{!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!}
@@ -138,7 +138,7 @@ This is how you would use `Query()` as the default value of your function parame
{!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="9"
{!> ../../../docs_src/query_params_str_validations/tutorial002.py!}
@@ -173,7 +173,7 @@ q: str | None = None
But it declares it explicitly as being a query parameter.
!!! info
- Have in mind that the most important part to make a parameter optional is the part:
+ Keep in mind that the most important part to make a parameter optional is the part:
```Python
= None
@@ -199,7 +199,7 @@ This will validate the data, show a clear error when the data is not valid, and
### `Query` as the default value or in `Annotated`
-Have in mind that when using `Query` inside of `Annotated` you cannot use the `default` parameter for `Query`.
+Keep in mind that when using `Query` inside of `Annotated` you cannot use the `default` parameter for `Query`.
Instead use the actual default value of the function parameter. Otherwise, it would be inconsistent.
@@ -251,7 +251,7 @@ You can also add a parameter `min_length`:
{!> ../../../docs_src/query_params_str_validations/tutorial003_an_py39.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="11"
{!> ../../../docs_src/query_params_str_validations/tutorial003_an.py!}
@@ -266,7 +266,7 @@ You can also add a parameter `min_length`:
{!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!}
```
-=== "Python 3.6+ non-Annotated"
+=== "Python 3.8+ non-Annotated"
!!! tip
Prefer to use the `Annotated` version if possible.
@@ -291,7 +291,7 @@ You can define a ../../../docs_src/query_params_str_validations/tutorial004_an.py!}
@@ -306,7 +306,7 @@ You can define a ../../../docs_src/query_params_str_validations/tutorial005_an_py39.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="8"
{!> ../../../docs_src/query_params_str_validations/tutorial005_an.py!}
```
-=== "Python 3.6+ non-Annotated"
+=== "Python 3.8+ non-Annotated"
!!! tip
Prefer to use the `Annotated` version if possible.
@@ -405,13 +405,13 @@ So, when you need to declare a value as required while using `Query`, you can si
{!> ../../../docs_src/query_params_str_validations/tutorial006_an_py39.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="8"
{!> ../../../docs_src/query_params_str_validations/tutorial006_an.py!}
```
-=== "Python 3.6+ non-Annotated"
+=== "Python 3.8+ non-Annotated"
!!! tip
Prefer to use the `Annotated` version if possible.
@@ -435,13 +435,13 @@ There's an alternative way to explicitly declare that a value is required. You c
{!> ../../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="8"
{!> ../../../docs_src/query_params_str_validations/tutorial006b_an.py!}
```
-=== "Python 3.6+ non-Annotated"
+=== "Python 3.8+ non-Annotated"
!!! tip
Prefer to use the `Annotated` version if possible.
@@ -475,7 +475,7 @@ To do that, you can declare that `None` is a valid type but still use `...` as t
{!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="10"
{!> ../../../docs_src/query_params_str_validations/tutorial006c_an.py!}
@@ -490,7 +490,7 @@ To do that, you can declare that `None` is a valid type but still use `...` as t
{!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!}
```
-=== "Python 3.6+ non-Annotated"
+=== "Python 3.8+ non-Annotated"
!!! tip
Prefer to use the `Annotated` version if possible.
@@ -502,33 +502,8 @@ To do that, you can declare that `None` is a valid type but still use `...` as t
!!! tip
Pydantic, which is what powers all the data validation and serialization in FastAPI, has a special behavior when you use `Optional` or `Union[Something, None]` without a default value, you can read more about it in the Pydantic docs about Required Optional fields.
-### Use Pydantic's `Required` instead of Ellipsis (`...`)
-
-If you feel uncomfortable using `...`, you can also import and use `Required` from Pydantic:
-
-=== "Python 3.9+"
-
- ```Python hl_lines="4 10"
- {!> ../../../docs_src/query_params_str_validations/tutorial006d_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="2 9"
- {!> ../../../docs_src/query_params_str_validations/tutorial006d_an.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="2 8"
- {!> ../../../docs_src/query_params_str_validations/tutorial006d.py!}
- ```
-
!!! tip
- Remember that in most of the cases, when something is required, you can simply omit the default, so you normally don't have to use `...` nor `Required`.
+ Remember that in most of the cases, when something is required, you can simply omit the default, so you normally don't have to use `...`.
## Query parameter list / multiple values
@@ -548,7 +523,7 @@ For example, to declare a query parameter `q` that can appear multiple times in
{!> ../../../docs_src/query_params_str_validations/tutorial011_an_py39.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="10"
{!> ../../../docs_src/query_params_str_validations/tutorial011_an.py!}
@@ -572,7 +547,7 @@ For example, to declare a query parameter `q` that can appear multiple times in
{!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!}
```
-=== "Python 3.6+ non-Annotated"
+=== "Python 3.8+ non-Annotated"
!!! tip
Prefer to use the `Annotated` version if possible.
@@ -617,7 +592,7 @@ And you can also define a default `list` of values if none are provided:
{!> ../../../docs_src/query_params_str_validations/tutorial012_an_py39.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="10"
{!> ../../../docs_src/query_params_str_validations/tutorial012_an.py!}
@@ -632,7 +607,7 @@ And you can also define a default `list` of values if none are provided:
{!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!}
```
-=== "Python 3.6+ non-Annotated"
+=== "Python 3.8+ non-Annotated"
!!! tip
Prefer to use the `Annotated` version if possible.
@@ -668,13 +643,13 @@ You can also use `list` directly instead of `List[str]` (or `list[str]` in Pytho
{!> ../../../docs_src/query_params_str_validations/tutorial013_an_py39.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="8"
{!> ../../../docs_src/query_params_str_validations/tutorial013_an.py!}
```
-=== "Python 3.6+ non-Annotated"
+=== "Python 3.8+ non-Annotated"
!!! tip
Prefer to use the `Annotated` version if possible.
@@ -684,7 +659,7 @@ You can also use `list` directly instead of `List[str]` (or `list[str]` in Pytho
```
!!! note
- Have in mind that in this case, FastAPI won't check the contents of the list.
+ Keep in mind that in this case, FastAPI won't check the contents of the list.
For example, `List[int]` would check (and document) that the contents of the list are integers. But `list` alone wouldn't.
@@ -695,7 +670,7 @@ You can add more information about the parameter.
That information will be included in the generated OpenAPI and used by the documentation user interfaces and external tools.
!!! note
- Have in mind that different tools might have different levels of OpenAPI support.
+ Keep in mind that different tools might have different levels of OpenAPI support.
Some of them might not show all the extra information declared yet, although in most of the cases, the missing feature is already planned for development.
@@ -713,7 +688,7 @@ You can add a `title`:
{!> ../../../docs_src/query_params_str_validations/tutorial007_an_py39.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="11"
{!> ../../../docs_src/query_params_str_validations/tutorial007_an.py!}
@@ -728,7 +703,7 @@ You can add a `title`:
{!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!}
```
-=== "Python 3.6+ non-Annotated"
+=== "Python 3.8+ non-Annotated"
!!! tip
Prefer to use the `Annotated` version if possible.
@@ -751,7 +726,7 @@ And a `description`:
{!> ../../../docs_src/query_params_str_validations/tutorial008_an_py39.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="15"
{!> ../../../docs_src/query_params_str_validations/tutorial008_an.py!}
@@ -762,11 +737,11 @@ And a `description`:
!!! tip
Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="12"
+ ```Python hl_lines="11"
{!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!}
```
-=== "Python 3.6+ non-Annotated"
+=== "Python 3.8+ non-Annotated"
!!! tip
Prefer to use the `Annotated` version if possible.
@@ -805,7 +780,7 @@ Then you can declare an `alias`, and that alias is what will be used to find the
{!> ../../../docs_src/query_params_str_validations/tutorial009_an_py39.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="10"
{!> ../../../docs_src/query_params_str_validations/tutorial009_an.py!}
@@ -820,7 +795,7 @@ Then you can declare an `alias`, and that alias is what will be used to find the
{!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!}
```
-=== "Python 3.6+ non-Annotated"
+=== "Python 3.8+ non-Annotated"
!!! tip
Prefer to use the `Annotated` version if possible.
@@ -849,7 +824,7 @@ Then pass the parameter `deprecated=True` to `Query`:
{!> ../../../docs_src/query_params_str_validations/tutorial010_an_py39.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="20"
{!> ../../../docs_src/query_params_str_validations/tutorial010_an.py!}
@@ -860,11 +835,11 @@ Then pass the parameter `deprecated=True` to `Query`:
!!! tip
Prefer to use the `Annotated` version if possible.
- ```Python hl_lines="17"
+ ```Python hl_lines="16"
{!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!}
```
-=== "Python 3.6+ non-Annotated"
+=== "Python 3.8+ non-Annotated"
!!! tip
Prefer to use the `Annotated` version if possible.
@@ -893,7 +868,7 @@ To exclude a query parameter from the generated OpenAPI schema (and thus, from t
{!> ../../../docs_src/query_params_str_validations/tutorial014_an_py39.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="11"
{!> ../../../docs_src/query_params_str_validations/tutorial014_an.py!}
@@ -908,7 +883,7 @@ To exclude a query parameter from the generated OpenAPI schema (and thus, from t
{!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!}
```
-=== "Python 3.6+ non-Annotated"
+=== "Python 3.8+ non-Annotated"
!!! tip
Prefer to use the `Annotated` version if possible.
@@ -932,7 +907,7 @@ Validations specific for strings:
* `min_length`
* `max_length`
-* `regex`
+* `pattern`
In these examples you saw how to declare validations for `str` values.
diff --git a/docs/en/docs/tutorial/query-params.md b/docs/en/docs/tutorial/query-params.md
index 0b74b10f8..bc3b11948 100644
--- a/docs/en/docs/tutorial/query-params.md
+++ b/docs/en/docs/tutorial/query-params.md
@@ -69,7 +69,7 @@ The same way, you can declare optional query parameters, by setting their defaul
{!> ../../../docs_src/query_params/tutorial002_py310.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="9"
{!> ../../../docs_src/query_params/tutorial002.py!}
@@ -90,7 +90,7 @@ You can also declare `bool` types, and they will be converted:
{!> ../../../docs_src/query_params/tutorial003_py310.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="9"
{!> ../../../docs_src/query_params/tutorial003.py!}
@@ -143,7 +143,7 @@ They will be detected by name:
{!> ../../../docs_src/query_params/tutorial004_py310.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="8 10"
{!> ../../../docs_src/query_params/tutorial004.py!}
@@ -173,16 +173,18 @@ http://127.0.0.1:8000/items/foo-item
```JSON
{
- "detail": [
- {
- "loc": [
- "query",
- "needy"
- ],
- "msg": "field required",
- "type": "value_error.missing"
- }
- ]
+ "detail": [
+ {
+ "type": "missing",
+ "loc": [
+ "query",
+ "needy"
+ ],
+ "msg": "Field required",
+ "input": null,
+ "url": "https://errors.pydantic.dev/2.1/v/missing"
+ }
+ ]
}
```
@@ -209,7 +211,7 @@ And of course, you can define some parameters as required, some as having a defa
{!> ../../../docs_src/query_params/tutorial006_py310.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="10"
{!> ../../../docs_src/query_params/tutorial006.py!}
diff --git a/docs/en/docs/tutorial/request-files.md b/docs/en/docs/tutorial/request-files.md
index 1fe1e7a33..8eb8ace64 100644
--- a/docs/en/docs/tutorial/request-files.md
+++ b/docs/en/docs/tutorial/request-files.md
@@ -19,13 +19,13 @@ Import `File` and `UploadFile` from `fastapi`:
{!> ../../../docs_src/request_files/tutorial001_an_py39.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="1"
{!> ../../../docs_src/request_files/tutorial001_an.py!}
```
-=== "Python 3.6+ non-Annotated"
+=== "Python 3.8+ non-Annotated"
!!! tip
Prefer to use the `Annotated` version if possible.
@@ -44,13 +44,13 @@ Create file parameters the same way you would for `Body` or `Form`:
{!> ../../../docs_src/request_files/tutorial001_an_py39.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="8"
{!> ../../../docs_src/request_files/tutorial001_an.py!}
```
-=== "Python 3.6+ non-Annotated"
+=== "Python 3.8+ non-Annotated"
!!! tip
Prefer to use the `Annotated` version if possible.
@@ -71,7 +71,7 @@ The files will be uploaded as "form data".
If you declare the type of your *path operation function* parameter as `bytes`, **FastAPI** will read the file for you and you will receive the contents as `bytes`.
-Have in mind that this means that the whole contents will be stored in memory. This will work well for small files.
+Keep in mind that this means that the whole contents will be stored in memory. This will work well for small files.
But there are several cases in which you might benefit from using `UploadFile`.
@@ -85,13 +85,13 @@ Define a file parameter with a type of `UploadFile`:
{!> ../../../docs_src/request_files/tutorial001_an_py39.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="13"
{!> ../../../docs_src/request_files/tutorial001_an.py!}
```
-=== "Python 3.6+ non-Annotated"
+=== "Python 3.8+ non-Annotated"
!!! tip
Prefer to use the `Annotated` version if possible.
@@ -181,7 +181,7 @@ You can make a file optional by using standard type annotations and setting a de
{!> ../../../docs_src/request_files/tutorial001_02_an_py39.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="10 18"
{!> ../../../docs_src/request_files/tutorial001_02_an.py!}
@@ -196,7 +196,7 @@ You can make a file optional by using standard type annotations and setting a de
{!> ../../../docs_src/request_files/tutorial001_02_py310.py!}
```
-=== "Python 3.6+ non-Annotated"
+=== "Python 3.8+ non-Annotated"
!!! tip
Prefer to use the `Annotated` version if possible.
@@ -215,13 +215,13 @@ You can also use `File()` with `UploadFile`, for example, to set additional meta
{!> ../../../docs_src/request_files/tutorial001_03_an_py39.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="8 14"
{!> ../../../docs_src/request_files/tutorial001_03_an.py!}
```
-=== "Python 3.6+ non-Annotated"
+=== "Python 3.8+ non-Annotated"
!!! tip
Prefer to use the `Annotated` version if possible.
@@ -244,7 +244,7 @@ To use that, declare a list of `bytes` or `UploadFile`:
{!> ../../../docs_src/request_files/tutorial002_an_py39.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="11 16"
{!> ../../../docs_src/request_files/tutorial002_an.py!}
@@ -259,7 +259,7 @@ To use that, declare a list of `bytes` or `UploadFile`:
{!> ../../../docs_src/request_files/tutorial002_py39.py!}
```
-=== "Python 3.6+ non-Annotated"
+=== "Python 3.8+ non-Annotated"
!!! tip
Prefer to use the `Annotated` version if possible.
@@ -285,7 +285,7 @@ And the same way as before, you can use `File()` to set additional parameters, e
{!> ../../../docs_src/request_files/tutorial003_an_py39.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="12 19-21"
{!> ../../../docs_src/request_files/tutorial003_an.py!}
@@ -300,7 +300,7 @@ And the same way as before, you can use `File()` to set additional parameters, e
{!> ../../../docs_src/request_files/tutorial003_py39.py!}
```
-=== "Python 3.6+ non-Annotated"
+=== "Python 3.8+ non-Annotated"
!!! tip
Prefer to use the `Annotated` version if possible.
diff --git a/docs/en/docs/tutorial/request-forms-and-files.md b/docs/en/docs/tutorial/request-forms-and-files.md
index 1818946c4..a58291dc8 100644
--- a/docs/en/docs/tutorial/request-forms-and-files.md
+++ b/docs/en/docs/tutorial/request-forms-and-files.md
@@ -15,13 +15,13 @@ You can define files and form fields at the same time using `File` and `Form`.
{!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="1"
{!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!}
```
-=== "Python 3.6+ non-Annotated"
+=== "Python 3.8+ non-Annotated"
!!! tip
Prefer to use the `Annotated` version if possible.
@@ -40,13 +40,13 @@ Create file and form parameters the same way you would for `Body` or `Query`:
{!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="9-11"
{!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!}
```
-=== "Python 3.6+ non-Annotated"
+=== "Python 3.8+ non-Annotated"
!!! tip
Prefer to use the `Annotated` version if possible.
diff --git a/docs/en/docs/tutorial/request-forms.md b/docs/en/docs/tutorial/request-forms.md
index 5d441a614..0e8ac5f4f 100644
--- a/docs/en/docs/tutorial/request-forms.md
+++ b/docs/en/docs/tutorial/request-forms.md
@@ -17,13 +17,13 @@ Import `Form` from `fastapi`:
{!> ../../../docs_src/request_forms/tutorial001_an_py39.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="1"
{!> ../../../docs_src/request_forms/tutorial001_an.py!}
```
-=== "Python 3.6+ non-Annotated"
+=== "Python 3.8+ non-Annotated"
!!! tip
Prefer to use the `Annotated` version if possible.
@@ -42,13 +42,13 @@ Create form parameters the same way you would for `Body` or `Query`:
{!> ../../../docs_src/request_forms/tutorial001_an_py39.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="8"
{!> ../../../docs_src/request_forms/tutorial001_an.py!}
```
-=== "Python 3.6+ non-Annotated"
+=== "Python 3.8+ non-Annotated"
!!! tip
Prefer to use the `Annotated` version if possible.
diff --git a/docs/en/docs/tutorial/response-model.md b/docs/en/docs/tutorial/response-model.md
index 2181cfb5a..d5683ac7f 100644
--- a/docs/en/docs/tutorial/response-model.md
+++ b/docs/en/docs/tutorial/response-model.md
@@ -16,7 +16,7 @@ You can use **type annotations** the same way you would for input data in functi
{!> ../../../docs_src/response_model/tutorial001_01_py39.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="18 23"
{!> ../../../docs_src/response_model/tutorial001_01.py!}
@@ -65,7 +65,7 @@ You can use the `response_model` parameter in any of the *path operations*:
{!> ../../../docs_src/response_model/tutorial001_py39.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="17 22 24-27"
{!> ../../../docs_src/response_model/tutorial001.py!}
@@ -101,7 +101,7 @@ Here we are declaring a `UserIn` model, it will contain a plaintext password:
{!> ../../../docs_src/response_model/tutorial002_py310.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="9 11"
{!> ../../../docs_src/response_model/tutorial002.py!}
@@ -121,7 +121,7 @@ And we are using this model to declare our input and the same model to declare o
{!> ../../../docs_src/response_model/tutorial002_py310.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="18"
{!> ../../../docs_src/response_model/tutorial002.py!}
@@ -146,7 +146,7 @@ We can instead create an input model with the plaintext password and an output m
{!> ../../../docs_src/response_model/tutorial003_py310.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="9 11 16"
{!> ../../../docs_src/response_model/tutorial003.py!}
@@ -160,7 +160,7 @@ Here, even though our *path operation function* is returning the same input user
{!> ../../../docs_src/response_model/tutorial003_py310.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="24"
{!> ../../../docs_src/response_model/tutorial003.py!}
@@ -174,7 +174,7 @@ Here, even though our *path operation function* is returning the same input user
{!> ../../../docs_src/response_model/tutorial003_py310.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="22"
{!> ../../../docs_src/response_model/tutorial003.py!}
@@ -208,7 +208,7 @@ And in those cases, we can use classes and inheritance to take advantage of func
{!> ../../../docs_src/response_model/tutorial003_01_py310.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="9-13 15-16 20"
{!> ../../../docs_src/response_model/tutorial003_01.py!}
@@ -284,7 +284,7 @@ The same would happen if you had something like a its `exclude_unset` parameter to achieve this.
@@ -447,7 +452,7 @@ This can be used as a quick shortcut if you have only one Pydantic model and wan
{!> ../../../docs_src/response_model/tutorial005_py310.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="31 37"
{!> ../../../docs_src/response_model/tutorial005.py!}
@@ -468,7 +473,7 @@ If you forget to use a `set` and use a `list` or `tuple` instead, FastAPI will s
{!> ../../../docs_src/response_model/tutorial006_py310.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="31 37"
{!> ../../../docs_src/response_model/tutorial006.py!}
diff --git a/docs/en/docs/tutorial/schema-extra-example.md b/docs/en/docs/tutorial/schema-extra-example.md
index 39d184763..9bb9ba4e3 100644
--- a/docs/en/docs/tutorial/schema-extra-example.md
+++ b/docs/en/docs/tutorial/schema-extra-example.md
@@ -20,13 +20,13 @@ You can declare `examples` for a Pydantic model that will be added to the genera
{!> ../../../docs_src/schema_extra_example/tutorial001_py310_pv1.py!}
```
-=== "Python 3.6+ Pydantic v2"
+=== "Python 3.8+ Pydantic v2"
```Python hl_lines="15-26"
{!> ../../../docs_src/schema_extra_example/tutorial001.py!}
```
-=== "Python 3.6+ Pydantic v1"
+=== "Python 3.8+ Pydantic v1"
```Python hl_lines="15-25"
{!> ../../../docs_src/schema_extra_example/tutorial001_pv1.py!}
@@ -38,13 +38,13 @@ That extra info will be added as-is to the output **JSON Schema** for that model
In Pydantic version 2, you would use the attribute `model_config`, that takes a `dict` as described in Pydantic's docs: Model Config.
- You can set `"json_schema_extra"` with a `dict` containing any additonal 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.
- You can set `schema_extra` with a `dict` containing any additonal data you would like to show up in the generated JSON Schema, including `examples`.
+ You can set `schema_extra` with a `dict` containing any additional data you would like to show up in the generated JSON Schema, including `examples`.
!!! tip
You could use the same technique to extend the JSON Schema and add your own custom extra info.
@@ -68,13 +68,13 @@ When using `Field()` with Pydantic models, you can also declare additional `exam
{!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="4 10-13"
{!> ../../../docs_src/schema_extra_example/tutorial002.py!}
```
-## `examples` in OpenAPI
+## `examples` in JSON Schema - OpenAPI
When using any of:
@@ -86,7 +86,7 @@ When using any of:
* `Form()`
* `File()`
-you can also declare a group of `examples` with additional information that will be added to **OpenAPI**.
+you can also declare a group of `examples` with additional information that will be added to their **JSON Schemas** inside of **OpenAPI**.
### `Body` with `examples`
@@ -104,7 +104,7 @@ Here we pass `examples` containing one example of the data expected in `Body()`:
{!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="23-30"
{!> ../../../docs_src/schema_extra_example/tutorial003_an.py!}
@@ -119,7 +119,7 @@ Here we pass `examples` containing one example of the data expected in `Body()`:
{!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!}
```
-=== "Python 3.6+ non-Annotated"
+=== "Python 3.8+ non-Annotated"
!!! tip
Prefer to use the `Annotated` version if possible.
@@ -150,7 +150,7 @@ You can of course also pass multiple `examples`:
{!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="24-39"
{!> ../../../docs_src/schema_extra_example/tutorial004_an.py!}
@@ -165,7 +165,7 @@ You can of course also pass multiple `examples`:
{!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!}
```
-=== "Python 3.6+ non-Annotated"
+=== "Python 3.8+ non-Annotated"
!!! tip
Prefer to use the `Annotated` version if possible.
@@ -174,9 +174,84 @@ You can of course also pass multiple `examples`:
{!> ../../../docs_src/schema_extra_example/tutorial004.py!}
```
-### Examples in the docs UI
+When you do this, the examples will be part of the internal **JSON Schema** for that body data.
-With `examples` added to `Body()` the `/docs` would look like:
+Nevertheless, at the time of writing this, Swagger UI, the tool in charge of showing the docs UI, doesn't support showing multiple examples for the data in **JSON Schema**. But read below for a workaround.
+
+### OpenAPI-specific `examples`
+
+Since before **JSON Schema** supported `examples` OpenAPI had support for a different field also called `examples`.
+
+This **OpenAPI-specific** `examples` goes in another section in the OpenAPI specification. It goes in the **details for each *path operation***, not inside each JSON Schema.
+
+And Swagger UI has supported this particular `examples` field for a while. So, you can use it to **show** different **examples in the docs UI**.
+
+The shape of this OpenAPI-specific field `examples` is a `dict` with **multiple examples** (instead of a `list`), each with extra information that will be added to **OpenAPI** too.
+
+This doesn't go inside of each JSON Schema contained in OpenAPI, this goes outside, in the *path operation* directly.
+
+### Using the `openapi_examples` Parameter
+
+You can declare the OpenAPI-specific `examples` in FastAPI with the parameter `openapi_examples` for:
+
+* `Path()`
+* `Query()`
+* `Header()`
+* `Cookie()`
+* `Body()`
+* `Form()`
+* `File()`
+
+The keys of the `dict` identify each example, and each value is another `dict`.
+
+Each specific example `dict` in the `examples` can contain:
+
+* `summary`: Short description for the example.
+* `description`: A long description that can contain Markdown text.
+* `value`: This is the actual example shown, e.g. a `dict`.
+* `externalValue`: alternative to `value`, a URL pointing to the example. Although this might not be supported by as many tools as `value`.
+
+You can use it like this:
+
+=== "Python 3.10+"
+
+ ```Python hl_lines="23-49"
+ {!> ../../../docs_src/schema_extra_example/tutorial005_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="23-49"
+ {!> ../../../docs_src/schema_extra_example/tutorial005_an_py39.py!}
+ ```
+
+=== "Python 3.8+"
+
+ ```Python hl_lines="24-50"
+ {!> ../../../docs_src/schema_extra_example/tutorial005_an.py!}
+ ```
+
+=== "Python 3.10+ non-Annotated"
+
+ !!! tip
+ Prefer to use the `Annotated` version if possible.
+
+ ```Python hl_lines="19-45"
+ {!> ../../../docs_src/schema_extra_example/tutorial005_py310.py!}
+ ```
+
+=== "Python 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
+
+With `openapi_examples` added to `Body()` the `/docs` would look like:
async def
... نیز استفاده کنیدuvicorn main:app --reload
...jinja2
- در صورتی که بخواهید از پیکربندی پیشفرض برای قالبها استفاده کنید.
* python-multipart
- در صورتی که بخواهید با استفاده از `request.form()` از قابلیت "تجزیه (parse)" فرم استفاده کنید.
* itsdangerous
- در صورتی که بخواید از `SessionMiddleware` پشتیبانی کنید.
-* pyyaml
- برای پشتیبانی `SchemaGenerator` در Starlet (به احتمال زیاد برای کار کردن با FastAPI به آن نیازی پیدا نمیکنید.).
+* pyyaml
- برای پشتیبانی `SchemaGenerator` در Starlet (به احتمال زیاد برای کار کردن با FastAPI به آن نیازی پیدا نمیکنید).
* graphene
- در صورتی که از `GraphQLApp` پشتیبانی میکنید.
* ujson
- در صورتی که بخواهید از `UJSONResponse` استفاده کنید.
diff --git a/docs/fa/docs/tutorial/middleware.md b/docs/fa/docs/tutorial/middleware.md
new file mode 100644
index 000000000..c5752a4b5
--- /dev/null
+++ b/docs/fa/docs/tutorial/middleware.md
@@ -0,0 +1,59 @@
+# میانافزار - middleware
+
+شما میتوانید میانافزارها را در **FastAPI** اضافه کنید.
+
+"میانافزار" یک تابع است که با هر درخواست(request) قبل از پردازش توسط هر path operation (عملیات مسیر) خاص کار میکند. همچنین با هر پاسخ(response) قبل از بازگشت آن نیز کار میکند.
+
+* هر **درخواستی (request)** که به برنامه شما می آید را می گیرد.
+* سپس می تواند کاری برای آن **درخواست** انجام دهید یا هر کد مورد نیازتان را اجرا کنید.
+* سپس **درخواست** را به بخش دیگری از برنامه (توسط یک path operation مشخص) برای پردازش ارسال می کند.
+* سپس **پاسخ** تولید شده توسط برنامه را (توسط یک path operation مشخص) دریافت میکند.
+* می تواند کاری با **پاسخ** انجام دهید یا هر کد مورد نیازتان را اجرا کند.
+* سپس **پاسخ** را برمی گرداند.
+
+!!! توجه "جزئیات فنی"
+ در صورت وجود وابستگی هایی با `yield`، کد خروجی **پس از** اجرای میانافزار اجرا خواهد شد.
+
+ در صورت وجود هر گونه وظایف پس زمینه (که در ادامه توضیح داده میشوند)، تمام میانافزارها *پس از آن* اجرا خواهند شد.
+
+## ساخت یک میان افزار
+
+برای ایجاد یک میانافزار، از دکوریتور `@app.middleware("http")` در بالای یک تابع استفاده میشود.
+
+تابع میان افزار دریافت می کند:
+* `درخواست`
+* تابع `call_next` که `درخواست` را به عنوان پارامتر دریافت می کند
+ * این تابع `درخواست` را به *path operation* مربوطه ارسال می کند.
+ * سپس `پاسخ` تولید شده توسط *path operation* مربوطه را برمیگرداند.
+* شما میتوانید سپس `پاسخ` را تغییر داده و پس از آن را برگردانید.
+
+```Python hl_lines="8-9 11 14"
+{!../../../docs_src/middleware/tutorial001.py!}
+```
+
+!!! نکته به خاطر داشته باشید که هدرهای اختصاصی سفارشی را می توان با استفاده از پیشوند "X-" اضافه کرد.
+
+ اما اگر هدرهای سفارشی دارید که میخواهید مرورگر کاربر بتواند آنها را ببیند، باید آنها را با استفاده از پارامتر `expose_headers` که در مستندات CORS از Starlette توضیح داده شده است، به پیکربندی CORS خود اضافه کنید.
+
+!!! توجه "جزئیات فنی"
+ شما همچنین میتوانید از `from starlette.requests import Request` استفاده کنید.
+
+ **FastAPI** این را به عنوان یک سهولت برای شما به عنوان برنامهنویس فراهم میکند. اما این مستقیما از Starlette به دست میآید.
+
+### قبل و بعد از `پاسخ`
+
+شما میتوانید کدی را برای اجرا با `درخواست`، قبل از اینکه هر *path operation* آن را دریافت کند، اضافه کنید.
+
+همچنین پس از تولید `پاسخ`، قبل از بازگشت آن، میتوانید کدی را اضافه کنید.
+
+به عنوان مثال، میتوانید یک هدر سفارشی به نام `X-Process-Time` که شامل زمان پردازش درخواست و تولید پاسخ به صورت ثانیه است، اضافه کنید.
+
+```Python hl_lines="10 12-13"
+{!../../../docs_src/middleware/tutorial001.py!}
+```
+
+ ## سایر میان افزار
+
+شما میتوانید بعداً در مورد میانافزارهای دیگر در [راهنمای کاربر پیشرفته: میانافزار پیشرفته](../advanced/middleware.md){.internal-link target=_blank} بیشتر بخوانید.
+
+شما در بخش بعدی در مورد این که چگونه با استفاده از یک میانافزار، CORS را مدیریت کنید، خواهید خواند.
diff --git a/docs/fa/docs/tutorial/security/index.md b/docs/fa/docs/tutorial/security/index.md
new file mode 100644
index 000000000..4e68ba961
--- /dev/null
+++ b/docs/fa/docs/tutorial/security/index.md
@@ -0,0 +1,100 @@
+# امنیت
+
+روشهای مختلفی برای مدیریت امنیت، تأیید هویت و اعتبارسنجی وجود دارد.
+
+عموماً این یک موضوع پیچیده و "سخت" است.
+
+در بسیاری از فریم ورک ها و سیستمها، فقط مدیریت امنیت و تأیید هویت نیاز به تلاش و کد نویسی زیادی دارد (در بسیاری از موارد میتواند 50% یا بیشتر کل کد نوشته شده باشد).
+
+
+فریم ورک **FastAPI** ابزارهای متعددی را در اختیار شما قرار می دهد تا به راحتی، با سرعت، به صورت استاندارد و بدون نیاز به مطالعه و یادگیری همه جزئیات امنیت، در مدیریت **امنیت** به شما کمک کند.
+
+اما قبل از آن، بیایید برخی از مفاهیم کوچک را بررسی کنیم.
+
+## عجله دارید؟
+
+اگر به هیچ یک از این اصطلاحات اهمیت نمی دهید و فقط نیاز به افزودن امنیت با تأیید هویت بر اساس نام کاربری و رمز عبور دارید، *همین الان* به فصل های بعدی بروید.
+
+## پروتکل استاندارد OAuth2
+
+پروتکل استاندارد OAuth2 یک مشخصه است که چندین روش برای مدیریت تأیید هویت و اعتبار سنجی تعریف می کند.
+
+این مشخصه بسیار گسترده است و چندین حالت استفاده پیچیده را پوشش می دهد.
+
+در آن روش هایی برای تأیید هویت با استفاده از "برنامه های شخص ثالث" وجود دارد.
+
+این همان چیزی است که تمامی سیستم های با "ورود با فیسبوک، گوگل، توییتر، گیت هاب" در پایین آن را استفاده می کنند.
+
+### پروتکل استاندارد OAuth 1
+
+پروتکل استاندارد OAuth1 نیز وجود داشت که با OAuth2 خیلی متفاوت است و پیچیدگی بیشتری داشت، زیرا شامل مشخصات مستقیم در مورد رمزگذاری ارتباط بود.
+
+در حال حاضر OAuth1 بسیار محبوب یا استفاده شده نیست.
+
+پروتکل استاندارد OAuth2 روش رمزگذاری ارتباط را مشخص نمی کند، بلکه انتظار دارد که برنامه شما با HTTPS سرویس دهی شود.
+
+!!! نکته
+ در بخش در مورد **استقرار** ، شما یاد خواهید گرفت که چگونه با استفاده از Traefik و Let's Encrypt رایگان HTTPS را راه اندازی کنید.
+
+## استاندارد OpenID Connect
+
+استاندارد OpenID Connect، مشخصهای دیگر است که بر پایه **OAuth2** ساخته شده است.
+
+این مشخصه، به گسترش OAuth2 میپردازد و برخی مواردی که در OAuth2 نسبتاً تردید برانگیز هستند را مشخص میکند تا سعی شود آن را با سایر سیستمها قابل ارتباط کند.
+
+به عنوان مثال، ورود به سیستم گوگل از OpenID Connect استفاده میکند (که در زیر از OAuth2 استفاده میکند).
+
+اما ورود به سیستم فیسبوک، از OpenID Connect پشتیبانی نمیکند. به جای آن، نسخه خودش از OAuth2 را دارد.
+
+### استاندارد OpenID (نه "OpenID Connect" )
+
+همچنین مشخصه "OpenID" نیز وجود داشت که سعی در حل مسائل مشابه OpenID Connect داشت، اما بر پایه OAuth2 ساخته نشده بود.
+
+بنابراین، یک سیستم جداگانه بود.
+
+اکنون این مشخصه کمتر استفاده میشود و محبوبیت زیادی ندارد.
+
+## استاندارد OpenAPI
+
+استاندارد OpenAPI (قبلاً با نام Swagger شناخته میشد) یک open specification برای ساخت APIs (که در حال حاضر جزئی از بنیاد لینوکس میباشد) است.
+
+فریم ورک **FastAPI** بر اساس **OpenAPI** است.
+
+این خاصیت، امکان دارد تا چندین رابط مستندات تعاملی خودکار(automatic interactive documentation interfaces)، تولید کد و غیره وجود داشته باشد.
+
+مشخصه OpenAPI روشی برای تعریف چندین "schemes" دارد.
+
+با استفاده از آنها، شما میتوانید از همه این ابزارهای مبتنی بر استاندارد استفاده کنید، از جمله این سیستمهای مستندات تعاملی(interactive documentation systems).
+
+استاندارد OpenAPI شیوههای امنیتی زیر را تعریف میکند:
+
+* شیوه `apiKey`: یک کلید اختصاصی برای برنامه که میتواند از موارد زیر استفاده شود:
+ * پارامتر جستجو.
+ * هدر.
+ * کوکی.
+* شیوه `http`: سیستمهای استاندارد احراز هویت HTTP، از جمله:
+ * مقدار `bearer`: یک هدر `Authorization` با مقدار `Bearer` به همراه یک توکن. این از OAuth2 به ارث برده شده است.
+ * احراز هویت پایه HTTP.
+ * ویژگی HTTP Digest و غیره.
+* شیوه `oauth2`: تمام روشهای OAuth2 برای مدیریت امنیت (به نام "flows").
+ * چندین از این flows برای ساخت یک ارائهدهنده احراز هویت OAuth 2.0 مناسب هستند (مانند گوگل، فیسبوک، توییتر، گیتهاب و غیره):
+ * ویژگی `implicit`
+ * ویژگی `clientCredentials`
+ * ویژگی `authorizationCode`
+ * اما یک "flow" خاص وجود دارد که میتواند به طور کامل برای مدیریت احراز هویت در همان برنامه به کار رود:
+ * بررسی `password`: چند فصل بعدی به مثالهای این مورد خواهیم پرداخت.
+* شیوه `openIdConnect`: یک روش برای تعریف نحوه کشف دادههای احراز هویت OAuth2 به صورت خودکار.
+ * کشف خودکار این موضوع را که در مشخصه OpenID Connect تعریف شده است، مشخص میکند.
+
+!!! نکته
+ ادغام سایر ارائهدهندگان احراز هویت/اجازهدهی مانند گوگل، فیسبوک، توییتر، گیتهاب و غیره نیز امکانپذیر و نسبتاً آسان است.
+
+ مشکل پیچیدهترین مسئله، ساخت یک ارائهدهنده احراز هویت/اجازهدهی مانند آنها است، اما **FastAPI** ابزارهای لازم برای انجام این کار را با سهولت به شما میدهد و همه کارهای سنگین را برای شما انجام میدهد.
+
+## ابزارهای **FastAPI**
+
+فریم ورک FastAPI ابزارهایی برای هر یک از این شیوههای امنیتی در ماژول`fastapi.security` فراهم میکند که استفاده از این مکانیزمهای امنیتی را سادهتر میکند.
+
+در فصلهای بعدی، شما یاد خواهید گرفت که چگونه با استفاده از این ابزارهای ارائه شده توسط **FastAPI**، امنیت را به API خود اضافه کنید.
+
+همچنین، خواهید دید که چگونه به صورت خودکار در سیستم مستندات تعاملی ادغام میشود.
diff --git a/docs/fr/docs/advanced/path-operation-advanced-configuration.md b/docs/fr/docs/advanced/path-operation-advanced-configuration.md
index ace9f19f9..7ded97ce1 100644
--- a/docs/fr/docs/advanced/path-operation-advanced-configuration.md
+++ b/docs/fr/docs/advanced/path-operation-advanced-configuration.md
@@ -66,7 +66,7 @@ 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étaonnées des Objets d'opération.
+ 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.
diff --git a/docs/fr/docs/alternatives.md b/docs/fr/docs/alternatives.md
index ee20438c3..8e58a3dfa 100644
--- a/docs/fr/docs/alternatives.md
+++ b/docs/fr/docs/alternatives.md
@@ -387,7 +387,7 @@ Gérer toute la validation des données, leur sérialisation et la documentation
### Starlette
-Starlette est un framework/toolkit léger ASGI, qui est idéal pour construire des services asyncio performants.
+Starlette est un framework/toolkit léger ASGI, qui est idéal pour construire des services asyncio performants.
Il est très simple et intuitif. Il est conçu pour être facilement extensible et avoir des composants modulaires.
diff --git a/docs/fr/docs/async.md b/docs/fr/docs/async.md
index db88c4663..af4d6ca06 100644
--- a/docs/fr/docs/async.md
+++ b/docs/fr/docs/async.md
@@ -250,7 +250,7 @@ Par exemple :
### Concurrence + Parallélisme : Web + Machine Learning
-Avec **FastAPI** vous pouvez bénéficier de la concurrence qui est très courante en developement web (c'est l'attrait principal de NodeJS).
+Avec **FastAPI** vous pouvez bénéficier de la concurrence qui est très courante en développement web (c'est l'attrait principal de NodeJS).
Mais vous pouvez aussi profiter du parallélisme et multiprocessing afin de gérer des charges **CPU bound** qui sont récurrentes dans les systèmes de *Machine Learning*.
diff --git a/docs/fr/docs/external-links.md b/docs/fr/docs/external-links.md
index 002e6d2b2..37b8c5b13 100644
--- a/docs/fr/docs/external-links.md
+++ b/docs/fr/docs/external-links.md
@@ -9,70 +9,21 @@ Voici une liste incomplète de certains d'entre eux.
!!! tip "Astuce"
Si vous avez un article, projet, outil, ou quoi que ce soit lié à **FastAPI** qui n'est actuellement pas listé ici, créez une Pull Request l'ajoutant.
-## Articles
+{% for section_name, section_content in external_links.items() %}
-### Anglais
+## {{ section_name }}
-{% if external_links %}
-{% for article in external_links.articles.english %}
+{% for lang_name, lang_content in section_content.items() %}
-* {{ article.title }} par {{ article.author }}.
-{% endfor %}
-{% endif %}
-
-### Japonais
-
-{% if external_links %}
-{% for article in external_links.articles.japanese %}
-
-* {{ article.title }} par {{ article.author }}.
-{% endfor %}
-{% endif %}
+### {{ lang_name }}
-### Vietnamien
+{% for item in lang_content %}
-{% if external_links %}
-{% for article in external_links.articles.vietnamese %}
+* {{ item.title }} by {{ item.author }}.
-* {{ article.title }} par {{ article.author }}.
{% endfor %}
-{% endif %}
-
-### Russe
-
-{% if external_links %}
-{% for article in external_links.articles.russian %}
-
-* {{ article.title }} par {{ article.author }}.
{% endfor %}
-{% endif %}
-
-### Allemand
-
-{% if external_links %}
-{% for article in external_links.articles.german %}
-
-* {{ article.title }} par {{ article.author }}.
-{% endfor %}
-{% endif %}
-
-## Podcasts
-
-{% if external_links %}
-{% for article in external_links.podcasts.english %}
-
-* {{ article.title }} par {{ article.author }}.
-{% endfor %}
-{% endif %}
-
-## Conférences
-
-{% if external_links %}
-{% for article in external_links.talks.english %}
-
-* {{ article.title }} par {{ article.author }}.
{% endfor %}
-{% endif %}
## Projets
diff --git a/docs/fr/docs/features.md b/docs/fr/docs/features.md
index dcc0e39ed..0c1f6269a 100644
--- a/docs/fr/docs/features.md
+++ b/docs/fr/docs/features.md
@@ -25,7 +25,7 @@ Documentation d'API interactive et interface web d'exploration. Comme le framewo
### Faite en python moderne
-Tout est basé sur la déclaration de type standard de **Python 3.6** (grâce à Pydantic). Pas de nouvelles syntaxes à apprendre. Juste du Python standard et moderne.
+Tout est basé sur la déclaration de type standard de **Python 3.8** (grâce à Pydantic). Pas de nouvelles syntaxes à apprendre. Juste du Python standard et moderne.
Si vous souhaitez un rappel de 2 minutes sur l'utilisation des types en Python (même si vous ne comptez pas utiliser FastAPI), jetez un oeil au tutoriel suivant: [Python Types](python-types.md){.internal-link target=_blank}.
@@ -71,9 +71,9 @@ my_second_user: User = User(**second_user_data)
Tout le framework a été conçu pour être facile et intuitif d'utilisation, toutes les décisions de design ont été testées sur de nombreux éditeurs avant même de commencer le développement final afin d'assurer la meilleure expérience de développement possible.
-Dans le dernier sondage effectué auprès de développeurs python il était clair que la fonctionnalité la plus utilisée est "l'autocomplètion".
+Dans le dernier sondage effectué auprès de développeurs python il était clair que la fonctionnalité la plus utilisée est "l’autocomplétion".
-Tout le framwork **FastAPI** a été conçu avec cela en tête. L'autocomplétion fonctionne partout.
+Tout le framework **FastAPI** a été conçu avec cela en tête. L'autocomplétion fonctionne partout.
Vous devrez rarement revenir à la documentation.
@@ -136,7 +136,7 @@ FastAPI contient un système simple mais extrêmement puissant d'Starlette. Le code utilisant Starlette que vous ajouterez fonctionnera donc aussi.
-En fait, `FastAPI` est un sous compposant de `Starlette`. Donc, si vous savez déjà comment utiliser Starlette, la plupart des fonctionnalités fonctionneront de la même manière.
+En fait, `FastAPI` est un sous composant de `Starlette`. Donc, si vous savez déjà comment utiliser Starlette, la plupart des fonctionnalités fonctionneront de la même manière.
Avec **FastAPI** vous aurez toutes les fonctionnalités de **Starlette** (FastAPI est juste Starlette sous stéroïdes):
-* Des performances vraiments impressionnantes. C'est l'un des framework Python les plus rapide, à égalité avec **NodeJS** et **GO**.
+* Des performances vraiment impressionnantes. C'est l'un des framework Python les plus rapide, à égalité avec **NodeJS** et **GO**.
* Le support des **WebSockets**.
* Le support de **GraphQL**.
* Les tâches d'arrière-plan.
@@ -180,7 +180,7 @@ Inclus des librairies externes basées, aussi, sur Pydantic, servent d' décorateur de validation
* 100% de couverture de test.
diff --git a/docs/fr/docs/help-fastapi.md b/docs/fr/docs/help-fastapi.md
index 0995721e1..525c699f5 100644
--- a/docs/fr/docs/help-fastapi.md
+++ b/docs/fr/docs/help-fastapi.md
@@ -36,8 +36,8 @@ Vous pouvez :
* Me suivre sur **Twitter**.
* Dites-moi comment vous utilisez FastAPI (j'adore entendre ça).
* Entendre quand je fais des annonces ou que je lance de nouveaux outils.
-* Vous connectez à moi sur **Linkedin**.
- * Etre notifié quand je fais des annonces ou que je lance de nouveaux outils (bien que j'utilise plus souvent Twitte 🤷♂).
+* Vous connectez à moi sur **LinkedIn**.
+ * Etre notifié quand je fais des annonces ou que je lance de nouveaux outils (bien que j'utilise plus souvent Twitter 🤷♂).
* Lire ce que j’écris (ou me suivre) sur **Dev.to** ou **Medium**.
* Lire d'autres idées, articles, et sur les outils que j'ai créés.
* Suivez-moi pour lire quand je publie quelque chose de nouveau.
@@ -84,24 +84,6 @@ Vous pouvez
- requests
- Obligatoire si vous souhaitez utiliser `TestClient`.
-* jinja2
- Obligatoire si vous souhaitez utiliser la configuration de template par defaut.
+* jinja2
- Obligatoire si vous souhaitez utiliser la configuration de template par défaut.
* python-multipart
- Obligatoire si vous souhaitez supporter le "décodage" de formulaire avec `request.form()`.
* itsdangerous
- Obligatoire pour la prise en charge de `SessionMiddleware`.
* pyyaml
- Obligatoire pour le support `SchemaGenerator` de Starlette (vous n'en avez probablement pas besoin avec FastAPI).
diff --git a/docs/fr/docs/python-types.md b/docs/fr/docs/python-types.md
index 4008ed96f..f49fbafd3 100644
--- a/docs/fr/docs/python-types.md
+++ b/docs/fr/docs/python-types.md
@@ -119,7 +119,7 @@ Comme l'éditeur connaît le type des variables, vous n'avez pas seulement l'aut
+ FastAPI keretrendszer, nagy teljesítmény, könnyen tanulható, gyorsan kódolható, productionre kész +
+ + +--- + +**Dokumentáció**: https://fastapi.tiangolo.com + +**Forrás kód**: https://github.com/tiangolo/fastapi + +--- +A FastAPI egy modern, gyors (nagy teljesítményű), webes keretrendszer API-ok építéséhez Python 3.8+-al, a Python szabványos típusjelöléseire építve. + + +Kulcs funkciók: + +* **Gyors**: Nagyon nagy teljesítmény, a **NodeJS**-el és a **Go**-val egyenrangú (a Starlettenek és a Pydantic-nek köszönhetően). [Az egyik leggyorsabb Python keretrendszer](#performance). +* **Gyorsan kódolható**: A funkciók fejlesztési sebességét 200-300 százalékkal megnöveli. * +* **Kevesebb hiba**: Körülbelül 40%-al csökkenti az emberi (fejlesztői) hibák számát. * +* **Intuitív**: Kiváló szerkesztő támogatás. Kiegészítés mindenhol. Kevesebb hibakereséssel töltött idő. +* **Egyszerű**: Egyszerű tanulásra és használatra tervezve. Kevesebb dokumentáció olvasással töltött idő. +* **Rövid**: Kód duplikáció minimalizálása. Több funkció minden paraméter deklarálásával. Kevesebb hiba. +* **Robosztus**: Production ready kód. Automatikus interaktív dokumentáció val. +* **Szabvány alapú**: Az API-ok nyílt szabványaira alapuló (és azokkal teljesen kompatibilis): OpenAPI (korábban Swagger néven ismert) és a JSON Schema. + +* Egy production alkalmazásokat építő belső fejlesztői csapat tesztjein alapuló becslés. + +## Szponzorok + + + +{% if sponsors %} +{% for sponsor in sponsors.gold -%} +async def
-et...uvicorn main:app --reload
...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.
+
+Starlette által használt:
+
+* httpx
- Követelmény ha a `TestClient`-et akarod használni.
+* jinja2
- Követelmény ha az alap template konfigurációt akarod használni.
+* python-multipart
- Követelmény ha "parsing"-ot akarsz támogatni, `request.form()`-al.
+* itsdangerous
- Követelmény `SessionMiddleware` támogatáshoz.
+* pyyaml
- Követelmény a Starlette `SchemaGenerator`-ának támogatásához (valószínűleg erre nincs szükség FastAPI használása esetén).
+* ujson
- Követelmény ha `UJSONResponse`-t akarsz használni.
+
+FastAPI / Starlette által használt
+
+* uvicorn
- Szerverekhez amíg betöltik és szolgáltatják az applikációdat.
+* orjson
- Követelmény ha `ORJSONResponse`-t akarsz használni.
+
+Ezeket mind telepítheted a `pip install "fastapi[all]"` paranccsal.
+
+## Licensz
+Ez a projekt az MIT license, licensz alatt fut
diff --git a/docs/hu/mkdocs.yml b/docs/hu/mkdocs.yml
new file mode 100644
index 000000000..de18856f4
--- /dev/null
+++ b/docs/hu/mkdocs.yml
@@ -0,0 +1 @@
+INHERIT: ../en/mkdocs.yml
diff --git a/docs/it/docs/index.md b/docs/it/docs/index.md
new file mode 100644
index 000000000..6190eb6aa
--- /dev/null
+++ b/docs/it/docs/index.md
@@ -0,0 +1,464 @@
+
+{!../../../docs/missing-translation.md!}
+
+
+
++ FastAPI framework, alte prestazioni, facile da imparare, rapido da implementare, pronto per il rilascio in produzione +
+ + +--- + +**Documentazione**: https://fastapi.tiangolo.com + +**Codice Sorgente**: https://github.com/tiangolo/fastapi + +--- + +FastAPI è un web framework moderno e veloce (a prestazioni elevate) che serve a creare API con Python 3.6+ basato sulle annotazioni di tipo di Python. + +Le sue caratteristiche principali sono: + +* **Velocità**: Prestazioni molto elevate, alla pari di **NodeJS** e **Go** (grazie a Starlette e Pydantic). [Uno dei framework Python più veloci in circolazione](#performance). +* **Veloce da programmare**: Velocizza il lavoro consentendo il rilascio di nuove funzionalità tra il 200% e il 300% più rapidamente. * +* **Meno bug**: Riduce di circa il 40% gli errori che commettono gli sviluppatori durante la scrittura del codice. * +* **Intuitivo**: Grande supporto per gli editor di testo con autocompletamento in ogni dove. In questo modo si può dedicare meno tempo al debugging. +* **Facile**: Progettato per essere facile da usare e imparare. Si riduce il tempo da dedicare alla lettura della documentazione. +* **Sintentico**: Minimizza la duplicazione di codice. Molteplici funzionalità, ognuna con la propria dichiarazione dei parametri. Meno errori. +* **Robusto**: Crea codice pronto per la produzione con documentazione automatica interattiva. +* **Basato sugli standard**: Basato su (e completamente compatibile con) gli open standard per le API: OpenAPI (precedentemente Swagger) e JSON Schema. + +* Stima basata sull'esito di test eseguiti su codice sorgente di applicazioni rilasciate in produzione da un team interno di sviluppatori. + +## Sponsor + + + +{% if sponsors %} +{% for sponsor in sponsors.gold -%} +async def
...uvicorn main:app --reload
...ujson
- per un "parsing" di JSON più veloce.
+* email_validator
- per la validazione di email.
+
+Usate da Starlette:
+
+* requests
- Richiesto se vuoi usare il `TestClient`.
+* aiofiles
- Richiesto se vuoi usare `FileResponse` o `StaticFiles`.
+* jinja2
- Richiesto se vuoi usare la configurazione template di default.
+* python-multipart
- Richiesto se vuoi supportare il "parsing" con `request.form()`.
+* itsdangerous
- Richiesto per usare `SessionMiddleware`.
+* pyyaml
- Richiesto per il supporto dello `SchemaGenerator` di Starlette (probabilmente non ti serve con FastAPI).
+* graphene
- Richiesto per il supporto di `GraphQLApp`.
+* ujson
- Richiesto se vuoi usare `UJSONResponse`.
+
+Usate da FastAPI / Starlette:
+
+* uvicorn
- per il server che carica e serve la tua applicazione.
+* orjson
- ichiesto se vuoi usare `ORJSONResponse`.
+
+Puoi installarle tutte con `pip install fastapi[all]`.
+
+## Licenza
+
+Questo progetto è concesso in licenza in base ai termini della licenza MIT.
diff --git a/docs/it/mkdocs.yml b/docs/it/mkdocs.yml
new file mode 100644
index 000000000..de18856f4
--- /dev/null
+++ b/docs/it/mkdocs.yml
@@ -0,0 +1 @@
+INHERIT: ../en/mkdocs.yml
diff --git a/docs/ja/docs/deployment/https.md b/docs/ja/docs/deployment/https.md
new file mode 100644
index 000000000..a291f870f
--- /dev/null
+++ b/docs/ja/docs/deployment/https.md
@@ -0,0 +1,200 @@
+# HTTPS について
+
+HTTPSは単に「有効」か「無効」かで決まるものだと思いがちです。
+
+しかし、それよりもはるかに複雑です。
+
+!!! tip
+ もし急いでいたり、HTTPSの仕組みについて気にしないのであれば、次のセクションに進み、さまざまなテクニックを使ってすべてをセットアップするステップ・バイ・ステップの手順をご覧ください。
+
+利用者の視点から **HTTPS の基本を学ぶ**に当たっては、次のリソースをオススメします: https://howhttps.works/.
+
+さて、**開発者の視点**から、HTTPSについて考える際に念頭に置くべきことをいくつかみていきましょう:
+
+* HTTPSの場合、**サーバ**は**第三者**によって生成された**「証明書」を持つ**必要があります。
+ * これらの証明書は「生成」されたものではなく、実際には第三者から**取得**されたものです。
+* 証明書には**有効期限**があります。
+ * つまりいずれ失効します。
+ * そのため**更新**をし、第三者から**再度取得**する必要があります。
+* 接続の暗号化は**TCPレベル**で行われます。
+ * それは**HTTPの1つ下**のレイヤーです。
+ * つまり、**証明書と暗号化**の処理は、**HTTPの前**に行われます。
+* **TCPは "ドメイン "について知りません**。IPアドレスについてのみ知っています。
+ * 要求された**特定のドメイン**に関する情報は、**HTTPデータ**に入ります。
+* **HTTPS証明書**は、**特定のドメイン**を「証明」しますが、プロトコルと暗号化はTCPレベルで行われ、どのドメインが扱われているかを**知る前**に行われます。
+* **デフォルトでは**、**IPアドレスごとに1つのHTTPS証明書**しか持てないことになります。
+ * これは、サーバーの規模やアプリケーションの規模に寄りません。
+ * しかし、これには**解決策**があります。
+* **TLS**プロトコル(HTTPの前に、TCPレベルで暗号化を処理するもの)には、**SNI**と呼ばれる**拡張**があります。
+ * このSNI拡張機能により、1つのサーバー(**単一のIPアドレス**を持つ)が**複数のHTTPS証明書**を持ち、**複数のHTTPSドメイン/アプリケーション**にサービスを提供できるようになります。
+ * これが機能するためには、**パブリックIPアドレス**でリッスンしている、サーバー上で動作している**単一の**コンポーネント(プログラム)が、サーバー内の**すべてのHTTPS証明書**を持っている必要があります。
+
+* セキュアな接続を取得した**後**でも、通信プロトコルは**HTTPのまま**です。
+ * コンテンツは**HTTPプロトコル**で送信されているにもかかわらず、**暗号化**されています。
+
+
+サーバー(マシン、ホストなど)上で**1つのプログラム/HTTPサーバー**を実行させ、**HTTPSに関する全てのこと**を管理するのが一般的です。
+
+**暗号化された HTTPS リクエスト** を受信し、**復号化された HTTP リクエスト** を同じサーバーで実行されている実際の HTTP アプリケーション(この場合は **FastAPI** アプリケーション)に送信し、アプリケーションから **HTTP レスポンス** を受け取り、適切な **HTTPS 証明書** を使用して **暗号化** し、そして**HTTPS** を使用してクライアントに送り返します。
+
+このサーバーはしばしば **TLS Termination Proxy**と呼ばれます。
+
+TLS Termination Proxyとして使えるオプションには、以下のようなものがあります:
+
+* Traefik(証明書の更新も対応)
+* Caddy (証明書の更新も対応)
+* Nginx
+* HAProxy
+
+
+## Let's Encrypt
+
+Let's Encrypt以前は、これらの**HTTPS証明書**は信頼できる第三者によって販売されていました。
+
+これらの証明書を取得するための手続きは面倒で、かなりの書類を必要とし、証明書はかなり高価なものでした。
+
+しかしその後、**Let's Encrypt** が作られました。
+
+これはLinux Foundationのプロジェクトから生まれたものです。 自動化された方法で、**HTTPS証明書を無料で**提供します。これらの証明書は、すべての標準的な暗号化セキュリティを使用し、また短命(約3ヶ月)ですが、こういった寿命の短さによって、**セキュリティは実際に優れています**。
+
+ドメインは安全に検証され、証明書は自動的に生成されます。また、証明書の更新も自動化されます。
+
+このアイデアは、これらの証明書の取得と更新を自動化することで、**安全なHTTPSを、無料で、永遠に**利用できるようにすることです。
+
+## 開発者のための HTTPS
+
+ここでは、HTTPS APIがどのように見えるかの例を、主に開発者にとって重要なアイデアに注意を払いながら、ステップ・バイ・ステップで説明します。
+
+### ドメイン名
+
+ステップの初めは、**ドメイン名**を**取得すること**から始まるでしょう。その後、DNSサーバー(おそらく同じクラウドプロバイダー)に設定します。
+
+おそらくクラウドサーバー(仮想マシン)かそれに類するものを手に入れ、固定の **パブリックIPアドレス**を持つことになるでしょう。
+
+DNSサーバーでは、**取得したドメイン**をあなたのサーバーのパプリック**IPアドレス**に向けるレコード(「`Aレコード`」)を設定します。
+
+これはおそらく、最初の1回だけあり、すべてをセットアップするときに行うでしょう。
+
+!!! tip
+ ドメイン名の話はHTTPSに関する話のはるか前にありますが、すべてがドメインとIPアドレスに依存するため、ここで言及する価値があります。
+
+### DNS
+
+では、実際のHTTPSの部分に注目してみよう。
+
+まず、ブラウザは**DNSサーバー**に**ドメインに対するIP**が何であるかを確認します。今回は、`someapp.example.com`とします。
+
+DNSサーバーは、ブラウザに特定の**IPアドレス**を使用するように指示します。このIPアドレスは、DNSサーバーで設定した、あなたのサーバーが使用するパブリックIPアドレスになります。
+
+kwargs
としても知られています。たとえデフォルト値がなくても。
+
+```Python hl_lines="8"
+{!../../../docs_src/path_params_numeric_validations/tutorial003.py!}
+```
+
+## 数値の検証: 以上
+
+`Query`と`Path`(、そして後述する他のもの)を用いて、文字列の制約を宣言することができますが、数値の制約も同様に宣言できます。
+
+ここで、`ge=1`の場合、`item_id`は`1`「より大きい`g`か、同じ`e`」整数でなれけばなりません。
+
+```Python hl_lines="8"
+{!../../../docs_src/path_params_numeric_validations/tutorial004.py!}
+```
+
+## 数値の検証: より大きいと小なりイコール
+
+以下も同様です:
+
+* `gt`: より大きい(`g`reater `t`han)
+* `le`: 小なりイコール(`l`ess than or `e`qual)
+
+```Python hl_lines="9"
+{!../../../docs_src/path_params_numeric_validations/tutorial005.py!}
+```
+
+## 数値の検証: 浮動小数点、 大なり小なり
+
+数値のバリデーションは`float`の値に対しても有効です。
+
+ここで重要になってくるのはgt
だけでなくge
も宣言できることです。これと同様に、例えば、値が`1`より小さくても`0`より大きくなければならないことを要求することができます。
+
+したがって、`0.5`は有効な値ですが、`0.0`や`0`はそうではありません。
+
+これはlt
も同じです。
+
+```Python hl_lines="11"
+{!../../../docs_src/path_params_numeric_validations/tutorial006.py!}
+```
+
+## まとめ
+
+`Query`と`Path`(そしてまだ見たことない他のもの)では、[クエリパラメータと文字列の検証](query-params-str-validations.md){.internal-link target=_blank}と同じようにメタデータと文字列の検証を宣言することができます。
+
+また、数値のバリデーションを宣言することもできます:
+
+* `gt`: より大きい(`g`reater `t`han)
+* `ge`: 以上(`g`reater than or `e`qual)
+* `lt`: より小さい(`l`ess `t`han)
+* `le`: 以下(`l`ess than or `e`qual)
+
+!!! info "情報"
+ `Query`、`Path`などは後に共通の`Param`クラスのサブクラスを見ることになります。(使う必要はありません)
+
+ そして、それらすべては、これまで見てきた追加のバリデーションとメタデータと同じパラメータを共有しています。
+
+!!! note "技術詳細"
+ `fastapi`から`Query`、`Path`などをインポートすると、これらは実際には関数です。
+
+ 呼び出されると、同じ名前のクラスのインスタンスを返します。
+
+ そのため、関数である`Query`をインポートし、それを呼び出すと、`Query`という名前のクラスのインスタンスが返されます。
+
+ これらの関数は(クラスを直接使うのではなく)エディタが型についてエラーとしないようにするために存在します。
+
+ この方法によって、これらのエラーを無視するための設定を追加することなく、通常のエディタやコーディングツールを使用することができます。
diff --git a/docs/ja/docs/tutorial/response-model.md b/docs/ja/docs/tutorial/response-model.md
new file mode 100644
index 000000000..749b33061
--- /dev/null
+++ b/docs/ja/docs/tutorial/response-model.md
@@ -0,0 +1,208 @@
+# レスポンスモデル
+
+*path operations* のいずれにおいても、`response_model`パラメータを使用して、レスポンスのモデルを宣言することができます:
+
+* `@app.get()`
+* `@app.post()`
+* `@app.put()`
+* `@app.delete()`
+* など。
+
+```Python hl_lines="17"
+{!../../../docs_src/response_model/tutorial001.py!}
+```
+
+!!! note "備考"
+ `response_model`は「デコレータ」メソッド(`get`、`post`など)のパラメータであることに注意してください。すべてのパラメータやボディのように、*path operation関数* のパラメータではありません。
+
+Pydanticモデルの属性に対して宣言するのと同じ型を受け取るので、Pydanticモデルになることもできますが、例えば、`List[Item]`のようなPydanticモデルの`list`になることもできます。
+
+FastAPIは`response_model`を使って以下のことをします:
+
+* 出力データを型宣言に変換します。
+* データを検証します。
+* OpenAPIの *path operation* で、レスポンス用のJSON Schemaを追加します。
+* 自動ドキュメントシステムで使用されます。
+
+しかし、最も重要なのは:
+
+* 出力データをモデルのデータに限定します。これがどのように重要なのか以下で見ていきましょう。
+
+!!! note "技術詳細"
+ レスポンスモデルは、関数の戻り値のアノテーションではなく、このパラメータで宣言されています。なぜなら、パス関数は実際にはそのレスポンスモデルを返すのではなく、`dict`やデータベースオブジェクト、あるいは他のモデルを返し、`response_model`を使用してフィールドの制限やシリアライズを行うからです。
+
+## 同じ入力データの返却
+
+ここでは`UserIn`モデルを宣言しています。それには平文のパスワードが含まれています:
+
+```Python hl_lines="9 11"
+{!../../../docs_src/response_model/tutorial002.py!}
+```
+
+そして、このモデルを使用して入力を宣言し、同じモデルを使って出力を宣言しています:
+
+```Python hl_lines="17 18"
+{!../../../docs_src/response_model/tutorial002.py!}
+```
+
+これで、ブラウザがパスワードを使ってユーザーを作成する際に、APIがレスポンスで同じパスワードを返すようになりました。
+
+この場合、ユーザー自身がパスワードを送信しているので問題ないかもしれません。
+
+しかし、同じモデルを別の*path operation*に使用すると、すべてのクライアントにユーザーのパスワードを送信してしまうことになります。
+
+!!! danger "危険"
+ ユーザーの平文のパスワードを保存したり、レスポンスで送信したりすることは絶対にしないでください。
+
+## 出力モデルの追加
+
+代わりに、平文のパスワードを持つ入力モデルと、パスワードを持たない出力モデルを作成することができます:
+
+```Python hl_lines="9 11 16"
+{!../../../docs_src/response_model/tutorial003.py!}
+```
+
+ここでは、*path operation関数*がパスワードを含む同じ入力ユーザーを返しているにもかかわらず:
+
+```Python hl_lines="24"
+{!../../../docs_src/response_model/tutorial003.py!}
+```
+
+...`response_model`を`UserOut`と宣言したことで、パスワードが含まれていません:
+
+```Python hl_lines="22"
+{!../../../docs_src/response_model/tutorial003.py!}
+```
+
+そのため、**FastAPI** は出力モデルで宣言されていない全てのデータをフィルタリングしてくれます(Pydanticを使用)。
+
+## ドキュメントを見る
+
+自動ドキュメントを見ると、入力モデルと出力モデルがそれぞれ独自のJSON Schemaを持っていることが確認できます。
+
+get
동작 사용
+* get
작동 사용
!!! info "`@decorator` 정보"
이 `@something` 문법은 파이썬에서 "데코레이터"라 부릅니다.
- 함수 맨 위에 놓습니다. 마치 예쁜 장식용(Decorative) 모자처럼(개인적으로 이 용어가 여기서 유래한거 같습니다).
+ 마치 예쁜 장식용(Decorative) 모자처럼(개인적으로 이 용어가 여기서 유래한 것 같습니다) 함수 맨 위에 놓습니다.
- "데코레이터" 아래 있는 함수를 받고 그걸 이용해 무언가 합니다.
+ "데코레이터"는 아래 있는 함수를 받아 그것으로 무언가를 합니다.
- 우리의 경우, 이 데코레이터는 **FastAPI**에게 아래 함수가 **경로** `/`에 해당하는 `get` **동작**하라고 알려줍니다.
+ 우리의 경우, 이 데코레이터는 **FastAPI**에게 아래 함수가 **경로** `/`의 `get` **작동**에 해당한다고 알려줍니다.
- 이것이 "**경로 동작 데코레이터**"입니다.
+ 이것이 "**경로 작동 데코레이터**"입니다.
-다른 동작도 쓸 수 있습니다:
+다른 작동도 사용할 수 있습니다:
* `@app.post()`
* `@app.put()`
* `@app.delete()`
-이국적인 것들도 있습니다:
+흔히 사용되지 않는 것들도 있습니다:
* `@app.options()`
* `@app.head()`
@@ -275,20 +275,20 @@ API를 빌드하는 동안 일반적으로 특정 행동을 수행하기 위해
* `@app.trace()`
!!! tip "팁"
- 각 동작(HTTP 메소드)을 원하는 대로 사용해도 됩니다.
+ 각 작동(HTTP 메소드)을 원하는 대로 사용해도 됩니다.
**FastAPI**는 특정 의미를 강제하지 않습니다.
- 여기서 정보는 지침서일뿐 요구사항이 아닙니다.
+ 여기서 정보는 지침서일뿐 강제사항이 아닙니다.
- 예를 들어 GraphQL을 사용할때 일반적으로 `POST` 동작만 사용하여 모든 행동을 수행합니다.
+ 예를 들어 GraphQL을 사용하는 경우, 일반적으로 `POST` 작동만 사용하여 모든 행동을 수행합니다.
-### 4 단계: **경로 동작 함수** 정의
+### 4 단계: **경로 작동 함수** 정의
-다음은 우리의 "**경로 동작 함수**"입니다:
+다음은 우리의 "**경로 작동 함수**"입니다:
* **경로**: 는 `/`입니다.
-* **동작**: 은 `get`입니다.
+* **작동**: 은 `get`입니다.
* **함수**: 는 "데코레이터" 아래에 있는 함수입니다 (`@app.get("/")` 아래).
```Python hl_lines="7"
@@ -297,19 +297,19 @@ API를 빌드하는 동안 일반적으로 특정 행동을 수행하기 위해
이것은 파이썬 함수입니다.
-`GET` 동작을 사용하여 URL "`/`"에 대한 요청을 받을 때마다 **FastAPI**에 의해 호출됩니다.
+URL "`/`"에 대한 `GET` 작동을 사용하는 요청을 받을 때마다 **FastAPI**에 의해 호출됩니다.
-위의 경우 `async` 함수입니다.
+위의 예시에서 이 함수는 `async`(비동기) 함수입니다.
---
-`async def` 대신 일반 함수로 정의할 수 있습니다:
+`async def`을 이용하는 대신 일반 함수로 정의할 수 있습니다:
```Python hl_lines="7"
{!../../../docs_src/first_steps/tutorial003.py!}
```
-!!! note 참고
+!!! note "참고"
차이점을 모르겠다면 [Async: *"In a hurry?"*](../async.md#in-a-hurry){.internal-link target=_blank}을 확인하세요.
### 5 단계: 콘텐츠 반환
@@ -322,12 +322,12 @@ API를 빌드하는 동안 일반적으로 특정 행동을 수행하기 위해
Pydantic 모델을 반환할 수도 있습니다(나중에 더 자세히 살펴봅니다).
-JSON으로 자동 변환되는 객체들과 모델들이 많이 있습니다(ORM 등을 포함해서요). 가장 마음에 드는 것을 사용하세요, 이미 지원되고 있을 겁니다.
+JSON으로 자동 변환되는 객체들과 모델들(ORM 등을 포함해서)이 많이 있습니다. 가장 마음에 드는 것을 사용하십시오, 이미 지원되고 있을 것입니다.
## 요약
* `FastAPI` 임포트.
* `app` 인스턴스 생성.
-* (`@app.get("/")`처럼) **경로 동작 데코레이터** 작성.
-* (위에 있는 `def root(): ...`처럼) **경로 동작 함수** 작성.
+* (`@app.get("/")`처럼) **경로 작동 데코레이터** 작성.
+* (위에 있는 `def root(): ...`처럼) **경로 작동 함수** 작성.
* (`uvicorn main:app --reload`처럼) 개발 서버 실행.
diff --git a/docs/ko/docs/tutorial/index.md b/docs/ko/docs/tutorial/index.md
index deb5ca8f2..94d6dfb92 100644
--- a/docs/ko/docs/tutorial/index.md
+++ b/docs/ko/docs/tutorial/index.md
@@ -1,16 +1,16 @@
# 자습서 - 사용자 안내서
-이 자습서는 **FastAPI**의 대부분의 기능을 단계별로 사용하는 방법을 보여줍니다.
+이 자습서는 단계별로 **FastAPI**의 대부분의 기능에 대해 설명합니다.
-각 섹션은 이전 섹션을 기반해서 점진적으로 만들어 졌지만, 주제에 따라 다르게 구성되었기 때문에 특정 API 요구사항을 해결하기 위해서라면 어느 특정 항목으로던지 직접 이동할 수 있습니다.
+각 섹션은 이전 섹션에 기반하는 순차적인 구조로 작성되었지만, 각 주제로 구분되어 있기 때문에 필요에 따라 특정 섹션으로 바로 이동하여 필요한 내용을 바로 확인할 수 있습니다.
-또한 향후 참조가 될 수 있도록 만들어졌습니다.
+또한 향후에도 참조 자료로 쓰일 수 있도록 작성되었습니다.
-그러므로 다시 돌아와서 정확히 필요한 것을 확인할 수 있습니다.
+그러므로 필요할 때에 다시 돌아와서 원하는 것을 정확히 찾을 수 있습니다.
## 코드 실행하기
-모든 코드 블록은 복사하고 직접 사용할 수 있습니다(실제로 테스트한 파이썬 파일입니다).
+모든 코드 블록은 복사하여 바로 사용할 수 있습니다(실제로 테스트된 파이썬 파일입니다).
예제를 실행하려면 코드를 `main.py` 파일에 복사하고 다음을 사용하여 `uvicorn`을 시작합니다:
@@ -28,17 +28,18 @@ $ uvicorn main:app --reload
POST
에 관한MDN웹 문서 를 참고하기 바랍니다,.
-!!! warning "주의"
+!!! warning "경고"
다수의 `File` 과 `Form` 매개변수를 한 *경로 작동*에 선언하는 것이 가능하지만, 요청의 본문이 `application/json` 가 아닌 `multipart/form-data` 로 인코딩 되기 때문에 JSON으로 받아야하는 `Body` 필드를 함께 선언할 수는 없습니다.
이는 **FastAPI**의 한계가 아니라, HTTP 프로토콜에 의한 것입니다.
diff --git a/docs/ko/docs/tutorial/request-forms-and-files.md b/docs/ko/docs/tutorial/request-forms-and-files.md
index ddf232e7f..fdf8dbad0 100644
--- a/docs/ko/docs/tutorial/request-forms-and-files.md
+++ b/docs/ko/docs/tutorial/request-forms-and-files.md
@@ -25,7 +25,7 @@
어떤 파일들은 `bytes`로, 또 어떤 파일들은 `UploadFile`로 선언할 수 있습니다.
-!!! warning "주의"
+!!! warning "경고"
다수의 `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
new file mode 100644
index 000000000..0c9d5c16e
--- /dev/null
+++ b/docs/ko/docs/tutorial/response-model.md
@@ -0,0 +1,210 @@
+# 응답 모델
+
+어떤 *경로 작동*이든 매개변수 `response_model`를 사용하여 응답을 위한 모델을 선언할 수 있습니다:
+
+* `@app.get()`
+* `@app.post()`
+* `@app.put()`
+* `@app.delete()`
+* 기타.
+
+```Python hl_lines="17"
+{!../../../docs_src/response_model/tutorial001.py!}
+```
+
+!!! note "참고"
+ `response_model`은 "데코레이터" 메소드(`get`, `post`, 등)의 매개변수입니다. 모든 매개변수들과 본문(body)처럼 *경로 작동 함수*가 아닙니다.
+
+Pydantic 모델 어트리뷰트를 선언한 것과 동일한 타입을 수신하므로 Pydantic 모델이 될 수 있지만, `List[Item]`과 같이 Pydantic 모델들의 `list`일 수도 있습니다.
+
+FastAPI는 이 `response_model`를 사용하여:
+
+* 출력 데이터를 타입 선언으로 변환.
+* 데이터 검증.
+* OpenAPI *경로 작동*의 응답에 JSON 스키마 추가.
+* 자동 생성 문서 시스템에 사용.
+
+하지만 가장 중요한 것은:
+
+* 해당 모델의 출력 데이터 제한. 이것이 얼마나 중요한지 아래에서 볼 것입니다.
+
+!!! note "기술 세부사항"
+ 응답 모델은 함수의 타입 어노테이션 대신 이 매개변수로 선언하는데, 경로 함수가 실제 응답 모델을 반환하지 않고 `dict`, 데이터베이스 객체나 기타 다른 모델을 `response_model`을 사용하여 필드 제한과 직렬화를 수행하고 반환할 수 있기 때문입니다
+
+## 동일한 입력 데이터 반환
+
+여기서 우리는 평문 비밀번호를 포함하는 `UserIn` 모델을 선언합니다:
+
+```Python hl_lines="9 11"
+{!../../../docs_src/response_model/tutorial002.py!}
+```
+
+그리고 이 모델을 사용하여 입력을 선언하고 같은 모델로 출력을 선언합니다:
+
+```Python hl_lines="17-18"
+{!../../../docs_src/response_model/tutorial002.py!}
+```
+
+이제 브라우저가 비밀번호로 사용자를 만들 때마다 API는 응답으로 동일한 비밀번호를 반환합니다.
+
+이 경우, 사용자가 스스로 비밀번호를 발신했기 때문에 문제가 되지 않을 수 있습니다.
+
+그러나 동일한 모델을 다른 *경로 작동*에서 사용할 경우, 모든 클라이언트에게 사용자의 비밀번호를 발신할 수 있습니다.
+
+!!! danger "위험"
+ 절대로 사용자의 평문 비밀번호를 저장하거나 응답으로 발신하지 마십시오.
+
+## 출력 모델 추가
+
+대신 평문 비밀번호로 입력 모델을 만들고 해당 비밀번호 없이 출력 모델을 만들 수 있습니다:
+
+```Python hl_lines="9 11 16"
+{!../../../docs_src/response_model/tutorial003.py!}
+```
+
+여기서 *경로 작동 함수*가 비밀번호를 포함하는 동일한 입력 사용자를 반환할지라도:
+
+```Python hl_lines="24"
+{!../../../docs_src/response_model/tutorial003.py!}
+```
+
+...`response_model`을 `UserOut` 모델로 선언했기 때문에 비밀번호를 포함하지 않습니다:
+
+```Python hl_lines="22"
+{!../../../docs_src/response_model/tutorial003.py!}
+```
+
+따라서 **FastAPI**는 출력 모델에서 선언하지 않은 모든 데이터를 (Pydantic을 사용하여) 필터링합니다.
+
+## 문서에서 보기
+
+자동 생성 문서를 보면 입력 모델과 출력 모델이 각자의 JSON 스키마를 가지고 있음을 확인할 수 있습니다:
+
+POST
.
+
+!!! warning "Внимание"
+ В операции *функции операции пути* можно объявить несколько параметров `File` и `Form`, но нельзя также объявлять поля `Body`, которые предполагается получить в виде JSON, поскольку тело запроса будет закодировано с помощью `multipart/form-data`, а не `application/json`.
+
+ Это не является ограничением **FastAPI**, это часть протокола HTTP.
+
+## Необязательная загрузка файлов
+
+Вы можете сделать загрузку файла необязательной, используя стандартные аннотации типов и установив значение по умолчанию `None`:
+
+=== "Python 3.10+"
+
+ ```Python hl_lines="9 17"
+ {!> ../../../docs_src/request_files/tutorial001_02_an_py310.py!}
+ ```
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="9 17"
+ {!> ../../../docs_src/request_files/tutorial001_02_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="10 18"
+ {!> ../../../docs_src/request_files/tutorial001_02_an.py!}
+ ```
+
+=== "Python 3.10+ без Annotated"
+
+ !!! tip "Подсказка"
+ Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+ ```Python hl_lines="7 15"
+ {!> ../../../docs_src/request_files/tutorial001_02_py310.py!}
+ ```
+
+=== "Python 3.6+ без Annotated"
+
+ !!! tip "Подсказка"
+ Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+ ```Python hl_lines="9 17"
+ {!> ../../../docs_src/request_files/tutorial001_02.py!}
+ ```
+
+## `UploadFile` с дополнительными метаданными
+
+Вы также можете использовать `File()` вместе с `UploadFile`, например, для установки дополнительных метаданных:
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="9 15"
+ {!> ../../../docs_src/request_files/tutorial001_03_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="8 14"
+ {!> ../../../docs_src/request_files/tutorial001_03_an.py!}
+ ```
+
+=== "Python 3.6+ без Annotated"
+
+ !!! tip "Подсказка"
+ Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+ ```Python hl_lines="7 13"
+ {!> ../../../docs_src/request_files/tutorial001_03.py!}
+ ```
+
+## Загрузка нескольких файлов
+
+Можно одновременно загружать несколько файлов.
+
+Они будут связаны с одним и тем же "полем формы", отправляемым с помощью данных формы.
+
+Для этого необходимо объявить список `bytes` или `UploadFile`:
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="10 15"
+ {!> ../../../docs_src/request_files/tutorial002_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="11 16"
+ {!> ../../../docs_src/request_files/tutorial002_an.py!}
+ ```
+
+=== "Python 3.9+ без Annotated"
+
+ !!! tip "Подсказка"
+ Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+ ```Python hl_lines="8 13"
+ {!> ../../../docs_src/request_files/tutorial002_py39.py!}
+ ```
+
+=== "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`.
+
+ **FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette.
+
+### Загрузка нескольких файлов с дополнительными метаданными
+
+Так же, как и раньше, вы можете использовать `File()` для задания дополнительных параметров, даже для `UploadFile`:
+
+=== "Python 3.9+"
+
+ ```Python hl_lines="11 18-20"
+ {!> ../../../docs_src/request_files/tutorial003_an_py39.py!}
+ ```
+
+=== "Python 3.6+"
+
+ ```Python hl_lines="12 19-21"
+ {!> ../../../docs_src/request_files/tutorial003_an.py!}
+ ```
+
+=== "Python 3.9+ без Annotated"
+
+ !!! tip "Подсказка"
+ Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+ ```Python hl_lines="9 16"
+ {!> ../../../docs_src/request_files/tutorial003_py39.py!}
+ ```
+
+=== "Python 3.6+ без Annotated"
+
+ !!! tip "Подсказка"
+ Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+ ```Python hl_lines="11 18"
+ {!> ../../../docs_src/request_files/tutorial003.py!}
+ ```
+
+## Резюме
+
+Используйте `File`, `bytes` и `UploadFile` для работы с файлами, которые будут загружаться и передаваться в виде данных формы.
diff --git a/docs/ru/docs/tutorial/request-forms-and-files.md b/docs/ru/docs/tutorial/request-forms-and-files.md
new file mode 100644
index 000000000..3f587c38a
--- /dev/null
+++ b/docs/ru/docs/tutorial/request-forms-and-files.md
@@ -0,0 +1,69 @@
+# Файлы и формы в запросе
+
+Вы можете определять файлы и поля формы одновременно, используя `File` и `Form`.
+
+!!! info "Дополнительная информация"
+ Чтобы получать загруженные файлы и/или данные форм, сначала установите `python-multipart`.
+
+ Например: `pip install python-multipart`.
+
+## Импортируйте `File` и `Form`
+
+=== "Python 3.9+"
+
+ ```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!}
+ ```
+
+=== "Python 3.6+ без Annotated"
+
+ !!! tip "Подсказка"
+ Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+ ```Python hl_lines="1"
+ {!> ../../../docs_src/request_forms_and_files/tutorial001.py!}
+ ```
+
+## Определите параметры `File` и `Form`
+
+Создайте параметры файла и формы таким же образом, как для `Body` или `Query`:
+
+=== "Python 3.9+"
+
+ ```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!}
+ ```
+
+=== "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`.
+
+ Это не ограничение **Fast API**, это часть протокола HTTP.
+
+## Резюме
+
+Используйте `File` и `Form` вместе, когда необходимо получить данные и файлы в одном запросе.
diff --git a/docs/ru/docs/tutorial/request-forms.md b/docs/ru/docs/tutorial/request-forms.md
index a20cf78e0..0fc9e4eda 100644
--- a/docs/ru/docs/tutorial/request-forms.md
+++ b/docs/ru/docs/tutorial/request-forms.md
@@ -17,13 +17,13 @@
{!> ../../../docs_src/request_forms/tutorial001_an_py39.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="1"
{!> ../../../docs_src/request_forms/tutorial001_an.py!}
```
-=== "Python 3.6+ без Annotated"
+=== "Python 3.8+ без Annotated"
!!! tip "Подсказка"
Рекомендуется использовать 'Annotated' версию, если это возможно.
@@ -42,13 +42,13 @@
{!> ../../../docs_src/request_forms/tutorial001_an_py39.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="8"
{!> ../../../docs_src/request_forms/tutorial001_an.py!}
```
-=== "Python 3.6+ без Annotated"
+=== "Python 3.8+ без Annotated"
!!! tip "Подсказка"
Рекомендуется использовать 'Annotated' версию, если это возможно.
diff --git a/docs/ru/docs/tutorial/response-model.md b/docs/ru/docs/tutorial/response-model.md
index c5e111790..38b45e2a5 100644
--- a/docs/ru/docs/tutorial/response-model.md
+++ b/docs/ru/docs/tutorial/response-model.md
@@ -16,7 +16,7 @@ FastAPI позволяет использовать **аннотации тип
{!> ../../../docs_src/response_model/tutorial001_01_py39.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="18 23"
{!> ../../../docs_src/response_model/tutorial001_01.py!}
@@ -65,7 +65,7 @@ FastAPI будет использовать этот возвращаемый т
{!> ../../../docs_src/response_model/tutorial001_py39.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="17 22 24-27"
{!> ../../../docs_src/response_model/tutorial001.py!}
@@ -101,7 +101,7 @@ FastAPI будет использовать значение `response_model` д
{!> ../../../docs_src/response_model/tutorial002_py310.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="9 11"
{!> ../../../docs_src/response_model/tutorial002.py!}
@@ -120,7 +120,7 @@ FastAPI будет использовать значение `response_model` д
{!> ../../../docs_src/response_model/tutorial002_py310.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="18"
{!> ../../../docs_src/response_model/tutorial002.py!}
@@ -145,7 +145,7 @@ FastAPI будет использовать значение `response_model` д
{!> ../../../docs_src/response_model/tutorial003_py310.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="9 11 16"
{!> ../../../docs_src/response_model/tutorial003.py!}
@@ -159,7 +159,7 @@ FastAPI будет использовать значение `response_model` д
{!> ../../../docs_src/response_model/tutorial003_py310.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="24"
{!> ../../../docs_src/response_model/tutorial003.py!}
@@ -173,7 +173,7 @@ FastAPI будет использовать значение `response_model` д
{!> ../../../docs_src/response_model/tutorial003_py310.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="22"
{!> ../../../docs_src/response_model/tutorial003.py!}
@@ -207,7 +207,7 @@ FastAPI будет использовать значение `response_model` д
{!> ../../../docs_src/response_model/tutorial003_01_py310.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="9-13 15-16 20"
{!> ../../../docs_src/response_model/tutorial003_01.py!}
@@ -283,7 +283,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма
{!> ../../../docs_src/response_model/tutorial003_04_py310.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="10"
{!> ../../../docs_src/response_model/tutorial003_04.py!}
@@ -305,7 +305,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма
{!> ../../../docs_src/response_model/tutorial003_05_py310.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="9"
{!> ../../../docs_src/response_model/tutorial003_05.py!}
@@ -329,7 +329,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма
{!> ../../../docs_src/response_model/tutorial004_py39.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="11 13-14"
{!> ../../../docs_src/response_model/tutorial004.py!}
@@ -359,7 +359,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма
{!> ../../../docs_src/response_model/tutorial004_py39.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="24"
{!> ../../../docs_src/response_model/tutorial004.py!}
@@ -446,7 +446,7 @@ FastAPI достаточно умен (на самом деле, это засл
{!> ../../../docs_src/response_model/tutorial005_py310.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="31 37"
{!> ../../../docs_src/response_model/tutorial005.py!}
@@ -467,7 +467,7 @@ FastAPI достаточно умен (на самом деле, это засл
{!> ../../../docs_src/response_model/tutorial006_py310.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="31 37"
{!> ../../../docs_src/response_model/tutorial006.py!}
diff --git a/docs/ru/docs/tutorial/schema-extra-example.md b/docs/ru/docs/tutorial/schema-extra-example.md
index a0363b9ba..a13ab5935 100644
--- a/docs/ru/docs/tutorial/schema-extra-example.md
+++ b/docs/ru/docs/tutorial/schema-extra-example.md
@@ -14,7 +14,7 @@
{!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="15-23"
{!> ../../../docs_src/schema_extra_example/tutorial001.py!}
@@ -39,7 +39,7 @@
{!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="4 10-13"
{!> ../../../docs_src/schema_extra_example/tutorial002.py!}
@@ -78,7 +78,7 @@
{!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="23-28"
{!> ../../../docs_src/schema_extra_example/tutorial003_an.py!}
@@ -93,7 +93,7 @@
{!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!}
```
-=== "Python 3.6+ non-Annotated"
+=== "Python 3.8+ non-Annotated"
!!! tip Заметка
Рекомендуется использовать версию с `Annotated`, если это возможно.
@@ -133,7 +133,7 @@
{!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!}
```
-=== "Python 3.6+"
+=== "Python 3.8+"
```Python hl_lines="24-50"
{!> ../../../docs_src/schema_extra_example/tutorial004_an.py!}
@@ -148,7 +148,7 @@
{!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!}
```
-=== "Python 3.6+ non-Annotated"
+=== "Python 3.8+ non-Annotated"
!!! tip Заметка
Рекомендуется использовать версию с `Annotated`, если это возможно.
diff --git a/docs/ru/docs/tutorial/security/first-steps.md b/docs/ru/docs/tutorial/security/first-steps.md
new file mode 100644
index 000000000..b70a60a38
--- /dev/null
+++ b/docs/ru/docs/tutorial/security/first-steps.md
@@ -0,0 +1,232 @@
+# Безопасность - первые шаги
+
+Представим, что у вас есть свой **бэкенд** API на некотором домене.
+
+И у вас есть **фронтенд** на другом домене или на другом пути того же домена (или в мобильном приложении).
+
+И вы хотите иметь возможность аутентификации фронтенда с бэкендом, используя **имя пользователя** и **пароль**.
+
+Мы можем использовать **OAuth2** для создания такой системы с помощью **FastAPI**.
+
+Но давайте избавим вас от необходимости читать всю длинную спецификацию, чтобы найти те небольшие кусочки информации, которые вам нужны.
+
+Для работы с безопасностью воспользуемся средствами, предоставленными **FastAPI**.
+
+## Как это выглядит
+
+Давайте сначала просто воспользуемся кодом и посмотрим, как он работает, а затем детально разберём, что происходит.
+
+## Создание `main.py`
+
+Скопируйте пример в файл `main.py`:
+
+=== "Python 3.9+"
+
+ ```Python
+ {!> ../../../docs_src/security/tutorial001_an_py39.py!}
+ ```
+
+=== "Python 3.8+"
+
+ ```Python
+ {!> ../../../docs_src/security/tutorial001_an.py!}
+ ```
+
+=== "Python 3.8+ без Annotated"
+
+ !!! tip "Подсказка"
+ Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+ ```Python
+ {!> ../../../docs_src/security/tutorial001.py!}
+ ```
+
+
+## Запуск
+
+!!! info "Дополнительная информация"
+ Вначале, установите библиотеку `python-multipart`.
+
+ А именно: `pip install python-multipart`.
+
+ Это связано с тем, что **OAuth2** использует "данные формы" для передачи `имени пользователя` и `пароля`.
+
+Запустите ваш сервер:
+
++ +Başkalarının daha önceki çalışmaları olmasaydı, **FastAPI** var olmazdı. + +Geçmişte oluşturulan pek çok araç **FastAPI**'a ilham kaynağı olmuştur. + +Yıllardır yeni bir framework oluşturmaktan kaçınıyordum. Başlangıçta **FastAPI**'ın çözdüğü sorunları çözebilmek için pek çok farklı framework, eklenti ve araç kullanmayı denedim. + +Ancak bir noktada, geçmişteki diğer araçlardan en iyi fikirleri alarak bütün bu çözümleri kapsayan, ayrıca bütün bunları Python'ın daha önce mevcut olmayan özelliklerini (Python 3.6+ ile gelen tip belirteçleri) kullanarak yapan bir şey üretmekten başka bir seçenek kalmamıştı. + ++ +## Araştırma + +Önceki alternatifleri kullanarak hepsinden bir şeyler öğrenip, fikirler alıp, bunları kendim ve çalıştığım geliştirici ekipler için en iyi şekilde birleştirebilme şansım oldu. + +Mesela, ideal olarak standart Python tip belirteçlerine dayanması gerektiği açıktı. + +Ayrıca, en iyi yaklaşım zaten mevcut olan standartları kullanmaktı. + +Sonuç olarak, **FastAPI**'ı kodlamaya başlamadan önce, birkaç ay boyunca OpenAPI, JSON Schema, OAuth2 ve benzerlerinin tanımlamalarını inceledim. İlişkilerini, örtüştükleri noktaları ve farklılıklarını anlamaya çalıştım. + +## Tasarım + +Sonrasında, (**FastAPI** kullanan bir geliştirici olarak) sahip olmak istediğim "API"ı tasarlamak için biraz zaman harcadım. + +Çeşitli fikirleri en popüler Python editörlerinde test ettim: PyCharm, VS Code, Jedi tabanlı editörler. + +Bu test, en son Python Developer Survey'ine göre, kullanıcıların yaklaşık %80'inin kullandığı editörleri kapsıyor. + +Bu da demek oluyor ki **FastAPI**, Python geliştiricilerinin %80'inin kullandığı editörlerle test edildi. Ve diğer editörlerin çoğu benzer şekilde çalıştığından, avantajları neredeyse tüm editörlerde çalışacaktır. + +Bu şekilde, kod tekrarını mümkün olduğunca azaltmak, her yerde otomatik tamamlama, tip ve hata kontrollerine sahip olmak için en iyi yolları bulabildim. + +Hepsi, tüm geliştiriciler için en iyi geliştirme deneyimini sağlayacak şekilde. + +## Gereksinimler + +Çeşitli alternatifleri test ettikten sonra, avantajlarından dolayı **Pydantic**'i kullanmaya karar verdim. + +Sonra, JSON Schema ile tamamen uyumlu olmasını sağlamak, kısıtlama bildirimlerini tanımlamanın farklı yollarını desteklemek ve birkaç editördeki testlere dayanarak editör desteğini (tip kontrolleri, otomatik tamamlama) geliştirmek için katkıda bulundum. + +Geliştirme sırasında, diğer ana gereksinim olan **Starlette**'e de katkıda bulundum. + +## Geliştirme + +**FastAPI**'ı oluşturmaya başladığımda, parçaların çoğu zaten yerindeydi, tasarım tanımlanmıştı, gereksinimler ve araçlar hazırdı, standartlar ve tanımlamalar hakkındaki bilgi net ve tazeydi. + +## Gelecek + +Şimdiye kadar, **FastAPI**'ın fikirleriyle birçok kişiye faydalı olduğu apaçık ortada. + +Birçok kullanım durumuna daha iyi uyduğu için, önceki alternatiflerin yerine seçiliyor. + +Ben ve ekibim dahil, birçok geliştirici ve ekip projelerinde **FastAPI**'ya bağlı. + +Tabi, geliştirilecek birçok özellik ve iyileştirme mevcut. + +**FastAPI**'ın önünde harika bir gelecek var. + +[Yardımlarınız](help-fastapi.md){.internal-link target=_blank} çok değerlidir. diff --git a/docs/tr/docs/how-to/index.md b/docs/tr/docs/how-to/index.md new file mode 100644 index 000000000..8ece29515 --- /dev/null +++ b/docs/tr/docs/how-to/index.md @@ -0,0 +1,11 @@ +# Nasıl Yapılır - Tarifler + +Burada çeşitli konular hakkında farklı tarifler veya "nasıl yapılır" kılavuzları yer alıyor. + +Bu fikirlerin büyük bir kısmı aşağı yukarı **bağımsız** olacaktır, çoğu durumda bunları sadece **projenize** hitap ediyorsa incelemelisiniz. + +Projeniz için ilginç ve yararlı görünen bir şey varsa devam edin ve inceleyin, aksi halde bunları atlayabilirsiniz. + +!!! tip "İpucu" + + **FastAPI**'ı düzgün (ve önerilen) şekilde öğrenmek istiyorsanız [Öğretici - Kullanıcı Rehberi](../tutorial/index.md){.internal-link target=_blank}'ni bölüm bölüm okuyun. diff --git a/docs/tr/docs/index.md b/docs/tr/docs/index.md index e74efbc2f..ac8830880 100644 --- a/docs/tr/docs/index.md +++ b/docs/tr/docs/index.md @@ -2,45 +2,47 @@
- FastAPI framework, yüksek performanslı, öğrenmesi kolay, geliştirmesi hızlı, kullanıma sunulmaya hazır. + FastAPI framework, yüksek performanslı, öğrenmesi oldukça kolay, kodlaması hızlı, kullanıma hazır
--- -**dokümantasyon**: https://fastapi.tiangolo.com +**Dokümantasyon**: https://fastapi.tiangolo.com -**Kaynak kodu**: https://github.com/tiangolo/fastapi +**Kaynak Kod**: https://github.com/tiangolo/fastapi --- -FastAPI, Python 3.6+'nın standart type hintlerine dayanan modern ve hızlı (yüksek performanslı) API'lar oluşturmak için kullanılabilecek web framework'ü. +FastAPI, Python 3.8+'nin standart tip belirteçlerine dayalı, modern ve hızlı (yüksek performanslı) API'lar oluşturmak için kullanılabilecek web framework'tür. -Ana özellikleri: +Temel özellikleri şunlardır: -* **Hızlı**: çok yüksek performanslı, **NodeJS** ve **Go** ile eşdeğer seviyede performans sağlıyor, (Starlette ve Pydantic sayesinde.) [Python'un en hızlı frameworklerinden bir tanesi.](#performans). -* **Kodlaması hızlı**: Yeni özellikler geliştirmek neredeyse %200 - %300 daha hızlı. * -* **Daha az bug**: Geliştirici (insan) kaynaklı hatalar neredeyse %40 azaltıldı. * -* **Sezgileri güçlü**: Editor (otomatik-tamamlama) desteği harika. Otomatik tamamlama her yerde. Debuglamak ile daha az zaman harcayacaksınız. -* **Kolay**: Öğrenmesi ve kullanması kolay olacak şekilde. Doküman okumak için harcayacağınız süre azaltıldı. -* **Kısa**: Kod tekrarını minimuma indirdik. Fonksiyon parametrelerinin tiplerini belirtmede farklı yollar sunarak karşılaşacağınız bug'ları azalttık. -* **Güçlü**: Otomatik dokümantasyon ile beraber, kullanıma hazır kod yaz. +* **Hızlı**: Çok yüksek performanslı, **NodeJS** ve **Go** ile eşit düzeyde (Starlette ve Pydantic sayesinde). [En hızlı Python framework'lerinden bir tanesidir](#performans). +* **Kodlaması Hızlı**: Geliştirme hızını yaklaşık %200 ile %300 aralığında arttırır. * +* **Daha az hata**: İnsan (geliştirici) kaynaklı hataları yaklaşık %40 azaltır. * +* **Sezgisel**: Muhteşem bir editör desteği. Her yerde otomatik tamamlama. Hata ayıklama ile daha az zaman harcayacaksınız. +* **Kolay**: Öğrenmesi ve kullanması kolay olacak şekilde tasarlandı. Doküman okuma ile daha az zaman harcayacaksınız. +* **Kısa**: Kod tekrarı minimize edildi. Her parametre tanımlamasında birden fazla özellik ve daha az hatayla karşılaşacaksınız. +* **Güçlü**: Otomatik ve etkileşimli dokümantasyon ile birlikte, kullanıma hazır kod elde edebilirsiniz. +* **Standard öncelikli**: API'lar için açık standartlara dayalı (ve tamamen uyumlu); OpenAPI (eski adıyla Swagger) ve JSON Schema. -* **Standartlar belirli**: Tamamiyle API'ların açık standartlara bağlı ve (tam uyumlululuk içerisinde); OpenAPI (eski adıyla Swagger) ve JSON Schema. +* ilgili kanılar, dahili geliştirme ekibinin geliştirdikleri ürünlere yaptıkları testlere dayanmaktadır. -* Bahsi geçen rakamsal ifadeler tamamiyle, geliştirme takımının kendi sundukları ürünü geliştirirken yaptıkları testlere dayanmakta. - -## Sponsors +## Sponsorlar @@ -55,74 +57,72 @@ Ana özellikleri: -Other sponsors +Diğer Sponsorlar ## Görüşler - -"_[...] Bugünlerde **FastAPI**'ı çok fazla kullanıyorum [...] Aslına bakarsanız **Microsoft'taki Machine Learning servislerimizin** hepsinde kullanmayı düşünüyorum. FastAPI ile geliştirdiğimiz servislerin bazıları çoktan **Windows**'un ana ürünlerine ve **Office** ürünlerine entegre edilmeye başlandı bile._" +"_[...] Bugünlerde **FastAPI**'ı çok fazla kullanıyorum. [...] Aslında bunu ekibimin **Microsoft'taki Machine Learning servislerinin** tamamında kullanmayı planlıyorum. Bunlardan bazıları **Windows**'un ana ürünlerine ve **Office** ürünlerine entegre ediliyor._"async def
...uvicorn main:app --reload
hakkında...uvicorn main:app --reload
komutuyla ilgili...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.
Starlette tarafında kullanılan:
-* httpx
- Eğer `TestClient` kullanmak istiyorsan gerekli.
-* jinja2
- Eğer kendine ait template konfigürasyonu oluşturmak istiyorsan gerekli
-* python-multipart
- Form kullanmak istiyorsan gerekli ("dönüşümü").
+* httpx
- Eğer `TestClient` yapısını kullanacaksanız gereklidir.
+* jinja2
- Eğer varsayılan template konfigürasyonunu kullanacaksanız gereklidir.
+* python-multipart
- Eğer `request.form()` ile form dönüşümü desteğini kullanacaksanız gereklidir.
* itsdangerous
- `SessionMiddleware` desteği için gerekli.
* pyyaml
- `SchemaGenerator` desteği için gerekli (Muhtemelen FastAPI kullanırken ihtiyacınız olmaz).
-* graphene
- `GraphQLApp` desteği için gerekli.
-* ujson
- `UJSONResponse` kullanmak istiyorsan gerekli.
+* ujson
- `UJSONResponse` kullanacaksanız gerekli.
Hem FastAPI hem de Starlette tarafından kullanılan:
-* uvicorn
- oluşturduğumuz uygulamayı bir web sunucusuna servis etmek için gerekli
-* orjson
- `ORJSONResponse` kullanmak istiyor isen gerekli.
+* uvicorn
- oluşturduğumuz uygulamayı servis edecek web sunucusu görevini üstlenir.
+* orjson
- `ORJSONResponse` kullanacaksanız gereklidir.
Bunların hepsini `pip install fastapi[all]` ile yükleyebilirsin.
## Lisans
-Bu proje, MIT lisansı şartlarına göre lisanslanmıştır.
+Bu proje, MIT lisansı şartları altında lisanslanmıştır.
diff --git a/docs/tr/docs/learn/index.md b/docs/tr/docs/learn/index.md
new file mode 100644
index 000000000..52e3aa54d
--- /dev/null
+++ b/docs/tr/docs/learn/index.md
@@ -0,0 +1,5 @@
+# Öğren
+
+**FastAPI** öğrenmek için giriş bölümleri ve öğreticiler burada yer alıyor.
+
+Burayı, bir **kitap**, bir **kurs**, ve FastAPI öğrenmenin **resmi** ve önerilen yolu olarak düşünülebilirsiniz. 😎
diff --git a/docs/tr/docs/newsletter.md b/docs/tr/docs/newsletter.md
new file mode 100644
index 000000000..22ca1b1e2
--- /dev/null
+++ b/docs/tr/docs/newsletter.md
@@ -0,0 +1,5 @@
+# FastAPI ve Arkadaşları Bülteni
+
+
+
+
diff --git a/docs/tr/docs/project-generation.md b/docs/tr/docs/project-generation.md
new file mode 100644
index 000000000..75e3ae339
--- /dev/null
+++ b/docs/tr/docs/project-generation.md
@@ -0,0 +1,84 @@
+# Proje oluşturma - Şablonlar
+
+Başlamak için bir proje oluşturucu kullanabilirsiniz, çünkü sizin için önceden yapılmış birçok başlangıç kurulumu, güvenlik, veritabanı ve temel API endpoinlerini içerir.
+
+Bir proje oluşturucu, her zaman kendi ihtiyaçlarınıza göre güncellemeniz ve uyarlamanız gereken esnek bir kuruluma sahip olacaktır, ancak bu, projeniz için iyi bir başlangıç noktası olabilir.
+
+## Full Stack FastAPI PostgreSQL
+
+GitHub: https://github.com/tiangolo/full-stack-fastapi-postgresql
+
+### Full Stack FastAPI PostgreSQL - Özellikler
+
+* Full **Docker** entegrasyonu (Docker based).
+* Docker Swarm Mode ile deployment.
+* **Docker Compose** entegrasyonu ve lokal geliştirme için optimizasyon.
+* Uvicorn ve Gunicorn ile **Production ready** Python web server'ı.
+* Python **FastAPI** backend:
+ * **Hızlı**: **NodeJS** ve **Go** ile eşit, çok yüksek performans (Starlette ve Pydantic'e teşekkürler).
+ * **Sezgisel**: Editor desteğı. Otomatik tamamlama. Daha az debugging.
+ * **Kolay**: Kolay öğrenip kolay kullanmak için tasarlandı. Daha az döküman okuma daha çok iş.
+ * **Kısa**: Minimum kod tekrarı. Her parametre bildiriminde birden çok özellik.
+ * **Güçlü**: Production-ready. Otomatik interaktif dökümantasyon.
+ * **Standartlara dayalı**: API'ler için açık standartlara dayanır (ve tamamen uyumludur): OpenAPI ve JSON Şeması.
+ * **Birçok diger özelliği** dahili otomatik doğrulama, serialization, interaktif dokümantasyon, OAuth2 JWT token ile authentication, vb.
+* **Güvenli şifreleme** .
+* **JWT token** kimlik doğrulama.
+* **SQLAlchemy** models (Flask dan bağımsızdır. Celery worker'ları ile kullanılabilir).
+* Kullanıcılar için temel başlangıç modeli (gerektiği gibi değiştirin ve kaldırın).
+* **Alembic** migration.
+* **CORS** (Cross Origin Resource Sharing).
+* **Celery** worker'ları ile backend içerisinden seçilen işleri çalıştırabilirsiniz.
+* **Pytest**'e dayalı, Docker ile entegre REST backend testleri ile veritabanından bağımsız olarak tam API etkileşimini test edebilirsiniz. Docker'da çalıştığı için her seferinde sıfırdan yeni bir veri deposu oluşturabilir (böylece ElasticSearch, MongoDB, CouchDB veya ne istersen kullanabilirsin ve sadece API'nin çalışıp çalışmadığını test edebilirsin).
+* Atom Hydrogen veya Visual Studio Code Jupyter gibi uzantılarla uzaktan veya Docker içi geliştirme için **Jupyter Çekirdekleri** ile kolay Python entegrasyonu.
+* **Vue** ile frontend:
+ * Vue CLI ile oluşturulmuş.
+ * Dahili **JWT kimlik doğrulama**.
+ * Dahili Login.
+ * Login sonrası, Kontrol paneli.
+ * Kullanıcı oluşturma ve düzenleme kontrol paneli
+ * Kendi kendine kullanıcı sürümü.
+ * **Vuex**.
+ * **Vue-router**.
+ * **Vuetify** güzel material design kompanentleri için.
+ * **TypeScript**.
+ * **Nginx** tabanlı Docker sunucusu (Vue-router için yapılandırılmış).
+ * Docker ile multi-stage yapı, böylece kodu derlemeniz, kaydetmeniz veya işlemeniz gerekmez.
+ * Derleme zamanında Frontend testi (devre dışı bırakılabilir).
+ * Mümkün olduğu kadar modüler yapılmıştır, bu nedenle kutudan çıktığı gibi çalışır, ancak Vue CLI ile yeniden oluşturabilir veya ihtiyaç duyduğunuz şekilde oluşturabilir ve istediğinizi yeniden kullanabilirsiniz.
+* **PGAdmin** PostgreSQL database admin tool'u, PHPMyAdmin ve MySQL ile kolayca değiştirilebilir.
+* **Flower** ile Celery job'larını monitörleme.
+* **Traefik** ile backend ve frontend arasında yük dengeleme, böylece her ikisini de aynı domain altında, path ile ayrılmış, ancak farklı kapsayıcılar tarafından sunulabilirsiniz.
+* Let's Encrypt **HTTPS** sertifikalarının otomatik oluşturulması dahil olmak üzere Traefik entegrasyonu.
+* GitLab **CI** (sürekli entegrasyon), backend ve frontend testi dahil.
+
+## Full Stack FastAPI Couchbase
+
+GitHub: https://github.com/tiangolo/full-stack-fastapi-couchbase
+
+⚠️ **UYARI** ⚠️
+
+Sıfırdan bir projeye başlıyorsanız alternatiflerine bakın.
+
+Örneğin, Full Stack FastAPI PostgreSQL daha iyi bir alternatif olabilir, aktif olarak geliştiriliyor ve kullanılıyor. Ve yeni özellik ve ilerlemelere sahip.
+
+İsterseniz Couchbase tabanlı generator'ı kullanmakta özgürsünüz, hala iyi çalışıyor olmalı ve onunla oluşturulmuş bir projeniz varsa bu da sorun değil (ve muhtemelen zaten ihtiyaçlarınıza göre güncellediniz).
+
+Bununla ilgili daha fazla bilgiyi repo belgelerinde okuyabilirsiniz.
+
+## Full Stack FastAPI MongoDB
+
+... müsaitliğime ve diğer faktörlere bağlı olarak daha sonra gelebilir. 😅 🎉
+
+## Machine Learning modelleri, spaCy ve FastAPI
+
+GitHub: https://github.com/microsoft/cookiecutter-spacy-fastapi
+
+### Machine Learning modelleri, spaCy ve FastAPI - Features
+
+* **spaCy** NER model entegrasyonu.
+* **Azure Cognitive Search** yerleşik istek biçimi.
+* Uvicorn ve Gunicorn ile **Production ready** Python web server'ı.
+* Dahili **Azure DevOps** Kubernetes (AKS) CI/CD deployment.
+* **Multilingual**, Proje kurulumu sırasında spaCy'nin yerleşik dillerinden birini kolayca seçin.
+* **Esnetilebilir** diğer frameworkler (Pytorch, Tensorflow) ile de çalışır sadece spaCy değil.
diff --git a/docs/tr/docs/resources/index.md b/docs/tr/docs/resources/index.md
new file mode 100644
index 000000000..fc71a9ca1
--- /dev/null
+++ b/docs/tr/docs/resources/index.md
@@ -0,0 +1,3 @@
+# Kaynaklar
+
+Ek kaynaklar, dış bağlantılar, makaleler ve daha fazlası. ✈️
diff --git a/docs/tr/docs/tutorial/first-steps.md b/docs/tr/docs/tutorial/first-steps.md
new file mode 100644
index 000000000..e66f73034
--- /dev/null
+++ b/docs/tr/docs/tutorial/first-steps.md
@@ -0,0 +1,333 @@
+# İlk Adımlar
+
+En sade FastAPI dosyası şu şekilde görünür:
+
+```Python
+{!../../../docs_src/first_steps/tutorial001.py!}
+```
+
+Yukarıdaki içeriği bir `main.py` dosyasına kopyalayalım.
+
+Uygulamayı çalıştıralım:
+
+get
operasyonu ile
+* `/` yoluna gelen istekler
+
+!!! info "`@decorator` Bilgisi"
+ Python'da `@something` sözdizimi "dekoratör" olarak adlandırılır.
+
+ Dekoratörler, dekoratif bir şapka gibi (sanırım terim buradan geliyor) fonksiyonların üzerlerine yerleştirilirler.
+
+ Bir "dekoratör" hemen altında bulunan fonksiyonu alır ve o fonksiyon ile bazı işlemler gerçekleştirir.
+
+ Bizim durumumuzda, kullandığımız dekoratör, **FastAPI**'a altındaki fonksiyonun `/` yoluna gelen `get` metodlu isteklerden sorumlu olduğunu söyler.
+
+ Bu bir **yol operasyonu dekoratörüdür**.
+
+Ayrıca diğer operasyonları da kullanabilirsiniz:
+
+* `@app.post()`
+* `@app.put()`
+* `@app.delete()`
+
+Daha az kullanılanları da kullanabilirsiniz:
+
+* `@app.options()`
+* `@app.head()`
+* `@app.patch()`
+* `@app.trace()`
+
+!!! tip "İpucu"
+ Her işlemi (HTTP metod) istediğiniz gibi kullanmakta özgürsünüz.
+
+ **FastAPI** herhangi bir özel amacı veya anlamı olması konusunda ısrarcı olmaz.
+
+ 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
+
+Aşağıdaki, bizim **yol operasyonu fonksiyonumuzdur**:
+
+* **yol**: `/`
+* **operasyon**: `get`
+* **fonksiyon**: "dekoratör"ün (`@app.get("/")`'in) altındaki fonksiyondur.
+
+```Python hl_lines="7"
+{!../../../docs_src/first_steps/tutorial001.py!}
+```
+
+Bu bir Python fonksiyonudur.
+
+Bu fonksiyon bir `GET` işlemi kullanılarak "`/`" bağlantısına bir istek geldiğinde **FastAPI** tarafından çağrılır.
+
+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!}
+```
+
+!!! 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!}
+```
+
+Bir `dict`, `list` veya `str`, `int` gibi tekil değerler döndürebilirsiniz.
+
+Ayrıca, Pydantic modelleri de döndürebilirsiniz (bu konu ileriki aşamalarda irdelenecektir).
+
+Otomatik olarak JSON'a dönüştürülecek (ORM'ler vb. dahil) başka birçok nesne ve model vardır. En beğendiklerinizi kullanmayı deneyin, yüksek ihtimalle destekleniyordur.
+
+## Özet
+
+* `FastAPI`'yı projemize dahil ettik.
+* Bir `app` örneği oluşturduk.
+* Bir **yol operasyonu dekoratörü** (`@app.get("/")` gibi) yazdık.
+* Bir **yol operasyonu fonksiyonu** (`def root(): ...` gibi) yazdık.
+* Geliştirme sunucumuzu (`uvicorn main:app --reload` gibi) çalıştırdık.
diff --git a/docs/tr/docs/tutorial/first_steps.md b/docs/tr/docs/tutorial/first_steps.md
deleted file mode 100644
index b39802f5d..000000000
--- a/docs/tr/docs/tutorial/first_steps.md
+++ /dev/null
@@ -1,336 +0,0 @@
-# İlk Adımlar
-
-En basit FastAPI dosyası şu şekildedir:
-
-```Python
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
-
-Bunu bir `main.py` dosyasına kopyalayın.
-
-Projeyi çalıştırın:
-
-get
işlemi kullanılarak
-
-
-!!! info "`@decorator` Bilgisi"
- Python `@something` şeklinde ifadeleri "decorator" olarak adlandırır.
-
- Decoratoru bir fonksiyonun üzerine koyarsınız. Dekoratif bir şapka gibi (Sanırım terim buradan gelmektedir).
-
- Bir "decorator" fonksiyonu alır ve bazı işlemler gerçekleştir.
-
- Bizim durumumzda decarator **FastAPI'ye** fonksiyonun bir `get` işlemi ile `/` pathine geldiğini söyler.
-
- Bu **path işlem decoratordür**
-
-Ayrıca diğer işlemleri de kullanabilirsiniz:
-
-* `@app.post()`
-* `@app.put()`
-* `@app.delete()`
-
-Ve daha egzotik olanları:
-
-* `@app.options()`
-* `@app.head()`
-* `@app.patch()`
-* `@app.trace()`
-
-!!! tip
- Her işlemi (HTTP method) istediğiniz gibi kullanmakta özgürsünüz.
-
- **FastAPI** herhangi bir özel anlamı zorlamaz.
-
- Buradaki bilgiler bir gereklilik değil, bir kılavuz olarak sunulmaktadır.
-
- Örneğin, GraphQL kullanırkan normalde tüm işlemleri yalnızca `POST` işlemini kullanarak gerçekleştirirsiniz.
-
-### Adım 4: **path işlem fonksiyonunu** tanımlayın
-
-Aşağıdakiler bizim **path işlem fonksiyonlarımızdır**:
-
-* **path**: `/`
-* **işlem**: `get`
-* **function**: "decorator"ün altındaki fonksiyondur (`@app.get("/")` altında).
-
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
-
-Bu bir Python fonksiyonudur.
-
-Bir `GET` işlemi kullanarak "`/`" URL'sine bir istek geldiğinde **FastAPI** tarafından çağrılır.
-
-Bu durumda bir `async` fonksiyonudur.
-
----
-
-Bunu `async def` yerine normal bir fonksiyon olarakta tanımlayabilirsiniz.
-
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial003.py!}
-```
-
-!!! note
-
- Eğer farkı bilmiyorsanız, [Async: *"Acelesi var?"*](../async.md#in-a-hurry){.internal-link target=_blank} kontrol edebilirsiniz.
-
-### Adım 5: İçeriği geri döndürün
-
-
-```Python hl_lines="8"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
-
-Bir `dict`, `list` döndürebilir veya `str`, `int` gibi tekil değerler döndürebilirsiniz.
-
-Ayrıca, Pydantic modellerini de döndürebilirsiniz. (Bununla ilgili daha sonra ayrıntılı bilgi göreceksiniz.)
-
-Otomatik olarak JSON'a dönüştürülecek(ORM'ler vb. dahil) başka birçok nesne ve model vardır. En beğendiklerinizi kullanmayı deneyin, yüksek ihtimalle destekleniyordur.
-
-## Özet
-
-* `FastAPI`'yi içe aktarın.
-* Bir `app` örneği oluşturun.
-* **path işlem decorator** yazın. (`@app.get("/")` gibi)
-* **path işlem fonksiyonu** yazın. (`def root(): ...` gibi)
-* Development sunucunuzu çalıştırın. (`uvicorn main:app --reload` gibi)
diff --git a/docs/tr/docs/tutorial/path-params.md b/docs/tr/docs/tutorial/path-params.md
new file mode 100644
index 000000000..cfcf881fd
--- /dev/null
+++ b/docs/tr/docs/tutorial/path-params.md
@@ -0,0 +1,254 @@
+# Yol Parametreleri
+
+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!}
+```
+
+Yol parametresi olan `item_id`'nin değeri, fonksiyonunuza `item_id` argümanı olarak aktarılacaktır.
+
+Eğer bu örneği çalıştırıp http://127.0.0.1:8000/items/foo sayfasına giderseniz, şöyle bir çıktı ile karşılaşırsınız:
+
+```JSON
+{"item_id":"foo"}
+```
+
+## Tip İçeren Yol Parametreleri
+
+Standart Python tip belirteçlerini kullanarak yol parametresinin tipini fonksiyonun içerisinde tanımlayabilirsiniz.
+
+```Python hl_lines="7"
+{!../../../docs_src/path_params/tutorial002.py!}
+```
+
+Bu durumda, `item_id` bir `int` olarak tanımlanacaktır.
+
+!!! check "Ek bilgi"
+ Bu sayede, fonksiyon içerisinde hata denetimi, kod tamamlama gibi konularda editör desteğine kavuşacaksınız.
+
+## Veri Dönüşümü
+
+Eğer bu örneği çalıştırıp tarayıcınızda http://127.0.0.1:8000/items/3 sayfasını açarsanız, şöyle bir yanıt ile karşılaşırsınız:
+
+```JSON
+{"item_id":3}
+```
+
+!!! check "Ek bilgi"
+ Dikkatinizi çekerim ki, fonksiyonunuzun aldığı (ve döndürdüğü) değer olan `3` bir string `"3"` değil aksine bir Python `int`'idir.
+
+ Bu tanımlamayla birlikte, **FastAPI** size otomatik istek "ayrıştırma" özelliği sağlar.
+
+## Veri Doğrulama
+
+Eğer tarayıcınızda http://127.0.0.1:8000/items/foo sayfasını açarsanız, şuna benzer güzel bir HTTP hatası ile karşılaşırsınız:
+
+```JSON
+{
+ "detail": [
+ {
+ "type": "int_parsing",
+ "loc": [
+ "path",
+ "item_id"
+ ],
+ "msg": "Input should be a valid integer, unable to parse string as an integer",
+ "input": "foo",
+ "url": "https://errors.pydantic.dev/2.1/v/int_parsing"
+ }
+ ]
+}
+```
+
+Çünkü burada `item_id` yol parametresi `int` tipinde bir değer beklerken `"foo"` yani `string` tipinde bir değer almıştı.
+
+Aynı hata http://127.0.0.1:8000/items/4.2 sayfasında olduğu gibi `int` yerine `float` bir değer verseydik de ortaya çıkardı.
+
+!!! check "Ek bilgi"
+ Böylece, aynı Python tip tanımlaması ile birlikte, **FastAPI** veri doğrulama özelliği sağlar.
+
+ Dikkatinizi çekerim ki, karşılaştığınız hata, doğrulamanın geçersiz olduğu mutlak noktayı da açık bir şekilde belirtiyor.
+
+ Bu özellik, API'ınızla iletişime geçen kodu geliştirirken ve ayıklarken inanılmaz derecede yararlı olacaktır.
+
+## Dokümantasyon
+
+Ayrıca, tarayıcınızı http://127.0.0.1:8000/docs adresinde açarsanız, aşağıdaki gibi otomatik ve interaktif bir API dökümantasyonu ile karşılaşırsınız:
+
++ Готовий до продакшину, високопродуктивний, простий у вивченні та швидкий для написання коду фреймворк +
+ + +--- + +**Документація**: https://fastapi.tiangolo.com + +**Програмний код**: https://github.com/tiangolo/fastapi + +--- + +FastAPI - це сучасний, швидкий (високопродуктивний), вебфреймворк для створення API за допомогою Python 3.8+,в основі якого лежить стандартна анотація типів Python. + +Ключові особливості: + +* **Швидкий**: Дуже висока продуктивність, на рівні з **NodeJS** та **Go** (завдяки Starlette та Pydantic). [Один із найшвидших фреймворків](#performance). + +* **Швидке написання коду**: Пришвидшує розробку функціоналу приблизно на 200%-300%. * +* **Менше помилок**: Зменшить кількість помилок спричинених людиною (розробником) на 40%. * +* **Інтуїтивний**: Чудова підтримка редакторами коду. Доповнення всюди. Зменште час на налагодження. +* **Простий**: Спроектований, для легкого використання та навчання. Знадобиться менше часу на читання документації. +* **Короткий**: Зведе до мінімуму дублювання коду. Кожен оголошений параметр може виконувати кілька функцій. +* **Надійний**: Ви матимете стабільний код готовий до продакшину з автоматичною інтерактивною документацією. +* **Стандартизований**: Оснований та повністю сумісний з відкритими стандартами для API: OpenAPI (попередньо відомий як Swagger) та JSON Schema. + +* оцінка на основі тестів внутрішньої команди розробників, створення продуктових застосунків. + +## Спонсори + + + +{% if sponsors %} +{% for sponsor in sponsors.gold -%} +async def
...uvicorn main:app --reload
...email_validator
- для валідації електронної пошти.
+* pydantic-settings
- для управління налаштуваннями.
+* pydantic-extra-types
- для додаткових типів, що можуть бути використані з Pydantic.
+
+
+Starlette використовує:
+
+* httpx
- Необхідно, якщо Ви хочете використовувати `TestClient`.
+* jinja2
- Необхідно, якщо Ви хочете використовувати шаблони як конфігурацію за замовчуванням.
+* python-multipart
- Необхідно, якщо Ви хочете підтримувати "розбір" форми за допомогою `request.form()`.
+* itsdangerous
- Необхідно для підтримки `SessionMiddleware`.
+* pyyaml
- Необхідно для підтримки Starlette `SchemaGenerator` (ймовірно, вам це не потрібно з FastAPI).
+* ujson
- Необхідно, якщо Ви хочете використовувати `UJSONResponse`.
+
+FastAPI / Starlette використовують:
+
+* uvicorn
- для сервера, який завантажує та обслуговує вашу програму.
+* orjson
- Необхідно, якщо Ви хочете використовувати `ORJSONResponse`.
+
+Ви можете встановити все це за допомогою `pip install fastapi[all]`.
+
+## Ліцензія
+
+Цей проєкт ліцензовано згідно з умовами ліцензії MIT.
diff --git a/docs/uk/docs/python-types.md b/docs/uk/docs/python-types.md
new file mode 100644
index 000000000..6c8e29016
--- /dev/null
+++ b/docs/uk/docs/python-types.md
@@ -0,0 +1,448 @@
+# Вступ до типів Python
+
+Python підтримує додаткові "підказки типу" ("type hints") (також звані "анотаціями типу" ("type annotations")).
+
+Ці **"type hints"** є спеціальним синтаксисом, що дозволяє оголошувати тип змінної.
+
+За допомогою оголошення типів для ваших змінних, редактори та інструменти можуть надати вам кращу підтримку.
+
+Це просто **швидкий посібник / нагадування** про анотації типів у Python. Він покриває лише мінімум, необхідний щоб використовувати їх з **FastAPI**... що насправді дуже мало.
+
+**FastAPI** повністю базується на цих анотаціях типів, вони дають йому багато переваг.
+
+Але навіть якщо ви ніколи не використаєте **FastAPI**, вам буде корисно дізнатись трохи про них.
+
+!!! note
+ Якщо ви експерт у Python і ви вже знаєте усе про анотації типів - перейдіть до наступного розділу.
+
+## Мотивація
+
+Давайте почнемо з простого прикладу:
+
+```Python
+{!../../../docs_src/python_types/tutorial001.py!}
+```
+
+Виклик цієї програми виводить:
+
+```
+John Doe
+```
+
+Функція виконує наступне:
+
+* Бере `first_name` та `last_name`.
+* Конвертує кожну літеру кожного слова у верхній регістр за допомогою `title()`.
+* Конкатенує їх разом із пробілом по середині.
+
+```Python hl_lines="2"
+{!../../../docs_src/python_types/tutorial001.py!}
+```
+
+### Редагуйте це
+
+Це дуже проста програма.
+
+Але тепер уявіть, що ви писали це з нуля.
+
+У певний момент ви розпочали б визначення функції, у вас були б готові параметри...
+
+Але тоді вам потрібно викликати "той метод, який переводить першу літеру у верхній регістр".
+
+Це буде `upper`? Чи `uppercase`? `first_uppercase`? `capitalize`?
+
+Тоді ви спробуєте давнього друга програміста - автозаповнення редактора коду.
+
+Ви надрукуєте перший параметр функції, `first_name`, тоді крапку (`.`), а тоді натиснете `Ctrl+Space`, щоб запустити автозаповнення.
+
+Але, на жаль, ви не отримаєте нічого корисного:
+
+get
+
+!!! info Thông tin về "`@decorator`"
+ Cú pháp `@something` trong Python được gọi là một "decorator".
+
+ Bạn đặt nó trên một hàm. Giống như một chiếc mũ xinh xắn (Tôi ddonas đó là lí do mà thuật ngữ này ra đời).
+
+ Một "decorator" lấy một hàm bên dưới và thực hiện một vài thứ với nó.
+
+ Trong trường hợp của chúng ta, decorator này nói **FastAPI** rằng hàm bên dưới ứng với **đường dẫn** `/` và một **toán tử** `get`.
+
+ 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:
+
+* `@app.post()`
+* `@app.put()`
+* `@app.delete()`
+
+Và nhiều hơn với các toán tử còn lại:
+
+* `@app.options()`
+* `@app.head()`
+* `@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.
+
+ **FastAPI** không bắt buộc bất kì ý nghĩa cụ thể nào.
+
+ Thông tin ở đây được biểu thị như là một chỉ dẫn, không phải là một yêu cầu bắt buộc.
+
+ 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ử**
+
+Đây là "**hàm cho đường dẫn toán tử**":
+
+* **đường dẫn**: là `/`.
+* **toán tử**: là `get`.
+* **hàm**: là hàm bên dưới "decorator" (bên dưới `@app.get("/")`).
+
+```Python hl_lines="7"
+{!../../../docs_src/first_steps/tutorial001.py!}
+```
+
+Đây là một hàm Python.
+
+Nó sẽ được gọi bởi **FastAPI** bất cứ khi nào nó nhận một request tới URL "`/`" sử dụng một toán tử `GET`.
+
+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!}
+```
+
+!!! 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!}
+```
+
+Bạn có thể trả về một `dict`, `list`, một trong những giá trị đơn như `str`, `int`,...
+
+Bạn cũng có thể trả về Pydantic model (bạn sẽ thấy nhiều hơn về nó sau).
+
+Có nhiều object và model khác nhau sẽ được tự động chuyển đổi sang JSON (bao gồm cả ORM,...). Thử sử dụng loại ưa thích của bạn, nó có khả năng cao đã được hỗ trợ.
+
+## Tóm lại
+
+* Import `FastAPI`.
+* Tạo một `app` instance.
+* Viết một **decorator cho đường dẫn toán tử** (giống như `@app.get("/")`).
+* Viết một **hàm cho đường dẫn toán tử** (giống như `def root(): ...` ở trên).
+* Chạy server trong môi trường phát triển (giống như `uvicorn main:app --reload`).
diff --git a/docs/vi/docs/tutorial/index.md b/docs/vi/docs/tutorial/index.md
new file mode 100644
index 000000000..e8a93fe40
--- /dev/null
+++ b/docs/vi/docs/tutorial/index.md
@@ -0,0 +1,80 @@
+# Hướng dẫn sử dụng
+
+Hướng dẫn này cho bạn thấy từng bước cách sử dụng **FastAPI** đa số các tính năng của nó.
+
+Mỗi phần được xây dựng từ những phần trước đó, nhưng nó được cấu trúc thành các chủ đề riêng biệt, do đó bạn có thể xem trực tiếp từng phần cụ thể bất kì để giải quyết những API cụ thể mà bạn cần.
+
+Nó cũng được xây dựng để làm việc như một tham chiếu trong tương lai.
+
+Do đó bạn có thể quay lại và tìm chính xác những gì bạn cần.
+
+## Chạy mã
+
+Tất cả các code block có thể được sao chép và sử dụng trực tiếp (chúng thực chất là các tệp tin Python đã được kiểm thử).
+
+Để chạy bất kì ví dụ nào, sao chép code tới tệp tin `main.py`, và bắt đầu `uvicorn` với:
+
++ Ìlànà wẹ́ẹ́bù FastAPI, iṣẹ́ gíga, ó rọrùn láti kọ̀, o yára láti kóòdù, ó sì ṣetán fún iṣelọpọ ní lílo +
+ + +--- + +**Àkọsílẹ̀**: https://fastapi.tiangolo.com + +**Orisun Kóòdù**: https://github.com/tiangolo/fastapi + +--- + +FastAPI jẹ́ ìgbàlódé, tí ó yára (iṣẹ-giga), ìlànà wẹ́ẹ́bù fún kikọ àwọn API pẹ̀lú Python 3.8+ èyí tí ó da lori àwọn ìtọ́kasí àmì irúfẹ́ Python. + +Àwọn ẹya pàtàkì ni: + +* **Ó yára**: Iṣẹ tí ó ga púpọ̀, tí ó wa ni ibamu pẹ̀lú **NodeJS** àti **Go** (ọpẹ si Starlette àti Pydantic). [Ọkan nínú àwọn ìlànà Python ti o yára jùlọ ti o wa](#performance). +* **Ó yára láti kóòdù**: O mu iyara pọ si láti kọ àwọn ẹya tuntun kóòdù nipasẹ "Igba ìdá ọgọ́rùn-ún" (i.e. 200%) si "ọ̀ọ́dúrún ìdá ọgọ́rùn-ún" (i.e. 300%). +* **Àìtọ́ kékeré**: O n din aṣiṣe ku bi ọgbon ìdá ọgọ́rùn-ún (i.e. 40%) ti eda eniyan (oṣiṣẹ kóòdù) fa. * +* **Ọgbọ́n àti ìmọ̀**: Atilẹyin olootu nla. Ìparí nibi gbogbo. Àkókò díẹ̀ nipa wíwá ibi tí ìṣòro kóòdù wà. +* **Irọrun**: A kọ kí ó le rọrun láti lo àti láti kọ ẹkọ nínú rè. Ó máa fún ọ ní àkókò díẹ̀ látı ka àkọsílẹ. +* **Ó kúkurú ní kikọ**: Ó dín àtúnkọ àti àtúntò kóòdù kù. Ìkéde àṣàyàn kọ̀ọ̀kan nínú rẹ̀ ní ọ̀pọ̀lọpọ̀ àwọn ìlò. O ṣe iranlọwọ láti má ṣe ní ọ̀pọ̀lọpọ̀ àṣìṣe. +* **Ó lágbára**: Ó ń ṣe àgbéjáde kóòdù tí ó ṣetán fún ìṣelọ́pọ̀. Pẹ̀lú àkọsílẹ̀ tí ó máa ṣàlàyé ara rẹ̀ fún ẹ ní ìbáṣepọ̀ aládàáṣiṣẹ́ pẹ̀lú rè. +* **Ajohunše/Ìtọ́kasí**: Ó da lori (àti ibamu ni kikun pẹ̀lú) àwọn ìmọ ajohunše/ìtọ́kasí fún àwọn API: OpenAPI (èyí tí a mọ tẹlẹ si Swagger) àti JSON Schema. + +* iṣiro yi da lori àwọn idanwo tí ẹgbẹ ìdàgbàsókè FastAPI ṣe, nígbàtí wọn kọ àwọn ohun elo iṣelọpọ kóòdù pẹ̀lú rẹ. + +## Àwọn onígbọ̀wọ́ + + + +{% if sponsors %} +{% for sponsor in sponsors.gold -%} +async def
...uvicorn main:app --reload
...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.
+
+Èyí tí Starlette ń lò:
+
+* httpx
- Nílò tí ó bá fẹ́ láti lọ `TestClient`.
+* jinja2
- Nílò tí ó bá fẹ́ láti lọ iṣeto awoṣe aiyipada.
+* python-multipart
- Nílò tí ó bá fẹ́ láti ṣe àtìlẹ́yìn fún "àyẹ̀wò" fọọmu, pẹ̀lú `request.form()`.
+* itsdangerous
- Nílò fún àtìlẹ́yìn `SessionMiddleware`.
+* pyyaml
- Nílò fún àtìlẹ́yìn Starlette's `SchemaGenerator` (ó ṣe ṣe kí ó má nílò rẹ̀ fún FastAPI).
+* ujson
- Nílò tí ó bá fẹ́ láti lọ `UJSONResponse`.
+
+Èyí tí FastAPI / Starlette ń lò:
+
+* uvicorn
- Fún olupin tí yóò sẹ́ àmúyẹ àti tí yóò ṣe ìpèsè fún iṣẹ́ rẹ tàbí ohun èlò rẹ.
+* orjson
- Nílò tí ó bá fẹ́ láti lọ `ORJSONResponse`.
+
+Ó lè fi gbogbo àwọn wọ̀nyí sórí ẹrọ pẹ̀lú `pip install "fastapi[all]"`.
+
+## Iwe-aṣẹ
+
+Iṣẹ́ yìí ni iwe-aṣẹ lábẹ́ àwọn òfin tí iwe-aṣẹ MIT.
diff --git a/docs/yo/mkdocs.yml b/docs/yo/mkdocs.yml
new file mode 100644
index 000000000..de18856f4
--- /dev/null
+++ b/docs/yo/mkdocs.yml
@@ -0,0 +1 @@
+INHERIT: ../en/mkdocs.yml
diff --git a/docs/zh-hant/docs/index.md b/docs/zh-hant/docs/index.md
new file mode 100644
index 000000000..e7a2efec9
--- /dev/null
+++ b/docs/zh-hant/docs/index.md
@@ -0,0 +1,470 @@
+
++ FastAPI 框架,高效能,易於學習,快速開發,適用於生產環境 +
+ + +--- + +**文件**: https://fastapi.tiangolo.com + +**程式碼**: https://github.com/tiangolo/fastapi + +--- + +FastAPI 是一個現代、快速(高效能)的 web 框架,用於 Python 3.8+ 並採用標準 Python 型別提示。 + +主要特點包含: + +- **快速**: 非常高的效能,可與 **NodeJS** 和 **Go** 效能相當 (歸功於 Starlette and Pydantic)。 [FastAPI 是最快的 Python web 框架之一](#performance)。 +- **極速開發**: 提高開發功能的速度約 200% 至 300%。 \* +- **更少的 Bug**: 減少約 40% 的人為(開發者)導致的錯誤。 \* +- **直覺**: 具有出色的編輯器支援,處處都有自動補全以減少偵錯時間。 +- **簡單**: 設計上易於使用和學習,大幅減少閱讀文件的時間。 +- **簡潔**: 最小化程式碼重複性。可以通過不同的參數聲明來實現更豐富的功能,和更少的錯誤。 +- **穩健**: 立即獲得生產級可用的程式碼,還有自動生成互動式文件。 +- **標準化**: 基於 (且完全相容於) OpenAPIs 的相關標準:OpenAPI(之前被稱為 Swagger)和JSON Schema。 + +\* 基於內部開發團隊在建立生產應用程式時的測試預估。 + +## 贊助 + + + +{% if sponsors %} +{% for sponsor in sponsors.gold -%} +async def
...uvicorn main:app --reload
...email_validator
- 用於電子郵件驗證。
+- pydantic-settings
- 用於設定管理。
+- pydantic-extra-types
- 用於與 Pydantic 一起使用的額外型別。
+
+用於 Starlette:
+
+- httpx
- 使用 `TestClient`時必須安裝。
+- jinja2
- 使用預設的模板配置時必須安裝。
+- python-multipart
- 需要使用 `request.form()` 對表單進行 "解析" 時安裝。
+- itsdangerous
- 需要使用 `SessionMiddleware` 支援時安裝。
+- pyyaml
- 用於支援 Starlette 的 `SchemaGenerator` (如果你使用 FastAPI,可能不需要它)。
+- ujson
- 使用 `UJSONResponse` 時必須安裝。
+
+用於 FastAPI / Starlette:
+
+- uvicorn
- 用於加載和運行應用程式的服務器。
+- orjson
- 使用 `ORJSONResponse`時必須安裝。
+
+你可以使用 `pip install "fastapi[all]"` 來安裝這些所有依賴套件。
+
+## 授權
+
+該項目遵循 MIT 許可協議。
diff --git a/docs/zh-hant/docs/learn/index.md b/docs/zh-hant/docs/learn/index.md
new file mode 100644
index 000000000..eb7d7096a
--- /dev/null
+++ b/docs/zh-hant/docs/learn/index.md
@@ -0,0 +1,5 @@
+# 學習
+
+以下是學習 FastAPI 的入門介紹和教學。
+
+你可以將其視為一本**書籍**或一門**課程**,這是**官方**認可並推薦的 FastAPI 學習方式。 😎
diff --git a/docs/zh-hant/mkdocs.yml b/docs/zh-hant/mkdocs.yml
new file mode 100644
index 000000000..de18856f4
--- /dev/null
+++ b/docs/zh-hant/mkdocs.yml
@@ -0,0 +1 @@
+INHERIT: ../en/mkdocs.yml
diff --git a/docs/zh/docs/advanced/additional-responses.md b/docs/zh/docs/advanced/additional-responses.md
new file mode 100644
index 000000000..2a1e1ed89
--- /dev/null
+++ b/docs/zh/docs/advanced/additional-responses.md
@@ -0,0 +1,219 @@
+# OPENAPI 中的其他响应
+
+您可以声明附加响应,包括附加状态代码、媒体类型、描述等。
+
+这些额外的响应将包含在OpenAPI模式中,因此它们也将出现在API文档中。
+
+但是对于那些额外的响应,你必须确保你直接返回一个像 `JSONResponse` 一样的 `Response` ,并包含你的状态代码和内容。
+
+## `model`附加响应
+您可以向路径操作装饰器传递参数 `responses` 。
+
+它接收一个 `dict`,键是每个响应的状态代码(如`200`),值是包含每个响应信息的其他 `dict`。
+
+每个响应字典都可以有一个关键模型,其中包含一个 `Pydantic` 模型,就像 `response_model` 一样。
+
+**FastAPI**将采用该模型,生成其`JSON Schema`并将其包含在`OpenAPI`中的正确位置。
+
+例如,要声明另一个具有状态码 `404` 和`Pydantic`模型 `Message` 的响应,可以写:
+```Python hl_lines="18 22"
+{!../../../docs_src/additional_responses/tutorial001.py!}
+```
+
+
+!!! Note
+ 请记住,您必须直接返回 `JSONResponse` 。
+
+!!! Info
+ `model` 密钥不是OpenAPI的一部分。
+ **FastAPI**将从那里获取`Pydantic`模型,生成` JSON Schema` ,并将其放在正确的位置。
+ - 正确的位置是:
+ - 在键 `content` 中,其具有另一个`JSON`对象( `dict` )作为值,该`JSON`对象包含:
+ - 媒体类型的密钥,例如 `application/json` ,它包含另一个`JSON`对象作为值,该对象包含:
+ - 一个键` schema` ,它的值是来自模型的`JSON Schema`,正确的位置在这里。
+ - **FastAPI**在这里添加了对OpenAPI中另一个地方的全局JSON模式的引用,而不是直接包含它。这样,其他应用程序和客户端可以直接使用这些JSON模式,提供更好的代码生成工具等。
+
+
+**在OpenAPI中为该路径操作生成的响应将是:**
+
+```json hl_lines="3-12"
+{
+ "responses": {
+ "404": {
+ "description": "Additional Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Message"
+ }
+ }
+ }
+ },
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Item"
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ }
+}
+
+```
+**模式被引用到OpenAPI模式中的另一个位置:**
+```json hl_lines="4-16"
+{
+ "components": {
+ "schemas": {
+ "Message": {
+ "title": "Message",
+ "required": [
+ "message"
+ ],
+ "type": "object",
+ "properties": {
+ "message": {
+ "title": "Message",
+ "type": "string"
+ }
+ }
+ },
+ "Item": {
+ "title": "Item",
+ "required": [
+ "id",
+ "value"
+ ],
+ "type": "object",
+ "properties": {
+ "id": {
+ "title": "Id",
+ "type": "string"
+ },
+ "value": {
+ "title": "Value",
+ "type": "string"
+ }
+ }
+ },
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": [
+ "loc",
+ "msg",
+ "type"
+ ],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "msg": {
+ "title": "Message",
+ "type": "string"
+ },
+ "type": {
+ "title": "Error Type",
+ "type": "string"
+ }
+ }
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/ValidationError"
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+```
+## 主响应的其他媒体类型
+
+您可以使用相同的 `responses` 参数为相同的主响应添加不同的媒体类型。
+
+例如,您可以添加一个额外的媒体类型` image/png` ,声明您的路径操作可以返回JSON对象(媒体类型 `application/json` )或PNG图像:
+
+```Python hl_lines="19-24 28"
+{!../../../docs_src/additional_responses/tutorial002.py!}
+```
+
+!!! Note
+ - 请注意,您必须直接使用 `FileResponse` 返回图像。
+
+!!! Info
+ - 除非在 `responses` 参数中明确指定不同的媒体类型,否则**FastAPI**将假定响应与主响应类具有相同的媒体类型(默认为` application/json` )。
+ - 但是如果您指定了一个自定义响应类,并将 `None `作为其媒体类型,**FastAPI**将使用 `application/json` 作为具有关联模型的任何其他响应。
+
+## 组合信息
+您还可以联合接收来自多个位置的响应信息,包括 `response_model `、 `status_code` 和 `responses `参数。
+
+您可以使用默认的状态码 `200` (或者您需要的自定义状态码)声明一个 `response_model `,然后直接在OpenAPI模式中在 `responses` 中声明相同响应的其他信息。
+
+**FastAPI**将保留来自 `responses` 的附加信息,并将其与模型中的JSON Schema结合起来。
+
+例如,您可以使用状态码 `404` 声明响应,该响应使用`Pydantic`模型并具有自定义的` description` 。
+
+以及一个状态码为 `200` 的响应,它使用您的 `response_model` ,但包含自定义的 `example` :
+
+```Python hl_lines="20-31"
+{!../../../docs_src/additional_responses/tutorial003.py!}
+```
+
+所有这些都将被合并并包含在您的OpenAPI中,并在API文档中显示:
+
+## 联合预定义响应和自定义响应
+
+您可能希望有一些应用于许多路径操作的预定义响应,但是你想将不同的路径和自定义的相应组合在一块。
+对于这些情况,你可以使用Python的技术,将 `dict` 与 `**dict_to_unpack` 解包:
+```Python
+old_dict = {
+ "old key": "old value",
+ "second old key": "second old value",
+}
+new_dict = {**old_dict, "new key": "new value"}
+```
+
+这里, new_dict 将包含来自 old_dict 的所有键值对加上新的键值对:
+```python
+{
+ "old key": "old value",
+ "second old key": "second old value",
+ "new key": "new value",
+}
+```
+您可以使用该技术在路径操作中重用一些预定义的响应,并将它们与其他自定义响应相结合。
+**例如:**
+```Python hl_lines="13-17 26"
+{!../../../docs_src/additional_responses/tutorial004.py!}
+```
+## 有关OpenAPI响应的更多信息
+
+要了解您可以在响应中包含哪些内容,您可以查看OpenAPI规范中的以下部分:
+ + [OpenAPI响应对象](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#responsesObject),它包括 Response Object 。
+ + [OpenAPI响应对象](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#responseObject),您可以直接在 `responses` 参数中的每个响应中包含任何内容。包括 `description` 、 `headers` 、 `content` (其中是声明不同的媒体类型和JSON Schemas)和 `links` 。
diff --git a/docs/zh/docs/advanced/advanced-dependencies.md b/docs/zh/docs/advanced/advanced-dependencies.md
new file mode 100644
index 000000000..b2f6e3559
--- /dev/null
+++ b/docs/zh/docs/advanced/advanced-dependencies.md
@@ -0,0 +1,71 @@
+# 高级依赖项
+
+## 参数化的依赖项
+
+我们之前看到的所有依赖项都是写死的函数或类。
+
+但也可以为依赖项设置参数,避免声明多个不同的函数或类。
+
+假设要创建校验查询参数 `q` 是否包含固定内容的依赖项。
+
+但此处要把待检验的固定内容定义为参数。
+
+## **可调用**实例
+
+Python 可以把类实例变为**可调用项**。
+
+这里说的不是类本身(类本就是可调用项),而是类实例。
+
+为此,需要声明 `__call__` 方法:
+
+```Python hl_lines="10"
+{!../../../docs_src/dependencies/tutorial011.py!}
+```
+
+本例中,**FastAPI** 使用 `__call__` 检查附加参数及子依赖项,稍后,还要调用它向*路径操作函数*传递值。
+
+## 参数化实例
+
+接下来,使用 `__init__` 声明用于**参数化**依赖项的实例参数:
+
+```Python hl_lines="7"
+{!../../../docs_src/dependencies/tutorial011.py!}
+```
+
+本例中,**FastAPI** 不使用 `__init__`,我们要直接在代码中使用。
+
+## 创建实例
+
+使用以下代码创建类实例:
+
+```Python hl_lines="16"
+{!../../../docs_src/dependencies/tutorial011.py!}
+```
+
+这样就可以**参数化**依赖项,它包含 `checker.fixed_content` 的属性 - `"bar"`。
+
+## 把实例作为依赖项
+
+然后,不要再在 `Depends(checker)` 中使用 `Depends(FixedContentQueryChecker)`, 而是要使用 `checker`,因为依赖项是类实例 - `checker`,不是类。
+
+处理依赖项时,**FastAPI** 以如下方式调用 `checker`:
+
+```Python
+checker(q="somequery")
+```
+
+……并用*路径操作函数*的参数 `fixed_content_included` 返回依赖项的值:
+
+```Python hl_lines="20"
+{!../../../docs_src/dependencies/tutorial011.py!}
+```
+
+!!! tip "提示"
+
+ 本章示例有些刻意,也看不出有什么用处。
+
+ 这个简例只是为了说明高级依赖项的运作机制。
+
+ 在有关安全的章节中,工具函数将以这种方式实现。
+
+ 只要能理解本章内容,就能理解安全工具背后的运行机制。
diff --git a/docs/zh/docs/advanced/behind-a-proxy.md b/docs/zh/docs/advanced/behind-a-proxy.md
new file mode 100644
index 000000000..738bd7119
--- /dev/null
+++ b/docs/zh/docs/advanced/behind-a-proxy.md
@@ -0,0 +1,351 @@
+# 使用代理
+
+有些情况下,您可能要使用 Traefik 或 Nginx 等**代理**服务器,并添加应用不能识别的附加路径前缀配置。
+
+此时,要使用 `root_path` 配置应用。
+
+`root_path` 是 ASGI 规范提供的机制,FastAPI 就是基于此规范开发的(通过 Starlette)。
+
+`root_path` 用于处理这些特定情况。
+
+在挂载子应用时,也可以在内部使用。
+
+## 移除路径前缀的代理
+
+本例中,移除路径前缀的代理是指在代码中声明路径 `/app`,然后在应用顶层添加代理,把 **FastAPI** 应用放在 `/api/v1` 路径下。
+
+本例的原始路径 `/app` 实际上是在 `/api/v1/app` 提供服务。
+
+哪怕所有代码都假设只有 `/app`。
+
+代理只在把请求传送给 Uvicorn 之前才会**移除路径前缀**,让应用以为它是在 `/app` 提供服务,因此不必在代码中加入前缀 `/api/v1`。
+
+但之后,在(前端)打开 API 文档时,代理会要求在 `/openapi.json`,而不是 `/api/v1/openapi.json` 中提取 OpenAPI 概图。
+
+因此, (运行在浏览器中的)前端会尝试访问 `/openapi.json`,但没有办法获取 OpenAPI 概图。
+
+这是因为应用使用了以 `/api/v1` 为路径前缀的代理,前端要从 `/api/v1/openapi.json` 中提取 OpenAPI 概图。
+
+```mermaid
+graph LR
+
+browser("Browser")
+proxy["Proxy on http://0.0.0.0:9999/api/v1/app"]
+server["Server on http://127.0.0.1:8000/app"]
+
+browser --> proxy
+proxy --> server
+```
+
+!!! tip "提示"
+
+ IP `0.0.0.0` 常用于指程序监听本机或服务器上的所有有效 IP。
+
+API 文档还需要 OpenAPI 概图声明 API `server` 位于 `/api/v1`(使用代理时的 URL)。例如:
+
+```JSON hl_lines="4-8"
+{
+ "openapi": "3.0.2",
+ // More stuff here
+ "servers": [
+ {
+ "url": "/api/v1"
+ }
+ ],
+ "paths": {
+ // More stuff here
+ }
+}
+```
+
+本例中的 `Proxy` 是 **Traefik**,`server` 是运行 FastAPI 应用的 **Uvicorn**。
+
+### 提供 `root_path`
+
+为此,要以如下方式使用命令行选项 `--root-path`:
+
++没有大家之前所做的工作,**FastAPI** 就不会存在。 + +以前创建的这些工具为它的出现提供了灵感。 + +在那几年中,我一直回避创建新的框架。首先,我尝试使用各种框架、插件、工具解决 **FastAPI** 现在的功能。 + +但到了一定程度之后,我别无选择,只能从之前的工具中汲取最优思路,并以尽量好的方式把这些思路整合在一起,使用之前甚至是不支持的语言特性(Python 3.6+ 的类型提示),从而创建一个能满足我所有需求的框架。 + ++ +## 调研 + +通过使用之前所有的备选方案,我有机会从它们之中学到了很多东西,获取了很多想法,并以我和我的开发团队能想到的最好方式把这些思路整合成一体。 + +例如,大家都清楚,在理想状态下,它应该基于标准的 Python 类型提示。 + +而且,最好的方式是使用现有的标准。 + +因此,甚至在开发 **FastAPI** 前,我就花了几个月的时间研究 OpenAPI、JSON Schema、OAuth2 等规范。深入理解它们之间的关系、重叠及区别之处。 + +## 设计 + +然后,我又花了一些时间从用户角度(使用 FastAPI 的开发者)设计了开发者 **API**。 + +同时,我还在最流行的 Python 代码编辑器中测试了很多思路,包括 PyCharm、VS Code、基于 Jedi 的编辑器。 + +根据最新 Python 开发者调研报告显示,这几种编辑器覆盖了约 80% 的用户。 + +也就是说,**FastAPI** 针对差不多 80% 的 Python 开发者使用的编辑器进行了测试,而且其它大多数编辑器的工作方式也与之类似,因此,**FastAPI** 的优势几乎能在所有编辑器上体现。 + +通过这种方式,我就能找到尽可能减少代码重复的最佳方式,进而实现处处都有自动补全、类型提示与错误检查等支持。 + +所有这些都是为了给开发者提供最佳的开发体验。 + +## 需求项 + +经过测试多种备选方案,我最终决定使用 **Pydantic**,并充分利用它的优势。 + +我甚至为它做了不少贡献,让它完美兼容了 JSON Schema,支持多种方式定义约束声明,并基于多个编辑器,改进了它对编辑器支持(类型检查、自动补全)。 + +在开发期间,我还为 **Starlette** 做了不少贡献,这是另一个关键需求项。 + +## 开发 + +当我启动 **FastAPI** 开发的时候,绝大多数部件都已经就位,设计已经定义,需求项和工具也已经准备就绪,相关标准与规范的知识储备也非常清晰而新鲜。 + +## 未来 + +至此,**FastAPI** 及其理念已经为很多人所用。 + +对于很多用例,它比以前很多备选方案都更适用。 + +很多开发者和开发团队已经依赖 **FastAPI** 开发他们的项目(包括我和我的团队)。 + +但,**FastAPI** 仍有很多改进的余地,也还需要添加更多的功能。 + +总之,**FastAPI** 前景光明。 + +在此,我们衷心感谢[您的帮助](help-fastapi.md){.internal-link target=_blank}。 diff --git a/docs/zh/docs/index.md b/docs/zh/docs/index.md index 1de2a8d36..d776e5813 100644 --- a/docs/zh/docs/index.md +++ b/docs/zh/docs/index.md @@ -24,7 +24,7 @@ --- -FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框架,使用 Python 3.6+ 并基于标准的 Python 类型提示。 +FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框架,使用 Python 3.8+ 并基于标准的 Python 类型提示。 关键特性: @@ -107,7 +107,7 @@ FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框 ## 依赖 -Python 3.6 及更高版本 +Python 3.8 及更高版本 FastAPI 站在以下巨人的肩膀之上: @@ -323,7 +323,7 @@ def update_item(item_id: int, item: Item): 你不需要去学习新的语法、了解特定库的方法或类,等等。 -只需要使用标准的 **Python 3.6 及更高版本**。 +只需要使用标准的 **Python 3.8 及更高版本**。 举个例子,比如声明 `int` 类型: diff --git a/docs/zh/docs/learn/index.md b/docs/zh/docs/learn/index.md new file mode 100644 index 000000000..38696f6fe --- /dev/null +++ b/docs/zh/docs/learn/index.md @@ -0,0 +1,5 @@ +# 学习 + +以下是学习 **FastAPI** 的介绍部分和教程。 + +您可以认为这是一本 **书**,一门 **课程**,是 **官方** 且推荐的学习FastAPI的方法。😎 diff --git a/docs/zh/docs/project-generation.md b/docs/zh/docs/project-generation.md new file mode 100644 index 000000000..feafa5333 --- /dev/null +++ b/docs/zh/docs/project-generation.md @@ -0,0 +1,84 @@ +# 项目生成 - 模板 + +项目生成器一般都会提供很多初始设置、安全措施、数据库,甚至还准备好了第一个 API 端点,能帮助您快速上手。 + +项目生成器的设置通常都很主观,您可以按需更新或修改,但对于您的项目来说,它是非常好的起点。 + +## 全栈 FastAPI + PostgreSQL + +GitHub:https://github.com/tiangolo/full-stack-fastapi-postgresql + +### 全栈 FastAPI + PostgreSQL - 功能 + +* 完整的 **Docker** 集成(基于 Docker) +* Docker Swarm 开发模式 +* **Docker Compose** 本地开发集成与优化 +* **生产可用**的 Python 网络服务器,使用 Uvicorn 或 Gunicorn +* Python **FastAPI** 后端: +* * **速度快**:可与 **NodeJS** 和 **Go** 比肩的极高性能(归功于 Starlette 和 Pydantic) + * **直观**:强大的编辑器支持,处处皆可自动补全,减少调试时间 + * **简单**:易学、易用,阅读文档所需时间更短 + * **简短**:代码重复最小化,每次参数声明都可以实现多个功能 + * **健壮**: 生产级别的代码,还有自动交互文档 + * **基于标准**:完全兼容并基于 API 开放标准:OpenAPI 和 JSON Schema + * **更多功能**包括自动验证、序列化、交互文档、OAuth2 JWT 令牌身份验证等 +* **安全密码**,默认使用密码哈希 +* **JWT 令牌**身份验证 +* **SQLAlchemy** 模型(独立于 Flask 扩展,可直接用于 Celery Worker) +* 基础的用户模型(可按需修改或删除) +* **Alembic** 迁移 +* **CORS**(跨域资源共享) +* **Celery** Worker 可从后端其它部分有选择地导入并使用模型和代码 +* REST 后端测试基于 Pytest,并与 Docker 集成,可独立于数据库实现完整的 API 交互测试。因为是在 Docker 中运行,每次都可从头构建新的数据存储(使用 ElasticSearch、MongoDB、CouchDB 等数据库,仅测试 API 运行) +* Python 与 **Jupyter Kernels** 集成,用于远程或 Docker 容器内部开发,使用 Atom Hydrogen 或 Visual Studio Code 的 Jupyter 插件 +* **Vue** 前端: + * 由 Vue CLI 生成 + * **JWT 身份验证**处理 + * 登录视图 + * 登录后显示主仪表盘视图 + * 主仪表盘支持用户创建与编辑 + * 用户信息编辑 + * **Vuex** + * **Vue-router** + * **Vuetify** 美化组件 + * **TypeScript** + * 基于 **Nginx** 的 Docker 服务器(优化了 Vue-router 配置) + * Docker 多阶段构建,无需保存或提交编译的代码 + * 在构建时运行前端测试(可禁用) + * 尽量模块化,开箱即用,但仍可使用 Vue CLI 重新生成或创建所需项目,或复用所需内容 +* 使用 **PGAdmin** 管理 PostgreSQL 数据库,可轻松替换为 PHPMyAdmin 或 MySQL +* 使用 **Flower** 监控 Celery 任务 +* 使用 **Traefik** 处理前后端负载平衡,可把前后端放在同一个域下,按路径分隔,但在不同容器中提供服务 +* Traefik 集成,包括自动生成 Let's Encrypt **HTTPS** 凭证 +* GitLab **CI**(持续集成),包括前后端测试 + +## 全栈 FastAPI + Couchbase + +GitHub:https://github.com/tiangolo/full-stack-fastapi-couchbase + +⚠️ **警告** ⚠️ + +如果您想从头开始创建新项目,建议使用以下备选方案。 + +例如,项目生成器全栈 FastAPI + PostgreSQL 会更适用,这个项目的维护积极,用的人也多,还包括了所有新功能和改进内容。 + +当然,您也可以放心使用这个基于 Couchbase 的生成器,它也能正常使用。就算用它生成项目也没有任何问题(为了更好地满足需求,您可以自行更新这个项目)。 + +详见资源仓库中的文档。 + +## 全栈 FastAPI + MongoDB + +……敬请期待,得看我有没有时间做这个项目。😅 🎉 + +## FastAPI + spaCy 机器学习模型 + +GitHub:https://github.com/microsoft/cookiecutter-spacy-fastapi + +### FastAPI + spaCy 机器学习模型 - 功能 + +* 集成 **spaCy** NER 模型 +* 内置 **Azure 认知搜索**请求格式 +* **生产可用**的 Python 网络服务器,使用 Uvicorn 与 Gunicorn +* 内置 **Azure DevOps** Kubernetes (AKS) CI/CD 开发 +* **多语**支持,可在项目设置时选择 spaCy 内置的语言 +* 不仅局限于 spaCy,可**轻松扩展**至其它模型框架(Pytorch、TensorFlow) diff --git a/docs/zh/docs/tutorial/background-tasks.md b/docs/zh/docs/tutorial/background-tasks.md index c8568298b..94b75d4fd 100644 --- a/docs/zh/docs/tutorial/background-tasks.md +++ b/docs/zh/docs/tutorial/background-tasks.md @@ -69,7 +69,7 @@ {!> ../../../docs_src/background_tasks/tutorial002_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="14 16 23 26" {!> ../../../docs_src/background_tasks/tutorial002_an.py!} @@ -84,7 +84,7 @@ {!> ../../../docs_src/background_tasks/tutorial002_py310.py!} ``` -=== "Python 3.6+ 没Annotated" +=== "Python 3.8+ 没Annotated" !!! tip 尽可能选择使用 `Annotated` 的版本。 diff --git a/docs/zh/docs/tutorial/bigger-applications.md b/docs/zh/docs/tutorial/bigger-applications.md index 9f0134f68..138959566 100644 --- a/docs/zh/docs/tutorial/bigger-applications.md +++ b/docs/zh/docs/tutorial/bigger-applications.md @@ -79,7 +79,7 @@ 你可以导入它并通过与 `FastAPI` 类相同的方式创建一个「实例」: -```Python hl_lines="1 3" +```Python hl_lines="1 3" title="app/routers/users.py" {!../../../docs_src/bigger_applications/app/routers/users.py!} ``` @@ -89,7 +89,7 @@ 使用方式与 `FastAPI` 类相同: -```Python hl_lines="6 11 16" +```Python hl_lines="6 11 16" title="app/routers/users.py" {!../../../docs_src/bigger_applications/app/routers/users.py!} ``` @@ -112,7 +112,7 @@ 现在我们将使用一个简单的依赖项来读取一个自定义的 `X-Token` 请求首部: -```Python hl_lines="1 4-6" +```Python hl_lines="1 4-6" title="app/dependencies.py" {!../../../docs_src/bigger_applications/app/dependencies.py!} ``` @@ -143,7 +143,7 @@ 因此,我们可以将其添加到 `APIRouter` 中,而不是将其添加到每个路径操作中。 -```Python hl_lines="5-10 16 21" +```Python hl_lines="5-10 16 21" title="app/routers/items.py" {!../../../docs_src/bigger_applications/app/routers/items.py!} ``` @@ -195,7 +195,7 @@ async def read_item(item_id: str): 因此,我们通过 `..` 对依赖项使用了相对导入: -```Python hl_lines="3" +```Python hl_lines="3" title="app/routers/items.py" {!../../../docs_src/bigger_applications/app/routers/items.py!} ``` @@ -265,7 +265,7 @@ from ...dependencies import get_token_header 但是我们仍然可以添加*更多*将会应用于特定的*路径操作*的 `tags`,以及一些特定于该*路径操作*的额外 `responses`: -```Python hl_lines="30-31" +```Python hl_lines="30-31" title="app/routers/items.py" {!../../../docs_src/bigger_applications/app/routers/items.py!} ``` @@ -290,7 +290,7 @@ from ...dependencies import get_token_header 我们甚至可以声明[全局依赖项](dependencies/global-dependencies.md){.internal-link target=_blank},它会和每个 `APIRouter` 的依赖项组合在一起: -```Python hl_lines="1 3 7" +```Python hl_lines="1 3 7" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` @@ -298,7 +298,7 @@ from ...dependencies import get_token_header 现在,我们导入具有 `APIRouter` 的其他子模块: -```Python hl_lines="5" +```Python hl_lines="5" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` @@ -360,7 +360,7 @@ from .routers.users import router 因此,为了能够在同一个文件中使用它们,我们直接导入子模块: -```Python hl_lines="4" +```Python hl_lines="5" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` @@ -368,7 +368,7 @@ from .routers.users import router 现在,让我们来包含来自 `users` 和 `items` 子模块的 `router`。 -```Python hl_lines="10-11" +```Python hl_lines="10-11" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` @@ -401,7 +401,7 @@ from .routers.users import router 对于此示例,它将非常简单。但是假设由于它是与组织中的其他项目所共享的,因此我们无法对其进行修改,以及直接在 `APIRouter` 中添加 `prefix`、`dependencies`、`tags` 等: -```Python hl_lines="3" +```Python hl_lines="3" title="app/internal/admin.py" {!../../../docs_src/bigger_applications/app/internal/admin.py!} ``` @@ -409,7 +409,7 @@ from .routers.users import router 我们可以通过将这些参数传递给 `app.include_router()` 来完成所有的声明,而不必修改原始的 `APIRouter`: -```Python hl_lines="14-17" +```Python hl_lines="14-17" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` @@ -432,7 +432,7 @@ from .routers.users import router 这里我们这样做了...只是为了表明我们可以做到🤷: -```Python hl_lines="21-23" +```Python hl_lines="21-23" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` diff --git a/docs/zh/docs/tutorial/body-fields.md b/docs/zh/docs/tutorial/body-fields.md index c153784dc..fb6c6d9b6 100644 --- a/docs/zh/docs/tutorial/body-fields.md +++ b/docs/zh/docs/tutorial/body-fields.md @@ -18,7 +18,7 @@ {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="4" {!> ../../../docs_src/body_fields/tutorial001_an.py!} @@ -33,7 +33,7 @@ {!> ../../../docs_src/body_fields/tutorial001_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip 尽可能选择使用 `Annotated` 的版本。 @@ -61,7 +61,7 @@ {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="12-15" {!> ../../../docs_src/body_fields/tutorial001_an.py!} @@ -76,7 +76,7 @@ {!> ../../../docs_src/body_fields/tutorial001_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip Prefer to use the `Annotated` version if possible. diff --git a/docs/zh/docs/tutorial/body-multiple-params.md b/docs/zh/docs/tutorial/body-multiple-params.md index ee2cba6df..c93ef2f5c 100644 --- a/docs/zh/docs/tutorial/body-multiple-params.md +++ b/docs/zh/docs/tutorial/body-multiple-params.md @@ -20,7 +20,7 @@ {!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="19-21" {!> ../../../docs_src/body_multiple_params/tutorial001_an.py!} @@ -35,7 +35,7 @@ {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip 尽可能选择使用 `Annotated` 的版本。 @@ -68,7 +68,7 @@ {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="22" {!> ../../../docs_src/body_multiple_params/tutorial002.py!} @@ -124,7 +124,7 @@ {!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="24" {!> ../../../docs_src/body_multiple_params/tutorial003_an.py!} @@ -139,7 +139,7 @@ {!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip 尽可能选择使用 `Annotated` 的版本。 @@ -193,7 +193,7 @@ q: str = None {!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="28" {!> ../../../docs_src/body_multiple_params/tutorial004_an.py!} @@ -208,7 +208,7 @@ q: str = None {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip 尽可能选择使用 `Annotated` 的版本。 @@ -247,7 +247,7 @@ item: Item = Body(embed=True) {!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="18" {!> ../../../docs_src/body_multiple_params/tutorial005_an.py!} @@ -262,7 +262,7 @@ item: Item = Body(embed=True) {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip 尽可能选择使用 `Annotated` 的版本。 diff --git a/docs/zh/docs/tutorial/body-nested-models.md b/docs/zh/docs/tutorial/body-nested-models.md index 7704d2624..c65308bef 100644 --- a/docs/zh/docs/tutorial/body-nested-models.md +++ b/docs/zh/docs/tutorial/body-nested-models.md @@ -12,7 +12,7 @@ {!> ../../../docs_src/body_nested_models/tutorial001_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="14" {!> ../../../docs_src/body_nested_models/tutorial001.py!} @@ -63,7 +63,7 @@ my_list: List[str] {!> ../../../docs_src/body_nested_models/tutorial002_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="14" {!> ../../../docs_src/body_nested_models/tutorial002.py!} @@ -89,7 +89,7 @@ Python 具有一种特殊的数据类型来保存一组唯一的元素,即 `se {!> ../../../docs_src/body_nested_models/tutorial003_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="1 14" {!> ../../../docs_src/body_nested_models/tutorial003.py!} @@ -127,7 +127,7 @@ Pydantic 模型的每个属性都具有类型。 {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9-11" {!> ../../../docs_src/body_nested_models/tutorial004.py!} @@ -149,7 +149,7 @@ Pydantic 模型的每个属性都具有类型。 {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="20" {!> ../../../docs_src/body_nested_models/tutorial004.py!} @@ -198,7 +198,7 @@ Pydantic 模型的每个属性都具有类型。 {!> ../../../docs_src/body_nested_models/tutorial005_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="4 10" {!> ../../../docs_src/body_nested_models/tutorial005.py!} @@ -222,7 +222,7 @@ Pydantic 模型的每个属性都具有类型。 {!> ../../../docs_src/body_nested_models/tutorial006_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="20" {!> ../../../docs_src/body_nested_models/tutorial006.py!} @@ -273,7 +273,7 @@ Pydantic 模型的每个属性都具有类型。 {!> ../../../docs_src/body_nested_models/tutorial007_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9 14 20 23 27" {!> ../../../docs_src/body_nested_models/tutorial007.py!} @@ -298,7 +298,7 @@ images: List[Image] {!> ../../../docs_src/body_nested_models/tutorial008_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="15" {!> ../../../docs_src/body_nested_models/tutorial008.py!} @@ -338,7 +338,7 @@ images: List[Image] {!> ../../../docs_src/body_nested_models/tutorial009_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9" {!> ../../../docs_src/body_nested_models/tutorial009.py!} diff --git a/docs/zh/docs/tutorial/body.md b/docs/zh/docs/tutorial/body.md index d00c96dc3..5cf53c0c2 100644 --- a/docs/zh/docs/tutorial/body.md +++ b/docs/zh/docs/tutorial/body.md @@ -23,7 +23,7 @@ {!> ../../../docs_src/body/tutorial001_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="4" {!> ../../../docs_src/body/tutorial001.py!} @@ -41,7 +41,7 @@ {!> ../../../docs_src/body/tutorial001_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="7-11" {!> ../../../docs_src/body/tutorial001.py!} @@ -79,7 +79,7 @@ {!> ../../../docs_src/body/tutorial001_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="18" {!> ../../../docs_src/body/tutorial001.py!} @@ -142,7 +142,7 @@ Pydantic 本身甚至也进行了一些更改以支持此功能。 {!> ../../../docs_src/body/tutorial002_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="21" {!> ../../../docs_src/body/tutorial002.py!} @@ -160,7 +160,7 @@ Pydantic 本身甚至也进行了一些更改以支持此功能。 {!> ../../../docs_src/body/tutorial003_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="17-18" {!> ../../../docs_src/body/tutorial003.py!} @@ -178,7 +178,7 @@ Pydantic 本身甚至也进行了一些更改以支持此功能。 {!> ../../../docs_src/body/tutorial004_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="18" {!> ../../../docs_src/body/tutorial004.py!} diff --git a/docs/zh/docs/tutorial/cookie-params.md b/docs/zh/docs/tutorial/cookie-params.md index 470fd8e82..f115f9677 100644 --- a/docs/zh/docs/tutorial/cookie-params.md +++ b/docs/zh/docs/tutorial/cookie-params.md @@ -18,7 +18,7 @@ {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="3" {!> ../../../docs_src/cookie_params/tutorial001_an.py!} @@ -33,7 +33,7 @@ {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip 尽可能选择使用 `Annotated` 的版本。 @@ -61,7 +61,7 @@ {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="10" {!> ../../../docs_src/cookie_params/tutorial001_an.py!} @@ -76,7 +76,7 @@ {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip 尽可能选择使用 `Annotated` 的版本。 diff --git a/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md index f404820df..1866da298 100644 --- a/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md @@ -12,7 +12,7 @@ {!> ../../../docs_src/dependencies/tutorial001_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9" {!> ../../../docs_src/dependencies/tutorial001.py!} @@ -85,7 +85,7 @@ fluffy = Cat(name="Mr Fluffy") {!> ../../../docs_src/dependencies/tutorial002_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="11-15" {!> ../../../docs_src/dependencies/tutorial002.py!} diff --git a/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md new file mode 100644 index 000000000..e24b9409f --- /dev/null +++ b/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md @@ -0,0 +1,253 @@ +# 使用yield的依赖项 + +FastAPI支持在完成后执行一些额外步骤的依赖项. + +为此,请使用 `yield` 而不是 `return`,然后再编写额外的步骤(代码)。 + +!!! 提示 + 确保只使用一次 `yield` 。 + +!!! 注意 "技术细节" + + 任何一个可以与以下内容一起使用的函数: + + * `@contextlib.contextmanager` 或者 + * `@contextlib.asynccontextmanager` + + 都可以作为 **FastAPI** 的依赖项。 + + 实际上,FastAPI内部就使用了这两个装饰器。 + + +## 使用 `yield` 的数据库依赖项 + +例如,您可以使用这种方式创建一个数据库会话,并在完成后关闭它。 + +在发送响应之前,只会执行 `yield` 语句及之前的代码: + +```Python hl_lines="2-4" +{!../../../docs_src/dependencies/tutorial007.py!} +``` + +生成的值会注入到*路径操作*和其他依赖项中: + +```Python hl_lines="4" +{!../../../docs_src/dependencies/tutorial007.py!} +``` + +"yield"语句后面的代码会在发送响应后执行:: + +```Python hl_lines="5-6" +{!../../../docs_src/dependencies/tutorial007.py!} +``` + +!!! 提示 + + 您可以使用 `async` 或普通函数。 + + **FastAPI** 会像处理普通依赖关系一样,对每个依赖关系做正确的处理。 + +## 同时包含了 `yield` 和 `try` 的依赖项 + +如果在带有 `yield` 的依赖关系中使用 `try` 代码块,就会收到使用依赖关系时抛出的任何异常。 + +例如,如果中间某个代码在另一个依赖中或在*路径操作*中使数据库事务 "回滚 "或产生任何其他错误,您就会在依赖中收到异常。 + +因此,你可以使用 `except SomeException` 在依赖关系中查找特定的异常。 + +同样,您也可以使用 `finally` 来确保退出步骤得到执行,无论是否存在异常。 + +```Python hl_lines="3 5" +{!../../../docs_src/dependencies/tutorial007.py!} +``` +## 使用`yield`的子依赖项 + +你可以拥有任意大小和形状的子依赖和子依赖的“树”,而且它们中的任何一个或所有的都可以使用`yield`。 + +**FastAPI** 会确保每个带有`yield`的依赖中的“退出代码”按正确顺序运行。 + +例如,`dependency_c` 可以依赖于 `dependency_b`,而 `dependency_b` 则依赖于 `dependency_a`。 + +=== "Python 3.9+" + + ```Python hl_lines="6 14 22" + {!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="5 13 21" + {!> ../../../docs_src/dependencies/tutorial008_an.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + 如果可能,请尽量使用“ Annotated”版本。 + + ```Python hl_lines="4 12 20" + {!> ../../../docs_src/dependencies/tutorial008.py!} + ``` + +所有这些依赖都可以使用`yield`。 + +在这种情况下,`dependency_c` 在执行其退出代码时需要`dependency_b`(此处称为 `dep_b`)的值仍然可用。 + +而`dependency_b` 反过来则需要`dependency_a`(此处称为 `dep_a`)的值在其退出代码中可用。 + +=== "Python 3.9+" + + ```Python hl_lines="18-19 26-27" + {!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="17-18 25-26" + {!> ../../../docs_src/dependencies/tutorial008_an.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + 如果可能,请尽量使用“ Annotated”版本。 + + ```Python hl_lines="16-17 24-25" + {!> ../../../docs_src/dependencies/tutorial008.py!} + ``` + +同样,你可以有混合了`yield`和`return`的依赖。 + +你也可以有一个单一的依赖需要多个其他带有`yield`的依赖,等等。 + +你可以拥有任何你想要的依赖组合。 + +**FastAPI** 将确保按正确的顺序运行所有内容。 + +!!! note "技术细节" + + 这是由 Python 的上下文管理器完成的。 + + **FastAPI** 在内部使用它们来实现这一点。 + + +## 使用 `yield` 和 `HTTPException` 的依赖项 + +您看到可以使用带有 `yield` 的依赖项,并且具有捕获异常的 `try` 块。 + +在 `yield` 后抛出 `HTTPException` 或类似的异常是很诱人的,但是**这不起作用**。 + +带有`yield`的依赖中的退出代码在响应发送之后执行,因此[异常处理程序](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}已经运行过。没有任何东西可以捕获退出代码(在`yield`之后)中的依赖抛出的异常。 + +所以,如果在`yield`之后抛出`HTTPException`,默认(或任何自定义)异常处理程序捕获`HTTPException`并返回HTTP 400响应的机制将不再能够捕获该异常。 + +这就是允许在依赖中设置的任何东西(例如数据库会话(DB session))可以被后台任务使用的原因。 + +后台任务在响应发送之后运行。因此,无法触发`HTTPException`,因为甚至没有办法更改*已发送*的响应。 + +但如果后台任务产生了数据库错误,至少你可以在带有`yield`的依赖中回滚或清理关闭会话,并且可能记录错误或将其报告给远程跟踪系统。 + +如果你知道某些代码可能会引发异常,那就做最“Pythonic”的事情,就是在代码的那部分添加一个`try`块。 + +如果你有自定义异常,希望在返回响应之前处理,并且可能修改响应甚至触发`HTTPException`,可以创建[自定义异常处理程序](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}。 + +!!! tip + + 在`yield`之前仍然可以引发包括`HTTPException`在内的异常,但在`yield`之后则不行。 + +执行的顺序大致如下图所示。时间从上到下流动。每列都是相互交互或执行代码的其中一部分。 + +```mermaid +sequenceDiagram + +participant client as Client +participant handler as Exception handler +participant dep as Dep with yield +participant operation as Path Operation +participant tasks as Background tasks + + Note over client,tasks: Can raise exception for dependency, handled after response is sent + Note over client,operation: Can raise HTTPException and can change the response + client ->> dep: Start request + Note over dep: Run code up to yield + opt raise + dep -->> handler: Raise HTTPException + handler -->> client: HTTP error response + dep -->> dep: Raise other exception + end + dep ->> operation: Run dependency, e.g. DB session + opt raise + operation -->> dep: Raise HTTPException + dep -->> handler: Auto forward exception + handler -->> client: HTTP error response + operation -->> dep: Raise other exception + dep -->> handler: Auto forward exception + end + operation ->> client: Return response to client + Note over client,operation: Response is already sent, can't change it anymore + opt Tasks + operation -->> tasks: Send background tasks + end + opt Raise other exception + tasks -->> dep: Raise other exception + end + Note over dep: After yield + opt Handle other exception + dep -->> dep: Handle exception, can't change response. E.g. close DB session. + end +``` + +!!! info + 只会向客户端发送**一次响应**,可能是一个错误响应之一,也可能是来自*路径操作*的响应。 + + 在发送了其中一个响应之后,就无法再发送其他响应了。 + +!!! tip + 这个图表展示了`HTTPException`,但你也可以引发任何其他你创建了[自定义异常处理程序](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}的异常。 + + 如果你引发任何异常,它将传递给带有`yield`的依赖,包括`HTTPException`,然后**再次**传递给异常处理程序。如果没有针对该异常的异常处理程序,那么它将被默认的内部`ServerErrorMiddleware`处理,返回500 HTTP状态码,告知客户端服务器发生了错误。 + +## 上下文管理器 + +### 什么是“上下文管理器” + +“上下文管理器”是您可以在`with`语句中使用的任何Python对象。 + +例如,您可以使用`with`读取文件: + +```Python +with open("./somefile.txt") as f: + contents = f.read() + print(contents) +``` + +在底层,`open("./somefile.txt")`创建了一个被称为“上下文管理器”的对象。 + +当`with`块结束时,它会确保关闭文件,即使发生了异常也是如此。 + +当你使用`yield`创建一个依赖项时,**FastAPI**会在内部将其转换为上下文管理器,并与其他相关工具结合使用。 + +### 在依赖项中使用带有`yield`的上下文管理器 + +!!! warning + 这是一个更为“高级”的想法。 + + 如果您刚开始使用**FastAPI**,您可能暂时可以跳过它。 + +在Python中,你可以通过创建一个带有`__enter__()`和`__exit__()`方法的类来创建上下文管理器。 + +你也可以在**FastAPI**的依赖项中使用带有`yield`的`with`或`async with`语句,通过在依赖函数内部使用它们。 + +```Python hl_lines="1-9 13" +{!../../../docs_src/dependencies/tutorial010.py!} +``` + +!!! tip + 另一种创建上下文管理器的方法是: + + * `@contextlib.contextmanager`或者 + * `@contextlib.asynccontextmanager` + + 使用上下文管理器装饰一个只有单个`yield`的函数。这就是**FastAPI**在内部用于带有`yield`的依赖项的方式。 + + 但是你不需要为FastAPI的依赖项使用这些装饰器(而且也不应该)。FastAPI会在内部为你处理这些。 diff --git a/docs/zh/docs/tutorial/encoder.md b/docs/zh/docs/tutorial/encoder.md index 76ed846ce..859ebc2e8 100644 --- a/docs/zh/docs/tutorial/encoder.md +++ b/docs/zh/docs/tutorial/encoder.md @@ -26,7 +26,7 @@ {!> ../../../docs_src/encoder/tutorial001_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="5 22" {!> ../../../docs_src/encoder/tutorial001.py!} diff --git a/docs/zh/docs/tutorial/extra-data-types.md b/docs/zh/docs/tutorial/extra-data-types.md index 76d606903..f4a77050c 100644 --- a/docs/zh/docs/tutorial/extra-data-types.md +++ b/docs/zh/docs/tutorial/extra-data-types.md @@ -44,11 +44,11 @@ * 产生的模式将指定那些 `set` 的值是唯一的 (使用 JSON 模式的 `uniqueItems`)。 * `bytes`: * 标准的 Python `bytes`。 - * 在请求和相应中被当作 `str` 处理。 + * 在请求和响应中被当作 `str` 处理。 * 生成的模式将指定这个 `str` 是 `binary` "格式"。 * `Decimal`: * 标准的 Python `Decimal`。 - * 在请求和相应中被当做 `float` 一样处理。 + * 在请求和响应中被当做 `float` 一样处理。 * 您可以在这里检查所有有效的pydantic数据类型: Pydantic data types. ## 例子 @@ -67,7 +67,7 @@ {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="1 3 13-17" {!> ../../../docs_src/extra_data_types/tutorial001_an.py!} @@ -82,7 +82,7 @@ {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip 尽可能选择使用 `Annotated` 的版本。 @@ -105,7 +105,7 @@ {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="19-20" {!> ../../../docs_src/extra_data_types/tutorial001_an.py!} @@ -120,7 +120,7 @@ {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip 尽可能选择使用 `Annotated` 的版本。 diff --git a/docs/zh/docs/tutorial/extra-models.md b/docs/zh/docs/tutorial/extra-models.md index 32f8f9df1..06427a73d 100644 --- a/docs/zh/docs/tutorial/extra-models.md +++ b/docs/zh/docs/tutorial/extra-models.md @@ -23,7 +23,7 @@ {!> ../../../docs_src/extra_models/tutorial001_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" {!> ../../../docs_src/extra_models/tutorial001.py!} @@ -164,7 +164,7 @@ UserInDB( {!> ../../../docs_src/extra_models/tutorial002_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9 15-16 19-20 23-24" {!> ../../../docs_src/extra_models/tutorial002.py!} @@ -188,7 +188,7 @@ UserInDB( {!> ../../../docs_src/extra_models/tutorial003_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="1 14-15 18-20 33" {!> ../../../docs_src/extra_models/tutorial003.py!} @@ -206,7 +206,7 @@ UserInDB( {!> ../../../docs_src/extra_models/tutorial004_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="1 20" {!> ../../../docs_src/extra_models/tutorial004.py!} @@ -226,7 +226,7 @@ UserInDB( {!> ../../../docs_src/extra_models/tutorial005_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="1 8" {!> ../../../docs_src/extra_models/tutorial005.py!} diff --git a/docs/zh/docs/tutorial/header-params.md b/docs/zh/docs/tutorial/header-params.md index 22ff6dc27..2701167b3 100644 --- a/docs/zh/docs/tutorial/header-params.md +++ b/docs/zh/docs/tutorial/header-params.md @@ -18,7 +18,7 @@ {!> ../../../docs_src/header_params/tutorial001_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="3" {!> ../../../docs_src/header_params/tutorial001_an.py!} @@ -33,7 +33,7 @@ {!> ../../../docs_src/header_params/tutorial001_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip 尽可能选择使用 `Annotated` 的版本。 @@ -60,7 +60,7 @@ {!> ../../../docs_src/header_params/tutorial001_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="10" {!> ../../../docs_src/header_params/tutorial001_an.py!} @@ -75,7 +75,7 @@ {!> ../../../docs_src/header_params/tutorial001_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip 尽可能选择使用 `Annotated` 的版本。 @@ -120,7 +120,7 @@ {!> ../../../docs_src/header_params/tutorial002_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="12" {!> ../../../docs_src/header_params/tutorial002_an.py!} @@ -135,7 +135,7 @@ {!> ../../../docs_src/header_params/tutorial002_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip 尽可能选择使用 `Annotated` 的版本。 @@ -170,7 +170,7 @@ {!> ../../../docs_src/header_params/tutorial003_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="10" {!> ../../../docs_src/header_params/tutorial003_an.py!} @@ -194,7 +194,7 @@ {!> ../../../docs_src/header_params/tutorial003_py39.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip 尽可能选择使用 `Annotated` 的版本。 diff --git a/docs/zh/docs/tutorial/path-params-numeric-validations.md b/docs/zh/docs/tutorial/path-params-numeric-validations.md index 78fa922b4..9b41ad7cf 100644 --- a/docs/zh/docs/tutorial/path-params-numeric-validations.md +++ b/docs/zh/docs/tutorial/path-params-numeric-validations.md @@ -18,7 +18,7 @@ {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="3-4" {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} @@ -33,7 +33,7 @@ {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip 尽可能选择使用 `Annotated` 的版本。 @@ -60,7 +60,7 @@ {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="11" {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} @@ -75,7 +75,7 @@ {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip 尽可能选择使用 `Annotated` 的版本。 @@ -107,7 +107,7 @@ 因此,你可以将函数声明为: -=== "Python 3.6 non-Annotated" +=== "Python 3.8 non-Annotated" !!! tip 尽可能选择使用 `Annotated` 的版本。 diff --git a/docs/zh/docs/tutorial/query-params-str-validations.md b/docs/zh/docs/tutorial/query-params-str-validations.md index 7244aeade..39253eb0d 100644 --- a/docs/zh/docs/tutorial/query-params-str-validations.md +++ b/docs/zh/docs/tutorial/query-params-str-validations.md @@ -10,7 +10,7 @@ {!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9" {!> ../../../docs_src/query_params_str_validations/tutorial001.py!} diff --git a/docs/zh/docs/tutorial/request-files.md b/docs/zh/docs/tutorial/request-files.md index 03474907e..2c48f33ca 100644 --- a/docs/zh/docs/tutorial/request-files.md +++ b/docs/zh/docs/tutorial/request-files.md @@ -130,7 +130,7 @@ contents = myfile.file.read() {!> ../../../docs_src/request_files/tutorial001_02_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9 17" {!> ../../../docs_src/request_files/tutorial001_02.py!} @@ -158,7 +158,7 @@ FastAPI 支持同时上传多个文件。 {!> ../../../docs_src/request_files/tutorial002_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="10 15" {!> ../../../docs_src/request_files/tutorial002.py!} @@ -183,7 +183,7 @@ FastAPI 支持同时上传多个文件。 {!> ../../../docs_src/request_files/tutorial003_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="18" {!> ../../../docs_src/request_files/tutorial003.py!} diff --git a/docs/zh/docs/tutorial/response-model.md b/docs/zh/docs/tutorial/response-model.md index f529cb0d8..e731b6989 100644 --- a/docs/zh/docs/tutorial/response-model.md +++ b/docs/zh/docs/tutorial/response-model.md @@ -20,7 +20,7 @@ {!> ../../../docs_src/response_model/tutorial001_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="17 22 24-27" {!> ../../../docs_src/response_model/tutorial001.py!} @@ -78,7 +78,7 @@ FastAPI 将使用此 `response_model` 来: {!> ../../../docs_src/response_model/tutorial003_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="9 11 16" {!> ../../../docs_src/response_model/tutorial003.py!} @@ -92,7 +92,7 @@ FastAPI 将使用此 `response_model` 来: {!> ../../../docs_src/response_model/tutorial003_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="24" {!> ../../../docs_src/response_model/tutorial003.py!} @@ -106,7 +106,7 @@ FastAPI 将使用此 `response_model` 来: {!> ../../../docs_src/response_model/tutorial003_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="22" {!> ../../../docs_src/response_model/tutorial003.py!} diff --git a/docs/zh/docs/tutorial/schema-extra-example.md b/docs/zh/docs/tutorial/schema-extra-example.md index 816e8f68e..ebc04da8b 100644 --- a/docs/zh/docs/tutorial/schema-extra-example.md +++ b/docs/zh/docs/tutorial/schema-extra-example.md @@ -16,7 +16,7 @@ {!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="15-23" {!> ../../../docs_src/schema_extra_example/tutorial001.py!} @@ -34,7 +34,7 @@ {!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="4 10-13" {!> ../../../docs_src/schema_extra_example/tutorial002.py!} @@ -61,7 +61,7 @@ {!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python hl_lines="23-28" {!> ../../../docs_src/schema_extra_example/tutorial003_an.py!} @@ -76,7 +76,7 @@ {!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip 尽可能选择使用 `Annotated` 的版本。 diff --git a/docs/zh/docs/tutorial/security/first-steps.md b/docs/zh/docs/tutorial/security/first-steps.md index 7b1052e12..dda956417 100644 --- a/docs/zh/docs/tutorial/security/first-steps.md +++ b/docs/zh/docs/tutorial/security/first-steps.md @@ -26,13 +26,13 @@ {!> ../../../docs_src/security/tutorial001_an_py39.py!} ``` -=== "Python 3.6+" +=== "Python 3.8+" ```Python {!> ../../../docs_src/security/tutorial001_an.py!} ``` -=== "Python 3.6+ non-Annotated" +=== "Python 3.8+ non-Annotated" !!! tip 尽可能选择使用 `Annotated` 的版本。 diff --git a/docs/zh/docs/tutorial/security/oauth2-jwt.md b/docs/zh/docs/tutorial/security/oauth2-jwt.md index 054198545..33a4d7fc7 100644 --- a/docs/zh/docs/tutorial/security/oauth2-jwt.md +++ b/docs/zh/docs/tutorial/security/oauth2-jwt.md @@ -170,7 +170,7 @@ $ openssl rand -hex 32 创建并返回真正的 JWT 访问令牌。 -```Python hl_lines="115-128" +```Python hl_lines="115-130" {!../../../docs_src/security/tutorial004.py!} ``` diff --git a/docs/zh/docs/tutorial/security/simple-oauth2.md b/docs/zh/docs/tutorial/security/simple-oauth2.md index 276f3d63b..c7f46177f 100644 --- a/docs/zh/docs/tutorial/security/simple-oauth2.md +++ b/docs/zh/docs/tutorial/security/simple-oauth2.md @@ -1,94 +1,98 @@ -# 使用密码和 Bearer 的简单 OAuth2 +# OAuth2 实现简单的 Password 和 Bearer 验证 -现在让我们接着上一章继续开发,并添加缺少的部分以实现一个完整的安全性流程。 +本章添加上一章示例中欠缺的部分,实现完整的安全流。 ## 获取 `username` 和 `password` -我们将使用 **FastAPI** 的安全性实用工具来获取 `username` 和 `password`。 +首先,使用 **FastAPI** 安全工具获取 `username` 和 `password`。 -OAuth2 规定在使用(我们打算用的)「password 流程」时,客户端/用户必须将 `username` 和 `password` 字段作为表单数据发送。 +OAuth2 规范要求使用**密码流**时,客户端或用户必须以表单数据形式发送 `username` 和 `password` 字段。 -而且规范明确了字段必须这样命名。因此 `user-name` 或 `email` 是行不通的。 +并且,这两个字段必须命名为 `username` 和 `password` ,不能使用 `user-name` 或 `email` 等其它名称。 -不过不用担心,你可以在前端按照你的想法将它展示给最终用户。 +不过也不用担心,前端仍可以显示终端用户所需的名称。 -而且你的数据库模型也可以使用你想用的任何其他名称。 +数据库模型也可以使用所需的名称。 -但是对于登录*路径操作*,我们需要使用这些名称来与规范兼容(以具备例如使用集成的 API 文档系统的能力)。 +但对于登录*路径操作*,则要使用兼容规范的 `username` 和 `password`,(例如,实现与 API 文档集成)。 -规范还写明了 `username` 和 `password` 必须作为表单数据发送(因此,此处不能使用 JSON)。 +该规范要求必须以表单数据形式发送 `username` 和 `password`,因此,不能使用 JSON 对象。 -### `scope` +### `Scope`(作用域) -规范还提到客户端可以发送另一个表单字段「`scope`」。 +OAuth2 还支持客户端发送**`scope`**表单字段。 -这个表单字段的名称为 `scope`(单数形式),但实际上它是一个由空格分隔的「作用域」组成的长字符串。 +虽然表单字段的名称是 `scope`(单数),但实际上,它是以空格分隔的,由多个**scope**组成的长字符串。 -每个「作用域」只是一个字符串(中间没有空格)。 +**作用域**只是不带空格的字符串。 -它们通常用于声明特定的安全权限,例如: +常用于声明指定安全权限,例如: -* `users:read` 或者 `users:write` 是常见的例子。 -* Facebook / Instagram 使用 `instagram_basic`。 -* Google 使用了 `https://www.googleapis.com/auth/drive` 。 +* 常见用例为,`users:read` 或 `users:write` +* 脸书和 Instagram 使用 `instagram_basic` +* 谷歌使用 `https://www.googleapis.com/auth/drive` -!!! info - 在 OAuth2 中「作用域」只是一个声明所需特定权限的字符串。 +!!! info "说明" - 它有没有 `:` 这样的其他字符或者是不是 URL 都没有关系。 + OAuth2 中,**作用域**只是声明指定权限的字符串。 - 这些细节是具体的实现。 + 是否使用冒号 `:` 等符号,或是不是 URL 并不重要。 - 对 OAuth2 来说它们就只是字符串而已。 + 这些细节只是特定的实现方式。 + + 对 OAuth2 来说,都只是字符串而已。 ## 获取 `username` 和 `password` 的代码 -现在,让我们使用 **FastAPI** 提供的实用工具来处理此问题。 +接下来,使用 **FastAPI** 工具获取用户名与密码。 ### `OAuth2PasswordRequestForm` -首先,导入 `OAuth2PasswordRequestForm`,然后在 `token` 的*路径操作*中通过 `Depends` 将其作为依赖项使用。 +首先,导入 `OAuth2PasswordRequestForm`,然后,在 `/token` *路径操作* 中,用 `Depends` 把该类作为依赖项。 ```Python hl_lines="4 76" {!../../../docs_src/security/tutorial003.py!} ``` -`OAuth2PasswordRequestForm` 是一个类依赖项,声明了如下的请求表单: +`OAuth2PasswordRequestForm` 是用以下几项内容声明表单请求体的类依赖项: + +* `username` +* `password` +* 可选的 `scope` 字段,由多个空格分隔的字符串组成的长字符串 +* 可选的 `grant_type` -* `username`。 -* `password`。 -* 一个可选的 `scope` 字段,是一个由空格分隔的字符串组成的大字符串。 -* 一个可选的 `grant_type`. +!!! tip "提示" -!!! tip - OAuth2 规范实际上*要求* `grant_type` 字段使用一个固定的值 `password`,但是 `OAuth2PasswordRequestForm` 没有作强制约束。 + 实际上,OAuth2 规范*要求* `grant_type` 字段使用固定值 `password`,但 `OAuth2PasswordRequestForm` 没有作强制约束。 - 如果你需要强制要求这一点,请使用 `OAuth2PasswordRequestFormStrict` 而不是 `OAuth2PasswordRequestForm`。 + 如需强制使用固定值 `password`,则不要用 `OAuth2PasswordRequestForm`,而是用 `OAuth2PasswordRequestFormStrict`。 -* 一个可选的 `client_id`(我们的示例不需要它)。 -* 一个可选的 `client_secret`(我们的示例不需要它)。 +* 可选的 `client_id`(本例未使用) +* 可选的 `client_secret`(本例未使用) -!!! info - `OAuth2PasswordRequestForm` 并不像 `OAuth2PasswordBearer` 一样是 FastAPI 的一个特殊的类。 +!!! info "说明" - `OAuth2PasswordBearer` 使得 **FastAPI** 明白它是一个安全方案。所以它得以通过这种方式添加到 OpenAPI 中。 + `OAuth2PasswordRequestForm` 与 `OAuth2PasswordBearer` 一样,都不是 FastAPI 的特殊类。 - 但 `OAuth2PasswordRequestForm` 只是一个你可以自己编写的类依赖项,或者你也可以直接声明 `Form` 参数。 + **FastAPI** 把 `OAuth2PasswordBearer` 识别为安全方案。因此,可以通过这种方式把它添加至 OpenAPI。 - 但是由于这是一种常见的使用场景,因此 FastAPI 出于简便直接提供了它。 + 但 `OAuth2PasswordRequestForm` 只是可以自行编写的类依赖项,也可以直接声明 `Form` 参数。 + + 但由于这种用例很常见,FastAPI 为了简便,就直接提供了对它的支持。 ### 使用表单数据 -!!! tip - 类依赖项 `OAuth2PasswordRequestForm` 的实例不会有用空格分隔的长字符串属性 `scope`,而是具有一个 `scopes` 属性,该属性将包含实际被发送的每个作用域字符串组成的列表。 +!!! tip "提示" + + `OAuth2PasswordRequestForm` 类依赖项的实例没有以空格分隔的长字符串属性 `scope`,但它支持 `scopes` 属性,由已发送的 scope 字符串列表组成。 - 在此示例中我们没有使用 `scopes`,但如果你需要的话可以使用该功能。 + 本例没有使用 `scopes`,但开发者也可以根据需要使用该属性。 -现在,使用表单字段中的 `username` 从(伪)数据库中获取用户数据。 +现在,即可使用表单字段 `username`,从(伪)数据库中获取用户数据。 -如果没有这个用户,我们将返回一个错误消息,提示「用户名或密码错误」。 +如果不存在指定用户,则返回错误消息,提示**用户名或密码错误**。 -对于这个错误,我们使用 `HTTPException` 异常: +本例使用 `HTTPException` 异常显示此错误: ```Python hl_lines="3 77-79" {!../../../docs_src/security/tutorial003.py!} @@ -96,27 +100,27 @@ OAuth2 规定在使用(我们打算用的)「password 流程」时,客户 ### 校验密码 -目前我们已经从数据库中获取了用户数据,但尚未校验密码。 +至此,我们已经从数据库中获取了用户数据,但尚未校验密码。 -让我们首先将这些数据放入 Pydantic `UserInDB` 模型中。 +接下来,首先将数据放入 Pydantic 的 `UserInDB` 模型。 -永远不要保存明文密码,因此,我们将使用(伪)哈希密码系统。 +注意:永远不要保存明文密码,本例暂时先使用(伪)哈希密码系统。 -如果密码不匹配,我们将返回同一个错误。 +如果密码不匹配,则返回与上面相同的错误。 -#### 哈希密码 +#### 密码哈希 -「哈希」的意思是:将某些内容(在本例中为密码)转换为看起来像乱码的字节序列(只是一个字符串)。 +**哈希**是指,将指定内容(本例中为密码)转换为形似乱码的字节序列(其实就是字符串)。 -每次你传入完全相同的内容(完全相同的密码)时,你都会得到完全相同的乱码。 +每次传入完全相同的内容(比如,完全相同的密码)时,得到的都是完全相同的乱码。 -但是你不能从乱码转换回密码。 +但这个乱码无法转换回传入的密码。 -##### 为什么使用哈希密码 +##### 为什么使用密码哈希 -如果你的数据库被盗,小偷将无法获得用户的明文密码,只有哈希值。 +原因很简单,假如数据库被盗,窃贼无法获取用户的明文密码,得到的只是哈希值。 -因此,小偷将无法尝试在另一个系统中使用这些相同的密码(由于许多用户在任何地方都使用相同的密码,因此这很危险)。 +这样一来,窃贼就无法在其它应用中使用窃取的密码,要知道,很多用户在所有系统中都使用相同的密码,风险超大。 ```Python hl_lines="80-83" {!../../../docs_src/security/tutorial003.py!} @@ -124,9 +128,9 @@ OAuth2 规定在使用(我们打算用的)「password 流程」时,客户 #### 关于 `**user_dict` -`UserInDB(**user_dict)` 表示: +`UserInDB(**user_dict)` 是指: -*直接将 `user_dict` 的键和值作为关键字参数传递,等同于:* +*直接把 `user_dict` 的键与值当作关键字参数传递,等效于:* ```Python UserInDB( @@ -138,75 +142,79 @@ UserInDB( ) ``` -!!! info - 有关 `user_dict` 的更完整说明,请参阅[**额外的模型**文档](../extra-models.md#about-user_indict){.internal-link target=_blank}。 +!!! info "说明" -## 返回令牌 + `user_dict` 的说明,详见[**更多模型**一章](../extra-models.md#about-user_indict){.internal-link target=_blank}。 -`token` 端点的响应必须是一个 JSON 对象。 +## 返回 Token -它应该有一个 `token_type`。在我们的例子中,由于我们使用的是「Bearer」令牌,因此令牌类型应为「`bearer`」。 +`token` 端点的响应必须是 JSON 对象。 -并且还应该有一个 `access_token` 字段,它是一个包含我们的访问令牌的字符串。 +响应返回的内容应该包含 `token_type`。本例中用的是**Bearer**Token,因此, Token 类型应为**`bearer`**。 -对于这个简单的示例,我们将极其不安全地返回相同的 `username` 作为令牌。 +返回内容还应包含 `access_token` 字段,它是包含权限 Token 的字符串。 -!!! tip - 在下一章中,你将看到一个真实的安全实现,使用了哈希密码和 JWT 令牌。 +本例只是简单的演示,返回的 Token 就是 `username`,但这种方式极不安全。 - 但现在,让我们仅关注我们需要的特定细节。 +!!! tip "提示" + + 下一章介绍使用哈希密码和 JWT Token 的真正安全机制。 + + 但现在,仅关注所需的特定细节。 ```Python hl_lines="85" {!../../../docs_src/security/tutorial003.py!} ``` -!!! tip - 根据规范,你应该像本示例一样,返回一个带有 `access_token` 和 `token_type` 的 JSON。 +!!! tip "提示" - 这是你必须在代码中自行完成的工作,并且要确保使用了这些 JSON 字段。 + 按规范的要求,应像本示例一样,返回带有 `access_token` 和 `token_type` 的 JSON 对象。 - 这几乎是唯一的你需要自己记住并正确地执行以符合规范的事情。 + 这是开发者必须在代码中自行完成的工作,并且要确保使用这些 JSON 的键。 - 其余的,**FastAPI** 都会为你处理。 + 这几乎是唯一需要开发者牢记在心,并按规范要求正确执行的事。 + + **FastAPI** 则负责处理其它的工作。 ## 更新依赖项 -现在我们将更新我们的依赖项。 +接下来,更新依赖项。 -我们想要仅当此用户处于启用状态时才能获取 `current_user`。 +使之仅在当前用户为激活状态时,才能获取 `current_user`。 -因此,我们创建了一个额外的依赖项 `get_current_active_user`,而该依赖项又以 `get_current_user` 作为依赖项。 +为此,要再创建一个依赖项 `get_current_active_user`,此依赖项以 `get_current_user` 依赖项为基础。 -如果用户不存在或处于未启用状态,则这两个依赖项都将仅返回 HTTP 错误。 +如果用户不存在,或状态为未激活,这两个依赖项都会返回 HTTP 错误。 -因此,在我们的端点中,只有当用户存在,身份认证通过且处于启用状态时,我们才能获得该用户: +因此,在端点中,只有当用户存在、通过身份验证、且状态为激活时,才能获得该用户: ```Python hl_lines="58-67 69-72 90" {!../../../docs_src/security/tutorial003.py!} ``` -!!! info - 我们在此处返回的值为 `Bearer` 的额外响应头 `WWW-Authenticate` 也是规范的一部分。 +!!! info "说明" + + 此处返回值为 `Bearer` 的响应头 `WWW-Authenticate` 也是规范的一部分。 - 任何的 401「未认证」HTTP(错误)状态码都应该返回 `WWW-Authenticate` 响应头。 + 任何 401**UNAUTHORIZED**HTTP(错误)状态码都应返回 `WWW-Authenticate` 响应头。 - 对于 bearer 令牌(我们的例子),该响应头的值应为 `Bearer`。 + 本例中,因为使用的是 Bearer Token,该响应头的值应为 `Bearer`。 - 实际上你可以忽略这个额外的响应头,不会有什么问题。 + 实际上,忽略这个附加响应头,也不会有什么问题。 - 但此处提供了它以符合规范。 + 之所以在此提供这个附加响应头,是为了符合规范的要求。 - 而且,(现在或将来)可能会有工具期望得到并使用它,然后对你或你的用户有用处。 + 说不定什么时候,就有工具用得上它,而且,开发者或用户也可能用得上。 - 这就是遵循标准的好处... + 这就是遵循标准的好处…… ## 实际效果 -打开交互式文档:http://127.0.0.1:8000/docs。 +打开 API 文档:http://127.0.0.1:8000/docs。 -### 身份认证 +### 身份验证 -点击「Authorize」按钮。 +点击**Authorize**按钮。 使用以下凭证: @@ -216,15 +224,15 @@ UserInDB(